loopctl-mcp-server 3.44.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,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
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * `bulk_verify` / `bulk_reject` — `POST /api/v1/stories/bulk/verify` and
3
+ * `POST /api/v1/stories/bulk/reject` (`BulkOperationsController.verify` / `.reject`),
4
+ * loopctl #872.
5
+ *
6
+ * KEY: these are custody verdicts, mounted `exact_role: :orchestrator` with NO hierarchy
7
+ * (`bulk_operations_controller.ex`), the same gate as `verify_story`, `reject_story` and
8
+ * `bulk_mark_complete`. index.js selects the key through `orchestratorKeyArgs`
9
+ * (`lib/custody-key.js`): LOOPCTL_ORCH_KEY sent exactly when set, else a global
10
+ * LOOPCTL_API_KEY. A user or superadmin key is 403 insufficient_role, so the user key is never
11
+ * reached for. Exposing them adds no key to this process: the orchestrator key is the one
12
+ * `verify_story` already sends, and loopctl runs the same lineage comparison per story that it
13
+ * runs for one (`Progress.ensure_verify_allowed/4`, the caller's lineage resolved from the key).
14
+ *
15
+ * WHAT THE ENDPOINTS DO, read from the controller and `Loopctl.BulkOperations`:
16
+ *
17
+ * - `stories` is at most 50 entries (422 when empty, too long or not a list). Each entry is
18
+ * processed in one transaction under row locks, partial success: 200 with `results` when any
19
+ * story succeeded, 422 with `results` when none did. Each result is
20
+ * `{story_id, status, reason?}`, and a story's custody refusal (`self_verify_blocked`,
21
+ * `caller_lineage_required`, `unresolvable_dispatch_lineage`, a chg landed-review or
22
+ * trunk-evidence refusal, `Story not found`, ...) is that story's `reason`.
23
+ * - Whole-batch refusals: 400 when the orchestrator key is linked to no agent, 409
24
+ * chg_root_cannot_verify for a chg-rooted key, 403 custody_tier_required on an agent-rooted
25
+ * tenant, 503 tenant_halted under a custody halt (custody surface). Verify only: under the
26
+ * LCP-1 `signed` profile an enrolled caller is refused 401 bulk_signature_unsupported (or 403
27
+ * agent_enrollment_required), because a set cannot carry a per-story claim signature. Reject
28
+ * only: 500 audit_chain_append_failed when a release's escalation could not append its chain
29
+ * entry, and the whole batch rolled back.
30
+ * - verify reads each entry's `summary`, `review_type` and `findings`; reject reads `reason`
31
+ * (required, non-empty: a per-story `reason_required` otherwise), `review_type` and
32
+ * `findings`. The published request schema names a `notes` field: the server never reads it.
33
+ *
34
+ * CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
35
+ *
36
+ * - a non-string `summary`/`review_type`/`reason` or a non-object `findings`: the
37
+ * verification_result insert fails its changeset, the failure is only LOGGED, and the story
38
+ * is verified or rejected anyway with no result row — a verdict whose record went missing;
39
+ * - a duplicate story id: the per-story parameters are a map keyed by id, so the last entry's
40
+ * fields silently replace the first's;
41
+ * - a non-UUID story id, which fails the lock query's cast instead of reading as one error.
42
+ *
43
+ * The batch bounds and a missing reject `reason` are refused too, so a call that cannot succeed
44
+ * sends nothing.
45
+ */
46
+
47
+ import { badStoryIdBatch } from "./story-claims.js";
48
+
49
+ function refuse(body) {
50
+ return { error: true, status: 0, body };
51
+ }
52
+
53
+ // ONE template literal per builder (see `test/tool-surface.js`).
54
+ export function bulkVerifyPath() {
55
+ return `/api/v1/stories/bulk/verify`;
56
+ }
57
+
58
+ export function bulkRejectPath() {
59
+ return `/api/v1/stories/bulk/reject`;
60
+ }
61
+
62
+ function badEntries(stories, { requireReason }) {
63
+ if (!Array.isArray(stories) || stories.length === 0) {
64
+ return refuse("`stories` is required: a non-empty array of `{story_id, ...}` entries.");
65
+ }
66
+
67
+ for (const [i, entry] of stories.entries()) {
68
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
69
+ return refuse(`\`stories[${i}]\` must be an object with a \`story_id\`.`);
70
+ }
71
+ }
72
+
73
+ const batch = badStoryIdBatch(
74
+ stories.map((s) => s.story_id),
75
+ "stories",
76
+ (i) => `stories[${i}].story_id`,
77
+ );
78
+ if (batch) return batch;
79
+
80
+ for (const [i, entry] of stories.entries()) {
81
+ for (const field of ["summary", "review_type", "reason"]) {
82
+ if (entry[field] != null && typeof entry[field] !== "string") {
83
+ return refuse(`\`stories[${i}].${field}\` must be a string.`);
84
+ }
85
+ }
86
+
87
+ if (
88
+ entry.findings != null &&
89
+ (typeof entry.findings !== "object" || Array.isArray(entry.findings))
90
+ ) {
91
+ return refuse(`\`stories[${i}].findings\` must be an object.`);
92
+ }
93
+
94
+ if (requireReason && (typeof entry.reason !== "string" || entry.reason.trim() === "")) {
95
+ return refuse(`\`stories[${i}].reason\` is required: why the story is rejected.`);
96
+ }
97
+ }
98
+
99
+ return null;
100
+ }
101
+
102
+ // Only the fields the server reads, so nothing a caller adds rides along unread.
103
+ function pick(entry, fields) {
104
+ const out = { story_id: entry.story_id };
105
+ for (const field of fields) {
106
+ if (entry[field] != null) out[field] = entry[field];
107
+ }
108
+ return out;
109
+ }
110
+
111
+ export async function bulkVerifyStories({ stories } = {}, { apiCall } = {}) {
112
+ const bad = badEntries(stories, { requireReason: false });
113
+ if (bad) return bad;
114
+
115
+ const body = { stories: stories.map((s) => pick(s, ["summary", "review_type", "findings"])) };
116
+ return apiCall("POST", bulkVerifyPath(), body);
117
+ }
118
+
119
+ export async function bulkRejectStories({ stories } = {}, { apiCall } = {}) {
120
+ const bad = badEntries(stories, { requireReason: true });
121
+ if (bad) return bad;
122
+
123
+ const body = { stories: stories.map((s) => pick(s, ["reason", "review_type", "findings"])) };
124
+ return apiCall("POST", bulkRejectPath(), body);
125
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * `channel_quarantine_list` / `channel_quarantine_release` — `GET /api/v1/channel/posts/quarantined` and
3
+ * `POST /api/v1/channel/posts/:id/release` (`ChannelPostController.quarantined` / `.release`,
4
+ * issue #499), loopctl #872.
5
+ *
6
+ * KEY: both are `role: :user` WITH the hierarchy plus `RequireHumanAnchor`, so an agent or
7
+ * orchestrator key is 403 insufficient_role and an agent-rooted tenant 403
8
+ * custody_tier_required. They travel on LOOPCTL_USER_KEY when set, else the default key (index.js
9
+ * `userKeyApiCall`). Neither is custody surface, so a custody halt does not block them.
10
+ *
11
+ * WHY THE BODIES GO TO A FILE. The quarantine read is the ONE endpoint that returns the full
12
+ * text of posts the secret rescan flagged as carrying a credential shape, and it is gated at
13
+ * user role precisely so that no agent reads one back. A tool result lands in the session
14
+ * transcript, so returning those fields would copy each suspected credential into the
15
+ * transcript of whichever session asked. `api_key_create` keeps a raw key out of the transcript
16
+ * the same way: the full rows are written to `rows_file` (an absolute path that must not exist
17
+ * yet, created 0600 before the request), and the result carries every row with the fields the
18
+ * rescan scans REMOVED — `quarantine_reason` names which of them tripped. A person reads the
19
+ * file, judges, then redacts (`channel_delete`) or releases (`channel_quarantine_release`), and deletes
20
+ * the file.
21
+ *
22
+ * The release answers with the released post; its scanned fields are removed from the result
23
+ * for the same reason (a mistaken release is still a credential), and `channel_get` reads it
24
+ * back. Release refusals: 404, byte-identical, for a post that is missing, another tenant's,
25
+ * malformed or not quarantined; 500 audit_write_failed when the audit entry could not be written
26
+ * (the release rolled back and the post is still quarantined).
27
+ *
28
+ * CHECKED HERE, because the server would answer it WRONGLY rather than refuse: a `limit`
29
+ * outside 1..100 (0 or less reads as the default 25, more is clamped to 100). A `project_id` is
30
+ * an id, or a slug or repo name `ResolveProjectRef` rewrites to one; a reference that resolves
31
+ * to no project is not refused by the server, it matches nothing and answers an empty list, and
32
+ * nothing here can tell that apart from an empty quarantine, so the description says so. A
33
+ * non-UUID post id is refused: it answers the same 404 as a post that is not quarantined.
34
+ */
35
+
36
+ import { isAbsolute } from "node:path";
37
+ import { uuid } from "./delivery-loop.js";
38
+ import { createSecretFile } from "./secret-file.js";
39
+
40
+ // `ChannelPost.secret_fields/1`'s scanned set (`@scanned_text_fields` + `refs`), as the
41
+ // controller's `quarantined_json/1` returns them.
42
+ export const SCANNED_FIELDS = [
43
+ "body",
44
+ "key",
45
+ "session_id",
46
+ "host",
47
+ "to_host",
48
+ "to_capability",
49
+ "idempotency_key",
50
+ "refs",
51
+ ];
52
+
53
+ function refuse(body) {
54
+ return { error: true, status: 0, body };
55
+ }
56
+
57
+ // ONE template literal per builder (see `test/tool-surface.js`).
58
+ export function quarantinedPath(query = "") {
59
+ return `/api/v1/channel/posts/quarantined${query}`;
60
+ }
61
+
62
+ export function releasePath(postId) {
63
+ return `/api/v1/channel/posts/${encodeURIComponent(postId)}/release`;
64
+ }
65
+
66
+ export function withoutScannedFields(row) {
67
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
68
+ const out = {};
69
+ for (const [field, value] of Object.entries(row)) {
70
+ if (!SCANNED_FIELDS.includes(field)) out[field] = value;
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * `deps.apiCall(method, path, body)` is the user-key caller; `deps.openRows(path)` creates the
77
+ * file and returns `{ writeSecret(text), discardSecret() }` (injected so a test owns the disk it touches).
78
+ */
79
+ export async function listQuarantinedPosts(
80
+ { project_id, limit, rows_file } = {},
81
+ { apiCall, openRows = createSecretFile } = {},
82
+ ) {
83
+ if (project_id != null && (typeof project_id !== "string" || project_id.trim() === "")) {
84
+ return refuse("`project_id` must be a non-empty string: a project's id, slug or repo name.");
85
+ }
86
+
87
+ if (limit != null && !(Number.isInteger(limit) && limit >= 1 && limit <= 100)) {
88
+ return refuse("`limit` must be an integer from 1 to 100 (default 25).");
89
+ }
90
+
91
+ if (typeof rows_file !== "string" || !isAbsolute(rows_file)) {
92
+ return refuse(
93
+ "`rows_file` must be an absolute path that does not exist yet. The quarantined posts' " +
94
+ "full fields are written there (mode 0600) and never returned, because a tool result " +
95
+ "lands in the transcript and these posts were quarantined as suspected credentials.",
96
+ );
97
+ }
98
+
99
+ let sink;
100
+ try {
101
+ sink = openRows(rows_file);
102
+ } catch (error) {
103
+ return refuse(
104
+ `${rows_file} could not be created (${error.code || error.message}); nothing was read. ` +
105
+ "Pass a path that does not exist yet, in a directory that does.",
106
+ );
107
+ }
108
+
109
+ const params = new URLSearchParams();
110
+ if (project_id != null) params.set("project_id", project_id);
111
+ if (limit != null) params.set("limit", String(limit));
112
+ const qs = params.toString();
113
+
114
+ let result;
115
+ try {
116
+ result = await apiCall("GET", quarantinedPath(qs === "" ? "" : `?${qs}`), null);
117
+ } catch (error) {
118
+ sink.discardSecret();
119
+ throw error;
120
+ }
121
+
122
+ if (!result || result.error || !Array.isArray(result.data)) {
123
+ sink.discardSecret();
124
+ return result;
125
+ }
126
+
127
+ try {
128
+ sink.writeSecret(JSON.stringify(result, null, 2) + "\n");
129
+ } catch (error) {
130
+ sink.discardSecret();
131
+ return refuse(
132
+ `${rows_file} could not be written (${error.code || error.message}); the posts were read ` +
133
+ "and are not returned here. Read again with a new rows_file.",
134
+ );
135
+ }
136
+
137
+ return {
138
+ data: result.data.map(withoutScannedFields),
139
+ meta: result.meta,
140
+ rows_file,
141
+ withheld_fields: SCANNED_FIELDS,
142
+ };
143
+ }
144
+
145
+ export async function releaseQuarantinedPost({ post_id } = {}, { apiCall } = {}) {
146
+ const bad = uuid(post_id, "post_id");
147
+ if (bad) return bad;
148
+
149
+ const result = await apiCall("POST", releasePath(post_id), null);
150
+
151
+ if (result && !result.error && result.post) {
152
+ return { ...result, post: withoutScannedFields(result.post), withheld_fields: SCANNED_FIELDS };
153
+ }
154
+
155
+ return result;
156
+ }
157
+