@wirecat/cli-core 0.692.0 → 0.694.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +1 -1
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/calendar/prepare.d.ts +11 -0
  5. package/dist/cli/bot/api-http.d.ts +4 -1
  6. package/dist/cli/bot/api-http.js +17 -4
  7. package/dist/cli/bot/api-input.d.ts +4 -0
  8. package/dist/cli/bot/api-input.js +9 -0
  9. package/dist/cli/bot/api.d.ts +4 -0
  10. package/dist/cli/bot/api.js +16 -2
  11. package/dist/cli/documents/words.d.ts +1 -1
  12. package/dist/cli/envelope.d.ts +22 -0
  13. package/dist/cli/index.d.ts +6 -4
  14. package/dist/cli/index.js +6 -4
  15. package/dist/cli/oauth-session.d.ts +60 -0
  16. package/dist/cli/oauth-session.js +224 -0
  17. package/dist/cli/service-api-call.d.ts +2 -1
  18. package/dist/cli/service-api-call.js +4 -6
  19. package/dist/cli/service-api-manifest.d.ts +10 -10
  20. package/dist/cli/service-api-manifest.js +37 -33
  21. package/dist/cli/service-api.d.ts +17 -2
  22. package/dist/cli/service-api.js +42 -24
  23. package/dist/cli/token-session.d.ts +33 -0
  24. package/dist/cli/token-session.js +121 -0
  25. package/dist/crm/index.d.ts +2 -1
  26. package/dist/crm/index.js +1 -0
  27. package/dist/crm/manifest/manifest.d.ts +19 -0
  28. package/dist/crm/manifest/manifest.js +6 -1
  29. package/dist/crm/manifest/map.d.ts +5 -0
  30. package/dist/crm/manifest/map.js +21 -15
  31. package/dist/crm/manifest/paths.d.ts +11 -0
  32. package/dist/crm/manifest/paths.js +161 -0
  33. package/dist/crm/manifest/source.js +105 -34
  34. package/dist/manifest/index.d.ts +53 -0
  35. package/dist/manifest/index.js +61 -0
  36. package/dist/search/lucene/plain.js +2 -1
  37. package/dist/services/metadata.d.ts +1 -1
  38. package/package.json +7 -3
