From 7f538e9d6b9a2ba72658872a5672478f082dd17c Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 21:41:50 +0100 Subject: [PATCH 1/2] feat(oauth): let oauthSessionCommand take the sign-ins a CLI kept before zm and drive move to the shared browser sign-in (NEED-2934 B), and nobody may have to sign in again. oauthSessionCommand gains optional options: - codec: the entry's format (zoomTokenCodec, driveSessionCodec). - legacyAccounts(env, profile): older entries, as an account or as a service and an account. They are copied on read and removed at session end. A run with moved folders only reads them. - startOptions: more session start options, which preset reads. - preset may be async. In start it gets the sign-in steps, so it can ask for a missing client id with --answer-stdin. - verify may return extra, saved in the entry (drive's principal). - afterSignIn(command, signedIn): gets the client the sign-in used. - profiles(env): the profiles session list names. session start gains --answer-stdin with a pasted redirect. status gives expires_at. session list rows gain state. Both the token and the oauth list mark a profile unknown instead of failing when the keyring cannot be reached or an entry is broken. credentialStorage reads older entries under another service, copies one found in the private file within the file, and removes older entries on remove outside moved runs. storageOf, timeLimit and withTimeLimit are exported, since CLIs copied them. Co-Authored-By: Claude Opus 5.5 --- changes/feat-oauth-session-options.md | 33 ++++ src/cli/index.ts | 3 + src/cli/oauth-session.test.ts | 185 ++++++++++++++++++++- src/cli/oauth-session.ts | 222 ++++++++++++++++++-------- src/cli/token-session.test.ts | 24 ++- src/cli/token-session.ts | 30 +++- src/oauth/index.ts | 1 + src/oauth/storage.test.ts | 28 ++++ src/oauth/storage.ts | 41 +++-- 9 files changed, 480 insertions(+), 87 deletions(-) create mode 100644 changes/feat-oauth-session-options.md diff --git a/changes/feat-oauth-session-options.md b/changes/feat-oauth-session-options.md new file mode 100644 index 000000000..3b144adeb --- /dev/null +++ b/changes/feat-oauth-session-options.md @@ -0,0 +1,33 @@ +### Added + +- **`oauthSessionCommand` takes the sign-ins a CLI kept before**, so zm and drive can move to it with nobody signing + in again. All new options are optional: + - `codec` is the entry's format (`zoomTokenCodec`, `driveSessionCodec`). The standard one stays the default. + - `legacyAccounts(env, profile)` names where older versions kept a profile's sign-in, as an account or as a service + and an account. The first read copies it to `oauth::`. `session end` removes it too. A run with + moved folders only reads it. + - `startOptions` adds options to `session start`, such as a client or the scopes to ask. `preset` reads them from + `command.opts()`. + - `preset` may be async. In `session start` it also gets the sign-in steps, so it can ask for a missing client id + with `--answer-stdin`. + - `verify` may return `extra`, which the codec saves in the entry at sign-in (drive's `principal`). + - `afterSignIn(command, signedIn)` runs once the sign-in is kept. It gets the profile, the account and the client + the sign-in used, so a CLI can save that client beside it (WC-SECR-25). + - `profiles(env)` is the list `session list` names, for a CLI that keeps its profiles in its own config. +- **`session start --answer-stdin`** in every CLI built on `oauthSessionCommand`. With `--json` it asks for the + redirected address as a `needs` line when the browser does not come back to this computer. +- **`session status` gives `expires_at`**, when the access token runs out. A refresh moves it on. +- **`session list` rows have `state`**: `saved`, `missing` or `unknown`, in `oauthSessionCommand` and + `tokenSessionCommand`. When the keyring cannot be reached, or an entry cannot be read, the row is `signed_in: null` + and `state: "unknown"` and the list still answers. One warning names the cause, and `session status` says more. +- **`storageOf`, `timeLimit` and `withTimeLimit` are exported** from `@wirecat/cli-core/cli`, so CLIs stop keeping + copies of them. +- **`credentialStorage` reads an older entry under another service** (`legacyAccounts: [{ service, account }]`). It + copies an entry it found in the private file within the file, never into the keyring. `remove` removes the older + entries too, except in a run with moved folders, so the next read does not sign the profile in again. + +### Fixed + +- **`tokenSessionCommand`'s `session list` no longer fails for every profile when one sign-in cannot be read**, from + a keyring this run cannot reach or a broken entry. That profile is `unknown` and the others are listed. WireCat + Desktop reads its profiles from this list. diff --git a/src/cli/index.ts b/src/cli/index.ts index 01946bad8..ab644f85f 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -57,6 +57,7 @@ export { syncProgress } from "../entities/store-records.js" export { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js" export { type AppErrors, failureContext } from "../errors/reasons.js" export { linkFetch } from "../http/link-fetch.js" +export { type TimeLimit, timeLimit, withTimeLimit } from "../http/time-limit.js" export { mailFindingFieldsHelp } from "../mail/findings.js" export { botInstructions } from "../mcp/bot/instructions.js" export type { BotServerOptions, RunBotCommand } from "../mcp/bot/server.js" @@ -611,6 +612,7 @@ export { type OAuthPreset, type OAuthPresetOptions, type OAuthSessionOptions, + type OAuthSignedIn, oauthFlowOf, oauthPreset, oauthSessionCommand, @@ -824,6 +826,7 @@ export { type ManifestVerifyOptions, manifestVerify, signedInSite, + storageOf, type TokenSessionOptions, tokenSessionCommand, } from "./token-session.js" diff --git a/src/cli/oauth-session.test.ts b/src/cli/oauth-session.test.ts index e3d579e09..e94d53f6e 100644 --- a/src/cli/oauth-session.test.ts +++ b/src/cli/oauth-session.test.ts @@ -1,11 +1,19 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" +import { PassThrough } from "node:stream" import { CliError, captureStreams, type KeyringStore } from "@wirecat/cli-base" import { memoryKeyring } from "@wirecat/cli-base/testing" -import type { Command } from "commander" -import { afterEach, describe, expect, it } from "vitest" -import { oauthFlowOf, oauthPreset, oauthSessionCommand } from "./oauth-session.js" +import { type Command, Option } from "commander" +import { afterEach, describe, expect, it, vi } from "vitest" +import { driveSessionCodec, zoomTokenCodec } from "../oauth/storage.js" +import { + type OAuthSessionOptions, + type OAuthSignedIn, + oauthFlowOf, + oauthPreset, + oauthSessionCommand, +} from "./oauth-session.js" import { run } from "./program.js" import type { ServiceApiManifest } from "./service-api-manifest.js" import { settingsFor } from "./settings.js" @@ -28,8 +36,19 @@ const manifest: ServiceApiManifest = { } const OWNER_ENTRY = "crm-cli:oauth:crm:personal" +// Every test folder is a moved run; the owner's own run, which copies an old entry, is only reached this way. +const owner = vi.hoisted(() => ({ run: false })) +vi.mock("@wirecat/cli-base", async (original) => { + const base = await original() + return { + ...base, + isMovedRun: (options: Parameters[0]) => !owner.run && base.isMovedRun(options), + } +}) + const roots: string[] = [] afterEach(() => { + owner.run = false for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) @@ -44,7 +63,18 @@ const visit = (url: string) => { return fetch(callback) } -const setup = (keyring: KeyringStore = memoryKeyring()) => { +const callbackOf = (url: string) => { + const authorization = new URL(url) + const callback = new URL(authorization.searchParams.get("redirect_uri") ?? "") + callback.search = new URLSearchParams({ state: authorization.searchParams.get("state") ?? "", code: "c" }).toString() + return callback.toString() +} + +const setup = ( + keyring: KeyringStore = memoryKeyring(), + more: Partial = {}, + browser: (url: string) => Promise = visit, +) => { const root = mkdtempSync(join(tmpdir(), "oauth-session-")) roots.push(root) mkdirSync(join(root, "config"), { recursive: true }) @@ -57,6 +87,8 @@ const setup = (keyring: KeyringStore = memoryKeyring()) => { } const tokenCalls: URLSearchParams[] = [] const verified: string[] = [] + const opened: string[] = [] + const stdin = new PassThrough() const service = (async (_url: string | URL | Request, init?: RequestInit) => { tokenCalls.push(new URLSearchParams(String(init?.body))) return Response.json({ @@ -91,6 +123,7 @@ const setup = (keyring: KeyringStore = memoryKeyring()) => { verify?.() return { id: "workspace-1", account: { workspace: "Synthetic" } } }, + ...more, }), ], }, @@ -100,7 +133,11 @@ const setup = (keyring: KeyringStore = memoryKeyring()) => { env, keyring, fetch: service, - openBrowser: async (url: string, _command?: Command) => void (await visit(url)), + stdin, + openBrowser: async (url: string, _command?: Command) => { + opened.push(url) + await browser(url) + }, } as never, ) const out = streams.stdout.join("") @@ -115,9 +152,20 @@ const setup = (keyring: KeyringStore = memoryKeyring()) => { .map((line) => JSON.parse(line).error)[0], } } - return { cli, keyring, tokenCalls, verified } + return { cli, keyring, tokenCalls, verified, opened, stdin } } +const zmEntry = JSON.stringify({ + accessToken: "synthetic-access-old", + refreshToken: "synthetic-refresh-old", + expiresAt: Date.UTC(2030, 0, 1), + scopes: ["record_permission:read"], +}) +const OLD_SERVICE = "crm-cli:/old/config" +const legacyAccounts = (_env: NodeJS.ProcessEnv, profile: string) => [ + { service: OLD_SERVICE, account: `c1:${profile}` }, +] + describe("oauthFlowOf and oauthPreset", () => { it("reads the authorization code flow and checks each scope the CLI asks for", () => { const flow = oauthFlowOf(manifest) @@ -175,6 +223,7 @@ describe("oauthSessionCommand", () => { expect((await cli(["session", "list", "--json"])).json.items).toContainEqual({ profile: "personal", signed_in: true, + state: "saved", }) expect((await cli(["personal", "session", "end", "--json"])).json.item).toMatchObject({ ended: true }) @@ -231,3 +280,127 @@ describe("oauthSessionCommand", () => { expect(memory.get("crm-cli", "oauth:crm:personal")).toBe(owner) }) }) + +describe("oauthSessionCommand for a CLI that kept its own sign-ins", () => { + it("reads an entry in the CLI's own format, with the access token's end", async () => { + const { cli } = setup(memoryKeyring({ [OWNER_ENTRY]: zmEntry }), { codec: zoomTokenCodec }) + expect((await cli(["personal", "session", "status", "--json"])).json.item).toMatchObject({ + state: "saved", + scopes: ["record_permission:read"], + expires_at: "2030-01-01T00:00:00.000Z", + }) + }) + + it("copies an older entry under another service to the profile's own, and session end removes both", async () => { + owner.run = true + const keyring = memoryKeyring({ [`${OLD_SERVICE}:c1:personal`]: zmEntry }) + const { cli } = setup(keyring, { codec: zoomTokenCodec, legacyAccounts }) + expect((await cli(["personal", "session", "status", "--json"])).json.item).toMatchObject({ state: "saved" }) + expect(keyring.get("crm-cli", "oauth:crm:personal")).toBe(zmEntry) + expect(keyring.get(OLD_SERVICE, "c1:personal")).toBe(zmEntry) + + expect((await cli(["personal", "session", "end", "--json"])).json.item).toMatchObject({ ended: true }) + expect(keyring.get("crm-cli", "oauth:crm:personal")).toBeNull() + expect(keyring.get(OLD_SERVICE, "c1:personal")).toBeNull() + expect((await cli(["personal", "session", "status", "--json"])).json.item).toMatchObject({ state: "missing" }) + }) + + it("in a run with moved folders reads the older entry but never copies or removes it", async () => { + const keyring = memoryKeyring({ [`${OLD_SERVICE}:c1:personal`]: zmEntry }) + const { cli } = setup(keyring, { codec: zoomTokenCodec, legacyAccounts }) + expect((await cli(["personal", "session", "status", "--json"])).json.item).toMatchObject({ state: "saved" }) + expect(keyring.get("crm-cli", "oauth:crm:personal")).toBeNull() + const ended = await cli(["personal", "session", "end", "--json"]) + expect(ended.json.item).toMatchObject({ ended: false }) + expect(ended.json.item.why).toContain("moved folders") + expect(keyring.get(OLD_SERVICE, "c1:personal")).toBe(zmEntry) + }) + + it("passes a start option to the preset, saves verify's extra and hands the client to afterSignIn", async () => { + const after: OAuthSignedIn[] = [] + const { cli, keyring, opened } = setup(memoryKeyring(), { + codec: driveSessionCodec, + startOptions: [new Option("--grant ", "more to ask")], + preset: (command) => + oauthPreset(oauthFlowOf(manifest), { + id: "crm", + name: "Crm", + client: { clientId: "own-client" }, + scopes: [ + "record_permission:read", + ...(command.opts<{ grant?: string }>().grant === "members" ? ["user_management:read"] : []), + ], + redirect: { kind: "loopback" }, + }), + verify: async () => ({ + id: "member-1", + account: { member: "Synthetic" }, + extra: { principal: "synthetic-principal" }, + }), + afterSignIn: (_command, signedIn) => void after.push(signedIn), + }) + const started = await cli(["personal", "session", "start", "--grant", "members", "--json"]) + expect(started.error).toBeUndefined() + expect(new URL(opened[0] ?? "").searchParams.get("scope")).toBe("record_permission:read user_management:read") + expect(JSON.parse(keyring.get("crm-cli", "oauth:crm:personal") ?? "")).toMatchObject({ + principal: "synthetic-principal", + clientId: "own-client", + }) + expect(after).toEqual([ + expect.objectContaining({ + profile: "personal", + id: "member-1", + account: { member: "Synthetic" }, + client: { clientId: "own-client" }, + }), + ]) + }) + + it("with --answer-stdin lets the preset ask for the client and reads the pasted redirect", async () => { + const after: OAuthSignedIn[] = [] + let feed = (_line: string) => {} + const { cli, tokenCalls, stdin } = setup( + memoryKeyring(), + { + preset: async (_command, steps) => { + const clientId = steps?.answers + ? await steps.ask({ field: "client_id", secret: false, prompt: "client" }) + : "" + return oauthPreset(oauthFlowOf(manifest), { + id: "crm", + name: "Crm", + client: { clientId }, + scopes: ["record_permission:read"], + redirect: { kind: "loopback" }, + }) + }, + afterSignIn: (_command, signedIn) => void after.push(signedIn), + }, + async (url) => feed(`${callbackOf(url)}\n`), + ) + feed = (line) => stdin.write(line) + stdin.write("asked-client\n") + const started = await cli(["personal", "session", "start", "--json", "--answer-stdin"]) + expect(started.error).toBeUndefined() + expect(started.err).toContain('"field":"redirect"') + expect(tokenCalls[0]?.get("client_id")).toBe("asked-client") + expect(after[0]?.client.clientId).toBe("asked-client") + }) + + it("lists every profile when the keyring cannot be reached, and takes the CLI's own profiles", async () => { + const keyring: KeyringStore = { + get: () => { + throw new Error("synthetic: no secret service") + }, + set: () => {}, + delete: () => false, + } + const { cli } = setup(keyring, { profiles: () => ["personal", "work"] }) + const listed = await cli(["session", "list", "--json"]) + expect(listed.code).toBe(0) + expect(listed.json.items).toEqual([ + { profile: "personal", signed_in: null, state: "unknown" }, + { profile: "work", signed_in: null, state: "unknown" }, + ]) + }) +}) diff --git a/src/cli/oauth-session.ts b/src/cli/oauth-session.ts index d08c2f40e..83cb243d6 100644 --- a/src/cli/oauth-session.ts +++ b/src/cli/oauth-session.ts @@ -2,14 +2,20 @@ import { CliError, isMovedRun, type KeyringStore, resolvePaths, systemKeyring } import type { OAuthFlow } from "@wirecat/cli-base/codegen/runtime" import { annotate } from "@wirecat/cli-base/commands" import { hostFetch } from "@wirecat/cli-base/http" -import { Command } from "commander" +import { Command, type Option } from "commander" import { type TokenKeeper, tokenKeeper } from "../oauth/keeper.js" import type { OAuthClient, OAuthProvider } from "../oauth/provider.js" -import { credentialStorage, oauthAccount, standardCodec } from "../oauth/storage.js" +import { + credentialStorage, + type LegacyAccount, + oauthAccount, + standardCodec, + type TokenCodec, +} from "../oauth/storage.js" import type { AppIdentity } from "../ports/app.js" import type { EventSink } from "../runs/events.js" import { editDistance } from "../search/correct.js" -import { signInSteps } from "../terminal/sign-in-steps.js" +import { answerStdinOption, type SignInSteps, signInSteps } from "../terminal/sign-in-steps.js" import { type BaseEnvironment, baseContext, environmentOf, outputFor } from "./context.js" import { refuseOffline } from "./early-refusal.js" import { LOCAL_READ, LOCAL_WRITE, logsInOrOut, REMOTE_READ, REMOTE_WRITE } from "./effects.js" @@ -19,7 +25,7 @@ import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile. import type { TokenStorage } from "./profile-token.js" import type { ServiceApiManifest } from "./service-api-manifest.js" import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js" -import { storageOf } from "./token-session.js" +import { storageOf, unknownSignIn } from "./token-session.js" /** * The authorization code flow an OpenAPI spec declares; a GraphQL service (Linear) writes the same object by hand. @@ -108,6 +114,18 @@ export interface OAuthEnvironment extends BaseEnvironment { openBrowser?: (url: string, command?: Command) => Promise } +/** What `afterSignIn` gets once the sign-in is kept. @experimental */ +export interface OAuthSignedIn { + env: NodeJS.ProcessEnv + profile: string + /** `verify`'s `id` and `account`. */ + id: string + account: Readonly> + /** The client the preset gave this sign-in, which its refreshes need. */ + client: OAuthClient + scopes: readonly string[] +} + /** @experimental */ export interface OAuthSessionOptions { app: AppIdentity @@ -115,18 +133,40 @@ export interface OAuthSessionOptions { /** The preset's `id` and `name`: `session list` and `status` read the sign-in without choosing a client. */ providerId: string service: string - /** From `oauthPreset`; the client is the CLI's own choice (a flag, a variable, the config, WireCat's app). */ - preset: (command: Command) => OAuthPreset - /** Asks the service whose the access token is; `id` names the account, `account` is what start and status show. */ + /** + * From `oauthPreset`; the client is the CLI's own choice (a flag, a variable, the config, WireCat's app). It reads its + * `startOptions` from `command.opts()`. In `session start` it gets the sign-in's steps too, so with `--answer-stdin` + * it may ask for what it lacks, such as the client id. + */ + preset: (command: Command, steps?: SignInSteps) => OAuthPreset | Promise + /** + * Asks the service whose the access token is; `id` names the account, `account` is what start and status show. + * `extra` is saved in the entry by the codec at sign-in, such as drive's `principal`. + */ verify: ( command: Command, accessToken: string, events: EventSink, - ) => Promise<{ id: string; account: Readonly> }> + ) => Promise<{ id: string; account: Readonly>; extra?: Record }> /** Runs before anything is saved; by default only remembers the account. A CLI that refuses a taken one throws. */ claim?: (env: NodeJS.ProcessEnv, profile: string, id: string) => void + /** The entry's format; `standardCodec` by default. A CLI that kept its sign-ins before passes the format it wrote. */ + codec?: TokenCodec + /** + * Where older versions kept a profile's sign-in. Read when the profile's own entry is empty and copied to it, so + * nobody signs in again; `session end` removes them too. A run with moved folders only reads them. + */ + legacyAccounts?: (env: NodeJS.ProcessEnv, profile: string) => readonly LegacyAccount[] + /** More `session start` options, such as the client or the scopes to ask; `preset` reads them. */ + startOptions?: readonly Option[] + /** Runs once the sign-in is kept, before the answer: the CLI saves what belongs beside it (WC-SECR-25). */ + afterSignIn?: (command: Command, signedIn: OAuthSignedIn) => void | Promise + /** The profiles `session list` names; by default the configured ones and those signed in here before. */ + profiles?: (env: NodeJS.ProcessEnv) => readonly string[] } +const PASTE_PROMPT = "the address the browser shows after you allow access, when it does not come back here" + /** * `session start | status | end | list` for a service signed in in the browser (WC-SECR-22): PKCE on the loopback, * the account checked before the tokens are kept, refreshes under one lock, and a run with moved folders that never @@ -135,6 +175,7 @@ export interface OAuthSessionOptions { */ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { const { app, providerId, service } = options + const codec = options.codec ?? standardCodec(providerId) const pathsOf = (env: NodeJS.ProcessEnv) => ({ appName: app.appName, prefix: app.envPrefix, env }) const storageFor = ( where: { env: NodeJS.ProcessEnv; keyring?: KeyringStore | undefined; warn?: (message: string) => void }, @@ -153,7 +194,8 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { ...(where.warn ? { warn: where.warn } : {}), }, account: oauthAccount(providerId, profile), - codec: rotating ? { ...standardCodec(providerId), rotating: true } : standardCodec(providerId), + ...(options.legacyAccounts ? { legacyAccounts: options.legacyAccounts(where.env, profile) } : {}), + codec: rotating && !codec.rotating ? { ...codec, rotating: true } : codec, }) const contextOf = (command: Command) => { const base = baseContext(command, options.resolveSettings) @@ -161,8 +203,8 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { const where = { env: base.env, keyring: base.keyring, warn: base.renderer.warn } const { profile } = base.settings /** The preset is asked only here, after the refusals: a CLI's client choice may fail on its own. */ - const keeperOf = (storage?: "file") => { - const { provider, scopes, rotating } = options.preset(command) + const keeperOf = async (storage?: "file", steps?: SignInSteps) => { + const { provider, scopes, rotating } = await options.preset(command, steps) const keeper: TokenKeeper = tokenKeeper({ provider, storage: storageFor(where, profile, storage ?? "auto", rotating), @@ -178,7 +220,7 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { signInCommand: `${app.command} ${profile} session start`, ...(environment.signal ? { signal: environment.signal } : {}), }) - return { keeper, scopes } + return { keeper, scopes, client: provider.client } } const saved = () => storageFor(where, profile).read() return { ...base, environment, where, profile, keeperOf, saved } @@ -190,7 +232,11 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { effects: REMOTE_WRITE, lifetime: "interactive", mcp: false, - examples: [`${app.command} personal session start`, `${app.command} personal session start --no-browser`], + examples: [ + `${app.command} personal session start`, + `${app.command} personal session start --no-browser`, + `${app.command} personal session start --json --answer-stdin`, + ], }), ) .summary(`sign in to ${service} in the browser`) @@ -205,51 +251,80 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { storageOf, "keyring" as TokenStorage, ) - .action(async function (this: Command, args: { browser: boolean; credentialStorage: TokenStorage }) { - const context = contextOf(this) - refuseCommandName(context.profile, commandWords(rootOf(this)), app.command) - refuseOffline(this, service) - const { keeper, scopes: asked } = context.keeperOf(args.credentialStorage === "file" ? "file" : undefined) - const { streams } = outputFor(this) - const steps = signInSteps({ - diagnostic: (line) => streams.diagnostic(`${line}\n`), - json: context.format !== "pretty" || context.environment.tty === false, - answers: false, - }) - let shown: Readonly> = {} - const { scopes } = await context.run((events) => - keeper.signIn({ - scopes: asked, - openBrowser: async (url) => { - if (args.browser) await context.environment.openBrowser?.(url, this) - }, - showUrl: (url) => { - steps.openUrl(url, `Sign in to ${service} and allow access`) - streams.diagnostic(`Open ${service} sign-in: ${url}\n`) - }, - // Before anything is saved, so a refused account leaves the profile's sign-in as it was. - accept: async (tokens) => { - if (!tokens.accessToken) throw new CliError("authentication_error", `${service} returned no access token`) - const { id, account } = await options.verify(this, tokens.accessToken, events) - ;(options.claim ?? ((env, profile, key) => rememberAccount(app, profile, key, env)))( - context.env, - context.profile, - id, - ) - shown = account - return undefined - }, - }), - ) - // The owner chose the file: an older keyring copy must not outlive it with a live refresh token. - if (args.credentialStorage === "file") - try { - storageFor(context.where, context.profile, "keyring").remove() - } catch { - // No keyring on this computer: there is no copy to forget. - } - answer(this, { ...shown, profile: context.profile, signed_in: true, scopes }) + .addOption(answerStdinOption()) + for (const option of options.startOptions ?? []) start.addOption(option) + start.action(async function ( + this: Command, + args: { browser: boolean; credentialStorage: TokenStorage; answerStdin?: boolean }, + ) { + const context = contextOf(this) + refuseCommandName(context.profile, commandWords(rootOf(this)), app.command) + refuseOffline(this, service) + const { streams } = outputFor(this) + const steps = signInSteps({ + diagnostic: (line) => streams.diagnostic(`${line}\n`), + json: context.format !== "pretty" || context.environment.tty === false, + answers: args.answerStdin === true, + ...(context.environment.stdin ? { input: context.environment.stdin } : {}), }) + const { + keeper, + scopes: asked, + client, + } = await context.keeperOf(args.credentialStorage === "file" ? "file" : undefined, steps) + let shown: Readonly> = {} + let accountId = "" + const { scopes } = await context.run((events) => + keeper.signIn({ + scopes: asked, + openBrowser: async (url) => { + if (args.browser) await context.environment.openBrowser?.(url, this) + }, + ...(steps.answers + ? { + readPaste: (stop: AbortSignal) => + steps + .ask({ field: "redirect", secret: true, prompt: PASTE_PROMPT }, stop) + // The browser's callback won the race; the question is withdrawn, not failed. + .catch((error: unknown) => (stop.aborted ? new Promise(() => {}) : Promise.reject(error))), + } + : {}), + showUrl: (url) => { + steps.openUrl(url, `Sign in to ${service} and allow access`) + streams.diagnostic(`Open ${service} sign-in: ${url}\n`) + }, + // Before anything is saved, so a refused account leaves the profile's sign-in as it was. + accept: async (tokens) => { + if (!tokens.accessToken) throw new CliError("authentication_error", `${service} returned no access token`) + const { id, account, extra } = await options.verify(this, tokens.accessToken, events) + ;(options.claim ?? ((env, profile, key) => rememberAccount(app, profile, key, env)))( + context.env, + context.profile, + id, + ) + shown = account + accountId = id + return extra + }, + }), + ) + // The owner chose the file: an older keyring copy must not outlive it with a live refresh token. + if (args.credentialStorage === "file") + try { + storageFor(context.where, context.profile, "keyring").remove() + } catch { + // No keyring on this computer: there is no copy to forget. + } + await options.afterSignIn?.(this, { + env: context.env, + profile: context.profile, + id: accountId, + account: shown, + client, + scopes, + }) + answer(this, { ...shown, profile: context.profile, signed_in: true, scopes }) + }) const status = annotate(new Command("status"), { effects: REMOTE_READ, @@ -262,10 +337,17 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { const context = contextOf(this) const saved = context.saved() if (!saved) return answer(this, { profile: context.profile, state: "missing", verified: false }) - const state = { profile: context.profile, state: "saved", scopes: saved.tokens.scopes } + const { expiresAt } = saved.tokens + const state = { + profile: context.profile, + state: "saved", + scopes: saved.tokens.scopes, + // The access token's end, which a refresh moves on; a sign-in itself ends only at session end or in the service. + expires_at: expiresAt ? new Date(expiresAt).toISOString() : null, + } if (!args.check) return answer(this, { ...state, verified: false }) refuseOffline(this, service) - const { keeper } = context.keeperOf() + const { keeper } = await context.keeperOf() const { account } = await context.run(async (events) => options.verify(this, await keeper.accessToken(), events)) answer(this, { ...account, ...state, verified: true }) }) @@ -285,7 +367,7 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { .action(async function (this: Command) { const context = contextOf(this) if (!context.saved()) return answer(this, { profile: context.profile, ended: false }) - const { removed } = await context.keeperOf().keeper.signOut() + const { removed } = await (await context.keeperOf()).keeper.signOut() if (!context.saved()) return answer(this, { profile: context.profile, ended: true, removed }) answer(this, { profile: context.profile, @@ -308,12 +390,20 @@ export const oauthSessionCommand = (options: OAuthSessionOptions): Command => { .action(function (this: Command) { const environment = environmentOf(this) const env = environment.env ?? process.env - const { configuredProfiles } = options.resolveSettings({}, { env, needsProfile: false }) - const where = { env, keyring: environment.keyring, warn: outputFor(this).renderer.warn } - const items = profilesHere(app, configuredProfiles, env).map((profile) => ({ - profile, - signed_in: storageFor(where, profile).read() !== undefined, - })) + const { warn } = outputFor(this).renderer + const where = { env, keyring: environment.keyring, warn } + const profiles = + options.profiles?.(env) ?? + profilesHere(app, options.resolveSettings({}, { env, needsProfile: false }).configuredProfiles, env) + const unknown = unknownSignIn(warn) + const items = profiles.map((profile) => { + try { + const saved = storageFor(where, profile).read() !== undefined + return { profile, signed_in: saved, state: saved ? "saved" : "missing" } + } catch (error) { + return unknown(profile, error) + } + }) renderAnswer( this, outputFor(this), diff --git a/src/cli/token-session.test.ts b/src/cli/token-session.test.ts index a8d047b20..c5a77dde6 100644 --- a/src/cli/token-session.test.ts +++ b/src/cli/token-session.test.ts @@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { PassThrough, Readable } from "node:stream" -import { CliError, captureStreams } from "@wirecat/cli-base" +import { CliError, captureStreams, type KeyringStore } from "@wirecat/cli-base" import { memoryKeyring } from "@wirecat/cli-base/testing" import { Command } from "commander" import { afterEach, describe, expect, it } from "vitest" @@ -19,7 +19,7 @@ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) -const setup = () => { +const setup = (keyring: KeyringStore = memoryKeyring()) => { const root = mkdtempSync(join(tmpdir(), "token-session-")) roots.push(root) mkdirSync(join(root, "config"), { recursive: true }) @@ -30,7 +30,6 @@ const setup = () => { PAGES_CONFIG_DIR: join(root, "config"), PAGES_CACHE_DIR: join(root, "cache"), } - const keyring = memoryKeyring() const checked: string[] = [] const cli = async (argv: string[], stdin?: string, claim?: TokenSessionOptions["claim"]) => { const streams = captureStreams() @@ -65,6 +64,25 @@ const setup = () => { return { env, cli, checked } } +it("session list names every profile when the keyring cannot be reached", async () => { + const memory = memoryKeyring() + let reachable = true + const keyring: KeyringStore = { + get: (service, account) => { + if (!reachable) throw new Error("synthetic: no secret service") + return memory.get(service, account) + }, + set: (service, account, secret) => memory.set(service, account, secret), + delete: (service, account) => memory.delete(service, account), + } + const { cli } = setup(keyring) + expect((await cli(["personal", "session", "start", "--json"], "good-token\n")).code).toBe(0) + reachable = false + const listed = await cli(["session", "list", "--json"]) + expect(listed.code).toBe(0) + expect(listed.json.items).toEqual([{ profile: "personal", signed_in: null, state: "unknown", token_from: null }]) +}) + it("session start checks the token before keeping it; status, list and end", async () => { const { env, cli, checked } = setup() const started = await cli(["personal", "session", "start", "--json"], "good-token\n") diff --git a/src/cli/token-session.ts b/src/cli/token-session.ts index 9c8a8ca83..8c1f5862b 100644 --- a/src/cli/token-session.ts +++ b/src/cli/token-session.ts @@ -115,6 +115,22 @@ export const manifestVerify = return { id: String(id), account: { id: String(id), ...(typeof name === "string" ? { name } : {}) } } } +const UNREADABLE = new Set(["keyring.unreachable", "oauth.not-saved", "oauth.invalid", "session.unreadable"]) + +/** + * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry + * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause. + */ +export const unknownSignIn = (warn: (message: string) => void) => { + const warned = new Set() + return (profile: string, error: unknown) => { + if (!(error instanceof CliError) || !UNREADABLE.has(String(error.details.reason))) throw error + if (!warned.has(error.message)) warn(error.message) + warned.add(error.message) + return { profile, signed_in: null, state: "unknown" } as const + } +} + export const storageOf = (raw: string): TokenStorage => { if (raw === "keyring" || raw === "file") return raw throw new CliError("validation_error", `--credential-storage takes keyring or file; got ${raw}`) @@ -268,9 +284,19 @@ export const tokenSessionCommand = (options: TokenSessionOptions): Command => { ...(environment.keyring ? { keyring: environment.keyring } : {}), warn: outputFor(this).renderer.warn, }) + const unknown = unknownSignIn(outputFor(this).renderer.warn) const items = profilesHere(app, configuredProfiles, env).map((profile) => { - const saved = tokens.read(profile) - return { profile, signed_in: saved !== undefined, token_from: saved?.source ?? null } + try { + const saved = tokens.read(profile) + return { + profile, + signed_in: saved !== undefined, + state: saved ? "saved" : "missing", + token_from: saved?.source ?? null, + } + } catch (error) { + return { ...unknown(profile, error), token_from: null } + } }) renderAnswer( this, diff --git a/src/oauth/index.ts b/src/oauth/index.ts index 0bd6d5ee6..c492efadf 100644 --- a/src/oauth/index.ts +++ b/src/oauth/index.ts @@ -24,6 +24,7 @@ export { driveSessionCodec, type EncodeInput, googleTokenCodec, + type LegacyAccount, oauthAccount, type StoredTokens, standardCodec, diff --git a/src/oauth/storage.test.ts b/src/oauth/storage.test.ts index 181a0858d..f46ff8d4f 100644 --- a/src/oauth/storage.test.ts +++ b/src/oauth/storage.test.ts @@ -196,6 +196,34 @@ describe("zm's existing entry", () => { }) }) +describe("an older entry kept in the private file", () => { + it("is copied within the file, never into the keyring", () => { + const configDir = folder() + const keyring = memoryKeyring() + const options = { service: "drive-cli", configDir, keyring, env: {}, warn: () => {} } + const tokens = { accessToken: "a", refreshToken: "r", expiresAt: NOW, scopes: ["s"] } + credentialStorage({ + credentials: { ...options, storage: "file" }, + account: "personal", + codec: driveSessionCodec, + }).write({ tokens, client: { clientId: "c" }, extra: { principal: "synthetic-principal" } }) + const storage = credentialStorage({ + credentials: options, + account: oauthAccount("google", "personal"), + legacyAccounts: ["personal"], + codec: driveSessionCodec, + }) + expect(storage.read()?.tokens.refreshToken).toBe("r") + expect(keyring.get("drive-cli", "oauth:google:personal")).toBeNull() + expect(Object.keys(JSON.parse(readFileSync(join(configDir, "credentials.json"), "utf8")))).toEqual([ + "personal", + "oauth:google:personal", + ]) + expect(storage.remove()).toEqual(["file"]) + expect(storage.read()).toBeUndefined() + }) +}) + describe("new entries", () => { it("keep the app's source, and the secret only of WireCat's public app", () => { const keyring = memoryKeyring() diff --git a/src/oauth/storage.ts b/src/oauth/storage.ts index 6696a2c12..b39c62dc2 100644 --- a/src/oauth/storage.ts +++ b/src/oauth/storage.ts @@ -259,12 +259,18 @@ export const zoomTokenCodec: TokenCodec = { }, } +/** An older entry: an account under the same service, or one an older version kept under another service. */ +export type LegacyAccount = string | { service: string; account: string } + export interface CredentialStorageOptions { /** What the CLI passes `Credentials` today; the same options address the same entry. */ credentials: CredentialsOptions account: string - /** Older accounts read when `account` is empty; a hit is copied to `account` and left in place. */ - legacyAccounts?: readonly string[] + /** + * Older entries read when `account` is empty. A hit is copied to `account`, in the store it was read from, and left + * in place; `remove` removes them too. A run with moved folders only reads them. + */ + legacyAccounts?: readonly LegacyAccount[] codec: TokenCodec } @@ -297,15 +303,21 @@ export const credentialStorage = (options: CredentialStorageOptions): TokenStora options.credentials.configDir, options.credentials.isolated, ) - const raw = (name: string) => { + const legacies = (options.legacyAccounts ?? []).map((legacy) => + typeof legacy === "string" + ? { account: legacy, store: credentials } + : { account: legacy.account, store: new Credentials({ ...options.credentials, service: legacy.service }) }, + ) + const sourced = (name: string, store = credentials) => { try { - return credentials.read(name)?.secret + return store.read(name) } catch (error) { // cli-base's own error already says what to do, in words safe for the answer. if (error instanceof CliError) throw error throw keyringFailure(error) } } + const raw = (name: string) => sourced(name)?.secret // A sign-in on a machine with no keyring writes to the file, so an old entry it cannot read is no old entry. With // `storage: "keyring"` there is no file to fall back on: the save would fail too, after the browser. const fallsBack = options.credentials.storage !== "keyring" @@ -327,12 +339,19 @@ export const credentialStorage = (options: CredentialStorageOptions): TokenStora const current = () => { const own = raw(account) if (own !== undefined) return own - for (const legacy of options.legacyAccounts ?? []) { - const found = raw(legacy) + for (const legacy of legacies) { + const found = sourced(legacy.account, legacy.store) if (found === undefined) continue - codec.decode(found) - if (!moved) save(found) - return found + codec.decode(found.secret) + // A sign-in the owner kept in the file must not move to the keyring by being copied. + if (!moved && found.source === "file") + try { + new Credentials({ ...options.credentials, storage: "file" }).write(account, found.secret) + } catch (error) { + throw keyringFailure(error, found.secret) + } + else if (!moved) save(found.secret) + return found.secret } return undefined } @@ -354,7 +373,9 @@ export const credentialStorage = (options: CredentialStorageOptions): TokenStora ), remove: () => { try { - return credentials.remove(account) + // The next read would copy an older entry back and sign the profile in again. + const older = moved ? [] : legacies.flatMap((legacy) => legacy.store.remove(legacy.account)) + return [...new Set([...credentials.remove(account), ...older])] } catch (error) { throw keyringFailure(error) } From 269dbdd652a94ae34fd4e9f8ee91884754adfb51 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 21:55:59 +0100 Subject: [PATCH 2/2] chore(api): report storageOf, timeLimit and withTimeLimit Co-Authored-By: Claude Opus 5.5 --- api/cli.api.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/api/cli.api.txt b/api/cli.api.txt index ab3447f8e..3bc3ff4d2 100644 --- a/api/cli.api.txt +++ b/api/cli.api.txt @@ -1423,6 +1423,10 @@ StoredMessages · interface · wroteTo(personId: Id): Promise; StoredMessages · interface · pollVotes(chatId: Id, messageId: Id): Promise; StoredMessages · interface · reactors(chatId: Id, messageId: Id): Promise; StoredMessages · interface · } +TimeLimit · interface · export interface TimeLimit { +TimeLimit · interface · signal: AbortSignal; +TimeLimit · interface · clear: () => void; +TimeLimit · interface · } TokenSessionOptions · interface · export interface TokenSessionOptions { TokenSessionOptions · interface · app: AppIdentity; TokenSessionOptions · interface · service: string; @@ -3153,6 +3157,7 @@ snakeKeys · const · export declare const snakeKeys: (value: unknown) => unknow startCli · const · export declare const startCli: (entry: CliEntry) => Promise; startRun · const · export declare const startRun: (options: StartRunOptions) => Run; statsCommand · const · export declare const statsCommand: (messenger: import("./index.js").Messenger, loadRenderer?: typeof import("../charts/render.js").chartRenderer | undefined) => import("commander").Command; +storageOf · const · export declare const storageOf: (raw: string) => TokenStorage; storeCommand · const · export declare const storeCommand: (messenger: import("./index.js").Messenger) => import("commander").Command; storeInfo · const · export declare const storeInfo: (env: NodeJS.ProcessEnv) => Promise; storeSummary · const · export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command, version }?: { @@ -3251,6 +3256,7 @@ tagsCommand · const · export declare const tagsCommand: (messenger: import("./ tasksCommand · const · export declare const tasksCommand: (messenger: import("./index.js").Messenger) => import("commander").Command; termField · const · export declare const termField: (name: string, type: FieldType, example: string, more?: Pick) => FieldSpec; terminalAsker · const · export declare const terminalAsker: (command: Command) => Asker; +timeLimit · const · export declare const timeLimit: (ms: number) => TimeLimit; tokenSessionCommand · const · export declare const tokenSessionCommand: (options: TokenSessionOptions) => Command; typedQuery · const · export declare const typedQuery: (words: QueryWords) => string; unfilteredQuery · const · export declare const unfilteredQuery: (entity: string, schema: Parameters[0]) => QueryRegistry; @@ -3266,6 +3272,7 @@ withSettingDefaults · const · config: unknown; withSettingDefaults · const · added: string[]; withSettingDefaults · const · }; withSqliteSidecars · const · export declare const withSqliteSidecars: (path: string) => string[]; +withTimeLimit · const · export declare const withTimeLimit: (ms: number, run: (deadline: AbortSignal) => Promise) => Promise; writeNewFile · const · export declare const writeNewFile: (path: string, content: string) => Promise; writesNewFileOnlyWith · const · export declare const writesNewFileOnlyWith: (command: T, option: string) => T; writesOwnerFiles · const · export declare const writesOwnerFiles: (command: T) => T;