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
8 changes: 8 additions & 0 deletions changes/feat-manifest-verify.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions docs/dev/CRM.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 8 additions & 2 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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"
2 changes: 1 addition & 1 deletion src/cli/profile-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
9 changes: 8 additions & 1 deletion src/cli/service-api-call.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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")

Expand Down
71 changes: 69 additions & 2 deletions src/cli/token-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = []
Expand Down Expand Up @@ -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<typeof manifestVerify>[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")
})
37 changes: 36 additions & 1 deletion src/cli/token-session.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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 {
Expand Down Expand Up @@ -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}`)
Expand Down
1 change: 1 addition & 0 deletions src/errors/reasons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
Loading