loopctl-mcp-server 3.43.0 → 3.45.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/lib/agents.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * `register_agent` / `list_agents` / `get_agent` — `POST /api/v1/agents/register`,
3
+ * `GET /api/v1/agents` and `GET /api/v1/agents/:id` (`AgentController`), loopctl #872.
4
+ *
5
+ * KEYS, from the controller's plugs:
6
+ *
7
+ * - register is `exact_role: :agent` with NO hierarchy: an orchestrator, user or superadmin
8
+ * key is 403 insufficient_role. It travels on the session's own key (`agentKey()`), because
9
+ * what it does is link THE CALLING KEY to a new agent row: a key that already carries an
10
+ * `agent_id` is 409 (so is a holder credential, which is always minted for an agent), and a
11
+ * key with none gets the new agent's id. `name` and `agent_type` are required (422 without
12
+ * them, and 422 for a name starting `system:`, any case, which loopctl reserves for its own
13
+ * agents). Not human-anchored and not custody surface.
14
+ * - list and show are `role: :orchestrator` WITH the hierarchy, so an agent key is 403
15
+ * insufficient_role. They travel on LOOPCTL_ORCH_KEY, else LOOPCTL_USER_KEY, sent verbatim
16
+ * when set (index.js `orchestratorPinnedApiCall`). Show answers 404 for another tenant's
17
+ * agent or a malformed id.
18
+ *
19
+ * CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
20
+ *
21
+ * - list's `agent_type`, `status` and `sort_by`: an unknown value is DROPPED (the filter is
22
+ * skipped, or the sort falls back to `name`), so a typo answers every agent as if filtered;
23
+ * - list's `page` / `page_size`: a non-integer is dropped and `page_size` is clamped to 1..100;
24
+ * - register's `agent_type` when it is not a string: the controller's coercion has no clause
25
+ * for one and the request 500s; an unknown string reads as missing ("can't be blank");
26
+ * - register's `metadata` when it is not an object;
27
+ * - a non-UUID agent id, which would answer the same 404 as a missing agent.
28
+ */
29
+
30
+ import { uuid } from "./delivery-loop.js";
31
+
32
+ export const AGENT_TYPES = ["orchestrator", "implementer"];
33
+ export const AGENT_STATUSES = ["active", "idle", "deactivated"];
34
+ export const AGENT_SORT_FIELDS = ["name", "agent_type", "status", "last_seen_at", "inserted_at"];
35
+
36
+ function refuse(body) {
37
+ return { error: true, status: 0, body };
38
+ }
39
+
40
+ // ONE template literal per builder (see `test/tool-surface.js`).
41
+ export function agentRegisterPath() {
42
+ return `/api/v1/agents/register`;
43
+ }
44
+
45
+ export function agentsPath(query = "") {
46
+ return `/api/v1/agents${query}`;
47
+ }
48
+
49
+ export function agentPath(agentId) {
50
+ return `/api/v1/agents/${encodeURIComponent(agentId)}`;
51
+ }
52
+
53
+ function oneOf(value, allowed, field) {
54
+ if (value != null && !allowed.includes(value)) {
55
+ return refuse(`\`${field}\` is one of: ${allowed.join(", ")}.`);
56
+ }
57
+ return null;
58
+ }
59
+
60
+ export async function registerAgent({ name, agent_type, metadata } = {}, { apiCall } = {}) {
61
+ if (typeof name !== "string" || name.trim() === "") {
62
+ return refuse("`name` is required: the agent's name, unique in the tenant.");
63
+ }
64
+
65
+ if (!AGENT_TYPES.includes(agent_type)) {
66
+ return refuse(`\`agent_type\` is required, one of: ${AGENT_TYPES.join(", ")}.`);
67
+ }
68
+
69
+ if (metadata != null && (typeof metadata !== "object" || Array.isArray(metadata))) {
70
+ return refuse("`metadata` must be an object.");
71
+ }
72
+
73
+ const body = { name, agent_type };
74
+ if (metadata != null) body.metadata = metadata;
75
+
76
+ return apiCall("POST", agentRegisterPath(), body);
77
+ }
78
+
79
+ export async function listAgents(
80
+ { agent_type, status, sort_by, page, page_size } = {},
81
+ { apiCall } = {},
82
+ ) {
83
+ const bad =
84
+ oneOf(agent_type, AGENT_TYPES, "agent_type") ??
85
+ oneOf(status, AGENT_STATUSES, "status") ??
86
+ oneOf(sort_by, AGENT_SORT_FIELDS, "sort_by");
87
+ if (bad) return bad;
88
+
89
+ if (page != null && !(Number.isInteger(page) && page >= 1)) {
90
+ return refuse("`page` must be a positive integer.");
91
+ }
92
+
93
+ if (page_size != null && !(Number.isInteger(page_size) && page_size >= 1 && page_size <= 100)) {
94
+ return refuse("`page_size` must be an integer from 1 to 100 (default 20).");
95
+ }
96
+
97
+ const params = new URLSearchParams();
98
+ if (agent_type != null) params.set("agent_type", agent_type);
99
+ if (status != null) params.set("status", status);
100
+ if (sort_by != null) params.set("sort_by", sort_by);
101
+ if (page != null) params.set("page", String(page));
102
+ if (page_size != null) params.set("page_size", String(page_size));
103
+ const qs = params.toString();
104
+
105
+ return apiCall("GET", agentsPath(qs === "" ? "" : `?${qs}`), null);
106
+ }
107
+
108
+ export async function getAgent({ agent_id } = {}, { apiCall } = {}) {
109
+ return uuid(agent_id, "agent_id") ?? apiCall("GET", agentPath(agent_id), null);
110
+ }
package/lib/api-keys.js CHANGED
@@ -13,9 +13,9 @@
13
13
  */
