diff --git a/src/auth.ts b/src/auth.ts index 1eb45109..fedeecd2 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,5 +1,6 @@ import { readFile, rm } from "node:fs/promises"; import { homedir } from "node:os"; +import { createInterface } from "node:readline/promises"; import { setTimeout as sleep } from "node:timers/promises"; import { pathToFileURL } from "node:url"; @@ -29,8 +30,13 @@ import { import { openBrowser } from "./lib/browser"; import { CommandError } from "./lib/command"; import { type Lock, LockTimeoutError } from "./lib/lock"; -import { getUserProfile, validateToken } from "./lib/prismic/client"; -import { ForbiddenRequestError, UnauthorizedRequestError } from "./lib/request"; +import { + createGuest, + getAuthenticationUrl, + getUserProfile, + validateToken, +} from "./lib/prismic/client"; +import { ForbiddenRequestError, RequestError, UnauthorizedRequestError } from "./lib/request"; import { dedent } from "./lib/string"; import { appendTrailingSlash } from "./lib/url"; import { @@ -155,6 +161,13 @@ async function renewLogin( ...storedLogin, session: { host, auth0Domain, clientId, pendingLogin: session.pendingLogin }, }); + if (session.guest) { + throw new CommandError( + session.guest.expiresAt > Date.now() + ? "Your temporary account was claimed, with its repositories. Run `prismic login` with the account that claimed it to keep working." + : "Your temporary account expired, and Prismic deleted its repositories. Run `prismic login` to keep working.", + ); + } ended = true; } @@ -188,8 +201,11 @@ async function isTokenRejected(token: string | undefined): Promise { } } -export async function reauthenticate(options: { browser?: boolean } = {}): Promise { - const token = await getSessionToken({ forceRefresh: true }); +export async function reauthenticate( + options: { browser?: boolean; guest?: boolean } = {}, +): Promise { + const token = + (await getSessionToken({ forceRefresh: true })) ?? (options.guest && (await startGuest())); if (token) return token; console.error(ended ? "Your login expired." : "You are not logged in."); return logIn(options); @@ -203,12 +219,10 @@ export async function logIn(options: { browser?: boolean } = {}): Promise { + const host = await getHost(); + const auth0 = getAuth0Config(host); + if (!auth0 || process.env.CI) return; + if ((await readCredentials().catch(() => undefined))?.login) return; + if (isPerson()) { + const prompt = createInterface({ + input: process.stdin, + output: process.stderr, + terminal: false, + }); + const answer = await prompt.question( + "You are not logged in. Start without an account? You can keep your work later by signing up or logging in. [Y/n] ", + ); + prompt.close(); + if (/^n/i.test(answer.trim())) return; + } + + return withCredentialsLock(async (lock) => { + const current = (await readCredentials()).login?.session; + if (current) return current.host === host ? getUnexpiredToken(current) : undefined; + + let guest; + try { + guest = await createGuest({ authenticationUrl: getAuthenticationApiUrl(host) }); + } catch (error) { + if (!(error instanceof RequestError) || (error.status !== 429 && error.status !== 503)) { + throw error; + } + console.error( + error.status === 429 + ? "Too many accounts were started without signing up from this network today." + : "Starting without an account isn't available right now.", + ); + return; + } + const store = await prepareLogin(lock); + await writeCredentials(lock, { + ...store, + session: { + host, + auth0Domain: auth0.auth0Domain, + clientId: guest.client_id, + accessToken: guest.access_token, + refreshToken: guest.refresh_token, + expiresAt: Date.now() + guest.expires_in * 1000, + guest: { claimUrl: guest.claim_url, expiresAt: Date.parse(guest.expires_at) }, + }, + }); + return guest.access_token; + }); +} + +export function getAuthenticationApiUrl(host: string): URL { + // Tests' fake Auth0 server also serves these routes. + if (process.env.PROD === "false" && env.PRISMIC_AUTH0_DOMAIN) { + return new URL("authentication/", appendTrailingSlash(env.PRISMIC_AUTH0_DOMAIN)); + } + return getAuthenticationUrl(host); +} + // Native client IDs are public. function getAuth0Config(host: string): Auth0Config | undefined { // Tests use a fake Auth0 server. Releases drop this branch, so a stray diff --git a/src/commands/index.ts b/src/commands/index.ts index d7e204f4..8bf1ef89 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -9,6 +9,8 @@ import init from "./init"; import locale from "./locale"; import login from "./login"; import logout from "./logout"; +import mcp from "./mcp"; +import open from "./open"; import preview from "./preview"; import pull from "./pull"; import push from "./push"; @@ -137,6 +139,14 @@ export default createCommandRouter({ handler: whoami, description: "Show the currently logged in user", }, + open: { + handler: open, + description: "Open your temporary account in a browser", + }, + mcp: { + handler: mcp, + description: "Connect the Prismic MCP server", + }, "task-id": { handler: taskId, description: "Print a task ID for --task-id", diff --git a/src/commands/init.ts b/src/commands/init.ts index 9b115adf..41a11de0 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -61,6 +61,12 @@ const config = { agents: ` Do not ask the user whether to create a new repository or connect an existing one. Use --repo only for a repository the user names, and run init. + + When nobody is logged in, init starts without an account. Give the user the + claim link and the deletion time it prints. If the user wants to use their + own account, run \`prismic login\` before init. + + After init, follow \`prismic mcp --help\` to connect the Prismic MCP server. `, options: { repo: { @@ -121,19 +127,20 @@ export default createCommand(config, async ({ values }) => { } } + let repo = (explicitRepo ?? legacySliceMachineConfig?.repositoryName)?.toLowerCase(); + const host = await getHost(); try { await getUserProfile({ getToken, host }); } catch (error) { if (error instanceof UnauthorizedRequestError || error instanceof ForbiddenRequestError) { if (env.PRISMIC_TOKEN) throw error; - await reauthenticate({ browser: !noBrowser }); + await reauthenticate({ browser: !noBrowser, guest: !repo }); } else { throw error; } } - let repo = (explicitRepo ?? legacySliceMachineConfig?.repositoryName)?.toLowerCase(); let connectedRepository: Repository | undefined; if (repo) { connectedRepository = await getRepository({ repo, getToken, host }).catch((error) => { diff --git a/src/commands/mcp-token.ts b/src/commands/mcp-token.ts new file mode 100644 index 00000000..156b403b --- /dev/null +++ b/src/commands/mcp-token.ts @@ -0,0 +1,16 @@ +import { getToken } from "../auth"; +import { CommandError, createCommand, type CommandConfig } from "../lib/command"; + +const config = { + name: "prismic mcp token", + description: ` + Print an Authorization header for the Prismic MCP server, as JSON. It uses + your CLI login and renews it when needed. + `, +} satisfies CommandConfig; + +export default createCommand(config, async () => { + const token = await getToken(); + if (!token) throw new CommandError("Not logged in. Run `prismic login` first."); + console.info(JSON.stringify({ Authorization: `Bearer ${token}` })); +}); diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts new file mode 100644 index 00000000..4959db28 --- /dev/null +++ b/src/commands/mcp.ts @@ -0,0 +1,34 @@ +import { createCommandRouter } from "../lib/command"; +import mcpToken from "./mcp-token"; + +export default createCommandRouter({ + name: "prismic mcp", + description: ` + Connect an agent to the Prismic MCP server with your CLI login. + + Run \`prismic docs view mcp#connect-with-the-prismic-cli\` for details. + `, + agents: ` + Connect the Prismic MCP server only if none is connected. Check: + 1. Your own tools. A tool from a server at mcp.prismic.io, including an + account-level connector with no local config, means it's connected. + 2. Claude Code: \`claude mcp list\`. + 3. Codex: \`codex mcp list\`. + 4. Cursor: ~/.cursor/mcp.json and .cursor/mcp.json. + 5. VS Code: .vscode/mcp.json and the mcp.json in the user profile. + If one is connected, or you can't tell, add nothing and use the CLI. + + Otherwise, add a project server named prismic at https://mcp.prismic.io/mcp. + In Claude Code, run: + claude mcp add-json --scope project prismic '{"type":"http","url":"https://mcp.prismic.io/mcp","headersHelper":"npx prismic mcp token"}' + In a client without a header command, such as Cursor, set the header that + \`prismic mcp token\` prints, and set it again after a 401. Keep a file that + holds the token out of git. + `, + commands: { + token: { + handler: mcpToken, + description: "Print an Authorization header for the Prismic MCP server", + }, + }, +}); diff --git a/src/commands/open.ts b/src/commands/open.ts new file mode 100644 index 00000000..27526eee --- /dev/null +++ b/src/commands/open.ts @@ -0,0 +1,36 @@ +import { getAuthenticationApiUrl, getHost, getToken, isPerson, onUnauthorized } from "../auth"; +import { readLoginSummary } from "../credentials"; +import { env } from "../env"; +import { openBrowser } from "../lib/browser"; +import { CommandError, createCommand, type CommandConfig } from "../lib/command"; +import { createGuestLink } from "../lib/prismic/client"; + +const config = { + name: "prismic open", + description: ` + Open your temporary account in a browser. There, you can keep its + repositories by signing up or logging in. + `, +} satisfies CommandConfig; + +export default createCommand(config, async () => { + const host = await getHost(); + const summary = await readLoginSummary(); + if (env.PRISMIC_TOKEN || !summary.guest || summary.host !== host) { + throw new CommandError( + `\`prismic open\` works only for an account started without signing up. Open https://${host}/dashboard instead.`, + ); + } + + const { url } = await createGuestLink({ + authenticationUrl: getAuthenticationApiUrl(host), + getToken, + onUnauthorized, + }); + console.info(`Open this link within 10 minutes. It works once:\n ${url}`); + // openBrowser() runs a shell, so the URL can't contain shell syntax, + // including cmd.exe's %NAME%. + if (isPerson() && /^https:\/\/[\w\-.:/?=&~+]+$/.test(url) && URL.canParse(url)) { + openBrowser(new URL(url)); + } +}); diff --git a/src/commands/repo-create.ts b/src/commands/repo-create.ts index 9bd851ff..7d3ec2f1 100644 --- a/src/commands/repo-create.ts +++ b/src/commands/repo-create.ts @@ -1,5 +1,5 @@ import { FRAMEWORKS, getAdapter } from "../adapters"; -import { getHost, getToken, onUnauthorized } from "../auth"; +import { getHost, getToken, onUnauthorized, reauthenticate } from "../auth"; import { detectAgent } from "../lib/ai"; import { CommandError, createCommand, type CommandConfig } from "../lib/command"; import { checkIsDomainAvailable, createRepository, upsertLocale } from "../lib/prismic/client"; @@ -52,6 +52,7 @@ export default createCommand(config, async ({ values }) => { } const host = await getHost(); + if (!process.env.CI && !(await getToken())) await reauthenticate({ guest: true }); const domain = await createRepo({ name, lang, framework, host }); console.info(`Repository created: ${domain}`); diff --git a/src/credentials.ts b/src/credentials.ts index eed447b0..48a8c716 100644 --- a/src/credentials.ts +++ b/src/credentials.ts @@ -30,6 +30,11 @@ const KEYCHAIN_TIMEOUT_MS = 30_000; // tag, then the ciphertext. const ENCRYPTED_FORMAT = Buffer.from([1]); +const GuestSchema = z.object({ + claimUrl: z.string(), + expiresAt: z.number(), +}); + const SessionSchema = z.object({ host: z.string(), auth0Domain: z.string(), @@ -41,6 +46,7 @@ const SessionSchema = z.object({ // Can be for another host, because the current session stays until the new // login saves. pendingLogin: z.optional(z.extend(PendingLoginSchema, { host: z.string() })), + guest: z.optional(GuestSchema), }); export type Session = z.infer; @@ -65,6 +71,7 @@ const LoginSummarySchema = z.object({ storeReason: z.catch(z.optional(FallbackReasonSchema), undefined), /** Set while a session has tokens. */ expiresAt: z.catch(z.optional(z.number()), undefined), + guest: z.catch(z.optional(GuestSchema), undefined), }); type LoginSummary = z.infer; @@ -144,11 +151,14 @@ export async function writeCredentials(lock: Lock, login: StoredLogin): Promise< const { store, storeReason, session } = login; let safe; if (store === "keyring") { - const { host, expiresAt, auth0Domain, clientId } = session; + const { host, expiresAt, auth0Domain, clientId, guest } = session; safe = await writePrivateFiles(lock, [ // credentials.enc is authoritative, so it's written first. [ENCRYPTED_CREDENTIALS_PATH, encrypt(JSON.stringify(session), await requireKey())], - [CREDENTIALS_PATH, stringify({ version: 2, host, expiresAt, store, auth0Domain, clientId })], + [ + CREDENTIALS_PATH, + stringify({ version: 2, host, expiresAt, store, auth0Domain, clientId, guest }), + ], ]); } else { safe = await writePrivateFiles(lock, [ diff --git a/src/index.ts b/src/index.ts index abd56413..58e02f00 100644 --- a/src/index.ts +++ b/src/index.ts @@ -50,6 +50,7 @@ import { sentrySetUser, setupSentry, } from "./lib/sentry"; +import { dedent } from "./lib/string"; import { genTaskId, isTaskId } from "./lib/task-id"; import { initUpdateNotifier } from "./lib/update-notifier"; import { isSubdomain } from "./lib/url"; @@ -148,8 +149,13 @@ async function main(): Promise { const userIntent = typeof intentValue === "string" ? intentValue : undefined; const taskId = typeof taskIdValue === "string" ? taskIdValue : undefined; + // MCP clients run `mcp token` themselves, without the agent's options. const agentNeedsTaskId = - !help && command !== "" && command !== "task-id" && detectAgent() !== undefined; + !help && + command !== "" && + command !== "task-id" && + command !== "mcp" && + detectAgent() !== undefined; const agentOptionsError = agentNeedsTaskId ? getAgentOptionsError(taskId, userIntent) : undefined; if (!help) { @@ -234,6 +240,17 @@ async function main(): Promise { throw error; } } + + const { guest, host } = env.PRISMIC_TOKEN || help ? {} : await readLoginSummary(); + if (guest && host === (await getHost())) { + console.warn( + `\n${dedent` + This is a temporary Prismic account. Prismic deletes it and its repositories on ${new Date(guest.expiresAt).toUTCString()}. + To keep them, open this link and sign up or log in: + ${guest.claimUrl} + `}`, + ); + } } async function initSentry(options: { diff --git a/src/lib/command.ts b/src/lib/command.ts index 59cb27ac..59ae7954 100644 --- a/src/lib/command.ts +++ b/src/lib/command.ts @@ -132,6 +132,7 @@ export function createCommand( export function createCommandRouter(config: { name: string; description: string; + agents?: string; sections?: Record; commands: Record Promise; description: string; hidden?: boolean }>; }): () => Promise { @@ -153,7 +154,7 @@ export function createCommandRouter(config: { } const blocks = { - ...agentsBlock(config.name), + ...agentsBlock(config.name, config.agents), USAGE: ` ${config.name} [options]`, COMMANDS: formatTable( Object.entries(config.commands) diff --git a/src/lib/prismic/client.ts b/src/lib/prismic/client.ts index b9075455..49825a81 100644 --- a/src/lib/prismic/client.ts +++ b/src/lib/prismic/client.ts @@ -34,6 +34,45 @@ function getAuthServiceUrl(host: string): URL { return new URL(`https://auth.${host}/`); } +const GuestSchema = z.object({ + access_token: z.string(), + refresh_token: z.string(), + expires_in: z.number(), + client_id: z.string(), + claim_url: z.string(), + expires_at: z.string(), +}); + +// The caller passes the authentication API's URL, because tests serve it +// locally. +export async function createGuest(config: { + authenticationUrl: URL; +}): Promise> { + const url = new URL("guest", config.authenticationUrl); + return request(url, { + method: "POST", + schema: GuestSchema, + unknownErrorMessage: "Failed to start without an account", + }); +} + +export async function createGuestLink( + config: Omit & { authenticationUrl: URL }, +): Promise<{ url: string }> { + const url = new URL("guest/link", config.authenticationUrl); + return request(url, { + method: "POST", + headers: { Authorization: `Bearer ${await config.getToken()}` }, + onUnauthorized: config.onUnauthorized, + schema: z.object({ url: z.string() }), + unknownErrorMessage: "Failed to create a link to your account", + }); +} + +export function getAuthenticationUrl(host: string): URL { + return new URL(`https://api.internal.${host}/authentication/`); +} + const ProfileSchema = z.object({ email: z.string(), shortId: z.string(), diff --git a/test/auth0.ts b/test/auth0.ts index 2efe3226..99100d70 100644 --- a/test/auth0.ts +++ b/test/auth0.ts @@ -7,6 +7,7 @@ import { setTimeout as sleep } from "node:timers/promises"; // approve it in a browser, so automated tests can't use Auth0 itself. const INTERVAL = 0.1; +export const GUEST_EXPIRES_AT = "2099-01-01T02:00:00.000Z"; type FakeAuth0Response = { status: number; body?: unknown; delayMs?: number }; @@ -43,7 +44,8 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise }[] = []; const responses = new Map(); const codes: DeviceCode[] = []; - const refreshTokens = new Set(); + const guestClientId = `${clientId}-guest`; + const refreshTokens = new Map(); const server = createServer(async (req, res) => { const path = new URL(req.url ?? "/", "http://localhost").pathname; @@ -59,7 +61,25 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise return; } - if (params.client_id !== clientId) { + if (path === "/authentication/guest") { + return send(res, 201, { + access_token: accessToken, + refresh_token: issueRefreshToken(guestClientId), + // Shorter than the CLI's renewal margin, so each command renews it. + expires_in: 60, + client_id: guestClientId, + claim_url: new URL(`dashboard/claim?code=${randomToken(24)}`, auth0Domain).href, + expires_at: GUEST_EXPIRES_AT, + }); + } + if (path === "/authentication/guest/link") { + if (req.headers.authorization !== `Bearer ${accessToken}`) return send(res, 401); + const url = new URL("authentication/guest/enter", auth0Domain); + url.searchParams.set("t", randomToken(24)); + return send(res, 200, { url: url.href }); + } + + if (params.client_id !== clientId && params.client_id !== guestClientId) { return sendError(res, 401, "invalid_client", "Unknown client."); } @@ -107,10 +127,11 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise if (params.grant_type === "refresh_token") { // Each refresh token works once. Auth0 accepts the previous one for 60 // seconds after rotation, then revokes the whole session. - if (!refreshTokens.delete(params.refresh_token)) { + const client = refreshTokens.get(params.refresh_token); + if (client !== params.client_id || !refreshTokens.delete(params.refresh_token)) { return sendError(res, 403, "invalid_grant", "Unknown or invalid refresh token."); } - return sendTokens(res); + return sendTokens(res, client === guestClientId ? 60 : undefined, client); } return sendError(res, 400, "unsupported_grant_type", "Unsupported grant type."); } @@ -124,16 +145,16 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise send(res, 404); }); - function issueRefreshToken(): string { + function issueRefreshToken(client = clientId): string { const refreshToken = randomToken(32); - refreshTokens.add(refreshToken); + refreshTokens.set(refreshToken, client); return refreshToken; } - function sendTokens(res: ServerResponse, expiresIn = 3600): void { + function sendTokens(res: ServerResponse, expiresIn = 3600, client = clientId): void { send(res, 200, { access_token: accessToken, - refresh_token: issueRefreshToken(), + refresh_token: issueRefreshToken(client), expires_in: expiresIn, token_type: "Bearer", }); diff --git a/test/init.test.ts b/test/init.test.ts index 2957e093..e7371f16 100644 --- a/test/init.test.ts +++ b/test/init.test.ts @@ -265,6 +265,28 @@ it("logs in when not logged in, even on CI", async ({ expect(JSON.parse(configRaw).repositoryName).toBe(repo); }, 60_000); +it("starts without an account when nobody is logged in", async ({ + expect, + project, + prismic, + logout, + token, + host, + password, + onTestFinished, +}) => { + await rm(new URL("prismic.config.json", project)); + await logout(); + + const { stdout, stderr, exitCode } = await prismic("init", ["--no-setup"], { + nodeOptions: { env: { CI: "" } }, + }); + const name = stdout.match(/^Created repository: ([a-z0-9-]+)$/m)?.[1]; + if (name) onTestFinished(() => deleteRepository(name, { token, password, host })); + expect(exitCode, stderr).toBe(0); + expect(stderr).toContain("This is a temporary Prismic account."); +}, 60_000); + it("renews a rejected token instead of logging in again", async ({ expect, project, diff --git a/test/it.ts b/test/it.ts index 19b4befb..5b92a3fb 100644 --- a/test/it.ts +++ b/test/it.ts @@ -41,6 +41,7 @@ export type Fixtures = { accessToken?: string; refreshToken?: string; expiresAt?: number; + guest?: { claimUrl: string; expiresAt: number }; }) => Promise<{ email: string }>; logout: () => Promise; token: string; diff --git a/test/mcp-token.test.ts b/test/mcp-token.test.ts new file mode 100644 index 00000000..4b38a6de --- /dev/null +++ b/test/mcp-token.test.ts @@ -0,0 +1,28 @@ +import { it } from "./it"; + +it("supports --help", async ({ expect, prismic }) => { + const { stdout, stderr, exitCode } = await prismic("mcp", ["token", "--help"]); + expect(exitCode, stderr).toBe(0); + expect(stdout).toContain("prismic mcp token [options]"); +}); + +it("prints an Authorization header, even for an agent without a task ID", async ({ + expect, + prismic, + login, + token, +}) => { + await login({ expiresAt: Date.now() - 1000 }); + const { stdout, stderr, exitCode } = await prismic("mcp", ["token"], { + nodeOptions: { env: { AI_AGENT: "test-agent" } }, + }); + expect(exitCode, stderr).toBe(0); + expect(JSON.parse(stdout)).toEqual({ Authorization: `Bearer ${token}` }); +}); + +it("fails when not logged in", async ({ expect, prismic, logout }) => { + await logout(); + const { stderr, exitCode } = await prismic("mcp", ["token"]); + expect(exitCode).toBe(1); + expect(stderr).toContain("Not logged in. Run `prismic login` first."); +}); diff --git a/test/mcp.test.ts b/test/mcp.test.ts new file mode 100644 index 00000000..2540720a --- /dev/null +++ b/test/mcp.test.ts @@ -0,0 +1,18 @@ +import { it } from "./it"; + +it("supports --help", async ({ expect, prismic }) => { + const { stdout, stderr, exitCode } = await prismic("mcp", ["--help"]); + expect(exitCode, stderr).toBe(0); + expect(stdout).toContain("prismic mcp [options]"); + expect(stdout).not.toContain("AGENTS"); +}); + +it("tells agents how to connect the MCP server", async ({ expect, prismic }) => { + const { stdout } = await prismic("mcp", ["--help"], { + nodeOptions: { env: { AI_AGENT: "test-agent" } }, + }); + expect(stdout).toContain("If one is connected, or you can't tell, add nothing"); + expect(stdout).toContain( + `claude mcp add-json --scope project prismic '{"type":"http","url":"https://mcp.prismic.io/mcp","headersHelper":"npx prismic mcp token"}'`, + ); +}); diff --git a/test/open.test.ts b/test/open.test.ts new file mode 100644 index 00000000..ff469abc --- /dev/null +++ b/test/open.test.ts @@ -0,0 +1,51 @@ +import { it } from "./it"; + +const DAY_MS = 24 * 60 * 60 * 1000; + +it("supports --help", async ({ expect, prismic }) => { + const { stdout, stderr, exitCode } = await prismic("open", ["--help"]); + expect(exitCode, stderr).toBe(0); + expect(stdout).toContain("prismic open [options]"); +}); + +it("prints a link that opens the temporary account", async ({ expect, prismic, login }) => { + await login({ guest: { claimUrl: "https://example.com/claim", expiresAt: Date.now() + DAY_MS } }); + const { stdout, stderr, exitCode } = await prismic("open"); + expect(exitCode, stderr).toBe(0); + expect(stdout).toMatch( + /Open this link within 10 minutes\. It works once:\n {2}http:\/\/127\.0\.0\.1:\d+\/authentication\/guest\/enter\?t=/, + ); +}); + +it("fails for an account that signed up", async ({ expect, prismic }) => { + const { stderr, exitCode } = await prismic("open"); + expect(exitCode).toBe(1); + expect(stderr).toContain("works only for an account started without signing up"); +}); + +it("says the temporary account was claimed, and logs out", async ({ expect, prismic, login }) => { + await login({ + expiresAt: Date.now() - 1000, + refreshToken: "deleted-by-claim", + guest: { claimUrl: "https://example.com/claim", expiresAt: Date.now() + DAY_MS }, + }); + const { stderr, exitCode } = await prismic("open"); + expect(exitCode).toBe(1); + expect(stderr).toContain( + "Your temporary account was claimed, with its repositories. Run `prismic login` with the account that claimed it to keep working.", + ); + expect(stderr).not.toContain("temporary Prismic account"); + expect((await prismic("whoami")).stderr).toContain("Not logged in."); +}); + +it("says the temporary account expired, and logs out", async ({ expect, prismic, login }) => { + await login({ + expiresAt: Date.now() - 1000, + refreshToken: "deleted-by-cleanup", + guest: { claimUrl: "https://example.com/claim", expiresAt: Date.now() - DAY_MS }, + }); + const { stderr, exitCode } = await prismic("open"); + expect(exitCode).toBe(1); + expect(stderr).toContain("Your temporary account expired, and Prismic deleted its repositories."); + expect((await prismic("whoami")).stderr).toContain("Not logged in."); +}); diff --git a/test/repo-create.test.ts b/test/repo-create.test.ts index 55ae33a4..a4670f35 100644 --- a/test/repo-create.test.ts +++ b/test/repo-create.test.ts @@ -1,6 +1,6 @@ import { fileURLToPath } from "node:url"; -import { it } from "./it"; +import { captureOutput, it, waitForLoginPrompt } from "./it"; import { deleteRepository, getLocales, getMCPActivationStatus, getRepository } from "./prismic"; it("supports --help", async ({ expect, prismic }) => { @@ -125,3 +125,65 @@ it("sets the master locale with --lang", async ({ const master = locales.find((locale) => locale.isMaster); expect(master?.id).toBe("fr-fr"); }); + +it("starts without an account when nobody is logged in, and reuses it", async ({ + expect, + prismic, + logout, + auth0, + token, + host, + password, + onTestFinished, +}) => { + await logout(); + const env = { CI: "" }; + + const claimLinks = new Set(); + for (let i = 0; i < 2; i++) { + const { stdout, stderr, exitCode } = await prismic("repo", ["create"], { + nodeOptions: { env }, + }); + expect(exitCode, stderr).toBe(0); + const domain = stdout.match(/Repository created: (\S+)/)?.[1]; + expect(domain).toBeDefined(); + onTestFinished(() => deleteRepository(domain!, { token, password, host })); + expect(stderr).toContain( + "This is a temporary Prismic account. Prismic deletes it and its repositories on Thu, 01 Jan 2099 02:00:00 GMT.", + ); + const claimLink = stderr.match( + /To keep them, open this link and sign up or log in:\n {2}(http:\/\/127\.0\.0\.1:\d+\/dashboard\/claim\?code=\S+)/, + )?.[1]; + expect(claimLink).toBeDefined(); + claimLinks.add(claimLink!); + } + expect(auth0.requestsTo("/authentication/guest")).toHaveLength(1); + expect(claimLinks.size).toBe(1); + // The fake refuses a renewal from any other client. + expect(auth0.requestsTo("/oauth/token").length).toBeGreaterThan(0); +}); + +it("doesn't start without an account on CI", async ({ expect, prismic, logout, auth0 }) => { + await logout(); + const { stderr, exitCode } = await prismic("repo", ["create"], { + nodeOptions: { env: { CI: "true" } }, + }); + expect(exitCode).toBe(1); + expect(stderr).not.toContain("temporary Prismic account"); + expect(auth0.requestsTo("/authentication/guest")).toHaveLength(0); +}); + +it.for([ + [429, "Too many accounts were started without signing up from this network today."], + [503, "Starting without an account isn't available right now."], +] as const)( + "logs in when Prismic answers %i to starting without an account", + async ([status, message], { expect, prismic, logout, auth0 }) => { + await logout(); + auth0.respondOnce("/authentication/guest", { status, body: { error: "unavailable" } }); + const proc = prismic("repo", ["create"], { nodeOptions: { env: { CI: "" } } }); + const output = captureOutput(proc); + await waitForLoginPrompt(expect, output); + expect(output()).toContain(message); + }, +);