@wirecat/cli-core 0.704.0 → 0.706.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 (93) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/dist/cli/bot/api-http.d.ts +8 -2
  3. package/dist/cli/bot/api-http.js +20 -4
  4. package/dist/cli/bot/api.d.ts +8 -0
  5. package/dist/cli/bot/api.js +31 -3
  6. package/dist/cli/documents/words.d.ts +1 -1
  7. package/dist/cli/index.d.ts +4 -4
  8. package/dist/cli/index.js +3 -3
  9. package/dist/cli/messenger/lacks.js +3 -0
  10. package/dist/cli/messenger/messages-delete-command.js +30 -25
  11. package/dist/cli/messenger/messages-edit-command.js +2 -0
  12. package/dist/cli/messenger/messages-scheduled-command.js +110 -4
  13. package/dist/cli/messenger/store-maintenance-command.js +6 -2
  14. package/dist/cli/service-api-call.d.ts +13 -3
  15. package/dist/cli/service-api-call.js +19 -9
  16. package/dist/cli/service-api-manifest.d.ts +11 -2
  17. package/dist/cli/service-api-manifest.js +30 -9
  18. package/dist/cli/service-api.d.ts +14 -6
  19. package/dist/cli/service-api.js +198 -52
  20. package/dist/cli/token-session.d.ts +5 -2
  21. package/dist/cli/token-session.js +13 -4
  22. package/dist/content/cli/index.d.ts +33 -0
  23. package/dist/content/cli/index.js +368 -0
  24. package/dist/content/index.d.ts +8 -0
  25. package/dist/content/index.js +7 -0
  26. package/dist/content/manifest/index.d.ts +4 -0
  27. package/dist/content/manifest/index.js +4 -0
  28. package/dist/content/manifest/manifest.d.ts +92 -0
  29. package/dist/content/manifest/manifest.js +137 -0
  30. package/dist/content/manifest/map.d.ts +25 -0
  31. package/dist/content/manifest/map.js +94 -0
  32. package/dist/content/manifest/source.d.ts +41 -0
  33. package/dist/content/manifest/source.js +288 -0
  34. package/dist/content/manifest/writer.d.ts +26 -0
  35. package/dist/content/manifest/writer.js +133 -0
  36. package/dist/content/source.d.ts +64 -0
  37. package/dist/content/source.js +2 -0
  38. package/dist/content/sync.d.ts +61 -0
  39. package/dist/content/sync.js +387 -0
  40. package/dist/content/testing/index.d.ts +4 -0
  41. package/dist/content/testing/index.js +4 -0
  42. package/dist/content/testing/source-contract.d.ts +38 -0
  43. package/dist/content/testing/source-contract.js +274 -0
  44. package/dist/content/testing/source.d.ts +55 -0
  45. package/dist/content/testing/source.js +276 -0
  46. package/dist/content/testing/sync-contract.d.ts +10 -0
  47. package/dist/content/testing/sync-contract.js +172 -0
  48. package/dist/content/testing/write-contract.d.ts +14 -0
  49. package/dist/content/testing/write-contract.js +102 -0
  50. package/dist/content/writer.d.ts +64 -0
  51. package/dist/content/writer.js +38 -0
  52. package/dist/content/writes.d.ts +58 -0
  53. package/dist/content/writes.js +129 -0
  54. package/dist/documents/file-mirror-model.d.ts +3 -1
  55. package/dist/documents/index.d.ts +3 -3
  56. package/dist/documents/index.js +1 -1
  57. package/dist/domain/content.d.ts +102 -0
  58. package/dist/domain/content.js +11 -0
  59. package/dist/entities/index.d.ts +8 -2
  60. package/dist/entities/index.js +4 -2
  61. package/dist/entities/message-change.d.ts +240 -0
  62. package/dist/entities/message-change.js +6 -0
  63. package/dist/errors/reasons.js +14 -0
  64. package/dist/kit/fake.d.ts +2 -2
  65. package/dist/kit/fake.js +21 -0
  66. package/dist/manifest/index.d.ts +21 -7
  67. package/dist/manifest/index.js +7 -4
  68. package/dist/mcp/surface.js +6 -3
  69. package/dist/ports/messenger.d.ts +20 -1
  70. package/dist/sends/permissions.js +11 -1
  71. package/dist/services/documents/mirrors.d.ts +13 -1
  72. package/dist/services/documents/mirrors.js +12 -3
  73. package/dist/services/files/mirror.d.ts +20 -8
  74. package/dist/services/files/mirror.js +84 -27
  75. package/dist/services/files/versions.d.ts +17 -7
  76. package/dist/services/files/versions.js +56 -21
  77. package/dist/services/messages.d.ts +31 -0
  78. package/dist/services/messages.js +62 -0
  79. package/dist/store/exports.d.ts +1 -0
  80. package/dist/store/exports.js +1 -0
  81. package/dist/store/recover.js +2 -0
  82. package/dist/store/sqlite/account-purge.js +7 -0
  83. package/dist/store/sqlite/content.d.ts +100 -0
  84. package/dist/store/sqlite/content.js +375 -0
  85. package/dist/store/sqlite/entity-types.d.ts +1 -0
  86. package/dist/store/sqlite/entity-types.js +1 -0
  87. package/dist/store/sqlite/manifest.js +2 -0
  88. package/dist/store/sqlite/migrations.generated.js +26 -0
  89. package/dist/store/sqlite/schema.d.ts +1140 -0
  90. package/dist/store/sqlite/schema.js +100 -0
  91. package/dist/store/store.d.ts +3 -0
  92. package/dist/store/store.js +5 -0
  93. package/package.json +12 -4
