From 8cf76df2f2331a5de3f59a527a43b1e0f2dd0622 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 18 Nov 2026 10:18:34 +0100 Subject: [PATCH 1/2] feat(cli): manifestVerify and hostsFetch, so a CLI made from a config keeps no token check of its own manifestVerify is tokenSessionCommand's verify from wirecat.config.ts's auth.verify: it sends the one operation, refuses a token the answer does not call active (Attio answers a revoked key with 200), names a missing id as the service's error, and keeps the id and the name when it is text. hostsFetch(hosts, fetch) is the hosts-only fetch over a test's fake. ProfileTokenStore takes keyring: undefined, so a CLI passes baseContext's keyring as it is. A CLI made by cli-template's new --from-config held this logic in its seed, with branches on the config's values that no test of that CLI can take both ways: its coverage floor failed (FIND-2767). Co-Authored-By: Claude Opus 5.5 --- changes/feat-manifest-verify.md | 8 ++++ docs/dev/CRM.md | 4 ++ src/cli/index.ts | 10 ++++- src/cli/profile-token.ts | 2 +- src/cli/service-api-call.ts | 9 ++++- src/cli/token-session.test.ts | 71 ++++++++++++++++++++++++++++++++- src/cli/token-session.ts | 37 ++++++++++++++++- 7 files changed, 134 insertions(+), 7 deletions(-) create mode 100644 changes/feat-manifest-verify.md diff --git a/changes/feat-manifest-verify.md b/changes/feat-manifest-verify.md new file mode 100644 index 000000000..ee5762420 --- /dev/null +++ b/changes/feat-manifest-verify.md @@ -0,0 +1,8 @@ +### Added + +- **`manifestVerify` and `hostsFetch` in `@wirecat/cli-core/cli`**, so a CLI made from `wirecat.config.ts` keeps no + token check of its own. `manifestVerify` is `tokenSessionCommand`'s `verify` from the config's `auth.verify`: it sends + the one operation, refuses a token the answer does not call `active` (Attio answers a revoked key with 200), names a + missing id as the service's error, and keeps the id and the name when it is text. `hostsFetch(hosts, fetch)` reaches + only the CLI's hosts, over a test's fake when one is given. +- **`ProfileTokenStore` takes `keyring: undefined`**, so a CLI passes `baseContext`'s keyring as it is. diff --git a/docs/dev/CRM.md b/docs/dev/CRM.md index e78ac8771..280c6b577 100644 --- a/docs/dev/CRM.md +++ b/docs/dev/CRM.md @@ -250,6 +250,10 @@ hooks })` builds the `CrmSource` (design and evidence: cli-private `plans/2026-1 `select.max` caps the account's own fields in `{select}`; mapped fields are always asked for. - `defineCli` and `parseCliConfig` (`@wirecat/cli-core/manifest`) give the whole CLI's `wirecat.config.ts`: identity, API description, sign-in preset, category and this source. +- `manifestVerify` (`@wirecat/cli-core/cli`) is `tokenSessionCommand`'s `verify` from the config's `auth.verify`: it + sends the one operation, refuses a token the answer does not call `active`, and keeps the id and name the answer + holds. `hostsFetch(hosts, environment.fetch)` is the fetch for it and the source: only the CLI's hosts, over a test's + fake when there is one. A CLI made from the config holds no check of its own. - Not yet: deletions named in the answer, a live `list`. - `src/crm/manifest/manifest.test.ts` writes HubSpot's contacts, companies and deals as a manifest and runs `crmSourceContract`, faults included, against a strict fake of HubSpot's API. diff --git a/src/cli/index.ts b/src/cli/index.ts index 1847ff6e8..a4c9b7efe 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -691,7 +691,7 @@ export { serviceApiOperations, serviceApiPermissions, } from "./service-api.js" -export { type ServiceApiCall, type ServiceApiCallOptions, serviceApiCall } from "./service-api-call.js" +export { hostsFetch, type ServiceApiCall, type ServiceApiCallOptions, serviceApiCall } from "./service-api-call.js" export { manifestBaseUrl, type ServiceApiManifest, signRequest, siteValue } from "./service-api-manifest.js" export { type DeclaredSetting, type SettingRow, settingRows, withSettingDefaults } from "./setting-defaults.js" export { @@ -807,5 +807,11 @@ export { } from "./store-recover.js" export { changeStoreSetting, isStoreSetting, STORE_SETTINGS, storeSettings } from "./store-settings.js" export type { TemplatesOptions } from "./templates-command.js" -export { signedInSite, type TokenSessionOptions, tokenSessionCommand } from "./token-session.js" +export { + type ManifestVerifyOptions, + manifestVerify, + signedInSite, + type TokenSessionOptions, + tokenSessionCommand, +} from "./token-session.js" export { restartServers, type UpgradeContext } from "./upgrade-command.js" diff --git a/src/cli/profile-token.ts b/src/cli/profile-token.ts index f242e5f77..baab1aca6 100644 --- a/src/cli/profile-token.ts +++ b/src/cli/profile-token.ts @@ -16,7 +16,7 @@ export type TokenStorage = "keyring" | "file" export interface ProfileTokenStoreOptions { app: AppIdentity env?: NodeJS.ProcessEnv - keyring?: KeyringStore + keyring?: KeyringStore | undefined /** Where the one warning about an unreachable keyring goes; stderr when left out. */ warn?: (message: string) => void } diff --git a/src/cli/service-api-call.ts b/src/cli/service-api-call.ts index 185cbeabb..b04ab221c 100644 --- a/src/cli/service-api-call.ts +++ b/src/cli/service-api-call.ts @@ -1,6 +1,6 @@ import { CliError } from "@wirecat/cli-base" import type { ManifestOperation } from "@wirecat/cli-base/codegen" -import type { FetchLike } from "@wirecat/cli-base/http" +import { type FetchLike, hostFetch } from "@wirecat/cli-base/http" import { Command } from "commander" import type { ApiCommandInput } from "./bot/api.js" import { type HttpApiSendOptions, httpApiRequest, httpApiSend } from "./bot/api-http.js" @@ -26,6 +26,13 @@ export interface ServiceApiCallOptions { failure?: HttpApiSendOptions["failure"] } +/** + * A fetch that reaches only `hosts` (WC-CMD-32), over the fetch a test gives in its environment, or the network when + * none: a CLI passes `environment.fetch` as it is. + */ +export const hostsFetch = (hosts: readonly string[], fetch: FetchLike | undefined): FetchLike => + hostFetch({ hosts, ...(fetch ? { fetch } : {}) }) + // The run record and the fetch are the only things httpApiSend asks a command for, and a sync has no command of its own. const NO_COMMAND = new Command("source") diff --git a/src/cli/token-session.test.ts b/src/cli/token-session.test.ts index 806a94291..27e540070 100644 --- a/src/cli/token-session.test.ts +++ b/src/cli/token-session.test.ts @@ -4,11 +4,14 @@ import { join } from "node:path" import { Readable } from "node:stream" import { CliError, captureStreams } from "@wirecat/cli-base" import { memoryKeyring } from "@wirecat/cli-base/testing" -import { afterEach, expect, it } from "vitest" +import { Command } from "commander" +import { afterEach, describe, expect, it } from "vitest" import { accountFileFor } from "./messenger/accounts.js" import { run } from "./program.js" +import { hostsFetch } from "./service-api-call.js" +import type { ServiceApiManifest } from "./service-api-manifest.js" import { settingsFor } from "./settings.js" -import { type TokenSessionOptions, tokenSessionCommand } from "./token-session.js" +import { manifestVerify, type TokenSessionOptions, tokenSessionCommand } from "./token-session.js" const app = { command: "pages", appName: "pages-cli", envPrefix: "PAGES", description: "synthetic", version: "1.0.0" } const roots: string[] = [] @@ -115,3 +118,67 @@ it("session status --check checks a token from the environment variable, and nev expect(checked).toEqual(["good-token"]) expect(JSON.stringify(status.json)).not.toContain("good-token") }) + +describe("manifestVerify", () => { + const manifest = { + servers: [{ url: "https://api.acme.test/v1" }], + securitySchemes: { bearer: { type: "http", scheme: "bearer" } }, + security: [{ bearer: [] }], + operations: [ + { id: "getSelf", command: "get-self", effect: "read", binding: { kind: "http", method: "GET", path: "/self" } }, + ], + } as unknown as ServiceApiManifest + const verifying = (answer: unknown, verify: Parameters[0]["verify"]) => { + const sent: { url: string; authorization: string | null }[] = [] + const fake = async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init) + sent.push({ url: request.url, authorization: request.headers.get("authorization") }) + return Response.json(answer) + } + const check = manifestVerify({ + manifest, + service: "Acme", + verify, + fetch: () => hostsFetch(["api.acme.test"], fake), + }) + return { sent, check: () => check(new Command("start"), "tok-1", () => undefined, undefined) } + } + + it("sends the one operation with the token and keeps the id and name the answer holds", async () => { + const { sent, check } = verifying( + { data: { workspace: 42, title: "Acme Inc" }, active: true }, + { operation: "getSelf", id: "data.workspace", name: "data.title", active: "active" }, + ) + expect(await check()).toEqual({ id: "42", account: { id: "42", name: "Acme Inc" } }) + expect(sent).toEqual([{ url: "https://api.acme.test/v1/self", authorization: "Bearer tok-1" }]) + }) + + it("leaves out a name that is not text, and asks nothing about activity when the config names no field", async () => { + const { check } = verifying({ id: "w1", name: { first: "A" } }, { operation: "getSelf", id: "id", name: "name" }) + expect(await check()).toEqual({ id: "w1", account: { id: "w1" } }) + expect(await verifying({ id: "w2" }, { operation: "getSelf", id: "id" }).check()).toEqual({ + id: "w2", + account: { id: "w2" }, + }) + }) + + it("refuses a token the answer does not call active, as Attio answers a revoked key with 200", async () => { + for (const active of [false, null, "yes"]) + await expect( + verifying({ id: "w1", active }, { operation: "getSelf", id: "id", active: "active" }).check(), + ).rejects.toMatchObject({ code: "authentication_error" }) + }) + + it("is the service's error when the answer holds no id", async () => { + await expect(verifying({ id: null }, { operation: "getSelf", id: "id" }).check()).rejects.toMatchObject({ + code: "provider_error", + details: { reason: "verify.no-id" }, + }) + }) +}) + +it("hostsFetch reaches only its hosts, over the network when no fetch is given", async () => { + await expect(hostsFetch(["api.acme.test"], undefined)("https://elsewhere.test/x")).rejects.toThrow(/elsewhere\.test/) + const fake = async () => new Response("ok") + expect(await (await hostsFetch(["api.acme.test"], fake)("https://api.acme.test/x")).text()).toBe("ok") +}) diff --git a/src/cli/token-session.ts b/src/cli/token-session.ts index 8771756e4..3485172b6 100644 --- a/src/cli/token-session.ts +++ b/src/cli/token-session.ts @@ -1,6 +1,9 @@ import { CliError } from "@wirecat/cli-base" import { annotate } from "@wirecat/cli-base/commands" +import type { FetchLike } from "@wirecat/cli-base/http" import { Command } from "commander" +import { at as valueAt } from "../crm/manifest/map.js" +import type { CliVerify } from "../manifest/index.js" import type { AppIdentity } from "../ports/app.js" import type { EventSink } from "../runs/events.js" import { readSecret } from "../terminal/prompt.js" @@ -11,7 +14,8 @@ import { itemOf, listOf, renderAnswer } from "./envelope.js" import { profilesHere, rememberAccount } from "./messenger/accounts.js" import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js" import { ProfileTokenStore, type TokenStorage } from "./profile-token.js" -import { siteValue } from "./service-api-manifest.js" +import { serviceApiCall } from "./service-api-call.js" +import { type ServiceApiManifest, siteValue } from "./service-api-manifest.js" import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js" export interface TokenSessionOptions { @@ -53,6 +57,37 @@ export interface TokenSessionOptions { endNote?: string } +export interface ManifestVerifyOptions { + manifest: ServiceApiManifest + /** The service's name in messages: "Attio". */ + service: string + /** The config's `auth.verify`: the operation, where its answer holds the id and a name, and whether it is live. */ + verify: CliVerify + /** The command's host-checked fetch, such as `hostsFetch(hosts, environment.fetch)`. */ + fetch: (command: Command) => FetchLike +} + +/** + * `verify` for `tokenSessionCommand` from a config's `auth.verify`: the one operation is sent with the token, a token the + * answer does not call active is refused, and the account is the id and name the answer holds. + */ +export const manifestVerify = + ({ manifest, service, verify, fetch }: ManifestVerifyOptions): TokenSessionOptions["verify"] => + async (command, token) => { + const call = serviceApiCall({ manifest, service, fetch: fetch(command), token: () => token }) + const answer = await call(verify.operation, { path: {}, query: {}, headers: {}, fields: {} }) + // A service such as Attio answers a revoked key with 200 and `active: false`, not with 401. + if (verify.active !== undefined && valueAt(answer, verify.active) !== true) + throw new CliError("authentication_error", `${service} does not accept this token; sign in again`) + const id = valueAt(answer, verify.id) + if (typeof id !== "string" && typeof id !== "number") + throw new CliError("provider_error", `${service} answered ${verify.operation} without ${verify.id}`, { + reason: "verify.no-id", + }) + const name = verify.name === undefined ? undefined : valueAt(answer, verify.name) + return { id: String(id), account: { id: String(id), ...(typeof name === "string" ? { name } : {}) } } + } + 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}`) From c7428b2a3d784791371ea8b2b376108df27b0fb6 Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 18 Nov 2026 10:33:51 +0100 Subject: [PATCH 2/2] fix(errors): register verify.no-id Co-Authored-By: Claude Opus 5.5 --- src/errors/reasons.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/errors/reasons.ts b/src/errors/reasons.ts index 6e16a9c0f..c0ec8a78a 100644 --- a/src/errors/reasons.ts +++ b/src/errors/reasons.ts @@ -74,6 +74,7 @@ const PROVIDER_API: Entry[] = [ validation("api.unknown-method", "the provider has no method by this name"), ["api.disabled", "configuration_error", "the provider's API is turned off for this OAuth project"], ["manifest.invalid", "configuration_error", "the source manifest does not match its shape or the generated API"], + ["verify.no-id", "provider_error", "the answer to the sign-in check holds no account id where auth.verify says"], ["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"], ["access.denied", "permission_error", "the provider refused this account access to the item"], ["item.not-found", "not_found", "the provider has no item by this id, or this account cannot see it"],