@wirecat/cli-core 0.694.0 → 0.696.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,64 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.696.0 — 17.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A service that signs in with a user name and a password, as WordPress's application passwords, gets the same
13
+ `session` group.** `tokenSessionCommand` takes `login: { page? }`: `session start --login <name>` asks only the
14
+ password hidden, shows where to make one first, and keeps `<name>:<password>` in the profile's entry;
15
+ `<PREFIX>_TOKEN` holds the same pair. A manifest whose scheme is `http` `basic` now signs each call with it, where
16
+ the `api` group refused that scheme; a token without a user name is refused before anything is sent, and a spec
17
+ that also offers a bearer or a key sends that. A name with a colon is refused, since Basic splits there. cli-base's
18
+ `fakeApi`, and so `crmManifestFake`, does not take Basic yet.
19
+ - **One CLI can serve a service that runs on each owner's own site, a profile per site.** `tokenSessionCommand` takes
20
+ `site: { example }`: `session start --site blog.example.com` checks the token on that site and keeps the site in
21
+ the token's own keyring entry, written and forgotten with it, so a token only goes to the site it signed in to.
22
+ `session status` shows the site. `<PREFIX>_TOKEN` needs `<PREFIX>_TOKEN_SITE` beside it. `serviceApiCommand` takes
23
+ `serverVariables`, read when a call is sent, so `api list` and `api show` work before sign-in; give it
24
+ `signedInSite(app, resolveSettings)`, and give `serviceApiCall` that function's value for the command. Build the
25
+ fetch per run with the site's host in `hostFetch`. A site is https only, a host with a port or a path, never a user
26
+ name, query or fragment. A free variable inside a host (`{subdomain}.example.com`) takes one name only.
27
+ - **`ProfileTokenStore.write` takes named secrets to keep in the same write, and `readWith` reads the token and one
28
+ named secret from the same place:** both from the environment, or both from the profile's entry.
29
+
30
+ ### Fixed
31
+
32
+ - **A generated `api` command no longer demands a required parameter that the spec gives a default.** Notion's
33
+ page-markdown calls stopped with `required option '--notion-version <value>' not specified`, though its spec says
34
+ `Notion-Version` defaults to `2026-03-11`. Such a flag is now optional, shows its default in `--help`, and the call
35
+ sends the default when the flag is left out; a value given on the command line wins. A required parameter with no
36
+ default is still required. This covers the Bot API group too.
37
+
38
+ ## 0.695.0 — 17.11.2026
39
+
40
+ ### Added
41
+
42
+ - **`wirecat.config`'s `auth.verify`: the call that checks a token.** For `token` and `oauth2-pkce`, `{ operation, id,
43
+ name? }` names the operation that answers whose the token is and where its answer holds the account's id and name;
44
+ cli-template's `session start` checks a token with it.
45
+ - **`recalledAccount` from `@wirecat/cli-core/cli`**: the account a profile signed in to, as `session start`
46
+ remembered it, for a CLI's own account key (cli-template's CRM wiring from `wirecat.config`).
47
+ - **`crmManifestContract` tests a CRM source from a manifest with no service code.** A CLI made from
48
+ `wirecat.config.ts` runs every `crmSourceContract` case, faults and paging included, in one line
49
+ ([CRM.md](docs/dev/CRM.md#a-test-for-a-source-from-a-manifest)). Under it, `crmManifestFake` holds rows sampled
50
+ from each answer's schema, pages them by each operation's own `pagination` and filters change reads by time;
51
+ `crmManifestFixture` gives the source, the rows it holds and the faults `deny`, `change`, `skewed`, `sameToken`. A
52
+ call the manifest never makes, a change read without its since and a read of an unknown id land in `refusals`.
53
+ - **`crmSourceContract` takes `held`, the ids of every row a fixture holds.** A full list must give each of them,
54
+ and a read of changes after `change()` must leave the untouched ones out. Optional: a fixture without it runs as
55
+ before.
56
+
57
+ ### Changed — may break callers
58
+
59
+ - **cli-core needs `@wirecat/cli-base` 0.112.0 or later** (peer `>=0.112.0 <1.0.0`), since 0.693.0, for
60
+ `signInRequirements` and `signInPlace`.
61
+ - **`parseCliConfig` refuses a URL that would put a secret, a space or no host into a CLI's files**: `spec.from`,
62
+ `auth.revokeUrl` and a relay redirect take an https URL with a host, and no user name, password, #fragment, or
63
+ key or token in its query. `auth.verify`'s `id` and `name` are dot paths. `hooks` takes a `.ts` or `.js` module
64
+ under `./`. An unknown field reads "not a field of wirecat.config", a missing one "missing".
65
+
8
66
  ## 0.694.0 — 17.11.2026
9
67
 
10
68
  ### Added
@@ -4,6 +4,7 @@ import { Command, Option } from "commander";
4
4
  import { secretInput } from "../../runs/run-context.js";
5
5
  import { REMOTE_READ, REMOTE_WRITE } from "../effects.js";
6
6
  import { apiFlagOf, apiOptionKey, readApiBody, readApiBytes, sendsBytes } from "./api-input.js";
7
+ const scalarOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : undefined;
7
8
  export const generatedApiCommand = (api) => {
8
9
  const group = new Command("api").description(api.description ?? "every operation of the official Bot API, generated from its schema");
9
10
  group.option("--store-token <profile>", "keep a returned authentication token only in this bot profile's OS keyring; never print it");
@@ -18,7 +19,15 @@ export const generatedApiCommand = (api) => {
18
19
  if (parameter.sensitive)
19
20
  continue;
20
21
  const option = new Option(`--${apiFlagOf(parameter.name)} <value>`, parameter.description?.split("\n")[0] ?? parameter.name);
21
- command.addOption(parameter.required && parameter.in !== "body" ? option.makeOptionMandatory() : option);
22
+ if (parameter.required && parameter.in !== "body") {
23
+ // A required parameter the spec gives a default (Notion's `Notion-Version`) is sent with it, never asked for.
24
+ const fallback = scalarOf(parameter.schema.default);
25
+ if (fallback === undefined)
26
+ option.makeOptionMandatory();
27
+ else
28
+ option.default(fallback);
29
+ }
30
+ command.addOption(option);
22
31
  }
23
32
  if (operation.request && sendsBytes(operation)) {
24
33
  command.option("--body-file <path>", `the file to upload, sent as ${operation.request.contentType}; - is stdin`);
@@ -118,7 +118,7 @@ export { readMeetingProjectCandidates } from "./meeting-project-candidates-read.
118
118
  export { meetingResultItem } from "./meeting-results.js";
119
119
  export { type MeetingSeriesInventoryReader, readMeetingSeriesInventory } from "./meeting-series-inventory-read.js";
120
120
  export { addMeetingTagsCommand, type MeetingTagsCommandDeps } from "./meeting-tags-command.js";
121
- export { accountFileFor, profilesHere, rememberAccount } from "./messenger/accounts.js";
121
+ export { accountFileFor, profilesHere, recalledAccount, rememberAccount, } from "./messenger/accounts.js";
122
122
  export { terminalAsker } from "./messenger/ask.js";
123
123
  export type { CompletionOptions } from "./messenger/complete-command.js";
124
124
  export { type ConnectOptions, connectFor, type Messenger, type MessengerContext, messengerContext, type ProfileState, type ReadConnection, type StoredMessages, } from "./messenger/context.js";
@@ -155,7 +155,7 @@ export { type AgentScheduleSpec, agentSchedule, backfillScheduleRun, pauseSchedu
155
155
  export { deniedKinds, deniedKindsOf, type LeftOut, type SearchedKind } from "./search-left-out.js";
156
156
  export { type BodyPermission, type ServiceApiOptions, type ServiceApiPermissionsInput, serviceApiKeys, serviceApiOperations, serviceApiPermissions, } from "./service-api.js";
157
157
  export { type ServiceApiCall, type ServiceApiCallOptions, serviceApiCall } from "./service-api-call.js";
158
- export { manifestBaseUrl, type ServiceApiManifest, signRequest } from "./service-api-manifest.js";
158
+ export { manifestBaseUrl, type ServiceApiManifest, signRequest, siteValue } from "./service-api-manifest.js";
159
159
  export { type DeclaredSetting, type SettingRow, settingRows, withSettingDefaults } from "./setting-defaults.js";
160
160
  export { type Config, type Configuration, count, first, flag, fromFile, type GlobalFlags, NONE_NAMED, namedProfile, type ProfileKind, plain, type ResolveOptions, type Settings, type SettingsExtension, type SettingsExtensionContext, type Source, settingsFor, } from "./settings.js";
161
161
  export { type PermissionAnswer, readSetupAnswers, type SetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
@@ -167,5 +167,5 @@ export { type StoreInfo, sharedStoreCommand, storeInfo, storeInfoCommand } from
167
167
  export { type RecoveryCheck, type RecoveryRun, recoveryNotes, storeRecoverCommand, storeRecoveryCheck, storeRecoveryRun, } from "./store-recover.js";
168
168
  export { changeStoreSetting, isStoreSetting, STORE_SETTINGS, storeSettings } from "./store-settings.js";
169
169
  export type { TemplatesOptions } from "./templates-command.js";
170
- export { type TokenSessionOptions, tokenSessionCommand } from "./token-session.js";
170
+ export { signedInSite, type TokenSessionOptions, tokenSessionCommand } from "./token-session.js";
171
171
  export { restartServers, type UpgradeContext } from "./upgrade-command.js";
package/dist/cli/index.js CHANGED
@@ -109,7 +109,7 @@ export { readMeetingProjectCandidates } from "./meeting-project-candidates-read.
109
109
  export { meetingResultItem } from "./meeting-results.js";
110
110
  export { readMeetingSeriesInventory } from "./meeting-series-inventory-read.js";
111
111
  export { addMeetingTagsCommand } from "./meeting-tags-command.js";
112
- export { accountFileFor, profilesHere, rememberAccount } from "./messenger/accounts.js";
112
+ export { accountFileFor, profilesHere, recalledAccount, rememberAccount, } from "./messenger/accounts.js";
113
113
  export { terminalAsker } from "./messenger/ask.js";
114
114
  export { connectFor, messengerContext, } from "./messenger/context.js";
115
115
  export { DOCTOR_DEEP_OPTION, damageNotes } from "./messenger/doctor-command.js";
@@ -144,7 +144,7 @@ export { agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runS
144
144
  export { deniedKinds, deniedKindsOf } from "./search-left-out.js";
145
145
  export { serviceApiKeys, serviceApiOperations, serviceApiPermissions, } from "./service-api.js";
146
146
  export { serviceApiCall } from "./service-api-call.js";
147
- export { manifestBaseUrl, signRequest } from "./service-api-manifest.js";
147
+ export { manifestBaseUrl, signRequest, siteValue } from "./service-api-manifest.js";
148
148
  export { settingRows, withSettingDefaults } from "./setting-defaults.js";
149
149
  export { count, first, flag, fromFile, NONE_NAMED, namedProfile, plain, settingsFor, } from "./settings.js";
150
150
  export { readSetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
@@ -155,5 +155,5 @@ export { runnable, withSafety } from "./steps.js";
155
155
  export { sharedStoreCommand, storeInfo, storeInfoCommand } from "./store-info.js";
156
156
  export { recoveryNotes, storeRecoverCommand, storeRecoveryCheck, storeRecoveryRun, } from "./store-recover.js";
157
157
  export { changeStoreSetting, isStoreSetting, STORE_SETTINGS, storeSettings } from "./store-settings.js";
158
- export { tokenSessionCommand } from "./token-session.js";
158
+ export { signedInSite, tokenSessionCommand } from "./token-session.js";
159
159
  export { restartServers } from "./upgrade-command.js";
@@ -24,8 +24,16 @@ export declare class ProfileTokenStore {
24
24
  readonly variable: string;
25
25
  constructor({ app, env, keyring, warn }: ProfileTokenStoreOptions);
26
26
  read(profile: string): StoredCredential | undefined;
27
- /** The token; the profile's named secrets stay as they were. */
28
- write(profile: string, token: string, storage?: TokenStorage): CredentialSource;
27
+ /** The token, and `secrets` beside it in the same write; the profile's other named secrets stay as they were. */
28
+ write(profile: string, token: string, storage?: TokenStorage, secrets?: Readonly<Record<string, string>>): CredentialSource;
29
+ /**
30
+ * The token and one named secret from the same place, never one of each: `<PREFIX>_TOKEN` with
31
+ * `<PREFIX>_TOKEN_<NAME>`, or the profile's entry. A site kept beside a token so stays the token's own.
32
+ */
33
+ readWith(profile: string, name: string): {
34
+ token: StoredCredential;
35
+ secret: string | undefined;
36
+ } | undefined;
29
37
  /** The token and every named secret: the whole entry, as `session end` wants. */
30
38
  remove(profile: string): CredentialSource[];
31
39
  /** A named secret: `<PREFIX>_TOKEN_<NAME>`, then the profile's entry. */
@@ -79,9 +79,25 @@ export class ProfileTokenStore {
79
79
  const { token } = unpack(found.secret);
80
80
  return token === undefined ? undefined : { secret: token, source: found.source };
81
81
  }
82
- /** The token; the profile's named secrets stay as they were. */
83
- write(profile, token, storage = "keyring") {
84
- return this.#put(profile, { ...this.#heldUnlessUnreachable(profile), token }, storage);
82
+ /** The token, and `secrets` beside it in the same write; the profile's other named secrets stay as they were. */
83
+ write(profile, token, storage = "keyring", secrets = {}) {
84
+ for (const name of Object.keys(secrets))
85
+ checkName(name);
86
+ const held = this.#heldUnlessUnreachable(profile);
87
+ return this.#put(profile, { ...held, token, secrets: { ...held.secrets, ...secrets } }, storage);
88
+ }
89
+ /**
90
+ * The token and one named secret from the same place, never one of each: `<PREFIX>_TOKEN` with
91
+ * `<PREFIX>_TOKEN_<NAME>`, or the profile's entry. A site kept beside a token so stays the token's own.
92
+ */
93
+ readWith(profile, name) {
94
+ checkName(name);
95
+ const token = this.read(profile);
96
+ if (!token)
97
+ return undefined;
98
+ if (token.source === "environment")
99
+ return { token, secret: this.#options.env?.[this.secretVariable(name)] || undefined };
100
+ return { token, secret: this.#held(profile).secrets[name] };
85
101
  }
86
102
  /** The token and every named secret: the whole entry, as `session end` wants. */
87
103
  remove(profile) {
@@ -15,6 +15,8 @@ export interface ServiceApiCallOptions {
15
15
  token?: () => string | Promise<string>;
16
16
  /** In place of the manifest's first server. */
17
17
  baseUrl?: string;
18
+ /** The values of the server's free variables, such as `{ site }` from the profile's sign-in (`recalledSite`). */
19
+ serverVariables?: Readonly<Record<string, string>>;
18
20
  /** Headers beside the sign-in, such as the API version. */
19
21
  headers?: (operation: ManifestOperation) => Record<string, string>;
20
22
  failure?: HttpApiSendOptions["failure"];
@@ -10,7 +10,7 @@ const NO_COMMAND = new Command("source");
10
10
  * sends reads only; a write goes through the `api` group, where the profile's guard asks.
11
11
  */
12
12
  export const serviceApiCall = (options) => {
13
- const baseUrl = manifestBaseUrl(options.manifest, options.baseUrl);
13
+ const baseUrl = manifestBaseUrl(options.manifest, options.baseUrl, options.serverVariables);
14
14
  const operations = new Map(options.manifest.operations.map((one) => [one.id, one]));
15
15
  const send = httpApiSend({ service: options.service, fetch: () => options.fetch, failure: options.failure });
16
16
  return async (id, input) => {
@@ -8,10 +8,16 @@ export interface ServiceApiManifest {
8
8
  security?: readonly SecurityRequirement[];
9
9
  }
10
10
  /**
11
- * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
12
- * free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
11
+ * The first server the spec names. A variable is filled from `variables` first, such as the site a profile signed in
12
+ * to; else with its default, only when its `enum` lists the choices: a free one (`{site}`) names the owner's own host,
13
+ * which the default would send the token past.
13
14
  */
14
- export declare const manifestBaseUrl: (manifest: ServiceApiManifest, given?: string) => string;
15
+ export declare const manifestBaseUrl: (manifest: ServiceApiManifest, given?: string, variables?: Readonly<Record<string, string>>) => string;
16
+ /**
17
+ * The site an owner types, as a server's free variable takes it: a host with a port or a path if any, from
18
+ * `blog.example.com` or `https://blog.example.com/`. Only https: an `http://` address is refused, not rewritten.
19
+ */
20
+ export declare const siteValue: (raw: string) => string;
15
21
  /**
16
22
  * Signs one request for its operation. Set the final URL first: a key in the query goes into it. Anything but the
17
23
  * standard sign-in header, or a key in the query, never follows a redirect, even to the same host: another host would
@@ -2,30 +2,83 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { signInPlace, signInRequirements, } from "@wirecat/cli-base/codegen";
3
3
  import { apiJson, parseApiJson } from "./bot/api-input.js";
4
4
  /**
5
- * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
6
- * free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
5
+ * The first server the spec names. A variable is filled from `variables` first, such as the site a profile signed in
6
+ * to; else with its default, only when its `enum` lists the choices: a free one (`{site}`) names the owner's own host,
7
+ * which the default would send the token past.
7
8
  */
