From 0191f69e1401720e9bda9beceef72cba4a2ca6d9 Mon Sep 17 00:00:00 2001 From: leemour Date: Tue, 17 Nov 2026 17:10:01 +0100 Subject: [PATCH 1/2] feat(cli): api uploads a file's bytes, signs only where the spec says, and takes no token without sign-in - A generated api command for an upload (application/octet-stream, as Petstore 3's uploadFile) takes --body-file and sends the bytes with the operation's content type; a file in the CLI's own folders is refused, as for a JSON body. - Signing follows cli-base's signInRequirements/signInPlace: the operation's own security, else the document's, and nothing when neither names one. The bearer default for a manifest without schemes is gone. - serviceApiCommand and serviceApiCall take no token for a CLI without sign-in. - serviceApiOperations lists what the api group offers; a body it cannot send (a multipart form) is left out with its reason in api show. - mcp check: a test that a CLI without signedIn is healthy with signed_in null. Co-Authored-By: Claude Opus 5.5 --- changes/feat-service-api-uploads-sign-in.md | 22 ++++++ src/cli/app-mcp-command.test.ts | 10 ++- src/cli/bot/api-http.ts | 24 +++++-- src/cli/bot/api-input.ts | 15 ++++ src/cli/bot/api.ts | 24 ++++++- src/cli/index.ts | 11 ++- src/cli/service-api-call.ts | 3 +- src/cli/service-api-manifest.ts | 65 +++++++----------- src/cli/service-api.test.ts | 76 ++++++++++++++++++++- src/cli/service-api.ts | 67 ++++++++++++------ 10 files changed, 240 insertions(+), 77 deletions(-) create mode 100644 changes/feat-service-api-uploads-sign-in.md diff --git a/changes/feat-service-api-uploads-sign-in.md b/changes/feat-service-api-uploads-sign-in.md new file mode 100644 index 000000000..44129dfcb --- /dev/null +++ b/changes/feat-service-api-uploads-sign-in.md @@ -0,0 +1,22 @@ +### Added + +- **A generated `api` command uploads a file's bytes.** For an operation whose body is an upload, as Petstore 3's + `application/octet-stream` image, `--body-file ` (or `-` for stdin) sends the file as it is, with the + operation's content type; such a command has no `--body`. A file in the CLI's own folders is refused, as for a JSON + body. Needs cli-base 0.112.0, whose generator reads such a body. +- **`serviceApiOperations(manifest)`** lists the operations the `api` group offers and why it leaves out the rest, so + a CLI's test runs exactly the commands that exist. `sendsBytes(operation)`, `readApiBytes(path)` and + `unsendableBody(operation)` are exported beside it. +- **`serviceApiCommand` and `serviceApiCall` take no `token` for a CLI without sign-in.** Left out, no call carries a + token, whatever the spec says; a CLI made with cli-template's `--sign-in none` passes none. + +### Changed — may break callers + +- **A call sends no token where the spec names no sign-in.** The `api` group and `serviceApiCall` now follow cli-base's + `signInRequirements`: the operation's own `security`, else the document's, and nothing when neither says anything. + Before, a manifest without `securitySchemes`, or an operation without requirements, got `Authorization: Bearer + `. A CLI whose spec omits its sign-in now gets the service's refusal (401): generate with `auth` + (`{ securitySchemes, security, reason }`) to name it. A Discovery manifest gets its OAuth from cli-base 0.112.0's + generator; regenerate before taking this version. +- **An operation whose body is neither JSON nor an upload's bytes, such as a multipart form, is no longer offered.** + It always failed when run; now `api list` leaves it out and `api show ` says why. diff --git a/src/cli/app-mcp-command.test.ts b/src/cli/app-mcp-command.test.ts index ae46ff4b1..7a14e4c31 100644 --- a/src/cli/app-mcp-command.test.ts +++ b/src/cli/app-mcp-command.test.ts @@ -351,7 +351,7 @@ describe("appDoctorCommand", () => { "})", ].join("\n") - const check = async (signedIn: NonNullable, keyring: KeyringStore) => { + const check = async (signedIn: AppMcpOptions["signedIn"], keyring: KeyringStore) => { const env = home() const scriptPath = join(env.CAL_STATE_DIR, "..", "server.mjs") writeFileSync(scriptPath, FAKE_SERVER) @@ -360,7 +360,7 @@ describe("appDoctorCommand", () => { name: "Calendar", untrusted: ["event titles"], permissionExample: "events.delete=deny", - signedIn, + ...(signedIn ? { signedIn } : {}), }) const code = await run(["work", "mcp", "check", "--json"], { app, configuration, commands: () => [mcp] }, { streams, @@ -388,5 +388,11 @@ describe("appDoctorCommand", () => { expect(code).toBe(0) expect(item).toMatchObject({ healthy: false, signed_in: false }) }) + + it("is healthy for a CLI without sign-in, which gives no signedIn, and says nothing of an account", async () => { + const { code, item } = await check(undefined, memoryKeyring()) + expect(code).toBe(0) + expect(item).toMatchObject({ healthy: true, signed_in: null }) + }) }) }) diff --git a/src/cli/bot/api-http.ts b/src/cli/bot/api-http.ts index 5ec8cfaab..4f7993fca 100644 --- a/src/cli/bot/api-http.ts +++ b/src/cli/bot/api-http.ts @@ -6,13 +6,14 @@ import { providerRequest } from "../command-runs.js" import { outputFor } from "../context.js" import { itemOf, renderAnswer } from "../envelope.js" import type { ApiCommandInput } from "./api.js" -import { parseApiJson } from "./api-input.js" +import { parseApiJson, sendsBytes } from "./api-input.js" export interface HttpApiRequest { method: string url: URL headers: Headers - body?: string + /** JSON text, or an upload's bytes. */ + body?: string | Uint8Array /** `manual` for a request whose sign-in header a redirect to another host would carry along. */ redirect?: "follow" | "manual" | "error" } @@ -50,6 +51,14 @@ const segment = (name: string, value: string | undefined): string => { return encodeURIComponent(value) } +/** Why the generated command cannot send the operation's body, or `undefined` when it can: JSON, or an upload's bytes. */ +export const unsendableBody = (operation: ManifestOperation): string | undefined => { + const type = operation.request?.contentType + return type === undefined || sendsBytes(operation) + ? undefined + : `it sends ${type}, which the generated command cannot send` +} + /** One generated HTTP operation and its flags as the request they stand for; nothing is sent. */ export const httpApiRequest = ( operation: ManifestOperation, @@ -59,10 +68,10 @@ export const httpApiRequest = ( const { binding } = operation if (binding.kind !== "http") throw new CliError("configuration_error", `${operation.command} is not an HTTP operation`) - if (operation.request?.contentType) + if (unsendableBody(operation)) throw new CliError( "validation_error", - `${operation.command} sends ${operation.request.contentType}, which the generated command cannot send; nothing was sent`, + `${operation.command} sends ${operation.request?.contentType}, which the generated command cannot send; nothing was sent`, { sent: false }, ) if (operation.response?.sensitive) @@ -85,11 +94,16 @@ export const httpApiRequest = ( else url.searchParams.set(name, raw) } const headers = new Headers(input.headers) + headers.set("accept", "application/json") + if (sendsBytes(operation)) { + if (input.bytes === undefined) return { method: binding.method, url, headers } + headers.set("content-type", operation.request?.contentType as string) + return { method: binding.method, url, headers, body: input.bytes } + } const body = input.body?.trim() ? input.body : undefined // The command's checkBody may not parse the body; text that is not JSON never reaches the service. if (body !== undefined) parseApiJson(body) if (body !== undefined) headers.set("content-type", "application/json") - headers.set("accept", "application/json") return { method: binding.method, url, headers, ...(body === undefined ? {} : { body }) } } diff --git a/src/cli/bot/api-input.ts b/src/cli/bot/api-input.ts index 87dfe809c..3429a3025 100644 --- a/src/cli/bot/api-input.ts +++ b/src/cli/bot/api-input.ts @@ -66,6 +66,21 @@ export const checkApiParameter = ( } } +const JSON_BODY = /[/+]json\s*(;|$)/i +const FORM_BODY = /^(multipart\/form-data|application\/x-www-form-urlencoded)\s*(;|$)/i + +/** An upload sent as the bytes themselves, as the spec types a binary body: `application/octet-stream`, `image/png`. */ +export const sendsBytes = (operation: ManifestOperation): boolean => { + const type = operation.request?.contentType + return type !== undefined && !JSON_BODY.test(type) && !FORM_BODY.test(type) +} + +/** The file `--body-file` names, `-` for stdin, as the bytes an upload sends. */ +export const readApiBytes = ( + path: string, + read: (path: string | number) => Uint8Array = (from) => new Uint8Array(readFileSync(from)), +): Uint8Array => read(path === "-" ? 0 : path) + export const readApiBody = ( options: { body?: string; bodyFile?: string }, read: (path: string | number) => string = (path) => readFileSync(path, "utf8"), diff --git a/src/cli/bot/api.ts b/src/cli/bot/api.ts index 0e42d04d2..f2912760b 100644 --- a/src/cli/bot/api.ts +++ b/src/cli/bot/api.ts @@ -4,7 +4,7 @@ import { annotate } from "@wirecat/cli-base/commands" import { Command, Option } from "commander" import { secretInput } from "../../runs/run-context.js" import { REMOTE_READ, REMOTE_WRITE } from "../effects.js" -import { apiFlagOf, apiOptionKey, readApiBody } from "./api-input.js" +import { apiFlagOf, apiOptionKey, readApiBody, readApiBytes, sendsBytes } from "./api-input.js" export interface ApiCommandInput { path: Record @@ -12,6 +12,8 @@ export interface ApiCommandInput { headers: Record fields: Record body?: string + /** An upload's bytes, from `--body-file`. */ + bytes?: Uint8Array bodySource?: "argument" | "stdin" | "file" tokenProfile?: string } @@ -23,6 +25,8 @@ export interface ApiCommands { checkBody?: (operation: ManifestOperation, text: string | undefined) => string | undefined before?: (command: Command, operation: ManifestOperation) => void | Promise readBody?: (command: Command, options: { body?: string; bodyFile?: string }) => string | undefined + /** An upload's file, `-` for stdin. */ + readBytes?: (command: Command, path: string) => Uint8Array execute: (command: Command, operation: ManifestOperation, input: ApiCommandInput) => Promise } @@ -50,7 +54,9 @@ export const generatedApiCommand = (api: ApiCommands): Command => { ) command.addOption(parameter.required && parameter.in !== "body" ? option.makeOptionMandatory() : option) } - if (operation.request) { + if (operation.request && sendsBytes(operation)) { + command.option("--body-file ", `the file to upload, sent as ${operation.request.contentType}; - is stdin`) + } else if (operation.request) { // A field the schema marks secret may ride in an inline body, and the flags never see it. command.addOption(secretInput(new Option("--body ", "the request body as JSON; - reads it from stdin"))) command.option("--body-file ", "the request body from a JSON file; - is stdin") @@ -91,6 +97,20 @@ export const generatedApiCommand = (api: ApiCommands): Command => { target[parameter.name] = raw } await api.before?.(this, operation) + if (sendsBytes(operation)) { + const path = options.bodyFile + if (path === undefined && operation.request?.required) + throw new CliError( + "validation_error", + `${operation.command} uploads a file: give --body-file , or - for stdin`, + ) + if (path !== undefined) { + input.bytes = (api.readBytes ?? ((_command, from) => readApiBytes(from)))(this, path) + input.bodySource = path === "-" ? "stdin" : "file" + } + await api.execute(this, operation, input) + return + } const text = (api.readBody ?? ((_command, body) => readApiBody(body)))(this, options) if (options.body !== undefined) input.bodySource = options.body === "-" ? "stdin" : "argument" else if (options.bodyFile !== undefined) input.bodySource = options.bodyFile === "-" ? "stdin" : "file" diff --git a/src/cli/index.ts b/src/cli/index.ts index 997e11950..165e721ee 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -255,7 +255,13 @@ export { askBeforeWrite } from "./ask-before-write.js" export { actorOf } from "./author.js" export { type BaseStagesCommandOptions, baseStagesCommand } from "./base-stages-command.js" export type { ApiCommandInput, ApiCommands } from "./bot/api.js" -export { type HttpApiExecutorOptions, type HttpApiRequest, httpApiExecutor, httpApiRequest } from "./bot/api-http.js" +export { + type HttpApiExecutorOptions, + type HttpApiRequest, + httpApiExecutor, + httpApiRequest, + unsendableBody, +} from "./bot/api-http.js" export { apiFlagOf, apiJson, @@ -265,6 +271,8 @@ export { checkApiParameter, parseApiJson, readApiBody, + readApiBytes, + sendsBytes, } from "./bot/api-input.js" export { prepareRpcApiBody, type RpcApiBody } from "./bot/api-rpc.js" export { type BotContext, botContext, botWords } from "./bot/context.js" @@ -675,6 +683,7 @@ export { type ServiceApiOptions, type ServiceApiPermissionsInput, serviceApiKeys, + serviceApiOperations, serviceApiPermissions, } from "./service-api.js" export { type ServiceApiCall, type ServiceApiCallOptions, serviceApiCall } from "./service-api-call.js" diff --git a/src/cli/service-api-call.ts b/src/cli/service-api-call.ts index f1558c60e..d64016c59 100644 --- a/src/cli/service-api-call.ts +++ b/src/cli/service-api-call.ts @@ -15,7 +15,8 @@ export interface ServiceApiCallOptions { service: string /** The host-checked fetch with the CLI's pace and retry of reads, as the `api` group gets it. */ fetch: FetchLike - token: () => string | Promise + /** Left out, for a CLI without sign-in, no call carries one. */ + token?: () => string | Promise /** In place of the manifest's first server. */ baseUrl?: string /** Headers beside the sign-in, such as the API version. */ diff --git a/src/cli/service-api-manifest.ts b/src/cli/service-api-manifest.ts index 41348c202..2a56c1675 100644 --- a/src/cli/service-api-manifest.ts +++ b/src/cli/service-api-manifest.ts @@ -1,10 +1,13 @@ import { CliError } from "@wirecat/cli-base" -import type { - ApiServer, - ManifestOperation, - Pagination, - SecurityRequirement, - SecurityScheme, +import { + type ApiServer, + type ManifestOperation, + type Pagination, + type SecurityRequirement, + type SecurityScheme, + type SignInPlace, + signInPlace, + signInRequirements, } from "@wirecat/cli-base/codegen" import type { ApiCommandInput } from "./bot/api.js" import { apiJson, parseApiJson } from "./bot/api-input.js" @@ -37,45 +40,23 @@ export const manifestBaseUrl = (manifest: ServiceApiManifest, given?: string): s return url } -type Auth = { name: string; value: (token: string) => string; in?: "query" } - -const BEARER: Auth = { name: "authorization", value: (token) => `Bearer ${token}` } - -/** Where one scheme puts the sign-in; `undefined` for one the api cannot send (basic, a key in a cookie). */ -const headerOf = (scheme: SecurityScheme): Auth | undefined => { - if (scheme.type === "apiKey") { - if (!scheme.name) return undefined - if (scheme.in === "header") return { name: scheme.name.toLowerCase(), value: (token) => token } - return scheme.in === "query" ? { name: scheme.name, value: (token) => token, in: "query" } : undefined - } - if (scheme.type === "http") { - if (!scheme.scheme || /^bearer$/i.test(scheme.scheme)) return BEARER - return /^(basic|digest)$/i.test(scheme.scheme) - ? undefined - : { name: "authorization", value: (token) => `${scheme.scheme} ${token}` } - } - return scheme.type === "oauth2" || scheme.type === "openIdConnect" ? BEARER : undefined -} - /** - * The header, or query parameter, that carries the sign-in for one operation, from the first scheme of its requirements the api can send; - * `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer - * token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token. A header wins over a - * key in the query, which a proxy or a server log could keep. + * Where the sign-in goes for one operation: the first place its requirements' schemes name that a token can be sent + * to, a header before a key in the query, which a proxy or a server log could keep. `undefined` for a call that needs + * none: its security, its own or else the document's, is absent, as in a spec that says nothing about sign-in, or + * empty (`[]`, `[{}]`). An optional sign-in (`[{}, { oauth: [] }]`) still sends the token. */ -const authOf = (manifest: ServiceApiManifest, operation: ManifestOperation): Auth | undefined => { - const requirements = operation.security ?? manifest.security - if (requirements?.every((one) => Object.keys(one).length === 0)) return undefined - if (!manifest.securitySchemes) return BEARER - const names = (requirements ?? []).flatMap((one) => Object.keys(one)) +const authOf = (manifest: ServiceApiManifest, operation: ManifestOperation): SignInPlace | undefined => { + const requirements = signInRequirements(operation, manifest.security) + if (!requirements) return undefined + const names = requirements.flatMap((one) => Object.keys(one)) const sendable = names.flatMap((name) => { const scheme = manifest.securitySchemes?.[name] - const auth = scheme && headerOf(scheme) - return auth ? [auth] : [] + const place = scheme && signInPlace(scheme) + return place ? [place] : [] }) - const auth = sendable.find((one) => one.in === undefined) ?? sendable[0] + const auth = sendable.find((one) => one.in === "header") ?? sendable[0] if (auth) return auth - if (names.length === 0) return BEARER throw new CliError( "configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`, @@ -85,14 +66,16 @@ const authOf = (manifest: ServiceApiManifest, operation: ManifestOperation): Aut /** * Signs one request for its operation. Set the final URL first: a key in the query goes into it. Anything but the * standard sign-in header, or a key in the query, never follows a redirect, even to the same host: another host would - * get the key. The URL then holds the key, so a fetch wrapper must not log it. + * get the key. The URL then holds the key, so a fetch wrapper must not log it. Without `token`, for a CLI that never + * signs in, nothing is added. */ export const signRequest = async ( manifest: ServiceApiManifest, operation: ManifestOperation, request: { url: URL; headers: Headers; redirect?: "follow" | "manual" | "error" }, - token: () => Promise | string, + token: (() => Promise | string) | undefined, ): Promise => { + if (!token) return const auth = authOf(manifest, operation) if (!auth) return const value = auth.value(await token()) diff --git a/src/cli/service-api.test.ts b/src/cli/service-api.test.ts index 5191d95be..9a39d4dbc 100644 --- a/src/cli/service-api.test.ts +++ b/src/cli/service-api.test.ts @@ -221,12 +221,21 @@ const api = { }, } -type Sent = { method: string; url: string; body?: string; authorization?: string; key?: string; redirect?: string } +type Sent = { + method: string + url: string + body?: string + bytes?: number[] + type?: string + authorization?: string + key?: string + redirect?: string +} const fixture = ( saved: Record = {}, answer: (sent: Sent) => Response = () => Response.json({ object: "page", id: "p1" }), - over: Partial = {}, + over: Partial & { signsIn?: false } = {}, ) => { const root = mkdtempSync(join(tmpdir(), "service-api-")) const env = { @@ -264,6 +273,9 @@ const fixture = ( method: init?.method ?? "GET", url: String(input), ...(typeof init?.body === "string" ? { body: init.body } : {}), + ...(init?.body instanceof Uint8Array + ? { bytes: [...init.body], type: headers.get("content-type") ?? "" } + : {}), ...(authorization ? { authorization } : {}), ...(key ? { key, redirect: String(init?.redirect) } : {}), } @@ -271,7 +283,7 @@ const fixture = ( return answer(one) }, }), - token: () => "page-token", + ...(over.signsIn === false ? {} : { token: () => "page-token" }), headers: () => ({ "pages-version": "2026-03-11" }), schemas: async () => { loads.schemas++ @@ -334,6 +346,64 @@ describe("the shared service api group", () => { expect(sent).toEqual([{ method: "GET", url: "https://api.pages.test/v1/status" }]) }) + it("**sends no sign-in where the spec names none, or for a CLI without one**, the token never read", async () => { + const silent = fixture({}, undefined, { + manifest: { operations, ...(manifest.servers ? { servers: manifest.servers } : {}) }, + }) + expect((await silent.cli("work", "api", "retrieve-a-page", "--page-id", "p1", "--json")).code).toBe(0) + expect(silent.sent).toEqual([{ method: "GET", url: "https://api.pages.test/v1/pages/p1" }]) + const unsigned = fixture({}, undefined, { signsIn: false }) + expect((await unsigned.cli("work", "api", "retrieve-a-page", "--page-id", "p1", "--json")).code).toBe(0) + expect(unsigned.sent).toEqual([{ method: "GET", url: "https://api.pages.test/v1/pages/p1" }]) + }) + + it("**uploads a file's bytes with --body-file**, as Petstore's octet-stream body, and leaves out a multipart form", async () => { + const http = (path: string) => ({ kind: "http" as const, method: "POST" as const, path }) + const upload: Operation = { + id: "uploadFile", + command: "upload-file", + binding: http("/pages/{page_id}/image"), + effect: "write", + tags: [], + parameters: [page("page_id")], + request: { required: false, confidence: "contract", contentType: "application/octet-stream" }, + } + const form: Operation = { + id: "importContacts", + command: "import-contacts", + binding: http("/imports"), + effect: "write", + tags: [], + parameters: [], + request: { required: true, confidence: "contract", contentType: "multipart/form-data" }, + } + const { cli, sent, root, env } = fixture({ api: "allow" }, undefined, { + manifest: { ...manifest, operations: [...operations, upload, form] }, + }) + const image = join(root, "pet.png") + writeFileSync(image, new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff])) + expect((await cli("work", "api", "upload-file", "--page-id", "p1", "--body-file", image, "--json")).code).toBe(0) + expect(sent).toEqual([ + { + method: "POST", + url: "https://api.pages.test/v1/pages/p1/image", + bytes: [0x89, 0x50, 0x4e, 0x47, 0x00, 0xff], + type: "application/octet-stream", + authorization: "OAuth page-token", + }, + ]) + expect((await cli("work", "api", "upload-file", "--page-id", "p1", "--body", "{}", "--json")).code).not.toBe(0) + const inside = join(env.PAGES_CONFIG_DIR, "config.json") + const refused = await cli("work", "api", "upload-file", "--page-id", "p1", "--body-file", inside, "--json") + expect(refused.error).toMatchObject({ code: "validation_error" }) + expect((await cli("api", "show", "import-contacts", "--json")).error?.message).toBe( + "import-contacts is not offered: it sends multipart/form-data, which the generated command cannot send", + ) + const listed = await cli("api", "list", "--json") + expect(listed.json.items.map((one: { command: string }) => one.command)).not.toContain("import-contacts") + expect(sent).toHaveLength(1) + }) + it("**offers no free-form call, no --store-token and no credential-returning operation**", async () => { const group = createProgram(fixture().definition).commands.find((one) => one.name() === "api") const paths = JSON.stringify( diff --git a/src/cli/service-api.ts b/src/cli/service-api.ts index 1771c92c0..9924c4c2c 100644 --- a/src/cli/service-api.ts +++ b/src/cli/service-api.ts @@ -13,8 +13,8 @@ import { levelFor } from "../sends/permissions.js" import { newOperationId } from "../sends/send-id.js" import { refusedPlace } from "../sends/upload.js" import { type ApiCommandInput, generatedApiCommand } from "./bot/api.js" -import { type HttpApiRequest, httpApiRequest, httpApiSend } from "./bot/api-http.js" -import { checkApiBody, checkApiParameter, parseApiJson, readApiBody } from "./bot/api-input.js" +import { type HttpApiRequest, httpApiRequest, httpApiSend, unsendableBody } from "./bot/api-http.js" +import { checkApiBody, checkApiParameter, parseApiJson, readApiBody, readApiBytes } from "./bot/api-input.js" import { baseContext, outputFor } from "./context.js" import { NO_EFFECTS } from "./effects.js" import { itemOf, listOf, renderAnswer } from "./envelope.js" @@ -55,8 +55,11 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput { baseUrl?: string /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */ fetch: (command: Command) => FetchLike - /** The profile's token, sent in the header the operation's security scheme names. Read before any guard asks. */ - token: (command: Command) => string | Promise + /** + * The profile's token, sent where the operation's security scheme names. Read before any guard asks. Left out, for a + * CLI without sign-in, no call carries one. + */ + token?: (command: Command) => string | Promise /** Headers beside the sign-in, such as the API version. */ headers?: (command: Command, operation: ManifestOperation) => Record /** Loaded only once an operation is about to check its input: a large spec is megabytes of code. */ @@ -70,6 +73,25 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput { failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined } +/** + * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a + * bot's `--store-token`, as a service CLI signs in through `session`; a body other than JSON or an upload's bytes (a + * multipart form) the generated command cannot send. + */ +export const serviceApiOperations = ( + manifest: ServiceApiManifest, +): { offered: readonly ManifestOperation[]; left: readonly { id: string; reason: string }[] } => { + const reasonOf = (operation: ManifestOperation) => + operation.response?.sensitive ? "it returns a credential, which is never printed" : unsendableBody(operation) + return { + offered: manifest.operations.filter((operation) => reasonOf(operation) === undefined), + left: manifest.operations.flatMap((operation) => { + const reason = reasonOf(operation) + return reason ? [{ id: operation.id, reason }] : [] + }), + } +} + /** How far `--all` reads: a service that never stops paging must not run a command forever. */ const MOST_PAGES = 500 @@ -174,8 +196,7 @@ const API_QUERY = { */ export const serviceApiCommand = (options: ServiceApiOptions): Command => { const { app, configuration, manifest } = options - // A credential-returning operation needs a bot's `--store-token`; a service CLI signs in through `session` instead. - const operations = manifest.operations.filter((operation) => !operation.response?.sensitive) + const { offered: operations, left } = serviceApiOperations(manifest) const baseUrl = manifestBaseUrl(manifest, options.baseUrl) const base = new URL(baseUrl) const own = serviceApiPermissions(options) @@ -212,21 +233,19 @@ export const serviceApiCommand = (options: ServiceApiOptions): Command => { const operationOf = (name: string): ManifestOperation => { const found = operations.find((operation) => operation.command === name || operation.id === name) if (found) return found - const left = - options.excluded?.find((one) => one.id === name) ?? - (manifest.operations.some((one) => one.command === name || one.id === name) - ? { reason: "it returns a credential, which is never printed" } - : undefined) + const id = manifest.operations.find((one) => one.command === name || one.id === name)?.id ?? name + const why = options.excluded?.find((one) => one.id === name) ?? left.find((one) => one.id === id) throw new CliError( "not_found", - left - ? `${name} is not offered: ${left.reason}` + why + ? `${name} is not offered: ${why.reason}` : `no ${options.service} API operation ${name}; see ${app.command} api list`, ) } const signed = async (command: Command, operation: ManifestOperation, request: HttpApiRequest) => { - await signRequest(manifest, operation, request, () => options.token(command)) + const { token } = options + await signRequest(manifest, operation, request, token && (() => token(command))) for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {})) request.headers.set(name, value) return request @@ -310,21 +329,25 @@ export const serviceApiCommand = (options: ServiceApiOptions): Command => { ) } + const refuseOwnFiles = (command: Command, path: string) => { + if (path === "-") return + const { env } = baseContext(command, configuration.resolveSettings) + if (refusedPlace(path, app, env)) + throw new CliError("validation_error", `--body-file may not read ${path}: it holds sign-ins or state`) + } + const generated = generatedApiCommand({ operations, checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()), checkBody: (operation, text) => checkApiBody(operation, text, loaded()), readBody: (command, body) => { - if (body.bodyFile !== undefined && body.bodyFile !== "-") { - const { env } = baseContext(command, configuration.resolveSettings) - if (refusedPlace(body.bodyFile, app, env)) - throw new CliError( - "validation_error", - `--body-file may not read ${body.bodyFile}: it holds sign-ins or state`, - ) - } + if (body.bodyFile !== undefined) refuseOwnFiles(command, body.bodyFile) return readApiBody(body) }, + readBytes: (command, path) => { + refuseOwnFiles(command, path) + return readApiBytes(path) + }, execute: async (command, operation, input) => { const extra = serviceApiKeys(options, operation, input) if (operation.pagination && command.opts<{ all?: unknown }>().all === true) { From 5184d89b17fc8f2580766eb31f4cf1a0bcf768ac Mon Sep 17 00:00:00 2001 From: leemour Date: Tue, 17 Nov 2026 17:31:21 +0100 Subject: [PATCH 2/2] chore(deps): cli-base 0.112.0, peer floor >=0.112.0; STANDARD.md tables follow Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- pnpm-lock.yaml | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 68da742fe..d82282cbe 100644 --- a/package.json +++ b/package.json @@ -301,7 +301,7 @@ "@types/pngjs": "6.0.5", "@types/ssh2": "1.15.5", "@vitest/coverage-v8": "^5.0.5", - "@wirecat/cli-base": "0.111.0", + "@wirecat/cli-base": "0.112.0", "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0", "ajv": "8.17.1", "commander": "15.0.0", @@ -325,7 +325,7 @@ }, "peerDependencies": { "@napi-rs/canvas": ">=0.1.69 <2", - "@wirecat/cli-base": ">=0.108.0 <1.0.0", + "@wirecat/cli-base": ">=0.112.0 <1.0.0", "commander": ">=15", "mysql2": "^3.24.6", "pg": "^8.23.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cbd37352a..0b9068b9b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -177,11 +177,11 @@ importers: specifier: ^5.0.5 version: 5.0.5(vitest@5.0.5) '@wirecat/cli-base': - specifier: 0.111.0 - version: 0.111.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) + specifier: 0.112.0 + version: 0.112.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) '@wirecat/cli-core-legacy-tags': specifier: npm:@wirecat/cli-core@0.414.0 - version: '@wirecat/cli-core@0.414.0(@napi-rs/canvas@1.0.13)(@wirecat/cli-base@0.111.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)' + version: '@wirecat/cli-core@0.414.0(@napi-rs/canvas@1.0.13)(@wirecat/cli-base@0.112.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)' ajv: specifier: 8.17.1 version: 8.17.1 @@ -1373,8 +1373,8 @@ packages: '@wasm-audio-decoders/opus-ml@0.0.3': resolution: {integrity: sha512-SEeTmk0eb3q5etJA/NHCRWW6BivTx9tqvNTmG0kg2ynuATEQRUZnwQE6Ibvl1BBvqIGHqI57+qyJMWmJBwb5XQ==} - '@wirecat/cli-base@0.111.0': - resolution: {integrity: sha512-0w8wbpE0l55iTv5UUdLEJctBuCSRaz57OXaP69lDMagbFZJrkO38ANOkBAT3lStuBxWwaVvYqubUiBQYlyrRQQ==} + '@wirecat/cli-base@0.112.0': + resolution: {integrity: sha512-TMk4qGU/C4vb3rEphKTkH6mAriIDXW4qnmReH37+TLp0f9ngDBJPZfNqVN5UlG1rKqWOCzomk+jY2Ynf5HUnAQ==} engines: {node: '>=22'} hasBin: true peerDependencies: @@ -3766,7 +3766,7 @@ snapshots: dependencies: '@wasm-audio-decoders/common': 9.0.7 - '@wirecat/cli-base@0.111.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5)': + '@wirecat/cli-base@0.112.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5)': dependencies: '@valibot/to-json-schema': 1.8.0(valibot@1.5.0(typescript@7.0.2)) cli-table3: 0.6.5 @@ -3792,7 +3792,7 @@ snapshots: '@wirecat/cli-core-sqlite@1.1.0': {} - '@wirecat/cli-core@0.414.0(@napi-rs/canvas@1.0.13)(@wirecat/cli-base@0.111.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': + '@wirecat/cli-core@0.414.0(@napi-rs/canvas@1.0.13)(@wirecat/cli-base@0.112.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 0.131.0(zod@4.6.7) '@bomb.sh/tab': 0.0.22(commander@15.0.0) @@ -3800,7 +3800,7 @@ snapshots: '@modelcontextprotocol/server': 2.3.0 '@resvg/resvg-js': 2.6.2 '@valibot/to-json-schema': 1.8.0(valibot@1.5.0(typescript@7.0.2)) - '@wirecat/cli-base': 0.111.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) + '@wirecat/cli-base': 0.112.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) '@wirecat/cli-core-onnx': 1.0.1 '@wirecat/cli-core-sqlite': 1.0.1 '@xmldom/xmldom': 0.9.12