@@ -1,38 +1,48 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { hostFetch } from "@wirecat/cli-base/http";
3
3
  import { Command } from "commander";
4
- import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
5
- import { manifestBaseUrl, signRequest } from "./service-api-manifest.js";
4
+ import { httpApiExchange, httpApiRequest } from "./bot/api-http.js";
5
+ import { manifestBaseUrl, signRequest, underBase } from "./service-api-manifest.js";
6
6
  /**
7
7
  * A fetch that reaches only `hosts` (WC-CMD-32), over the fetch a test gives in its environment, or the network when
8
8
  * none: a CLI passes `environment.fetch` as it is.
9
9
  */
10
- export const hostsFetch = (hosts, fetch) => hostFetch({ hosts, ...(fetch ? { fetch } : {}) });
10
+ export const hostsFetch = (hosts, fetch,
11
+ /** Where the sign-in may go, for a site under a path (`https://host/blog/wp-json`): see cli-base `hostFetch`. */
12
+ credentialScope) => hostFetch({ hosts, ...(fetch ? { fetch } : {}), ...(credentialScope ? { credentialScope } : {}) });
11
13
  // The run record and the fetch are the only things httpApiSend asks a command for, and a sync has no command of its own.
12
14
  const NO_COMMAND = new Command("source");
13
15
  /**
14
16
  * The `api` group's request path for code that is not a command, such as a source read from a manifest: the same
15
17
  * request building, sign-in header, redirect rule, run record and refusals as `serviceApiCommand`, without a guard. It
16
- * sends reads only; a write goes through the `api` group, where the profile's guard asks.
18
+ * sends reads only; a write goes through `serviceApiWriter` or the `api` group, where the profile's guard asks. A
19
+ * request is sent only under the server's address, path included: a site at `host/blog` never signs `host/other`.
17
20
  */
18
21
  export const serviceApiCall = (options) => {
19
22
  const baseUrl = manifestBaseUrl(options.manifest, options.baseUrl, options.serverVariables);
20
23
  const operations = new Map(options.manifest.operations.map((one) => [one.id, one]));
21
- const send = httpApiSend({ service: options.service, fetch: () => options.fetch, failure: options.failure });
22
- return async (id, input) => {
24
+ const exchange = httpApiExchange({ service: options.service, fetch: () => options.fetch, failure: options.failure });
25
+ const withHeaders = async (id, input) => {
23
26
  const operation = operations.get(id);
24
27
  if (!operation)
25
28
  throw new CliError("configuration_error", `no ${options.service} API operation ${id}`);
26
29
  if (operation.effect !== "read")
27
30
  throw new CliError("configuration_error", `${operation.command} is not a read; a source only reads`);
28
31
  const request = httpApiRequest(operation, input, baseUrl);
32
+ if (!underBase(request.url, baseUrl))
33
+ throw new CliError("validation_error", `${operation.command} would leave ${baseUrl}`, { sent: false });
29
34
  const extra = Object.entries(options.headers?.(operation) ?? {});
30
35
  for (const [name, value] of extra)
31
36
  request.headers.set(name, value);
32
37
  await signRequest(options.manifest, operation, request, options.token);
33
- // A redirect to another host drops only the standard sign-in headers; a hook's header would go along.
34
- if (extra.length)
38
+ // A redirect to another host drops only the standard sign-in headers; a hook's header would go along. A site
39
+ // shares its host with others, and only its path tells them apart, so its sign-in follows no redirect.
40
+ if (extra.length || options.serverVariables)
35
41
  request.redirect = "manual";
36
- return send(NO_COMMAND, operation, request);
42
+ const { answer, headers } = await exchange(NO_COMMAND, operation, request);
43
+ return { body: answer, headers };
37
44
  };
45
+ return Object.assign(async (id, input) => (await withHeaders(id, input)).body, {
46
+ withHeaders,
47
+ });
38
48
  };
@@ -29,6 +29,11 @@ export declare const signRequest: (manifest: ServiceApiManifest, operation: Mani
29
29
  headers: Headers;
30
30
  redirect?: "follow" | "manual" | "error";
31
31
  }, token: (() => Promise<string> | string) | undefined) => Promise<void>;