8
- export const manifestBaseUrl = (manifest, given) => {
9
+ export const manifestBaseUrl = (manifest, given, variables = {}) => {
9
10
  const server = manifest.servers?.[0];
10
11
  if (given === undefined && !server)
11
12
  throw new CliError("configuration_error", "the manifest names no server; give the api a baseUrl");
12
13
  const url = given ??
13
14
  server.url.replace(/\{([^}]+)\}/g, (_, name) => {
15
+ const value = variables[name];
16
+ // Only a variable that is the whole host takes a host with a port or a path: `{subdomain}.example.com` given
17
+ // `evil.test/x` would send the token to evil.test.
18
+ if (value !== undefined)
19
+ return wholeHost(server, name) ? serverValue(name, value) : labelValue(name, value);
14
20
  const variable = server?.variables?.[name];
15
21
  if (variable?.default === undefined || !variable.enum?.includes(variable.default))
16
- throw new CliError("configuration_error", `the server's {${name}} is the owner's own; give the api a baseUrl`);
22
+ throw new CliError("configuration_error", `the server's {${name}} is the owner's own; sign in with session start --${name}, or give the api a baseUrl`);
17
23
  return variable.default;
18
24
  });
19
25
  if (!/^https:\/\//.test(url))
20
26
  throw new CliError("configuration_error", `the api's server ${url} is not https`);
27
+ if (!URL.canParse(url) || new URL(url).username || new URL(url).password)
28
+ throw new CliError("configuration_error", `the api's server ${url} is not a URL without a user name`);
21
29
  return url;
22
30
  };
31
+ /**
32
+ * The site an owner types, as a server's free variable takes it: a host with a port or a path if any, from
33
+ * `blog.example.com` or `https://blog.example.com/`. Only https: an `http://` address is refused, not rewritten.
34
+ */
35
+ export const siteValue = (raw) => {
36
+ const text = raw
37
+ .trim()
38
+ .replace(/^https:\/\//i, "")
39
+ .replace(/\/+$/, "");
40
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text))
41
+ throw new CliError("validation_error", `--site takes an https address or a host, not ${JSON.stringify(raw)}`);
42
+ const [host = "", ...path] = serverValue("site", text, "validation_error").split("/");
43
+ const site = [host.toLowerCase(), ...path].join("/");
44
+ // What a URL makes of it must be what was typed: `0x7f.1`, `a.test/..` or a port past 65535 lands elsewhere.
45
+ const url = URL.canParse(`https://${site}`) ? new URL(`https://${site}`) : undefined;
46
+ if (!url ||
47
+ url.host !== site.split("/")[0] ||
48
+ url.pathname.replace(/\/$/, "") !== site.slice(site.split("/")[0]?.length))
49
+ throw new CliError("validation_error", `--site ${JSON.stringify(raw)} is not a plain https address`);
50
+ return site;
51
+ };
52
+ const wholeHost = (server, name) => server.url === `https://{${name}}` || server.url.startsWith(`https://{${name}}/`);
53
+ const labelValue = (name, value) => {
54
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(value))
55
+ throw new CliError("configuration_error", `{${name}} ${JSON.stringify(value)} is not one name without dots`);
56
+ return value;
57
+ };
58
+ // A value only names a place: a user name, query or fragment in it would change where the token goes, or add to it.
59
+ const serverValue = (name, value, code = "configuration_error") => {
60
+ if (!/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(:\d+)?(\/[A-Za-z0-9._~%-]+)*$/.test(value))
61
+ throw new CliError(code, `{${name}} ${JSON.stringify(value)} is not a host, with a port or a path if any`);
62
+ return value;
63
+ };
23
64
  /**
24
65
  * Where the sign-in goes for one operation: the first place its requirements' schemes name that a token can be sent
25
66
  * 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
67
  * none: its security, its own or else the document's, is absent, as in a spec that says nothing about sign-in, or
27
68
  * empty (`[]`, `[{}]`). An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
28
69
  */