14
14
 
15
15
  import { isAbsolute } from "node:path";
16
- import { closeSync, openSync, unlinkSync, writeSync } from "node:fs";
17
16
 
18
17
  import { uuid } from "./delivery-loop.js";
18
+ import { createSecretFile } from "./secret-file.js";
19
19
 
20
20
  export const API_KEY_ROLES = ["user", "orchestrator", "agent"];
21
21
 
@@ -25,11 +25,12 @@ function refuse(body) {
25
25
 
26
26
  /**
27
27
  * `deps.apiCall(method, path, body)` is the user-key caller; `deps.openKey(path)` creates the
28
- * file and returns `{ writeRawKey(raw), discardKeyFile() }` (injected so a test owns the disk it touches).
28
+ * file and returns `{ writeSecret(text), discardSecret() }` (lib/secret-file.js; injected so a test owns
29
+ * the disk it touches).
29
30
  */
30
31
  export async function apiKeyCreate(
31
32
  { name, role, snapshot_project_id, expires_at, key_file } = {},
32
- { apiCall, openKey = defaultOpenKey } = {},
33
+ { apiCall, openKey = createSecretFile } = {},
33
34
  ) {
34
35
  if (typeof name !== "string" || name.trim() === "") {
35
36
  return refuse("`name` is required.");
@@ -69,14 +70,14 @@ export async function apiKeyCreate(
69
70
  try {
70
71
  result = await apiCall("POST", "/api/v1/api_keys", body);
71
72
  } catch (error) {
72
- sink.discardKeyFile();
73
+ sink.discardSecret();
73
74
  throw error;
74
75
  }
75
76
 
76
77
  const created = result && result.api_key;
77
78
 
78
79
  if (!created || typeof created.raw_key !== "string") {
79
- sink.discardKeyFile();
80
+ sink.discardSecret();
80
81
  return transportUnknown(result) ? mayHaveMinted(result, name) : stripRaw(result);
81
82
  }
82
83
 
@@ -85,7 +86,7 @@ export async function apiKeyCreate(
85
86
  // A server without US-54.14 (an older release, a rollback) ignores the unknown field and
86
87
  // mints a TENANT-WIDE key. Never hand that over as the scoped key it was asked for.
87
88
  if (snapshot_project_id !== undefined && rest.snapshot_project_id !== snapshot_project_id) {
88
- sink.discardKeyFile();
89
+ sink.discardSecret();
89
90
  const revoked = await apiCall("DELETE", `/api/v1/api_keys/${rest.id}`);
90
91
  const revokeNote =
91
92
  revoked && revoked.error
@@ -99,9 +100,9 @@ export async function apiKeyCreate(
99
100
  }
100
101
 
101
102
  try {
102
- sink.writeRawKey(raw_key);
103
+ sink.writeSecret(raw_key + "\n");
103
104
  } catch (error) {
104
- sink.discardKeyFile();
105
+ sink.discardSecret();
105
106
  return {
106
107
  error: true,
107
108
  status: 0,
@@ -115,30 +116,138 @@ export async function apiKeyCreate(
115
116
  return { api_key: rest, key_file };
116
117
  }
117
118
 
118
- function defaultOpenKey(path) {
119
- const fd = openSync(path, "wx", 0o600);
120
- let open = true;
119
+ /**
120
+ * `api_key_list` / `api_key_rotate` (loopctl #872): `GET /api/v1/api_keys` and
121
+ * `POST /api/v1/api_keys/:id/rotate`, sent on the same user-key caller as `api_key_create`.
122
+ *
123
+ * Both are `role: :user` WITH the hierarchy (`ApiKeyController`'s one plug), so an agent or
124
+ * orchestrator key is 403 insufficient_role. Rotate also sits behind `RequireUnlineagedCaller`:
125
+ * it mints a raw key that belongs to no dispatch lineage, so a caller whose own key a dispatch
126
+ * minted is 403 api_key_mint_forbidden. Neither is human-anchored or custody surface.
127
+ *
128
+ * The list never carries a raw key or hash. Only the literal `include_revoked=true` widens it,
129
+ * so the flag is sent only when it is `true`.
130
+ *
131
+ * Rotate mints a replacement with the old key's name, role, agent and snapshot scope and puts
132
+ * the old key on an expiry `grace_period_hours` from now (default 24). Its raw key is handled
133
+ * exactly as `api_key_create`'s: written to `key_file`, created 0600 BEFORE the request, and
134
+ * never in the result. The server clamps `grace_period_hours` to 168 without saying so, so a
135
+ * larger value (or a non-integer, which it parses or rounds) is refused here, and so is a value
136
+ * under 1: zero or less expires the old key at once, and when that key is the caller's own a
137
+ * lost answer leaves no key to recover with. Refusals: 404 for
138
+ * an unknown id or another tenant's key, 422 `Cannot rotate a revoked key` (an expired
139
+ * agent-linked agent/orchestrator key is revoked by a sweep), 422 for a runner's key.
140
+ */
141
+ export const MAX_GRACE_PERIOD_HOURS = 168;
142
+ export const MIN_GRACE_PERIOD_HOURS = 1;
121
143
 
122
- const closeKeyFd = () => {
123
- if (open) {
124
- open = false;
125
- closeSync(fd);
126
- }
127
- };
144
+ export function apiKeysPath(query = "") {
145
+ return `/api/v1/api_keys${query}`;
146
+ }
147
+
148
+ export function apiKeyRotatePath(keyId) {
149
+ return `/api/v1/api_keys/${encodeURIComponent(keyId)}/rotate`;
150
+ }
151
+
152
+ export async function apiKeyList({ include_revoked } = {}, { apiCall } = {}) {
153
+ if (include_revoked != null && typeof include_revoked !== "boolean") {
154
+ return refuse("`include_revoked` must be a boolean.");
155
+ }
156
+
157
+ return apiCall("GET", apiKeysPath(include_revoked === true ? "?include_revoked=true" : ""), null);
158
+ }
159
+
160
+ export async function apiKeyRotate(
161
+ { api_key_id, grace_period_hours, key_file } = {},
162
+ { apiCall, openKey = createSecretFile } = {},
163
+ ) {
164
+ const bad = uuid(api_key_id, "api_key_id");
165
+ if (bad) return bad;
166
+
167
+ // At least one hour: the key being rotated may be the one making this call, and with no grace
168
+ // a lost answer leaves no working key to list, revoke or rotate with (the new raw key is gone).
169
+ if (
170
+ grace_period_hours != null &&
171
+ !(
172
+ Number.isInteger(grace_period_hours) &&
173
+ grace_period_hours >= MIN_GRACE_PERIOD_HOURS &&
174
+ grace_period_hours <= MAX_GRACE_PERIOD_HOURS
175
+ )
176
+ ) {
177
+ return refuse(
178
+ `\`grace_period_hours\` must be an integer from ${MIN_GRACE_PERIOD_HOURS} to ` +
179
+ `${MAX_GRACE_PERIOD_HOURS} (default 24). loopctl would silently clamp a larger one, and ` +
180
+ "0 or less expires the old key at once, which locks the caller out if it is rotating " +
181
+ "its own key and the answer is lost. Revoke the old key separately once the new one is " +
182
+ "in place.",
183
+ );
184
+ }
185
+
186
+ if (typeof key_file !== "string" || !isAbsolute(key_file)) {
187
+ return refuse(
188
+ "`key_file` must be an absolute path that does not exist yet. The new raw key is " +
189
+ "written there (mode 0600) and never returned, because a tool result lands in the " +
190
+ "transcript.",
191
+ );
192
+ }
193
+
194
+ let sink;
195
+ try {
196
+ sink = openKey(key_file);
197
+ } catch (error) {
198
+ return refuse(
199
+ `${key_file} could not be created (${error.code || error.message}); nothing was ` +
200
+ "rotated. Pass a path that does not exist yet, in a directory that does.",
201
+ );
202
+ }
203
+
204
+ const body = grace_period_hours != null ? { grace_period_hours } : null;
205
+
206
+ let result;
207
+ try {
208
+ result = await apiCall("POST", apiKeyRotatePath(api_key_id), body);
209
+ } catch (error) {
210
+ sink.discardSecret();
211
+ throw error;
212
+ }
213
+
214
+ const minted = result && result.new_key;
215
+
216
+ if (!minted || typeof minted.raw_key !== "string") {
217
+ sink.discardSecret();
218
+ return transportUnknown(result) ? mayHaveRotated(result, api_key_id) : result;
219
+ }
220
+
221
+ const { raw_key, ...rest } = minted;
128
222
 
223
+ try {
224
+ sink.writeSecret(raw_key + "\n");
225
+ } catch (error) {
226
+ sink.discardSecret();
227
+ return {
228
+ error: true,
229
+ status: 0,
230
+ body:
231
+ `${api_key_id} was rotated to ${rest.id} but ${key_file} could not be written ` +
232
+ `(${error.code || error.message}); the new raw key is lost. Revoke ${rest.id} and ` +
233
+ "rotate again with a new key_file before the old key's grace period ends " +
234
+ `(${result.old_key_expires_at}).`,
235
+ };
236
+ }
237
+
238
+ return { new_key: rest, old_key_expires_at: result.old_key_expires_at, key_file };
239
+ }
240
+
241
+ function mayHaveRotated(result, keyId) {
129
242
  return {
130
- writeRawKey: (raw) => {
131
- writeSync(fd, raw + "\n");
132
- closeKeyFd();
133
- },
134
- discardKeyFile: () => {
135
- closeKeyFd();
136
- try {
137
- unlinkSync(path);
138
- } catch {
139
- // already gone
140
- }
141
- },
243
+ ...result,
244
+ body:
245
+ `${typeof result.body === "string" ? result.body : JSON.stringify(result.body)}. ` +
246
+ `The request may have rotated ${keyId}, minting a replacement whose raw value is lost, ` +
247
+ `and if it did, ${keyId} now expires when its grace period ends. Before then, list the ` +
248
+ "tenant's keys (api_key_list) and, if a second key by that name appeared, revoke it and " +
249
+ `rotate ${keyId} again with a new key_file. If ${keyId} is the key making these calls, ` +
250
+ "do it before the grace period ends: after it, no user-role tool can authenticate.",
142
251
  };
143
252
  }
144
253
 
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `changes_since` / `audit_log` — the change feed (`GET /api/v1/changes`,
3
+ * `ChangeController.index`) and the tenant audit log (`GET /api/v1/audit`,
4
+ * `AuditController.index`), loopctl #872.
5
+ *
6
+ * Both read the same `audit_log` rows, and they are two tools because the endpoints answer two
7
+ * different questions on two different gates:
8
+ *
9
+ * - `changes_since` POLLS: every entry after a position, oldest first, keyset-paged. No role
10
+ * plug (any key of the tenant). For an agent-role key the controller drops each `article`
11
+ * entry, and each `article_link` entry, whose article the caller cannot see (#163), so the
12
+ * feed never reads around the knowledge visibility barrier. `since` (ISO 8601) is required
13
+ * unless `cursor` is sent; `cursor` wins when both are. `limit` is clamped to 1..1000.
14
+ * Refusals: 400 without `since`/`cursor`, 400 for a `since` that is not ISO 8601, 400 for a
15
+ * cursor the endpoint did not issue to this tenant (integrity-protected), 422 for a
16
+ * `project_id` that names no project.
17
+ * - `audit_log` SEARCHES: filtered, newest first, page-numbered, with `old_state` and
18
+ * `actor_id` (the change feed carries neither). `role: :user` WITH the hierarchy, so it
19
+ * travels on LOOPCTL_USER_KEY when that is set (index.js `userKeyApiCall`); an agent or
20
+ * orchestrator key is 403 insufficient_role. 422 for a `project_id` that names no project.
21
+ *
22
+ * WHAT IS CHECKED HERE, AND WHY. `project_id` is NOT checked for UUID shape: since #652
23
+ * `ResolveProjectRef` rewrites a slug or repo directory name into the project's id before the
24
+ * controller runs, so a non-UUID is often exactly right. What the controllers would answer
25
+ * WRONGLY rather than refuse is checked:
26
+ *
27
+ * - `audit_log`'s `from`/`to`: `maybe_put_datetime/3` DROPS a value `DateTime.from_iso8601/1`
28
+ * cannot parse, so a mistyped bound answers 200 with the bound silently gone — a wider read
29
+ * that looks like a correct one. Only the full form with seconds and an offset is sent.
30
+ * - `audit_log`'s `entity_id`/`actor_id`: both are `:binary_id` columns, and a non-UUID
31
+ * would fail the query's cast instead of matching nothing.
32
+ * - page and limit integers, which `Integer.parse/1` would otherwise truncate or drop.
33
+ */
34
+
35
+ import { uuid } from "./delivery-loop.js";
36
+
37
+ function refuse(body) {
38
+ return { error: true, status: 0, body };
39
+ }
40
+
41
+ // DateTime.from_iso8601/1 needs a date, a time WITH seconds and an offset. It takes only an
42
+ // uppercase `T` or a space as the separator and an uppercase `Z`, refuses `-00:00`, and refuses
43
+ // any field out of range. A bound it refuses is DROPPED by the controller and the read widens to
44
+ // the whole log, so anything it would refuse is refused here instead.
45
+ const ISO_DATETIME =
46
+ /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|([+-])(\d{2}):(\d{2}))$/;
47
+
48
+ export function serverParsesDatetime(value) {
49
+ if (typeof value !== "string") return false;
50
+ const m = ISO_DATETIME.exec(value);
51
+ if (!m) return false;
52
+ const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number);
53
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
54
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth) return false;
55
+ if (hour > 23 || minute > 59 || second > 59) return false;
56
+ if (m[8] !== "Z") {
57
+ if (m[9] === "-" && m[10] === "00" && m[11] === "00") return false;
58
+ if (Number(m[10]) > 23 || Number(m[11]) > 59) return false;
59
+ }
60
+ return true;
61
+ }
62
+
63
+ function optionalString(value, field) {
64
+ if (value != null && typeof value !== "string") return refuse(`\`${field}\` must be a string.`);
65
+ return null;
66
+ }
67
+
68
+ // ONE template literal per builder (see `test/tool-surface.js`): the query string contributes
69
+ // nothing to the route.
70
+ export function changesPath(query = "") {
71
+ return `/api/v1/changes${query}`;
72
+ }
73
+
74
+ export function auditPath(query = "") {
75
+ return `/api/v1/audit${query}`;
76
+ }
77
+
78
+ function toQuery(pairs) {
79
+ const params = new URLSearchParams();
80
+ for (const [key, value] of pairs) {
81
+ if (value != null && value !== "") params.set(key, String(value));
82
+ }
83
+ const qs = params.toString();
84
+ return qs === "" ? "" : `?${qs}`;
85
+ }
86
+
87
+ export async function readChanges(
88
+ { since, cursor, project_id, entity_type, action, limit } = {},
89
+ { apiCall } = {},
90
+ ) {
91
+ for (const [field, value] of [
92
+ ["since", since],
93
+ ["cursor", cursor],
94
+ ["project_id", project_id],
95
+ ["entity_type", entity_type],
96
+ ["action", action],
97
+ ]) {
98
+ const bad = optionalString(value, field);
99
+ if (bad) return bad;
100
+ }
101
+
102
+ if ((since == null || since === "") && (cursor == null || cursor === "")) {
103
+ return refuse(
104
+ "`since` (an ISO 8601 timestamp, e.g. 2026-11-25T00:00:00Z) is required for the first " +
105
+ "page; after it, send the page's `next_cursor` back as `cursor`.",
106
+ );
107
+ }
108
+
109
+ if (limit != null && !(Number.isInteger(limit) && limit >= 1 && limit <= 1000)) {
110
+ return refuse("`limit` must be an integer from 1 to 1000.");
111
+ }
112
+
113
+ const query = toQuery([
114
+ ["since", since],
115
+ ["cursor", cursor],
116
+ ["project_id", project_id],
117
+ ["entity_type", entity_type],
118
+ ["action", action],
119
+ ["limit", limit],
120
+ ]);
121
+
122
+ return apiCall("GET", changesPath(query), null);
123
+ }
124
+
125
+ export async function readAuditLog(
126
+ { entity_type, entity_id, action, actor_type, actor_id, project_id, from, to, page, page_size } = {},
127
+ { apiCall } = {},
128
+ ) {
129
+ for (const [field, value] of [
130
+ ["entity_type", entity_type],
131
+ ["action", action],
132
+ ["actor_type", actor_type],
133
+ ["project_id", project_id],
134
+ ]) {
135
+ const bad = optionalString(value, field);
136
+ if (bad) return bad;
137
+ }
138
+
139
+ for (const [field, value] of [
140
+ ["entity_id", entity_id],
141
+ ["actor_id", actor_id],
142
+ ]) {
143
+ if (value != null && value !== "") {
144
+ const bad = uuid(value, field);
145
+ if (bad) return bad;
146
+ }
147
+ }
148
+
149
+ for (const [field, value] of [
150
+ ["from", from],
151
+ ["to", to],
152
+ ]) {
153
+ if (value != null && value !== "" && !serverParsesDatetime(value)) {
154
+ return refuse(
155
+ `\`${field}\` must be an ISO 8601 date-time with seconds and an offset, e.g. ` +
156
+ "2026-11-25T00:00:00Z. loopctl drops a bound it cannot parse and answers as if none " +
157
+ "was given, so it is refused here instead.",
158
+ );
159
+ }
160
+ }
161
+
162
+ if (page != null && !(Number.isInteger(page) && page >= 1)) {
163
+ return refuse("`page` must be a positive integer.");
164
+ }
165
+
166
+ if (page_size != null && !(Number.isInteger(page_size) && page_size >= 1 && page_size <= 100)) {
167
+ return refuse("`page_size` must be an integer from 1 to 100 (default 20).");
168
+ }
169
+
170
+ const query = toQuery([
171
+ ["entity_type", entity_type],
172
+ ["entity_id", entity_id],
173
+ ["action", action],
174
+ ["actor_type", actor_type],
175
+ ["actor_id", actor_id],
176
+ ["project_id", project_id],
177
+ ["from", from],
178
+ ["to", to],
179
+ ["page", page],
180
+ ["page_size", page_size],
181
+ ]);
182
+
183
+ return apiCall("GET", auditPath(query), null);
184
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `audit_inclusion_proof` — `GET /api/v1/audit/sth/:tenant_id/inclusion/:position`
3
+ * (`AuditSthController.inclusion`, US-41.7 AC-41.7.4), loopctl #872.
4
+ *
5
+ * NO KEY. The route is public and unauthenticated, like the signed tree head it proves against
6
+ * (`get_sth`): it carries hashes and the already-published STH, never an entry's payload. It is
7
+ * sent through index.js `publicApiCall`, with no Authorization header, so it works in a session
8
+ * whose keys are failing and for any tenant id. Its own pipeline carries
9
+ * `PublicProofThrottle`, a per-IP budget, because producing a proof reads every entry hash up to
10
+ * the STH: 429 with a `retry-after` past it.
11
+ *
12
+ * The answer is `{leaf_index, leaf_hash, tree_size, audit_path: [{position, hash}], sth}`,
13
+ * hashes URL-safe base64 without padding. Fold `leaf_hash` up the `audit_path` and compare with
14
+ * `sth.merkle_root`, then check `sth.signature` against the tenant's public audit key. Refusals:
15
+ * 400 invalid_tenant_id for a tenant id that is not a UUID, 404 for a position with no entry
16
+ * (or out of range), 409 not_yet_included when the entry exists and no signed tree head covers
17
+ * it yet (retry after the next STH).
18
+ *
19
+ * CHECKED HERE: the tenant id's shape, and the position, which must be a non-negative integer —
20
+ * the server reads anything else as no position and answers the same 404 as a missing entry.
21
+ */
22
+
23
+ import { uuid } from "./delivery-loop.js";
24
+
25
+ function refuse(body) {
26
+ return { error: true, status: 0, body };
27
+ }
28
+
29
+ // ONE template literal per builder (see `test/tool-surface.js`).
30
+ export function inclusionPath(tenantId, position) {
31
+ return `/api/v1/audit/sth/${encodeURIComponent(tenantId)}/inclusion/${encodeURIComponent(position)}`;
32
+ }
33
+
34
+ export async function auditInclusionProof({ tenant_id, position } = {}, { apiCall } = {}) {
35
+ const bad = uuid(tenant_id, "tenant_id");
36
+ if (bad) return bad;
37
+
38
+ if (!(Number.isSafeInteger(position) && position >= 0)) {
39
+ return refuse(
40
+ "`position` is required: the entry's chain_position, a non-negative integer (a custody " +
41
+ "claim or an audit entry names it).",
42
+ );
43
+ }
44
+
45
+ return apiCall("GET", inclusionPath(tenant_id, String(position)), null);
46
+ }