32
+ /**
33
+ * A URL on the server's origin and under its path: a site at `host/blog` shares its host with `host/other`, which
34
+ * must never get its sign-in.
35
+ */
36
+ export declare const underBase: (url: URL, baseUrl: string) => boolean;
32
37
  export declare const parameterValue: (input: ApiCommandInput, parameter: {
33
38
  in: "query" | "body";
34
39
  name: string;
@@ -46,5 +51,9 @@ export interface PageStep {
46
51
  url: string;
47
52
  };
48
53
  }
49
- /** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
50
- export declare const nextPage: (pagination: Pagination, input: ApiCommandInput, answer: unknown) => PageStep;
54
+ /**
55
+ * Reads one answer by the manifest's pagination: where its items are and what the next request is. `headers` are the
56
+ * response's, where a page style's `pagesHeader` gives the number of pages: the page that reaches it is the last, as
57
+ * WordPress refuses a page past the end.
58
+ */
59
+ export declare const nextPage: (pagination: Pagination, input: ApiCommandInput, answer: unknown, headers?: Headers) => PageStep;
@@ -121,9 +121,21 @@ export const signRequest = async (manifest, operation, request, token) => {
121
121
  if (auth.in === "query" || auth.name !== "authorization")
122
122
  request.redirect = "manual";
123
123
  };
124
- const at = (value, path) => path
125
- .split(".")
126
- .reduce((inner, key) => (inner && typeof inner === "object" ? inner[key] : undefined), value);
124
+ /**
125
+ * A URL on the server's origin and under its path: a site at `host/blog` shares its host with `host/other`, which
126
+ * must never get its sign-in.
127
+ */
128
+ export const underBase = (url, baseUrl) => {
129
+ const base = new URL(baseUrl);
130
+ const prefix = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
131
+ return url.origin === base.origin && (url.pathname === base.pathname || url.pathname.startsWith(prefix));
132
+ };
133
+ /** `""` is the answer itself: WordPress answers the list. */
134
+ const at = (value, path) => path === ""
135
+ ? value
136
+ : path
137
+ .split(".")
138
+ .reduce((inner, key) => (inner && typeof inner === "object" ? inner[key] : undefined), value);
127
139
  const numberOf = (value) => {
128
140
  const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number(String(value));
129
141
  return Number.isFinite(number) ? number : undefined;
@@ -142,8 +154,12 @@ export const withValue = (input, parameter, value) => {
142
154
  const { [parameter.name]: _, ...fields } = input.fields;
143
155
  return { ...input, fields, body: apiJson({ ...body, [parameter.name]: value }) };
144
156
  };
145
- /** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
146
- export const nextPage = (pagination, input, answer) => {
157
+ /**
158
+ * Reads one answer by the manifest's pagination: where its items are and what the next request is. `headers` are the
159
+ * response's, where a page style's `pagesHeader` gives the number of pages: the page that reaches it is the last, as
160
+ * WordPress refuses a page past the end.
161
+ */
162
+ export const nextPage = (pagination, input, answer, headers) => {
147
163
  const listed = pagination.items === undefined ? [answer] : at(answer, pagination.items);
148
164
  const items = Array.isArray(listed) ? listed : [];
149
165
  switch (pagination.style) {
@@ -158,11 +174,16 @@ export const nextPage = (pagination, input, answer) => {
158
174
  case "page": {
159
175
  const parameter = pagination.style === "offset" ? pagination.offset : pagination.page;
160
176
  const total = pagination.total === undefined ? undefined : numberOf(at(answer, pagination.total));
161
- const current = numberOf(parameterValue(input, parameter)) ?? (pagination.style === "offset" ? 0 : 1);
177
+ const current = numberOf(parameterValue(input, parameter)) ?? (pagination.style === "offset" ? 0 : (pagination.start ?? 1));
162
178
  const next = pagination.style === "offset" ? current + items.length : current + 1;
163
- // A short page is not the last: a service may cap the page below the limit asked for. Only a total or an
164
- // empty page ends it.
165
- const last = items.length === 0 || (total !== undefined && pagination.style === "offset" && next >= total);
179
+ const pages = pagination.style === "page" && pagination.pagesHeader !== undefined
180
+ ? numberOf(headers?.get(pagination.pagesHeader) ?? undefined)
181
+ : undefined;
182
+ // A short page is not the last: a service may cap the page below the limit asked for. Only a total, the number
183
+ // of pages or an empty page ends it.
184
+ const last = items.length === 0 ||
185
+ (total !== undefined && pagination.style === "offset" && next >= total) ||
186
+ (pages !== undefined && current >= pages);
166
187
  return last ? { items } : { items, next: { input: withValue(input, parameter, next) } };
167
188
  }
168
189
  case "link": {
@@ -83,11 +83,19 @@ export declare const serviceApiPermissions: (input: ServiceApiPermissionsInput)
83
83
  /** The keys, so a profile may name one that no command path spells. */
84
84
  extra: readonly PermissionKey[];
85
85
  };
86
+ export declare const serviceApiCommand: (options: ServiceApiOptions) => Command;
87
+ /** One write of a manifest's operation from code, such as a content command's publish. */
88
+ export type ServiceApiWrite = (command: Command, operation: string, input: ApiCommandInput, options?: {
89
+ /** Keys the caller already asked about in this run: not asked again, but a `deny` or `readonly` still stops them. */
90
+ confirmed?: readonly PermissionKey[];
91
+ }) => Promise<{
92
+ operation_id: string;
93
+ result: unknown;
94
+ }>;
86
95
  /**
87
- * The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
88
- * operation of the generated manifest, sent to its server with the sign-in its security scheme names. Every write goes
89
- * through the profile's guard on `api.<operation>` and on each manifest key that applies to the call (`files.delete`
90
- * when `permanently` is true); the journal records that it ran, never its body. A read that pages takes `--all`. There
91
- * is no free-form `api call`: a request is always one operation of the spec, with its own key (SEC-196).
96
+ * The `api` group's write path for code that is not one of its commands: the same keys (`api.<operation>` and each
97
+ * manifest key the call sets off, as `posts.publish`), levels, question and journal line, so a writer is never a
98
+ * looser door than the command. `command` is the one running, which carries the profile and says whether a terminal
99
+ * can be asked. A read that no key guards goes through `serviceApiCall`.
92
100
  */
93
- export declare const serviceApiCommand: (options: ServiceApiOptions) => Command;
101
+ export declare const serviceApiWriter: (options: ServiceApiOptions) => ServiceApiWrite;
@@ -7,15 +7,15 @@ import { keyedGuard } from "../sends/keyed-guard.js";
7
7
  import { levelFor } from "../sends/permissions.js";
8
8
  import { newOperationId } from "../sends/send-id.js";
9
9
  import { refusedPlace } from "../sends/upload.js";
10
- import { generatedApiCommand } from "./bot/api.js";
11
- import { httpApiRequest, httpApiSend, unsendableBody } from "./bot/api-http.js";
12
- import { checkApiBody, checkApiParameter, parseApiJson, readApiBody, readApiBytes } from "./bot/api-input.js";
10
+ import { apiPathOf, generatedApiCommand } from "./bot/api.js";
11
+ import { httpApiExchange, httpApiRequest, unsendableBody } from "./bot/api-http.js";
12
+ import { apiJson, checkApiBody, checkApiParameter, graphqlVariables, parseApiJson, readApiBody, readApiBytes, sendsBytes, } 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 { manifestBaseUrl, nextPage, parameterValue, signRequest, } from "./service-api-manifest.js";
18
+ import { manifestBaseUrl, nextPage, parameterValue, signRequest, underBase, } from "./service-api-manifest.js";
19
19
  /**
20
20
  * The operations the `api` group offers, and why it leaves out the rest: one that answers with a credential needs a
21
21
  * bot's `--store-token`, as a service CLI signs in through `session`; a body other than JSON or an upload's bytes (a
@@ -34,29 +34,53 @@ export const serviceApiOperations = (manifest) => {
34
34
  /** How far `--all` reads: a service that never stops paging must not run a command forever. */
35
35
  const MOST_PAGES = 500;
36
36
  const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
37
- const keyOf = (operation) => `api.${operation.command}`;
37
+ const keyOf = (operation) => ["api", ...apiPathOf(operation)].join(".");
38
+ /** `contacts list`: what follows `api` on the command line. */
39
+ const pathOf = (operation) => apiPathOf(operation).join(" ");
40
+ /**
41
+ * The key a grouped operation had while `api` was flat, `api.contacts-list`. A profile that still names it keeps its
42
+ * hold on that one command: checked beside the new key, it only ever tightens. A group never takes an old command's
43
+ * name (the generator refuses it), so the old key never reaches past its command.
44
+ */
45
+ const formerKeyOf = (operation) => {
46
+ const former = `api.${operation.command}`;
47
+ return former === keyOf(operation) ? undefined : former;
48
+ };
38
49
  const permissionsOf = (operation) => operation.permissions ?? [];
39
50
  /** By its method too: an override may have marked a DELETE as a plain write. */
40
51
  const destructive = (operation) => operation.effect === "destructive" || (operation.binding.kind === "http" && operation.binding.method === "DELETE");
41
52
  const flagsOf = ({ body = [], query = [] }) => [...body, ...query];
42
53
  const valuesOf = ({ values = {} }) => Object.entries(values);
43
- /** Always, unless its flags or values name when; `with status publish or future`, `with archived set`. */
54
+ const unlessOf = ({ unless = {} }) => Object.entries(unless);
55
+ /**
56
+ * Always, unless its flags or values name when; `with status publish or future`, `with archived set`, `with status
57
+ * publish or future or date set, unless status draft or pending`.
58
+ */
44
59
  const whenOf = (permission) => {
45
60
  const flags = flagsOf(permission);
46
61
  const values = valuesOf(permission).map(([field, listed]) => `${field} ${listed.join(" or ")}`);
47
62
  if (flags.length === 0 && values.length === 0)
48
63
  return undefined;
49
- return `with ${[...(flags.length > 0 ? [`${flags.join(" or ")} set`] : []), ...values].join(" or ")}`;
64
+ const unless = unlessOf(permission).map(([field, listed]) => `${field} ${listed.join(" or ")}`);
65
+ return `with ${[...values, ...(flags.length > 0 ? [`${flags.join(" or ")} set`] : [])].join(" or ")}${unless.length > 0 && flags.length > 0 ? `, unless ${unless.join(" or ")}` : ""}`;
50
66
  };
51
67
  /** A body field or query parameter holding one of the values: WordPress publishes from either. */
52
68
  const holds = (value, listed) => typeof value === "string" && listed.includes(value);
53
69
  /** A flag counts unless it is absent or plainly false: a service may read `1` or `True` as true. */
54
70
  const set = (value) => value !== undefined && value !== null && value !== false && value !== "false";
55
71
  /** Whether a manifest key applies to this call: always, or when one of its flags is set or a field holds a value. */
56
- const applies = (permission, body, input) => whenOf(permission) === undefined ||
57
- (permission.body ?? []).some((field) => isObject(body) && set(body[field])) ||
58
- (permission.query ?? []).some((name) => set(input.query[name])) ||
59
- valuesOf(permission).some(([field, listed]) => (isObject(body) && holds(body[field], listed)) || holds(input.query[field], listed));
72
+ const applies = (permission, body, input) => {
73
+ const sends = ([field, listed]) => (isObject(body) && holds(body[field], listed)) || holds(input.query[field], listed);
74
+ // Beside a value, a field is another door to the same change and counts once sent at all: WordPress resets a `date`
75
+ // sent as null to now, which publishes a scheduled post. Either place, as WordPress merges the query with the body.
76
+ const sent = permission.values === undefined ? set : (value) => value !== undefined;
77
+ const flagged = flagsOf(permission).some((name) => (isObject(body) && sent(body[name])) || sent(input.query[name]));
78
+ // `unless` lifts only the flags: WordPress keeps a draft a draft whatever its date, and a call that names no status
79
+ // may move a scheduled post's date into the past, which publishes it.
80
+ return (whenOf(permission) === undefined ||
81
+ valuesOf(permission).some(sends) ||
82
+ (flagged && !unlessOf(permission).some(sends)));
83
+ };
60
84
  /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
61
85
  export const serviceApiKeys = (input, operation, call) => {
62
86
  const body = call.body?.trim() ? parseApiJson(call.body) : undefined;
@@ -76,18 +100,28 @@ export const serviceApiKeys = (input, operation, call) => {
76
100
  */
77
101
  export const serviceApiPermissions = (input) => {
78
102
  const checks = new Map();
79
- for (const operation of input.manifest.operations)
80
- checks.set(operation.command, [
103
+ const former = [];
104
+ for (const operation of input.manifest.operations) {
105
+ const old = formerKeyOf(operation);
106
+ if (old)
107
+ former.push(old);
108
+ checks.set(pathOf(operation), [
81
109
  ...permissionsOf(operation).map((permission) => {
82
110
  const when = whenOf(permission);
83
111
  return when === undefined ? permission.key : { key: permission.key, when };
84
112
  }),
85
113
  ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
114
+ ...(old ? [{ key: old, when: "while a profile still names this old key" }] : []),
86
115
  ]);
87
- const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))];
116
+ }
117
+ const keys = [
118
+ ...new Set([...checks.values()]
119
+ .flat()
120
+ .flatMap((one) => (typeof one === "string" ? [one] : former.includes(one.key) ? [] : [one.key]))),
121
+ ];
88
122
  return {
89
- extra: keys,
90
- alsoChecks: (path) => (path[0] === "api" && path.length === 2 ? (checks.get(path[1] ?? "") ?? []) : []),
123
+ extra: [...keys, ...former],
124
+ alsoChecks: (path) => (path[0] === "api" ? (checks.get(path.slice(1).join(" ")) ?? []) : []),
91
125
  defaults: {
92
126
  ...Object.fromEntries(keys.map((key) => [key, "ask"])),
93
127
  ...Object.fromEntries(input.manifest.operations.filter(destructive).map((operation) => [keyOf(operation), "ask"])),
@@ -95,7 +129,8 @@ export const serviceApiPermissions = (input) => {
95
129
  };
96
130
  };
97
131
  const rowOf = (operation) => ({
98
- command: operation.command,
132
+ command: pathOf(operation),
133
+ group: apiPathOf(operation).length > 1 ? apiPathOf(operation)[0] : null,
99
134
  method: operation.binding.kind === "http" ? operation.binding.method : operation.binding.kind === "graphql" ? "POST" : "",
100
135
  path: operation.binding.kind === "http"
101
136
  ? operation.binding.path
@@ -120,7 +155,11 @@ const API_QUERY = {
120
155
  * when `permanently` is true); the journal records that it ran, never its body. A read that pages takes `--all`. There
121
156
  * is no free-form `api call`: a request is always one operation of the spec, with its own key (SEC-196).
122
157
  */
123
- export const serviceApiCommand = (options) => {
158
+ /**
159
+ * What the `api` group and `serviceApiWriter` share, so a write from code passes the very guard a command's does: the
160
+ * offered operations, the server, the sign-in, the levels, and the guarded send.
161
+ */
162
+ const serviceApiCore = (options) => {
124
163
  const { app, configuration, manifest } = options;
125
164
  const { offered: operations, left } = serviceApiOperations(manifest);
126
165
  // Without variables the server is known now, and a CLI built against a manifest it cannot reach fails at once.
@@ -139,22 +178,17 @@ export const serviceApiCommand = (options) => {
139
178
  .filter(({ key }) => !named.has(key));
140
179
  if (unnamed.length > 0)
141
180
  throw new CliError("configuration_error", `bodyPermissions name ${unnamed.map(({ key }) => key).join(", ")}, which the manifest does not: the keys come from \`permissions\``);
142
- let schemas;
143
- const loaded = () => {
144
- if (!schemas)
145
- throw new CliError("configuration_error", "the api schemas were not loaded before the command ran");
146
- return schemas;
147
- };
148
- const send = httpApiSend({
181
+ const exchange = httpApiExchange({
149
182
  service: options.service,
150
183
  fetch: options.fetch,
151
184
  ...(options.failure ? { failure: options.failure } : {}),
152
185
  });
153
186
  const operationOf = (name) => {
154
- const found = operations.find((operation) => operation.command === name || operation.id === name);
187
+ const named = (one) => pathOf(one) === name || one.command === name || one.id === name;
188
+ const found = operations.find(named);
155
189
  if (found)
156
190
  return found;
157
- const id = manifest.operations.find((one) => one.command === name || one.id === name)?.id ?? name;
191
+ const id = manifest.operations.find(named)?.id ?? name;
158
192
  const why = options.excluded?.find((one) => one.id === name) ?? left.find((one) => one.id === id);
159
193
  throw new CliError("not_found", why
160
194
  ? `${name} is not offered: ${why.reason}`
@@ -162,19 +196,53 @@ export const serviceApiCommand = (options) => {
162
196
  };
163
197
  const signed = async (command, operation, request) => {
164
198
  const { token } = options;
199
+ const baseUrl = baseUrlOf(command);
200
+ if (!underBase(request.url, baseUrl))
201
+ throw new CliError("validation_error", `${operation.command} would leave ${baseUrl}`, { sent: false });
165
202
  await signRequest(manifest, operation, request, token && (() => token(command)));
203
+ // A site's sign-in follows no redirect: the host is shared with other sites, and only its path tells them apart.
204
+ if (options.serverVariables)
205
+ request.redirect = "manual";
166
206
  for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {}))
167
207
  request.headers.set(name, value);
168
208
  return request;
169
209
  };
170
- const write = async (command, operation, extra, request) => {
171
- const { settings, env, renderer, run } = baseContext(command, configuration.resolveSettings);
210
+ // `own` is the call's own key (`api.<operation>`), asked with the others when the caller confirmed some.
211
+ const guardOf = (command, extra, confirmed = [], own) => {
212
+ const { settings, env, renderer } = baseContext(command, configuration.resolveSettings);
213
+ const levelOf = (key) => levelFor(settings.permissions, key, defaults).level;
214
+ const asker = terminalAsker(command);
215
+ return keyedGuard((ask) => guardFor(app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, renderer.warn, env, ask), confirmed.length === 0
216
+ ? asker
217
+ : async (_key, asked) => {
218
+ // A caller that already asked about a key in this run is not asked again; `deny` and `readonly` still
219
+ // stop it.
220
+ const asking = [...(own ? [own] : []), ...extra].filter((key) => levelOf(key) === "ask" && !confirmed.includes(key));
221
+ if (asking.length > 0)
222
+ await asker(asking.join(" and "), asked);
223
+ }, levelOf, extra);
224
+ };
225
+ /**
226
+ * A read whose keys all allow it is sent as a read, `--all` included; `deny` refuses it here, and `ask` makes it ask
227
+ * as a write does. So a CLI can put its CRM command's read key (`people.list`) on the raw read.
228
+ */
229
+ const readsFreely = (command, operation, extra) => {
230
+ if (operation.effect !== "read")
231
+ return false;
232
+ if (extra.length === 0)
233
+ return true;
234
+ guardOf(command, extra).refuse({ chatId: null, kind: "edit", key: keyOf(operation), operationId: newOperationId() });
235
+ const { settings } = baseContext(command, configuration.resolveSettings);
236
+ return extra.every((key) => levelFor(settings.permissions, key, defaults).level !== "ask");
237
+ };
238
+ const write = async (command, operation, extra, request, confirmed = []) => {
239
+ const { run } = baseContext(command, configuration.resolveSettings);
172
240
  const operationId = newOperationId();
173
- const guard = keyedGuard((ask) => guardFor(app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, renderer.warn, env, ask), terminalAsker(command), (key) => levelFor(settings.permissions, key, defaults).level, extra);
241
+ const guard = guardOf(command, extra, confirmed, keyOf(operation));
174
242
  const guarded = { chatId: null, kind: "edit", key: keyOf(operation), operationId };
175
243
  guard.refuse(guarded);
176
244
  try {
177
- const result = await guardedWrite(guard, guarded, () => run(() => send(command, operation, request)));
245
+ const result = await guardedWrite(guard, guarded, () => run(async () => (await exchange(command, operation, request)).answer));
178
246
  return { operation_id: operationId, result };
179
247
  }
180
248
  catch (error) {
@@ -183,11 +251,40 @@ export const serviceApiCommand = (options) => {
183
251
  throw error;
184
252
  }
185
253
  };
186
- /** Every page, in one run; a next page on another host is never sent the sign-in. */
254
+ /** The old flat key, when the profile names it: on a read only its refusal or its question applies. */
255
+ const formerKeys = (command, operation) => {
256
+ const former = formerKeyOf(operation);
257
+ if (!former)
258
+ return [];
259
+ const { settings, renderer } = baseContext(command, configuration.resolveSettings);
260
+ const level = settings.permissions[former];
261
+ if (level === undefined)
262
+ return [];
263
+ renderer.warn(`permissions name ${former}, the old key of api ${pathOf(operation)}: rename it to ${keyOf(operation)}`);
264
+ return operation.effect === "read" && level !== "deny" && level !== "ask" ? [] : [former];
265
+ };
266
+ return { operations, left, baseUrlOf, defaults, exchange, formerKeys, operationOf, readsFreely, signed, write };
267
+ };
268
+ export const serviceApiCommand = (options) => {
269
+ const { app, configuration } = options;
270
+ const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, signed, write } = serviceApiCore(options);
271
+ const send = async (command, operation, request) => (await exchange(command, operation, request)).answer;
272
+ let schemas;
273
+ const loaded = () => {
274
+ if (!schemas)
275
+ throw new CliError("configuration_error", "the api schemas were not loaded before the command ran");
276
+ return schemas;
277
+ };
278
+ const load = async () => {
279
+ schemas ??= await options.schemas();
280
+ };
281
+ /** Every page, in one run; a next page outside the server's address is never sent the sign-in. */
187
282
  const allPages = async (command, operation, input) => {
188
283
  const pagination = operation.pagination;
189
- // Services number pages from 0 or from 1, and the manifest does not say which.
190
- if (pagination.style === "page" && parameterValue(input, pagination.page) === undefined)
284
+ // Services number pages from 0 or from 1, and the manifest says which only where the source did.
285
+ if (pagination.style === "page" &&
286
+ pagination.start === undefined &&
287
+ parameterValue(input, pagination.page) === undefined)
191
288
  throw new CliError("validation_error", `--all on ${operation.command} needs the first page: give --${pagination.page.name} 0 or 1, as ${options.service} counts`);
192
289
  const items = [];
193
290
  const asked = new Set();
@@ -207,21 +304,22 @@ export const serviceApiCommand = (options) => {
207
304
  if (asked.has(key))
208
305
  throw new CliError("invalid_response", `${options.service} gave the same next page twice; nothing more read`);
209
306
  asked.add(key);
210
- const step = nextPage(pagination, call, await send(command, operation, request));
307
+ const { answer, headers } = await exchange(command, operation, request);
308
+ const step = nextPage(pagination, call, answer, headers);
211
309
  for (const item of step.items)
212
310
  items.push(item);
213
311
  if (!step.next)
214
312
  return;
215
313
  if ("url" in step.next) {
216
314
  url = new URL(step.next.url, request.url);
217
- if (url.origin !== new URL(baseUrl).origin)
218
- throw new CliError("invalid_response", `${options.service} pointed the next page at another host`);
315
+ if (!underBase(url, baseUrl))
316
+ throw new CliError("invalid_response", `${options.service} pointed the next page outside ${baseUrl}`);
219
317
  }
220
318
  else
221
319
  call = step.next.input;
222
320
  }
223
321
  });
224
- renderAnswer(command, outputFor(command), listOf(`api ${operation.command}`, { items, limit: items.length, has_more: false }));
322
+ renderAnswer(command, outputFor(command), listOf(`api ${pathOf(operation)}`, { items, limit: items.length, has_more: false }));
225
323
  };
226
324
  const refuseOwnFiles = (command, path) => {
227
325
  if (path === "-")
@@ -243,15 +341,21 @@ export const serviceApiCommand = (options) => {
243
341
  refuseOwnFiles(command, path);
244
342
  return readApiBytes(path);
245
343
  },
344
+ configure: (command, operation) => {
345
+ if (operation.pagination && !operation.parameters.some(({ name }) => name === "all"))
346
+ command.option("--all", "read every page, as the API pages it");
347
+ command.hook("preAction", load);
348
+ },
246
349
  execute: async (command, operation, input) => {
247
- const extra = serviceApiKeys(options, operation, input);
350
+ const extra = [...serviceApiKeys(options, operation, input), ...formerKeys(command, operation)];
351
+ const read = readsFreely(command, operation, extra);
248
352
  if (operation.pagination && command.opts().all === true) {
249
- if (operation.effect !== "read" || extra.length > 0)
353
+ if (!read)
250
354
  throw new CliError("validation_error", `--all reads only; this call of ${operation.command} is guarded by ${extra.join(", ") || "its write"}`);
251
355
  return allPages(command, operation, input);
252
356
  }
253
357
  const request = await signed(command, operation, httpApiRequest(operation, input, baseUrlOf(command)));
254
- const answer = operation.effect === "read" && extra.length === 0
358
+ const answer = read
255
359
  ? await baseContext(command, configuration.resolveSettings).run(() => send(command, operation, request))
256
360
  : await write(command, operation, extra, request);
257
361
  renderAnswer(command, outputFor(command), itemOf(answer));
@@ -273,10 +377,12 @@ export const serviceApiCommand = (options) => {
273
377
  });
274
378
  const show = annotate(new Command("show"), {
275
379
  effects: NO_EFFECTS,
276
- examples: [`${app.command} api show ${operations[0]?.command ?? "<operation>"} --json`],
380
+ examples: [
381
+ `${app.command} api show ${operations[0] ? JSON.stringify(pathOf(operations[0])) : "<operation>"} --json`,
382
+ ],
277
383
  })
278
384
  .description(`show one operation's parameters and request schema, without calling ${options.service}`)
279
- .argument("<operation>", "the operation, as api list prints it")
385
+ .argument("<operation>", "the operation as api list prints it (quoted), its old name, or its operation id")
280
386
  .action(async function (name) {
281
387
  const operation = operationOf(name);
282
388
  const definitions = await options.definitions();
@@ -285,14 +391,54 @@ export const serviceApiCommand = (options) => {
285
391
  });
286
392
  const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its OpenAPI document`);
287
393
  group.addCommand(list).addCommand(show);
288
- const load = async () => {
289
- schemas ??= await options.schemas();
290
- };
291
- for (const child of generated.commands) {
292
- const operation = operations.find((one) => one.command === child.name());
293
- if (operation?.pagination && !operation.parameters.some(({ name }) => name === "all"))
294
- child.option("--all", "read every page, as the API pages it");
295
- group.addCommand(child.hook("preAction", load));
296
- }
394
+ for (const child of [...generated.commands])
395
+ group.addCommand(child);
297
396
  return group;
298
397
  };
398
+ // Code may pass a number, a boolean or a list where a person types text; the check reads the text it stands for.
399
+ const flagText = (raw) => (Array.isArray(raw) ? raw.join(",") : String(raw));
400
+ /** The body as the command checks it: an upload and an rpc call as given, GraphQL's flags joined to its variables. */
401
+ const writerBody = (operation, input, schemas) => {
402
+ if (sendsBytes(operation) || operation.binding.kind === "rpc")
403
+ return input;
404
+ const graphql = operation.binding.kind === "graphql";
405
+ const given = graphql ? apiJson(graphqlVariables(operation, input.body, input.fields ?? {})) : input.body;
406
+ const body = checkApiBody(operation, given, schemas);
407
+ return { ...input, ...(graphql ? { fields: {} } : {}), ...(body === undefined ? {} : { body }) };
408
+ };
409
+ /**
410
+ * The `api` group's write path for code that is not one of its commands: the same keys (`api.<operation>` and each
411
+ * manifest key the call sets off, as `posts.publish`), levels, question and journal line, so a writer is never a
412
+ * looser door than the command. `command` is the one running, which carries the profile and says whether a terminal
413
+ * can be asked. A read that no key guards goes through `serviceApiCall`.
414
+ */
415
+ export const serviceApiWriter = (options) => {
416
+ const { baseUrlOf, formerKeys, operationOf, signed, write } = serviceApiCore(options);
417
+ return async (command, name, input, { confirmed } = {}) => {
418
+ const operation = operationOf(name);
419
+ // The api group offers only declared parameters; code must not reach further, as WordPress's `_method` turns a
420
+ // write into a delete that no delete key guards.
421
+ const undeclared = Object.keys(input.query).filter((one) => !operation.parameters.some((parameter) => parameter.in === "query" && parameter.name === one));
422
+ const overriding = Object.keys(input.headers ?? {}).filter((one) => !operation.parameters.some((parameter) => parameter.in === "header" && parameter.name.toLowerCase() === one.toLowerCase()));
423
+ if (undeclared.length > 0 || overriding.length > 0)
424
+ throw new CliError("configuration_error", `${operation.command} does not take ${[...undeclared, ...overriding].join(", ")}`, { sent: false });
425
+ const extra = serviceApiKeys(options, operation, input);
426
+ if (operation.effect === "read" && extra.length === 0)
427
+ throw new CliError("configuration_error", `${operation.command} is a read; send it with serviceApiCall`);
428
+ // The checks the command runs on what a person typed, so code sends nothing a person could not.
429
+ const schemas = await options.schemas();
430
+ const headers = Object.entries(input.headers ?? {});
431
+ for (const parameter of operation.parameters) {
432
+ const raw = parameter.in === "header"
433
+ ? headers.find(([one]) => one.toLowerCase() === parameter.name.toLowerCase())?.[1]
434
+ : parameter.in === "query" || parameter.in === "path"
435
+ ? input[parameter.in][parameter.name]
436
+ : undefined;
437
+ const problem = raw === undefined ? undefined : checkApiParameter(parameter.name, parameter.schema, flagText(raw), schemas);
438
+ if (problem)
439
+ throw new CliError("validation_error", problem);
440
+ }
441
+ const request = await signed(command, operation, httpApiRequest(operation, writerBody(operation, input, schemas), baseUrlOf(command)));
442
+ return write(command, operation, [...extra, ...formerKeys(command, operation)], request, confirmed);
443
+ };
444
+ };
@@ -52,8 +52,11 @@ export interface ManifestVerifyOptions {
52
52
  service: string;
53
53
  /** The config's `auth.verify`: the operation, where its answer holds the id and a name, and whether it is live. */
54
54
  verify: CliVerify;
55
- /** The command's host-checked fetch, such as `hostsFetch(hosts, environment.fetch)`. */
56
- fetch: (command: Command) => FetchLike;
55
+ /**
56
+ * The command's host-checked fetch, such as `hostsFetch(hosts, environment.fetch)`. `site` is the one `session start
57
+ * --site` names, for a service on the owner's own site: its host is not among the CLI's own.
58
+ */
59
+ fetch: (command: Command, site: string | undefined) => FetchLike;
57
60
  }
58
61
  /**
59
62
  * `verify` for `tokenSessionCommand` from a config's `auth.verify`: the one operation is sent with the token, a token the
@@ -16,8 +16,14 @@ import { siteValue } from "./service-api-manifest.js";
16
16
  * `verify` for `tokenSessionCommand` from a config's `auth.verify`: the one operation is sent with the token, a token the
17
17
  * answer does not call active is refused, and the account is the id and name the answer holds.
18
18
  */
19
- export const manifestVerify = ({ manifest, service, verify, fetch }) => async (command, token) => {
20
- const call = serviceApiCall({ manifest, service, fetch: fetch(command), token: () => token });
19
+ export const manifestVerify = ({ manifest, service, verify, fetch }) => async (command, token, _events, site) => {
20
+ const call = serviceApiCall({
21
+ manifest,
22
+ service,
23
+ fetch: fetch(command, site),
24
+ token: () => token,
25
+ ...(site === undefined ? {} : { serverVariables: { site } }),
26
+ });
21
27
  const answer = await call(verify.operation, { path: {}, query: {}, headers: {}, fields: {} });
22
28
  // A service such as Attio answers a revoked key with 200 and `active: false`, not with 401.
23
29
  if (verify.active !== undefined && valueAt(answer, verify.active) !== true)
@@ -86,7 +92,9 @@ export const tokenSessionCommand = (options) => {
86
92
  throw new CliError("validation_error", "a user name with a colon cannot sign in");
87
93
  refuseOffline(this, service);
88
94
  const page = options.login?.page?.(site);
89
- if (page)
95
+ const input = secretInputOf(this).input ?? process.stdin;
96
+ // Only a person at a terminal pastes it; piped in, the note would stand before the answer on stderr.
97
+ if (page && input.isTTY)
90
98
  renderer.note(`the ${word} of ${login}: make one at ${page}, then paste it here`);
91
99
  // A secret is never an argument: it would land in shell history and in the run record (WC-SECR-5).
92
100
  const secret = (await readSecret(`${service} ${word}: `, secretInputOf(this))).trim();
@@ -175,6 +183,7 @@ export const signedInSite = (app, resolveSettings) => {
175
183
  const site = tokens.readWith(settings.profile, SITE)?.secret;
176
184
  if (site === undefined)
177
185
  throw noSite(app, settings.profile);
178
- return { site };
186
+ // <PREFIX>_TOKEN_SITE skips session start's cleaning, and `host/blog/..` would be the root site.
187
+ return { site: siteValue(site) };
179
188
  };
180
189
  };