70
+ // cli-base reads no basic scheme yet; the token of one is `<user>:<password>`, as `session start --login` keeps it.
71
+ const basicPlace = (scheme) => scheme.type === "http" && /^basic$/i.test(scheme.scheme ?? "")
72
+ ? {
73
+ in: "header",
74
+ name: "authorization",
75
+ value: (token) => {
76
+ if (!token.includes(":"))
77
+ throw new CliError("authentication_error", "this service signs in with a user name and a password: run session start --login <name>");
78
+ return `Basic ${Buffer.from(token).toString("base64")}`;
79
+ },
80
+ }
81
+ : undefined;
29
82
  const authOf = (manifest, operation) => {
30
83
  const requirements = signInRequirements(operation, manifest.security);
31
84
  if (!requirements)
@@ -33,10 +86,13 @@ const authOf = (manifest, operation) => {
33
86
  const names = requirements.flatMap((one) => Object.keys(one));
34
87
  const sendable = names.flatMap((name) => {
35
88
  const scheme = manifest.securitySchemes?.[name];
36
- const place = scheme && signInPlace(scheme);
37
- return place ? [place] : [];
89
+ const place = scheme && (signInPlace(scheme) ?? basicPlace(scheme));
90
+ return place ? [{ place, basic: !signInPlace(scheme) }] : [];
38
91
  });
39
- const auth = sendable.find((one) => one.in === "header") ?? sendable[0];
92
+ // Basic only when nothing else is offered: it needs a user name a token sign-in does not keep.
93
+ const auth = (sendable.find((one) => one.place.in === "header" && !one.basic) ??
94
+ sendable.find((one) => !one.basic) ??
95
+ sendable[0])?.place;
40
96
  if (auth)
41
97
  return auth;
42
98
  throw new CliError("configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`);
@@ -30,6 +30,11 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
30
30
  service: string;
31
31
  /** In place of the manifest's first server. */
32
32
  baseUrl?: string;
33
+ /**
34
+ * The values of the server's free variables for this run, such as `{ site }` from the profile's sign-in
35
+ * (`recalledSite`). Read only when a call is sent, so `api list` and `api show` work before sign-in.
36
+ */
37
+ serverVariables?: (command: Command) => Readonly<Record<string, string>>;
33
38
  /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
34
39
  fetch: (command: Command) => FetchLike;
35
40
  /**
@@ -106,8 +106,10 @@ const API_QUERY = {
106
106
  export const serviceApiCommand = (options) => {
107
107
  const { app, configuration, manifest } = options;
108
108
  const { offered: operations, left } = serviceApiOperations(manifest);
109
- const baseUrl = manifestBaseUrl(manifest, options.baseUrl);
110
- const base = new URL(baseUrl);
109
+ // Without variables the server is known now, and a CLI built against a manifest it cannot reach fails at once.
110
+ if (!options.serverVariables)
111
+ manifestBaseUrl(manifest, options.baseUrl);
112
+ const baseUrlOf = (command) => manifestBaseUrl(manifest, options.baseUrl, options.serverVariables?.(command));
111
113
  const own = serviceApiPermissions(options);
112
114
  // The group's own levels hold even where the CLI's permissions left them out.
113
115
  const defaults = { ...own.defaults, ...configuration.permissions?.defaults };
@@ -172,6 +174,7 @@ export const serviceApiCommand = (options) => {
172
174
  throw new CliError("validation_error", `--all on ${operation.command} needs the first page: give --${pagination.page.name} 0 or 1, as ${options.service} counts`);
173
175
  const items = [];
174
176
  const asked = new Set();
177
+ const baseUrl = baseUrlOf(command);
175
178
  let call = input;
176
179
  let url;
177
180
  await baseContext(command, configuration.resolveSettings).run(async () => {
@@ -194,7 +197,7 @@ export const serviceApiCommand = (options) => {
194
197
  return;
195
198
  if ("url" in step.next) {
196
199
  url = new URL(step.next.url, request.url);
197
- if (url.origin !== base.origin)
200
+ if (url.origin !== new URL(baseUrl).origin)
198
201
  throw new CliError("invalid_response", `${options.service} pointed the next page at another host`);
199
202
  }
200
203
  else
@@ -230,7 +233,7 @@ export const serviceApiCommand = (options) => {
230
233
  throw new CliError("validation_error", `--all reads only; this call of ${operation.command} is guarded by ${extra.join(", ") || "its write"}`);
231
234
  return allPages(command, operation, input);
232
235
  }
233
- const request = await signed(command, operation, httpApiRequest(operation, input, baseUrl));
236
+ const request = await signed(command, operation, httpApiRequest(operation, input, baseUrlOf(command)));
234
237
  const answer = operation.effect === "read" && extra.length === 0
235
238
  ? await baseContext(command, configuration.resolveSettings).run(() => send(command, operation, request))
236
239
  : await write(command, operation, extra, request);
@@ -12,10 +12,28 @@ export interface TokenSessionOptions {
12
12
  * Asks the service whose the token is. `id` names the account, so one profile stays one account; `account` is what
13
13
  * `session start` and `session status --check` show.
14
14
  */
15
- verify: (command: Command, token: string, events: EventSink) => Promise<{
15
+ verify: (command: Command, token: string, events: EventSink, site: string | undefined) => Promise<{
16
16
  id: string;
17
17
  account: Readonly<Record<string, unknown>>;
18
18
  }>;
19
+ /**
20
+ * The service runs on the owner's own site, its server's `{site}`: `session start` takes `--site`, verifies the
21
+ * token there and keeps the site in the token's own entry, written and forgotten with it, so the token only ever
22
+ * goes to that site (`signedInSite`). `<PREFIX>_TOKEN` needs `<PREFIX>_TOKEN_SITE` beside it. The example is a site
23
+ * for the help, such as "blog.example.com".
24
+ */
25
+ site?: {
26
+ example: string;
27
+ };
28
+ /**
29
+ * The secret is a password for a user name, as WordPress's application passwords: `session start --login <name>`
30
+ * asks only the password hidden, and the profile keeps `<name>:<password>`, which a `basic` scheme sends.
31
+ * `page` names where the owner makes one, shown before the question. `<PREFIX>_TOKEN` then holds
32
+ * `<name>:<password>` too.
33
+ */
34
+ login?: {
35
+ page?: (site: string | undefined) => string;
36
+ };
19
37
  /** Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so. */
20
38
  claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
21
39
  /** What the token is, for the prompt and help: "API token" when not given. */
@@ -31,3 +49,11 @@ export declare const storageOf: (raw: string) => TokenStorage;
31
49
  * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
32
50
  */
33
51
  export declare const tokenSessionCommand: (options: TokenSessionOptions) => Command;
52
+ /**
53
+ * The site this run's profile signed in to, as the `{ site }` server variable of `serviceApiCommand` (give it as is)
54
+ * and `serviceApiCall` (give it the command's). It comes from where the token does: the profile's entry, or
55
+ * `<PREFIX>_TOKEN_SITE` beside `<PREFIX>_TOKEN`; never one of each.
56
+ */
57
+ export declare const signedInSite: (app: AppIdentity, resolveSettings: TokenSessionOptions["resolveSettings"]) => ((command: Command) => {
58
+ site: string;
59
+ });
@@ -9,6 +9,7 @@ import { itemOf, listOf, renderAnswer } from "./envelope.js";
9
9
  import { profilesHere, rememberAccount } from "./messenger/accounts.js";
10
10
  import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
11
11
  import { ProfileTokenStore } from "./profile-token.js";
12
+ import { siteValue } from "./service-api-manifest.js";
12
13
  export const storageOf = (raw) => {
13
14
  if (raw === "keyring" || raw === "file")
14
15
  return raw;
@@ -20,7 +21,7 @@ export const storageOf = (raw) => {
20
21
  */
21
22
  export const tokenSessionCommand = (options) => {
22
23
  const { app, service } = options;
23
- const word = options.token ?? "API token";
24
+ const word = options.token ?? (options.login ? "password" : "API token");
24
25
  const contextOf = (command) => {
25
26
  const base = baseContext(command, options.resolveSettings);
26
27
  const tokens = new ProfileTokenStore({
@@ -32,12 +33,13 @@ export const tokenSessionCommand = (options) => {
32
33
  return { ...base, profile: base.settings.profile, tokens };
33
34
  };
34
35
  const answer = (command, item) => renderAnswer(command, outputFor(command), itemOf(item));
36
+ const siteOf = (site) => (options.site ? { site: site ?? null } : {});
35
37
  const start = logsInOrOut(annotate(new Command("start"), {
36
38
  effects: FETCH,
37
39
  lifetime: "interactive",
38
40
  mcp: false,
39
41
  examples: [
40
- `${app.command} personal session start`,
42
+ `${app.command} personal session start${options.site ? ` --site ${options.site.example}` : ""}${options.login ? " --login <name>" : ""}`,
41
43
  `${app.command} personal session start --credential-storage file`,
42
44
  ],
43
45
  }))
@@ -45,19 +47,36 @@ export const tokenSessionCommand = (options) => {
45
47
  .description(`sign this profile in: the ${service} ${word} is asked hidden or read from stdin, never taken as an argument, ` +
46
48
  `checked with ${service}, and only then kept in the keyring, or in a private file` +
47
49
  (options.about ? `. ${options.about}` : ""))
48
- .option("--credential-storage <storage>", "where the token is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring")
49
- .action(async function (args) {
50
- const { env, profile, tokens, run } = contextOf(this);
50
+ .option("--credential-storage <storage>", "where the token is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring");
51
+ if (options.login)
52
+ start.option("--login <name>", `the ${service} user name the password belongs to`);
53
+ if (options.site)
54
+ start.option("--site <address>", `the ${service} site, as https://${options.site.example} or ${options.site.example}`);
55
+ start.action(async function (args) {
56
+ const { env, profile, tokens, run, renderer } = contextOf(this);
51
57
  refuseCommandName(profile, commandWords(rootOf(this)), app.command);
58
+ if (options.site && args.site === undefined)
59
+ throw new CliError("validation_error", `give the ${service} site: --site ${options.site.example}`);
60
+ const site = options.site && args.site !== undefined ? siteValue(args.site) : undefined;
61
+ const login = args.login?.trim();
62
+ if (options.login && !login)
63
+ throw new CliError("validation_error", `give the ${service} user name: --login <name>`);
64
+ // Basic sign-in splits at the first colon, so a colon in the name would move part of it into the password.
65
+ if (login?.includes(":"))
66
+ throw new CliError("validation_error", "a user name with a colon cannot sign in");
52
67
  refuseOffline(this, service);
68
+ const page = options.login?.page?.(site);
69
+ if (page)
70
+ renderer.note(`the ${word} of ${login}: make one at ${page}, then paste it here`);
53
71
  // A secret is never an argument: it would land in shell history and in the run record (WC-SECR-5).
54
- const token = (await readSecret(`${service} ${word}: `, secretInputOf(this))).trim();
55
- if (!token)
56
- throw new CliError("validation_error", "no token was given");
57
- const { id, account } = await run((events) => options.verify(this, token, events));
72
+ const secret = (await readSecret(`${service} ${word}: `, secretInputOf(this))).trim();
73
+ if (!secret)
74
+ throw new CliError("validation_error", `no ${word} was given`);
75
+ const token = login === undefined ? secret : `${login}:${secret}`;
76
+ const { id, account } = await run((events) => options.verify(this, token, events, site));
58
77
  (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, id, tokens);
59
- const storedIn = tokens.write(profile, token, args.credentialStorage);
60
- answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...account });
78
+ const storedIn = tokens.write(profile, token, args.credentialStorage, site === undefined ? {} : { site });
79
+ answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...siteOf(site), ...account });
61
80
  });
62
81
  const status = annotate(new Command("status"), {
63
82
  effects: REMOTE_READ,
@@ -70,11 +89,14 @@ export const tokenSessionCommand = (options) => {
70
89
  .action(async function (args) {
71
90
  const { profile, tokens, run } = contextOf(this);
72
91
  const saved = tokens.read(profile);
73
- const state = { profile, state: saved ? "saved" : "missing", token_from: saved?.source ?? null };
92
+ const site = options.site ? tokens.readWith(profile, SITE)?.secret : undefined;
93
+ const state = { profile, state: saved ? "saved" : "missing", token_from: saved?.source ?? null, ...siteOf(site) };
74
94
  if (!args.check || !saved)
75
95
  return answer(this, { ...state, verified: false });
96
+ if (options.site && site === undefined)
97
+ throw noSite(app, profile);
76
98
  refuseOffline(this, service);
77
- const { account } = await run((events) => options.verify(this, saved.secret, events));
99
+ const { account } = await run((events) => options.verify(this, saved.secret, events, site));
78
100
  answer(this, { ...state, verified: true, ...account });
79
101
  });
80
102
  const end = logsInOrOut(annotate(new Command("end"), {
@@ -119,3 +141,20 @@ export const tokenSessionCommand = (options) => {
119
141
  .addCommand(end)
120
142
  .addCommand(list);
121
143
  };
144
+ const SITE = "site";
145
+ const noSite = (app, profile) => new CliError("authentication_error", `profile ${profile} is not signed in to a site — run \`${app.command} ${profile} session start --site <address>\``, { reason: "session.missing" });
146
+ /**
147
+ * The site this run's profile signed in to, as the `{ site }` server variable of `serviceApiCommand` (give it as is)
148
+ * and `serviceApiCall` (give it the command's). It comes from where the token does: the profile's entry, or
149
+ * `<PREFIX>_TOKEN_SITE` beside `<PREFIX>_TOKEN`; never one of each.
150
+ */
151
+ export const signedInSite = (app, resolveSettings) => {
152
+ return (command) => {
153
+ const { env, keyring, settings } = baseContext(command, resolveSettings);
154
+ const tokens = new ProfileTokenStore({ app, env, ...(keyring ? { keyring } : {}) });
155
+ const site = tokens.readWith(settings.profile, SITE)?.secret;
156
+ if (site === undefined)
157
+ throw noSite(app, settings.profile);
158
+ return { site };
159
+ };
160
+ };
@@ -2,6 +2,18 @@ import type { SchemaNode } from "@wirecat/cli-base/codegen";
2
2
  import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
3
  import type { CrmManifest } from "./manifest.js";
4
4
  type Definitions = Readonly<Record<string, SchemaNode>>;
5
+ export declare const resolve: (node: SchemaNode, definitions: Definitions, seen?: Set<string>) => SchemaNode;
6
+ /** The node one step down, `null` when the schema has no such field, `undefined` when the schema cannot say. */
7
+ export declare const step: (node: SchemaNode, key: string, definitions: Definitions) => SchemaNode | null | undefined;
8
+ type Walked = {
9
+ node: SchemaNode | undefined;
10
+ } | {
11
+ missing: string;
12
+ near?: string;
13
+ };
14
+ export declare const walk: (node: SchemaNode, path: string, definitions: Definitions) => Walked;
15
+ /** One item of the list a path ends on; a path that ends on one object is read as a list of it, as the map does. */
16
+ export declare const itemOf: (node: SchemaNode | undefined, definitions: Definitions) => SchemaNode | undefined;
5
17
  /**
6
18
  * Every path the manifest reads, checked against the schema each operation answers (`definitions` of the generated
7
19
  * API): a misspelt or moved field is named with the operation, and the field it likely meant, before a sync runs.
@@ -1,13 +1,13 @@
1
1
  import { editDistance } from "../../search/correct.js";
2
2
  import { rulePaths } from "./map.js";
3
- const resolve = (node, definitions, seen = new Set()) => {
3
+ export const resolve = (node, definitions, seen = new Set()) => {
4
4
  if (node.type !== "ref" || seen.has(node.ref))
5
5
  return node;
6
6
  const found = definitions[node.ref];
7
7
  return found ? resolve(found, definitions, new Set([...seen, node.ref])) : { type: "unknown" };
8
8
  };
9
9
  /** The node one step down, `null` when the schema has no such field, `undefined` when the schema cannot say. */
10
- const step = (node, key, definitions) => {
10
+ export const step = (node, key, definitions) => {
11
11
  const at = resolve(node, definitions);
12
12
  switch (at.type) {
13
13
  case "object": {
@@ -43,7 +43,7 @@ const keysOf = (node, definitions) => {
43
43
  return at.of.flatMap((one) => keysOf(one, definitions));
44
44
  return [];
45
45
  };
46
- const walk = (node, path, definitions) => {
46
+ export const walk = (node, path, definitions) => {
47
47
  let at = node;
48
48
  const segments = path === "." ? [] : path.split(".");
49
49
  for (const [place, key] of segments.entries()) {
@@ -65,7 +65,7 @@ const walk = (node, path, definitions) => {
65
65
  return { node: at };
66
66
  };
67
67
  /** One item of the list a path ends on; a path that ends on one object is read as a list of it, as the map does. */
68
- const itemOf = (node, definitions) => {
68
+ export const itemOf = (node, definitions) => {
69
69
  if (node === undefined)
70
70
  return undefined;
71
71
  const at = resolve(node, definitions);
@@ -1,5 +1,6 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, type AcmeScenario, acmeScenario, } from "./acme-scenario.js";
2
2
  export { type CrmFilesFixture, crmFilesContract } from "./files-contract.js";
3
+ export { type CrmManifestFake, type CrmManifestFakeOptions, type CrmManifestFixtureOptions, crmManifestContract, crmManifestFake, crmManifestFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
3
4
  export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
4
5
  export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
5
6
  export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
@@ -1,5 +1,6 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, acmeScenario, } from "./acme-scenario.js";
2
2
  export { crmFilesContract } from "./files-contract.js";
3
+ export { crmManifestContract, crmManifestFake, crmManifestFixture, FAKE_MANIFEST_TOKEN, } from "./manifest-fake.js";
3
4
  export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
4
5
  export { crmSourceContract } from "./source-contract.js";
5
6
  export { CRM_TRAIT_COMBINATIONS, crmSyncContract } from "./sync-contract.js";