@@ -0,0 +1,224 @@
1
+ import { CliError, isMovedRun, resolvePaths, systemKeyring } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { hostFetch } from "@wirecat/cli-base/http";
4
+ import { Command } from "commander";
5
+ import { tokenKeeper } from "../oauth/keeper.js";
6
+ import { credentialStorage, oauthAccount, standardCodec } from "../oauth/storage.js";
7
+ import { editDistance } from "../search/correct.js";
8
+ import { signInSteps } from "../terminal/sign-in-steps.js";
9
+ import { baseContext, environmentOf, outputFor } from "./context.js";
10
+ import { refuseOffline } from "./early-refusal.js";
11
+ import { LOCAL_READ, LOCAL_WRITE, logsInOrOut, REMOTE_READ, REMOTE_WRITE } from "./effects.js";
12
+ import { itemOf, listOf, renderAnswer } from "./envelope.js";
13
+ import { profilesHere, rememberAccount } from "./messenger/accounts.js";
14
+ import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
15
+ import { storageOf } from "./token-session.js";
16
+ /** The authorization code flow an OpenAPI spec declares; a GraphQL service (Linear) writes the same object by hand. */
17
+ export const oauthFlowOf = (manifest, scheme) => {
18
+ const schemes = Object.entries(manifest.securitySchemes ?? {}).filter(([name, one]) => (scheme === undefined || name === scheme) && one.flows?.authorizationCode !== undefined);
19
+ const flow = schemes.length === 1 ? schemes[0]?.[1].flows?.authorizationCode : undefined;
20
+ if (!flow?.authorizationUrl || !flow.tokenUrl)
21
+ throw new CliError("configuration_error", schemes.length > 1
22
+ ? `the api has ${schemes.length} OAuth sign-ins in the browser; name one`
23
+ : `the api declares no OAuth authorization code flow with its URLs${scheme ? ` under ${scheme}` : ""}`);
24
+ return flow;
25
+ };
26
+ /** An installed app's sign-in (authorization code with PKCE) from the flow a spec declares, and the scopes it asks. */
27
+ export const oauthPreset = (flow, options) => {
28
+ const known = Object.keys(flow.scopes);
29
+ const unknown = options.scopes.filter((scope) => !known.includes(scope));
30
+ if (unknown.length)
31
+ throw new CliError("configuration_error", unknown
32
+ .map((scope) => {
33
+ const near = known.find((one) => editDistance(scope, one, 2) <= 2);
34
+ return `the ${options.name} sign-in has no scope ${scope}${near ? `; did you mean ${near}?` : ""}`;
35
+ })
36
+ .join("; "));
37
+ if (flow.refreshUrl && flow.refreshUrl !== flow.tokenUrl)
38
+ throw new CliError("configuration_error", `${options.name} refreshes at another URL, which the sign-in cannot use`);
39
+ const plain = [flow.authorizationUrl, flow.tokenUrl, options.revokeUrl].find((url) => url !== undefined && !url.startsWith("https://"));
40
+ // The code, the client secret and the tokens would cross the network in the clear.
41
+ if (plain)
42
+ throw new CliError("configuration_error", `${options.name} signs in at ${plain}, which is not https`);
43
+ const provider = {
44
+ id: options.id,
45
+ name: options.name,
46
+ authorizeUrl: flow.authorizationUrl,
47
+ tokenUrl: flow.tokenUrl,
48
+ client: options.client,
49
+ redirect: options.redirect,
50
+ ...(options.revokeUrl ? { revokeUrl: options.revokeUrl } : {}),
51
+ ...(options.authorizeParams ? { authorizeParams: options.authorizeParams } : {}),
52
+ };
53
+ return { provider, scopes: [...options.scopes], rotating: options.rotating === true };
54
+ };
55
+ /**
56
+ * `session start | status | end | list` for a service signed in in the browser (WC-SECR-22): PKCE on the loopback,
57
+ * the account checked before the tokens are kept, refreshes under one lock, and a run with moved folders that never
58
+ * removes the owner's sign-in.
59
+ */
60
+ export const oauthSessionCommand = (options) => {
61
+ const { app, providerId, service } = options;
62
+ const pathsOf = (env) => ({ appName: app.appName, prefix: app.envPrefix, env });
63
+ const storageFor = (where, profile, storage = "auto", rotating = false) => credentialStorage({
64
+ credentials: {
65
+ service: app.appName,
66
+ configDir: resolvePaths(pathsOf(where.env)).config,
67
+ storage,
68
+ env: where.env,
69
+ isolated: isMovedRun(pathsOf(where.env)),
70
+ keyring: where.keyring ?? systemKeyring,
71
+ ...(where.warn ? { warn: where.warn } : {}),
72
+ },
73
+ account: oauthAccount(providerId, profile),
74
+ codec: rotating ? { ...standardCodec(providerId), rotating: true } : standardCodec(providerId),
75
+ });
76
+ const contextOf = (command) => {
77
+ const base = baseContext(command, options.resolveSettings);
78
+ const environment = environmentOf(command);
79
+ const where = { env: base.env, keyring: base.keyring, warn: base.renderer.warn };
80
+ const { profile } = base.settings;
81
+ /** The preset is asked only here, after the refusals: a CLI's client choice may fail on its own. */
82
+ const keeperOf = (storage) => {
83
+ const { provider, scopes, rotating } = options.preset(command);
84
+ const keeper = tokenKeeper({
85
+ provider,
86
+ storage: storageFor(where, profile, storage ?? "auto", rotating),
87
+ lockDir: resolvePaths(pathsOf(base.env)).config,
88
+ // Only the provider's own sign-in hosts: a token request never reaches anything else.
89
+ fetch: environment.fetch ??
90
+ hostFetch({
91
+ hosts: [provider.authorizeUrl, provider.tokenUrl, provider.revokeUrl]
92
+ .filter((url) => url !== undefined)
93
+ .map((url) => new URL(url).hostname),
94
+ }),
95
+ signInCommand: `${app.command} ${profile} session start`,
96
+ ...(environment.signal ? { signal: environment.signal } : {}),
97
+ });
98
+ return { keeper, scopes };
99
+ };
100
+ const saved = () => storageFor(where, profile).read();
101
+ return { ...base, environment, where, profile, keeperOf, saved };
102
+ };
103
+ const answer = (command, item) => renderAnswer(command, outputFor(command), itemOf(item));
104
+ const start = logsInOrOut(annotate(new Command("start"), {
105
+ effects: REMOTE_WRITE,
106
+ lifetime: "interactive",
107
+ mcp: false,
108
+ examples: [`${app.command} personal session start`, `${app.command} personal session start --no-browser`],
109
+ }))
110
+ .summary(`sign in to ${service} in the browser`)
111
+ .description(`sign this profile in to ${service} in the browser; the account is checked before anything is kept, in the ` +
112
+ "keyring or, with --credential-storage file, a private file")
113
+ .option("--no-browser", "print the sign-in URL instead of opening a browser")
114
+ .option("--credential-storage <storage>", "where the sign-in is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring")
115
+ .action(async function (args) {
116
+ const context = contextOf(this);
117
+ refuseCommandName(context.profile, commandWords(rootOf(this)), app.command);
118
+ refuseOffline(this, service);
119
+ const { keeper, scopes: asked } = context.keeperOf(args.credentialStorage === "file" ? "file" : undefined);
120
+ const { streams } = outputFor(this);
121
+ const steps = signInSteps({
122
+ diagnostic: (line) => streams.diagnostic(`${line}\n`),
123
+ json: context.format !== "pretty" || context.environment.tty === false,
124
+ answers: false,
125
+ });
126
+ let shown = {};
127
+ const { scopes } = await context.run((events) => keeper.signIn({
128
+ scopes: asked,
129
+ openBrowser: async (url) => {
130
+ if (args.browser)
131
+ await context.environment.openBrowser?.(url, this);
132
+ },
133
+ showUrl: (url) => {
134
+ steps.openUrl(url, `Sign in to ${service} and allow access`);
135
+ streams.diagnostic(`Open ${service} sign-in: ${url}\n`);
136
+ },
137
+ // Before anything is saved, so a refused account leaves the profile's sign-in as it was.
138
+ accept: async (tokens) => {
139
+ if (!tokens.accessToken)
140
+ throw new CliError("authentication_error", `${service} returned no access token`);
141
+ const { id, account } = await options.verify(this, tokens.accessToken, events);
142
+ (options.claim ?? ((env, profile, key) => rememberAccount(app, profile, key, env)))(context.env, context.profile, id);
143
+ shown = account;
144
+ return undefined;
145
+ },
146
+ }));
147
+ // The owner chose the file: an older keyring copy must not outlive it with a live refresh token.
148
+ if (args.credentialStorage === "file")
149
+ try {
150
+ storageFor(context.where, context.profile, "keyring").remove();
151
+ }
152
+ catch {
153
+ // No keyring on this computer: there is no copy to forget.
154
+ }
155
+ answer(this, { ...shown, profile: context.profile, signed_in: true, scopes });
156
+ });
157
+ const status = annotate(new Command("status"), {
158
+ effects: REMOTE_READ,
159
+ examples: [`${app.command} personal session status`, `${app.command} personal session status --check --json`],
160
+ })
161
+ .summary("show this profile's sign-in; tokens are never printed")
162
+ .description(`show this profile's sign-in and its scopes, never a token; --check asks ${service} whose it is`)
163
+ .option("--check", `ask ${service} whether the sign-in still works, and whose it is`)
164
+ .action(async function (args) {
165
+ const context = contextOf(this);
166
+ const saved = context.saved();
167
+ if (!saved)
168
+ return answer(this, { profile: context.profile, state: "missing", verified: false });
169
+ const state = { profile: context.profile, state: "saved", scopes: saved.tokens.scopes };
170
+ if (!args.check)
171
+ return answer(this, { ...state, verified: false });
172
+ refuseOffline(this, service);
173
+ const { keeper } = context.keeperOf();
174
+ const { account } = await context.run(async (events) => options.verify(this, await keeper.accessToken(), events));
175
+ answer(this, { ...account, ...state, verified: true });
176
+ });
177
+ const end = logsInOrOut(annotate(new Command("end"), {
178
+ effects: LOCAL_WRITE,
179
+ mcp: false,
180
+ examples: [`${app.command} personal session end`],
181
+ }))
182
+ .summary("sign this profile out on this computer")
183
+ .description(`forget this profile's sign-in on this computer; the grant stays in ${service}, and a run with moved folders ` +
184
+ "never removes the owner's sign-in")
185
+ .action(async function () {
186
+ const context = contextOf(this);
187
+ if (!context.saved())
188
+ return answer(this, { profile: context.profile, ended: false });
189
+ const { removed } = await context.keeperOf().keeper.signOut();
190
+ if (!context.saved())
191
+ return answer(this, { profile: context.profile, ended: true, removed });
192
+ answer(this, {
193
+ profile: context.profile,
194
+ ended: false,
195
+ removed,
196
+ why: isMovedRun(pathsOf(context.env))
197
+ ? "this run has moved folders: the owner's sign-in in the system keyring stays, and this run still reads it"
198
+ : "the sign-in could not be removed from the keyring",
199
+ });
200
+ });
201
+ const list = profileFree(annotate(new Command("list"), {
202
+ effects: LOCAL_READ,
203
+ examples: [`${app.command} session list`, `${app.command} session list --json`],
204
+ }))
205
+ .summary("list the profiles here and whether each is signed in")
206
+ .description("list the profiles on this computer and whether each is signed in; picks none")
207
+ .action(function () {
208
+ const environment = environmentOf(this);
209
+ const env = environment.env ?? process.env;
210
+ const { configuredProfiles } = options.resolveSettings({}, { env, needsProfile: false });
211
+ const where = { env, keyring: environment.keyring, warn: outputFor(this).renderer.warn };
212
+ const items = profilesHere(app, configuredProfiles, env).map((profile) => ({
213
+ profile,
214
+ signed_in: storageFor(where, profile).read() !== undefined,
215
+ }));
216
+ renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
217
+ });
218
+ return annotate(new Command("session"), { effects: LOCAL_READ })
219
+ .description(`sign in to ${service} in the browser and manage this profile's sign-in`)
220
+ .addCommand(start)
221
+ .addCommand(status)
222
+ .addCommand(end)
223
+ .addCommand(list);
224
+ };
@@ -11,7 +11,8 @@ export interface ServiceApiCallOptions {
11
11
  service: string;
12
12
  /** The host-checked fetch with the CLI's pace and retry of reads, as the `api` group gets it. */
13
13
  fetch: FetchLike;
14
- token: () => string | Promise<string>;
14
+ /** Left out, for a CLI without sign-in, no call carries one. */
15
+ token?: () => string | Promise<string>;
15
16
  /** In place of the manifest's first server. */
16
17
  baseUrl?: string;
17
18
  /** Headers beside the sign-in, such as the API version. */
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { Command } from "commander";
3
3
  import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
4
- import { authHeader, manifestBaseUrl } from "./service-api-manifest.js";
4
+ import { manifestBaseUrl, signRequest } from "./service-api-manifest.js";
5
5
  // The run record and the fetch are the only things httpApiSend asks a command for, and a sync has no command of its own.
6
6
  const NO_COMMAND = new Command("source");
7
7
  /**
@@ -23,11 +23,9 @@ export const serviceApiCall = (options) => {
23
23
  const extra = Object.entries(options.headers?.(operation) ?? {});
24
24
  for (const [name, value] of extra)
25
25
  request.headers.set(name, value);
26
- const auth = authHeader(options.manifest, operation);
27
- if (auth)
28
- request.headers.set(auth.name, auth.value(await options.token()));
29
- // A redirect to another host drops only the standard sign-in headers; an API key or a hook's header would go along.
30
- if ((auth && auth.name !== "authorization") || extra.length)
26
+ await signRequest(options.manifest, operation, request, options.token);
27
+ // A redirect to another host drops only the standard sign-in headers; a hook's header would go along.
28
+ if (extra.length)
31
29
  request.redirect = "manual";
32
30
  return send(NO_COMMAND, operation, request);
33
31
  };
@@ -1,4 +1,4 @@
1
- import type { ApiServer, ManifestOperation, Pagination, SecurityRequirement, SecurityScheme } from "@wirecat/cli-base/codegen";
1
+ import { type ApiServer, type ManifestOperation, type Pagination, type SecurityRequirement, type SecurityScheme } from "@wirecat/cli-base/codegen";
2
2
  import type { ApiCommandInput } from "./bot/api.js";
3
3
  /** What `generate` writes into a CLI's `generated/manifest.ts`: `import * as manifest from "./generated/manifest.js"`. */
4
4
  export interface ServiceApiManifest {
@@ -12,16 +12,17 @@ export interface ServiceApiManifest {
12
12
  * free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
13
13
  */
14
14
  export declare const manifestBaseUrl: (manifest: ServiceApiManifest, given?: string) => string;
15
- type Auth = {
16
- name: string;
17
- value: (token: string) => string;
18
- };
19
15
  /**
20
- * The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
21
- * `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
22
- * token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
16
+ * Signs one request for its operation. Set the final URL first: a key in the query goes into it. Anything but the
17
+ * standard sign-in header, or a key in the query, never follows a redirect, even to the same host: another host would
18
+ * get the key. The URL then holds the key, so a fetch wrapper must not log it. Without `token`, for a CLI that never
19
+ * signs in, nothing is added.
23
20
  */
24
- export declare const authHeader: (manifest: ServiceApiManifest, operation: ManifestOperation) => Auth | undefined;
21
+ export declare const signRequest: (manifest: ServiceApiManifest, operation: ManifestOperation, request: {
22
+ url: URL;
23
+ headers: Headers;
24
+ redirect?: "follow" | "manual" | "error";
25
+ }, token: (() => Promise<string> | string) | undefined) => Promise<void>;
25
26
  export declare const parameterValue: (input: ApiCommandInput, parameter: {
26
27
  in: "query" | "body";
27
28
  name: string;
@@ -41,4 +42,3 @@ export interface PageStep {
41
42
  }
42
43
  /** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
43
44
  export declare const nextPage: (pagination: Pagination, input: ApiCommandInput, answer: unknown) => PageStep;
44
- export {};
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { signInPlace, signInRequirements, } from "@wirecat/cli-base/codegen";
2
3
  import { apiJson, parseApiJson } from "./bot/api-input.js";
3
4
  /**
4
5
  * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
@@ -19,44 +20,47 @@ export const manifestBaseUrl = (manifest, given) => {
19
20
  throw new CliError("configuration_error", `the api's server ${url} is not https`);
20
21
  return url;
21
22
  };
22
- const BEARER = { name: "authorization", value: (token) => `Bearer ${token}` };
23
- /** The header one scheme signs in with; `undefined` for one the api cannot send (basic, a key in the query). */
24
- const headerOf = (scheme) => {
25
- if (scheme.type === "apiKey")
26
- return scheme.in === "header" && scheme.name
27
- ? { name: scheme.name.toLowerCase(), value: (token) => token }
28
- : undefined;
29
- if (scheme.type === "http") {
30
- if (!scheme.scheme || /^bearer$/i.test(scheme.scheme))
31
- return BEARER;
32
- return /^(basic|digest)$/i.test(scheme.scheme)
33
- ? undefined
34
- : { name: "authorization", value: (token) => `${scheme.scheme} ${token}` };
35
- }
36
- return scheme.type === "oauth2" || scheme.type === "openIdConnect" ? BEARER : undefined;
37
- };
38
23
  /**
39
- * The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
40
- * `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
41
- * token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
24
+ * Where the sign-in goes for one operation: the first place its requirements' schemes name that a token can be sent
25
+ * to, a header before a key in the query, which a proxy or a server log could keep. `undefined` for a call that needs
26
+ * none: its security, its own or else the document's, is absent, as in a spec that says nothing about sign-in, or
27
+ * empty (`[]`, `[{}]`). An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
42
28
  */
43
- export const authHeader = (manifest, operation) => {
44
- const requirements = operation.security ?? manifest.security;
45
- if (requirements?.every((one) => Object.keys(one).length === 0))
29
+ const authOf = (manifest, operation) => {
30
+ const requirements = signInRequirements(operation, manifest.security);
31
+ if (!requirements)
46
32
  return undefined;
47
- if (!manifest.securitySchemes)
48
- return BEARER;
49
- const names = (requirements ?? []).flatMap((one) => Object.keys(one));
50
- for (const name of names) {
51
- const scheme = manifest.securitySchemes[name];
52
- const auth = scheme && headerOf(scheme);
53
- if (auth)
54
- return auth;
55
- }
56
- if (names.length === 0)
57
- return BEARER;
33
+ const names = requirements.flatMap((one) => Object.keys(one));
34
+ const sendable = names.flatMap((name) => {
35
+ const scheme = manifest.securitySchemes?.[name];
36
+ const place = scheme && signInPlace(scheme);
37
+ return place ? [place] : [];
38
+ });
39
+ const auth = sendable.find((one) => one.in === "header") ?? sendable[0];
40
+ if (auth)
41
+ return auth;
58
42
  throw new CliError("configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`);
59
43
  };
44
+ /**
45
+ * Signs one request for its operation. Set the final URL first: a key in the query goes into it. Anything but the
46
+ * standard sign-in header, or a key in the query, never follows a redirect, even to the same host: another host would
47
+ * get the key. The URL then holds the key, so a fetch wrapper must not log it. Without `token`, for a CLI that never
48
+ * signs in, nothing is added.
49
+ */
50
+ export const signRequest = async (manifest, operation, request, token) => {
51
+ if (!token)
52
+ return;
53
+ const auth = authOf(manifest, operation);
54
+ if (!auth)
55
+ return;
56
+ const value = auth.value(await token());
57
+ if (auth.in === "query")
58
+ request.url.searchParams.set(auth.name, value);
59
+ else
60
+ request.headers.set(auth.name, value);
61
+ if (auth.in === "query" || auth.name !== "authorization")
62
+ request.redirect = "manual";
63
+ };
60
64
  const at = (value, path) => path
61
65
  .split(".")
62
66
  .reduce((inner, key) => (inner && typeof inner === "object" ? inner[key] : undefined), value);
@@ -32,8 +32,11 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
32
32
  baseUrl?: string;
33
33
  /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
34
34
  fetch: (command: Command) => FetchLike;
35
- /** The profile's token, sent in the header the operation's security scheme names. Read before any guard asks. */
36
- token: (command: Command) => string | Promise<string>;
35
+ /**
36
+ * The profile's token, sent where the operation's security scheme names. Read before any guard asks. Left out, for a
37
+ * CLI without sign-in, no call carries one.
38
+ */
39
+ token?: (command: Command) => string | Promise<string>;
37
40
  /** Headers beside the sign-in, such as the API version. */
38
41
  headers?: (command: Command, operation: ManifestOperation) => Record<string, string>;
39
42
  /** Loaded only once an operation is about to check its input: a large spec is megabytes of code. */
@@ -49,6 +52,18 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
49
52
  shown?: Readonly<Record<string, unknown>>;
50
53
  failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined;
51
54
  }
55
+ /**
56
+ * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
57
+ * bot's `--store-token`, as a service CLI signs in through `session`; a body other than JSON or an upload's bytes (a
58
+ * multipart form) the generated command cannot send.
59
+ */
60
+ export declare const serviceApiOperations: (manifest: ServiceApiManifest) => {
61
+ offered: readonly ManifestOperation[];
62
+ left: readonly {
63
+ id: string;
64
+ reason: string;
65
+ }[];
66
+ };
52
67
  /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
53
68
  export declare const serviceApiKeys: (input: ServiceApiPermissionsInput, operation: ManifestOperation, call: ApiCommandInput) => PermissionKey[];
54
69
  /**
@@ -8,14 +8,29 @@ import { levelFor } from "../sends/permissions.js";
8
8
  import { newOperationId } from "../sends/send-id.js";
9
9
  import { refusedPlace } from "../sends/upload.js";
10
10
  import { generatedApiCommand } from "./bot/api.js";
11
- import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
12
- import { checkApiBody, checkApiParameter, parseApiJson, readApiBody } from "./bot/api-input.js";
11
+ import { httpApiRequest, httpApiSend, unsendableBody } from "./bot/api-http.js";
12
+ import { checkApiBody, checkApiParameter, parseApiJson, readApiBody, readApiBytes } from "./bot/api-input.js";
13
13
  import { baseContext, outputFor } from "./context.js";
14
14
  import { NO_EFFECTS } from "./effects.js";
15
15
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
16
16
  import { queryTerms, termField, withQuery } from "./list-query.js";
17
17
  import { terminalAsker } from "./messenger/ask.js";
18
- import { authHeader, manifestBaseUrl, nextPage, parameterValue, } from "./service-api-manifest.js";
18
+ import { manifestBaseUrl, nextPage, parameterValue, signRequest, } from "./service-api-manifest.js";
19
+ /**
20
+ * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
21
+ * bot's `--store-token`, as a service CLI signs in through `session`; a body other than JSON or an upload's bytes (a
22
+ * multipart form) the generated command cannot send.
23
+ */
24
+ export const serviceApiOperations = (manifest) => {
25
+ const reasonOf = (operation) => operation.response?.sensitive ? "it returns a credential, which is never printed" : unsendableBody(operation);
26
+ return {
27
+ offered: manifest.operations.filter((operation) => reasonOf(operation) === undefined),
28
+ left: manifest.operations.flatMap((operation) => {
29
+ const reason = reasonOf(operation);
30
+ return reason ? [{ id: operation.id, reason }] : [];
31
+ }),
32
+ };
33
+ };
19
34
  /** How far `--all` reads: a service that never stops paging must not run a command forever. */
20
35
  const MOST_PAGES = 500;
21
36
  const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -90,8 +105,7 @@ const API_QUERY = {
90
105
  */
91
106
  export const serviceApiCommand = (options) => {
92
107
  const { app, configuration, manifest } = options;
93
- // A credential-returning operation needs a bot's `--store-token`; a service CLI signs in through `session` instead.
94
- const operations = manifest.operations.filter((operation) => !operation.response?.sensitive);
108
+ const { offered: operations, left } = serviceApiOperations(manifest);
95
109
  const baseUrl = manifestBaseUrl(manifest, options.baseUrl);
96
110
  const base = new URL(baseUrl);
97
111
  const own = serviceApiPermissions(options);
@@ -121,21 +135,15 @@ export const serviceApiCommand = (options) => {
121
135
  const found = operations.find((operation) => operation.command === name || operation.id === name);
122
136
  if (found)
123
137
  return found;
124
- const left = options.excluded?.find((one) => one.id === name) ??
125
- (manifest.operations.some((one) => one.command === name || one.id === name)
126
- ? { reason: "it returns a credential, which is never printed" }
127
- : undefined);
128
- throw new CliError("not_found", left
129
- ? `${name} is not offered: ${left.reason}`
138
+ const id = manifest.operations.find((one) => one.command === name || one.id === name)?.id ?? name;
139
+ const why = options.excluded?.find((one) => one.id === name) ?? left.find((one) => one.id === id);
140
+ throw new CliError("not_found", why
141
+ ? `${name} is not offered: ${why.reason}`
130
142
  : `no ${options.service} API operation ${name}; see ${app.command} api list`);
131
143
  };
132
144
  const signed = async (command, operation, request) => {
133
- const auth = authHeader(manifest, operation);
134
- if (auth)
135
- request.headers.set(auth.name, auth.value(await options.token(command)));
136
- // A redirect to another host drops only the standard sign-in headers; an API key header would go along.
137
- if (auth && auth.name !== "authorization")
138
- request.redirect = "manual";
145
+ const { token } = options;
146
+ await signRequest(manifest, operation, request, token && (() => token(command)));
139
147
  for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {}))
140
148
  request.headers.set(name, value);
141
149
  return request;
@@ -170,9 +178,11 @@ export const serviceApiCommand = (options) => {
170
178
  for (let page = 0;; page++) {
171
179
  if (page >= MOST_PAGES)
172
180
  throw new CliError("validation_error", `${operation.command} has more than ${MOST_PAGES} pages; narrow it with its own flags, or page it yourself`);
173
- const request = await signed(command, operation, httpApiRequest(operation, call, baseUrl));
181
+ const unsigned = httpApiRequest(operation, call, baseUrl);
182
+ // A next link replaces the URL, so the request is signed after: a key in the query goes into the link.
174
183
  if (url !== undefined)
175
- request.url = url;
184
+ unsigned.url = new URL(url);
185
+ const request = await signed(command, operation, unsigned);
176
186
  const key = `${request.url.href} ${request.body ?? ""}`;
177
187
  if (asked.has(key))
178
188
  throw new CliError("invalid_response", `${options.service} gave the same next page twice; nothing more read`);
@@ -193,18 +203,26 @@ export const serviceApiCommand = (options) => {
193
203
  });
194
204
  renderAnswer(command, outputFor(command), listOf(`api ${operation.command}`, { items, limit: items.length, has_more: false }));
195
205
  };
206
+ const refuseOwnFiles = (command, path) => {
207
+ if (path === "-")
208
+ return;
209
+ const { env } = baseContext(command, configuration.resolveSettings);
210
+ if (refusedPlace(path, app, env))
211
+ throw new CliError("validation_error", `--body-file may not read ${path}: it holds sign-ins or state`);
212
+ };
196
213
  const generated = generatedApiCommand({
197
214
  operations,
198
215
  checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
199
216
  checkBody: (operation, text) => checkApiBody(operation, text, loaded()),
200
217
  readBody: (command, body) => {
201
- if (body.bodyFile !== undefined && body.bodyFile !== "-") {
202
- const { env } = baseContext(command, configuration.resolveSettings);
203
- if (refusedPlace(body.bodyFile, app, env))
204
- throw new CliError("validation_error", `--body-file may not read ${body.bodyFile}: it holds sign-ins or state`);
205
- }
218
+ if (body.bodyFile !== undefined)
219
+ refuseOwnFiles(command, body.bodyFile);
206
220
  return readApiBody(body);
207
221
  },
222
+ readBytes: (command, path) => {
223
+ refuseOwnFiles(command, path);
224
+ return readApiBytes(path);
225
+ },
208
226
  execute: async (command, operation, input) => {
209
227
  const extra = serviceApiKeys(options, operation, input);
210
228
  if (operation.pagination && command.opts().all === true) {
@@ -0,0 +1,33 @@
1
+ import { Command } from "commander";
2
+ import type { AppIdentity } from "../ports/app.js";
3
+ import type { EventSink } from "../runs/events.js";
4
+ import { ProfileTokenStore, type TokenStorage } from "./profile-token.js";
5
+ import type { GlobalFlags, ResolveOptions, Settings } from "./settings.js";
6
+ export interface TokenSessionOptions {
7
+ app: AppIdentity;
8
+ /** The service's name, as the owner knows it: "Notion". */
9
+ service: string;
10
+ resolveSettings: (flags: GlobalFlags, options?: ResolveOptions) => Settings;
11
+ /**
12
+ * Asks the service whose the token is. `id` names the account, so one profile stays one account; `account` is what
13
+ * `session start` and `session status --check` show.
14
+ */
15
+ verify: (command: Command, token: string, events: EventSink) => Promise<{
16
+ id: string;
17
+ account: Readonly<Record<string, unknown>>;
18
+ }>;
19
+ /** Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so. */
20
+ claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
21
+ /** What the token is, for the prompt and help: "API token" when not given. */
22
+ token?: string;
23
+ /** One sentence more for `session start --help`: which token, and what it can see. */
24
+ about?: string;
25
+ /** One sentence more for `session end --help`, such as what of the service's own tools it leaves alone. */
26
+ endNote?: string;
27
+ }
28
+ export declare const storageOf: (raw: string) => TokenStorage;
29
+ /**
30
+ * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
31
+ * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
32
+ */
33
+ export declare const tokenSessionCommand: (options: TokenSessionOptions) => Command;