Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 90 additions & 8 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -188,8 +201,11 @@ async function isTokenRejected(token: string | undefined): Promise<boolean> {
}
}

export async function reauthenticate(options: { browser?: boolean } = {}): Promise<string> {
const token = await getSessionToken({ forceRefresh: true });
export async function reauthenticate(
options: { browser?: boolean; guest?: boolean } = {},
): Promise<string> {
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);
Expand All @@ -203,12 +219,10 @@ export async function logIn(options: { browser?: boolean } = {}): Promise<string

// An agent stops before its command times out and runs it again to continue.
// Without a terminal, nobody may be there to approve, so it stops too.
const isPerson =
detectAgent() === undefined && process.stdin.isTTY === true && process.stderr.isTTY === true;
const login: Login = {
host,
auth0,
deadline: isPerson ? Infinity : Date.now() + AGENT_WAIT_MS,
deadline: isPerson() ? Infinity : Date.now() + AGENT_WAIT_MS,
startedAt: Date.now(),
resumed: false,
waited: false,
Expand Down Expand Up @@ -238,7 +252,7 @@ export async function logIn(options: { browser?: boolean } = {}): Promise<string

let outcome: LoginOutcome;
try {
outcome = await completeLogin(login, { browser: browser && isPerson });
outcome = await completeLogin(login, { browser: browser && isPerson() });
} catch (error) {
recordLogin({
result: getLoginResult(error),
Expand Down Expand Up @@ -270,6 +284,74 @@ export async function logIn(options: { browser?: boolean } = {}): Promise<string
return token;
}

export function isPerson(): boolean {
return (
detectAgent() === undefined && process.stdin.isTTY === true && process.stderr.isTTY === true
);
}

// Nobody could claim an account started in CI.
async function startGuest(): Promise<string | undefined> {
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
Expand Down
10 changes: 10 additions & 0 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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",
Expand Down
11 changes: 9 additions & 2 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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) => {
Expand Down
16 changes: 16 additions & 0 deletions src/commands/mcp-token.ts
Original file line number Diff line number Diff line change
@@ -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}` }));
});
34 changes: 34 additions & 0 deletions src/commands/mcp.ts
Original file line number Diff line number Diff line change
@@ -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",
},
},
});
36 changes: 36 additions & 0 deletions src/commands/open.ts
Original file line number Diff line number Diff line change
@@ -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));
}
});
3 changes: 2 additions & 1 deletion src/commands/repo-create.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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}`);
Expand Down
14 changes: 12 additions & 2 deletions src/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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<typeof SessionSchema>;

Expand All @@ -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<typeof LoginSummarySchema>;

Expand Down Expand Up @@ -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, [
Expand Down
19 changes: 18 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -148,8 +149,13 @@ async function main(): Promise<void> {
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) {
Expand Down Expand Up @@ -234,6 +240,17 @@ async function main(): Promise<void> {
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: {
Expand Down
Loading
Loading