From f6c98c24890db5adcf4f36263e3d46792e591b6e Mon Sep 17 00:00:00 2001 From: lihbr Date: Thu, 19 Nov 2026 17:51:50 +0900 Subject: [PATCH 1/5] feat: start without an account, and connect the Prismic MCP server with the CLI's login Co-Authored-By: Claude Opus 5.5 --- src/auth.ts | 107 +++++++++++++++++++++++++++++++++--- src/commands/index.ts | 10 ++++ src/commands/init.ts | 11 +++- src/commands/mcp-token.ts | 16 ++++++ src/commands/mcp.ts | 34 ++++++++++++ src/commands/open.ts | 36 ++++++++++++ src/commands/repo-create.ts | 3 +- src/credentials.ts | 16 +++++- src/index.ts | 19 ++++++- src/lib/command.ts | 3 +- src/lib/prismic/client.ts | 39 +++++++++++++ test/auth0.ts | 21 ++++++- test/init.test.ts | 22 ++++++++ test/it.ts | 1 + test/mcp-token.test.ts | 28 ++++++++++ test/mcp.test.ts | 18 ++++++ test/open.test.ts | 51 +++++++++++++++++ test/repo-create.test.ts | 61 +++++++++++++++++++- 18 files changed, 479 insertions(+), 17 deletions(-) create mode 100644 src/commands/mcp-token.ts create mode 100644 src/commands/mcp.ts create mode 100644 src/commands/open.ts create mode 100644 test/mcp-token.test.ts create mode 100644 test/mcp.test.ts create mode 100644 test/open.test.ts diff --git a/src/auth.ts b/src/auth.ts index 1eb45109..b7d31e0c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,9 +1,11 @@ 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"; import { + clearCredentials, CredentialsError, lockLogin, prepareLogin, @@ -29,10 +31,16 @@ 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 { getRepositoryName } from "./project"; import { forgetTrackedUser, getLoginResult, @@ -151,6 +159,18 @@ async function renewLogin( return renewLogin(lock, latest, staleToken, { canRetry: false }); } + // A temporary account ends when someone claims it or it expires. + if (session.guest) { + await clearCredentials(lock); + const repo = await getRepositoryName().catch(() => undefined); + const repository = repo ? `Your repository ${repo}` : "Your repository"; + throw new CommandError( + session.guest.expiresAt > Date.now() + ? `${repository} was claimed. Run \`prismic login\` with the account that claimed it to keep working.` + : `${repository} expired and was deleted. Run \`prismic login\` to keep working.`, + ); + } + await writeCredentials(lock, { ...storedLogin, session: { host, auth0Domain, clientId, pendingLogin: session.pendingLogin }, @@ -188,8 +208,12 @@ async function isTokenRejected(token: string | undefined): Promise { } } -export async function reauthenticate(options: { browser?: boolean } = {}): Promise { - const token = await getSessionToken({ forceRefresh: true }); +/** `guest` offers to start without an account when nobody is logged in. */ +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 +227,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..46e8d058 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 (!(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..0ab11a21 100644 --- a/src/credentials.ts +++ b/src/credentials.ts @@ -30,6 +30,12 @@ const KEYCHAIN_TIMEOUT_MS = 30_000; // tag, then the ciphertext. const ENCRYPTED_FORMAT = Buffer.from([1]); +const GuestSchema = z.object({ + claimUrl: z.string(), + /** Milliseconds since the epoch. */ + expiresAt: z.number(), +}); + const SessionSchema = z.object({ host: z.string(), auth0Domain: z.string(), @@ -41,6 +47,8 @@ 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() })), + /** Set for a temporary account, started without signing up. */ + guest: z.optional(GuestSchema), }); export type Session = z.infer; @@ -65,6 +73,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 +153,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..408b0871 100644 --- a/test/auth0.ts +++ b/test/auth0.ts @@ -4,9 +4,11 @@ import type { AddressInfo } from "node:net"; import { setTimeout as sleep } from "node:timers/promises"; // A fake Auth0 tenant for login tests. A real device login needs a person to -// approve it in a browser, so automated tests can't use Auth0 itself. +// approve it in a browser, so automated tests can't use Auth0 itself. It also +// fakes Prismic's routes for accounts started without signing up. const INTERVAL = 0.1; +export const GUEST_EXPIRES_AT = "2099-01-01T02:00:00.000Z"; type FakeAuth0Response = { status: number; body?: unknown; delayMs?: number }; @@ -59,6 +61,23 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise return; } + if (path === "/authentication/guest") { + return send(res, 201, { + access_token: accessToken, + refresh_token: issueRefreshToken(), + expires_in: 3600, + client_id: clientId, + 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) { return sendError(res, 401, "invalid_client", "Unknown client."); } 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..3c34f778 --- /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 repository was claimed, and logs out", async ({ expect, prismic, login, repo }) => { + 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 repository ${repo} was claimed. 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 repository expired, and logs out", async ({ expect, prismic, login, repo }) => { + 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 repository ${repo} expired and was deleted.`); + 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..18f780fd 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,62 @@ 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: "" }; + + 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.", + ); + expect(stderr).toMatch( + /To keep them, open this link and sign up or log in:\n {2}http:\/\/127\.0\.0\.1:\d+\/dashboard\/claim\?code=/, + ); + } + expect(auth0.requestsTo("/authentication/guest")).toHaveLength(1); +}); + +it("logs in on CI instead of starting without an account", async ({ + expect, + prismic, + logout, + auth0, +}) => { + await logout(); + const proc = prismic("repo", ["create"], { nodeOptions: { env: { CI: "true" } } }); + const output = captureOutput(proc); + await waitForLoginPrompt(expect, output); + 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); + }, +); From 44f46391af9d5a3d38c7143bc1ad543d172c2464 Mon Sep 17 00:00:00 2001 From: lihbr Date: Thu, 19 Nov 2026 17:55:44 +0900 Subject: [PATCH 2/5] refactor: drop a comment that restates the option Co-Authored-By: Claude Opus 5.5 --- src/auth.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/auth.ts b/src/auth.ts index b7d31e0c..d8c01542 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -208,7 +208,6 @@ async function isTokenRejected(token: string | undefined): Promise { } } -/** `guest` offers to start without an account when nobody is logged in. */ export async function reauthenticate( options: { browser?: boolean; guest?: boolean } = {}, ): Promise { From d504493a65d66f9795fa89fae2d59f13b07ef183 Mon Sep 17 00:00:00 2001 From: lihbr Date: Thu, 19 Nov 2026 18:00:26 +0900 Subject: [PATCH 3/5] fix: keep a pending login when a temporary account ends, and don't log in on CI before creating a repository Co-Authored-By: Claude Opus 5.5 --- src/auth.ts | 18 ++++++------------ src/commands/repo-create.ts | 2 +- test/auth0.ts | 26 +++++++++++++++----------- test/open.test.ts | 8 ++++---- test/repo-create.test.ts | 27 +++++++++++++++------------ 5 files changed, 41 insertions(+), 40 deletions(-) diff --git a/src/auth.ts b/src/auth.ts index d8c01542..023a4ce8 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -5,7 +5,6 @@ import { setTimeout as sleep } from "node:timers/promises"; import { pathToFileURL } from "node:url"; import { - clearCredentials, CredentialsError, lockLogin, prepareLogin, @@ -40,7 +39,6 @@ import { import { ForbiddenRequestError, RequestError, UnauthorizedRequestError } from "./lib/request"; import { dedent } from "./lib/string"; import { appendTrailingSlash } from "./lib/url"; -import { getRepositoryName } from "./project"; import { forgetTrackedUser, getLoginResult, @@ -159,22 +157,18 @@ async function renewLogin( return renewLogin(lock, latest, staleToken, { canRetry: false }); } + await writeCredentials(lock, { + ...storedLogin, + session: { host, auth0Domain, clientId, pendingLogin: session.pendingLogin }, + }); // A temporary account ends when someone claims it or it expires. if (session.guest) { - await clearCredentials(lock); - const repo = await getRepositoryName().catch(() => undefined); - const repository = repo ? `Your repository ${repo}` : "Your repository"; throw new CommandError( session.guest.expiresAt > Date.now() - ? `${repository} was claimed. Run \`prismic login\` with the account that claimed it to keep working.` - : `${repository} expired and was deleted. Run \`prismic login\` to keep working.`, + ? "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.", ); } - - await writeCredentials(lock, { - ...storedLogin, - session: { host, auth0Domain, clientId, pendingLogin: session.pendingLogin }, - }); ended = true; } diff --git a/src/commands/repo-create.ts b/src/commands/repo-create.ts index 46e8d058..7d3ec2f1 100644 --- a/src/commands/repo-create.ts +++ b/src/commands/repo-create.ts @@ -52,7 +52,7 @@ export default createCommand(config, async ({ values }) => { } const host = await getHost(); - if (!(await getToken())) await reauthenticate({ guest: true }); + 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/test/auth0.ts b/test/auth0.ts index 408b0871..1dd1bde0 100644 --- a/test/auth0.ts +++ b/test/auth0.ts @@ -45,7 +45,9 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise }[] = []; const responses = new Map(); const codes: DeviceCode[] = []; - const refreshTokens = new Set(); + const guestClientId = `${clientId}-guest`; + // Maps each refresh token to the client it was issued to. + const refreshTokens = new Map(); const server = createServer(async (req, res) => { const path = new URL(req.url ?? "/", "http://localhost").pathname; @@ -64,9 +66,10 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise if (path === "/authentication/guest") { return send(res, 201, { access_token: accessToken, - refresh_token: issueRefreshToken(), - expires_in: 3600, - client_id: clientId, + 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, }); @@ -78,7 +81,7 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise return send(res, 200, { url: url.href }); } - if (params.client_id !== clientId) { + if (params.client_id !== clientId && params.client_id !== guestClientId) { return sendError(res, 401, "invalid_client", "Unknown client."); } @@ -126,10 +129,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, undefined, client); } return sendError(res, 400, "unsupported_grant_type", "Unsupported grant type."); } @@ -143,16 +147,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/open.test.ts b/test/open.test.ts index 3c34f778..ff469abc 100644 --- a/test/open.test.ts +++ b/test/open.test.ts @@ -23,7 +23,7 @@ it("fails for an account that signed up", async ({ expect, prismic }) => { expect(stderr).toContain("works only for an account started without signing up"); }); -it("says the repository was claimed, and logs out", async ({ expect, prismic, login, repo }) => { +it("says the temporary account was claimed, and logs out", async ({ expect, prismic, login }) => { await login({ expiresAt: Date.now() - 1000, refreshToken: "deleted-by-claim", @@ -32,13 +32,13 @@ it("says the repository was claimed, and logs out", async ({ expect, prismic, lo const { stderr, exitCode } = await prismic("open"); expect(exitCode).toBe(1); expect(stderr).toContain( - `Your repository ${repo} was claimed. Run \`prismic login\` with the account that claimed it to keep working.`, + "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 repository expired, and logs out", async ({ expect, prismic, login, repo }) => { +it("says the temporary account expired, and logs out", async ({ expect, prismic, login }) => { await login({ expiresAt: Date.now() - 1000, refreshToken: "deleted-by-cleanup", @@ -46,6 +46,6 @@ it("says the repository expired, and logs out", async ({ expect, prismic, login, }); const { stderr, exitCode } = await prismic("open"); expect(exitCode).toBe(1); - expect(stderr).toContain(`Your repository ${repo} expired and was deleted.`); + 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 18f780fd..a4670f35 100644 --- a/test/repo-create.test.ts +++ b/test/repo-create.test.ts @@ -139,6 +139,7 @@ it("starts without an account when nobody is logged in, and reuses it", async ({ 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 }, @@ -150,23 +151,25 @@ it("starts without an account when nobody is logged in, and reuses it", async ({ expect(stderr).toContain( "This is a temporary Prismic account. Prismic deletes it and its repositories on Thu, 01 Jan 2099 02:00:00 GMT.", ); - expect(stderr).toMatch( - /To keep them, open this link and sign up or log in:\n {2}http:\/\/127\.0\.0\.1:\d+\/dashboard\/claim\?code=/, - ); + 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("logs in on CI instead of starting without an account", async ({ - expect, - prismic, - logout, - auth0, -}) => { +it("doesn't start without an account on CI", async ({ expect, prismic, logout, auth0 }) => { await logout(); - const proc = prismic("repo", ["create"], { nodeOptions: { env: { CI: "true" } } }); - const output = captureOutput(proc); - await waitForLoginPrompt(expect, output); + 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); }); From b29dcb7186d20138203fc0a35d5acca8aa342bd7 Mon Sep 17 00:00:00 2001 From: lihbr Date: Thu, 19 Nov 2026 18:02:28 +0900 Subject: [PATCH 4/5] test: keep renewed temporary-account tokens short-lived Co-Authored-By: Claude Opus 5.5 --- test/auth0.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/auth0.ts b/test/auth0.ts index 1dd1bde0..a9c131e3 100644 --- a/test/auth0.ts +++ b/test/auth0.ts @@ -133,7 +133,7 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise if (client !== params.client_id || !refreshTokens.delete(params.refresh_token)) { return sendError(res, 403, "invalid_grant", "Unknown or invalid refresh token."); } - return sendTokens(res, undefined, client); + return sendTokens(res, client === guestClientId ? 60 : undefined, client); } return sendError(res, 400, "unsupported_grant_type", "Unsupported grant type."); } From 4e10f53d424e64950196bb1f22ed7b06a0b88b9d Mon Sep 17 00:00:00 2001 From: lihbr Date: Thu, 19 Nov 2026 18:06:26 +0900 Subject: [PATCH 5/5] refactor: drop comments that restate the code Co-Authored-By: Claude Opus 5.5 --- src/auth.ts | 4 +--- src/credentials.ts | 2 -- test/auth0.ts | 4 +--- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/auth.ts b/src/auth.ts index 023a4ce8..fedeecd2 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -161,7 +161,6 @@ async function renewLogin( ...storedLogin, session: { host, auth0Domain, clientId, pendingLogin: session.pendingLogin }, }); - // A temporary account ends when someone claims it or it expires. if (session.guest) { throw new CommandError( session.guest.expiresAt > Date.now() @@ -291,8 +290,7 @@ export function isPerson(): boolean { ); } -// Reuses a temporary account another command started meanwhile. In CI, nobody -// could claim it. +// Nobody could claim an account started in CI. async function startGuest(): Promise { const host = await getHost(); const auth0 = getAuth0Config(host); diff --git a/src/credentials.ts b/src/credentials.ts index 0ab11a21..48a8c716 100644 --- a/src/credentials.ts +++ b/src/credentials.ts @@ -32,7 +32,6 @@ const ENCRYPTED_FORMAT = Buffer.from([1]); const GuestSchema = z.object({ claimUrl: z.string(), - /** Milliseconds since the epoch. */ expiresAt: z.number(), }); @@ -47,7 +46,6 @@ 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() })), - /** Set for a temporary account, started without signing up. */ guest: z.optional(GuestSchema), }); export type Session = z.infer; diff --git a/test/auth0.ts b/test/auth0.ts index a9c131e3..99100d70 100644 --- a/test/auth0.ts +++ b/test/auth0.ts @@ -4,8 +4,7 @@ import type { AddressInfo } from "node:net"; import { setTimeout as sleep } from "node:timers/promises"; // A fake Auth0 tenant for login tests. A real device login needs a person to -// approve it in a browser, so automated tests can't use Auth0 itself. It also -// fakes Prismic's routes for accounts started without signing up. +// 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"; @@ -46,7 +45,6 @@ export async function createFakeAuth0(options: { accessToken: string }): Promise const responses = new Map(); const codes: DeviceCode[] = []; const guestClientId = `${clientId}-guest`; - // Maps each refresh token to the client it was issued to. const refreshTokens = new Map(); const server = createServer(async (req, res) => {