Skip to content
Merged
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
7 changes: 7 additions & 0 deletions api/cli.api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1423,6 +1423,10 @@ StoredMessages · interface · wroteTo(personId: Id): Promise<boolean>;
StoredMessages · interface · pollVotes(chatId: Id, messageId: Id): Promise<PollVote[]>;
StoredMessages · interface · reactors(chatId: Id, messageId: Id): Promise<Reactor[]>;
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;
Expand Down Expand Up @@ -3153,6 +3157,7 @@ snakeKeys · const · export declare const snakeKeys: (value: unknown) => unknow
startCli · const · export declare const startCli: (entry: CliEntry) => Promise<void>;
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<StoreInfo>;
storeSummary · const · export declare const storeSummary: (env: NodeJS.ProcessEnv, { deep, command, version }?: {
Expand Down Expand Up @@ -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, "values" | "relation">) => 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<typeof queryFieldsOf>[0]) => QueryRegistry;
Expand All @@ -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: <T>(ms: number, run: (deadline: AbortSignal) => Promise<T>) => Promise<T>;
writeNewFile · const · export declare const writeNewFile: (path: string, content: string) => Promise<void>;
writesNewFileOnlyWith · const · export declare const writesNewFileOnlyWith: <T extends Command>(command: T, option: string) => T;
writesOwnerFiles · const · export declare const writesOwnerFiles: <T extends Command>(command: T) => T;
33 changes: 33 additions & 0 deletions changes/feat-oauth-session-options.md
Original file line number Diff line number Diff line change
@@ -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:<provider>:<profile>`. `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.
3 changes: 3 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -611,6 +612,7 @@ export {
type OAuthPreset,
type OAuthPresetOptions,
type OAuthSessionOptions,
type OAuthSignedIn,
oauthFlowOf,
oauthPreset,
oauthSessionCommand,
Expand Down Expand Up @@ -824,6 +826,7 @@ export {
type ManifestVerifyOptions,
manifestVerify,
signedInSite,
storageOf,
type TokenSessionOptions,
tokenSessionCommand,
} from "./token-session.js"
Expand Down
185 changes: 179 additions & 6 deletions src/cli/oauth-session.test.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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<typeof import("@wirecat/cli-base")>()
return {
...base,
isMovedRun: (options: Parameters<typeof base.isMovedRun>[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 })
})

Expand All @@ -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<OAuthSessionOptions> = {},
browser: (url: string) => Promise<unknown> = visit,
) => {
const root = mkdtempSync(join(tmpdir(), "oauth-session-"))
roots.push(root)
mkdirSync(join(root, "config"), { recursive: true })
Expand All @@ -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({
Expand Down Expand Up @@ -91,6 +123,7 @@ const setup = (keyring: KeyringStore = memoryKeyring()) => {
verify?.()
return { id: "workspace-1", account: { workspace: "Synthetic" } }
},
...more,
}),
],
},
Expand All @@ -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("")
Expand All @@ -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)
Expand Down Expand Up @@ -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 })
Expand Down Expand Up @@ -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 <scopes>", "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" },
])
})
})
Loading
Loading