@indigoai-us/hq-cli 5.345.214 → 5.345.215-beta.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 (103) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/command-catalog.generated.d.ts +134 -7
  3. package/dist/command-catalog.generated.js +168 -7
  4. package/dist/commands/agents.d.ts +51 -1
  5. package/dist/commands/agents.js +154 -2
  6. package/dist/commands/bot-jobs.d.ts +2 -15
  7. package/dist/commands/bot-jobs.js +2 -94
  8. package/dist/commands/bot-runtime.d.ts +46 -5
  9. package/dist/commands/bot-runtime.js +228 -18
  10. package/dist/commands/bot.d.ts +16 -9
  11. package/dist/commands/bot.js +169 -51
  12. package/dist/commands/cloud.d.ts +66 -13
  13. package/dist/commands/cloud.js +120 -39
  14. package/dist/commands/company-restore.d.ts +23 -0
  15. package/dist/commands/company-restore.js +128 -0
  16. package/dist/commands/company.js +2 -0
  17. package/dist/commands/integrations-connect.d.ts +10 -3
  18. package/dist/commands/integrations-connect.js +87 -13
  19. package/dist/commands/lanes.js +26 -9
  20. package/dist/commands/sources.js +6 -0
  21. package/dist/commands/storage-offload.d.ts +12 -0
  22. package/dist/commands/storage-offload.js +41 -3
  23. package/dist/commands/sync-mode.js +5 -0
  24. package/dist/commands/whoami.js +4 -0
  25. package/dist/lib/bot/config.d.ts +1 -0
  26. package/dist/lib/bot/config.js +10 -0
  27. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  28. package/dist/lib/bot/eventbridge-cron.js +104 -0
  29. package/dist/lib/bot/fleet-local.d.ts +33 -1
  30. package/dist/lib/bot/fleet-local.js +215 -31
  31. package/dist/lib/bot/fleet-python.d.ts +3 -0
  32. package/dist/lib/bot/fleet-python.js +34 -4
  33. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  34. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  36. package/dist/lib/bot/legacy-provider-login.js +19 -2
  37. package/dist/lib/bot/prompt.js +1 -1
  38. package/dist/lib/bot/readiness.d.ts +8 -0
  39. package/dist/lib/bot/readiness.js +17 -3
  40. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  41. package/dist/lib/bot/runtime-auth.js +94 -3
  42. package/dist/lib/bot/status.d.ts +2 -0
  43. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  44. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  45. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  46. package/dist/lib/capacity/collectors/grok.js +56 -5
  47. package/dist/lib/daemon/catalog.js +11 -1
  48. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  49. package/dist/lib/db/sqlite-binding.js +1 -1
  50. package/dist/lib/delivery/artifacts.d.ts +99 -0
  51. package/dist/lib/delivery/artifacts.js +548 -0
  52. package/dist/lib/delivery/backup.d.ts +78 -0
  53. package/dist/lib/delivery/backup.js +343 -0
  54. package/dist/lib/delivery/cache.d.ts +29 -0
  55. package/dist/lib/delivery/cache.js +33 -0
  56. package/dist/lib/delivery/contracts.d.ts +142 -0
  57. package/dist/lib/delivery/contracts.js +289 -0
  58. package/dist/lib/delivery/credentials.d.ts +54 -0
  59. package/dist/lib/delivery/credentials.js +119 -0
  60. package/dist/lib/delivery/enrollment.d.ts +142 -0
  61. package/dist/lib/delivery/enrollment.js +382 -0
  62. package/dist/lib/delivery/identity.d.ts +25 -0
  63. package/dist/lib/delivery/identity.js +82 -0
  64. package/dist/lib/delivery/inbox.d.ts +116 -0
  65. package/dist/lib/delivery/inbox.js +260 -0
  66. package/dist/lib/delivery/migrations.d.ts +139 -0
  67. package/dist/lib/delivery/migrations.js +623 -0
  68. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  69. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  70. package/dist/lib/delivery/mqtt.d.ts +61 -0
  71. package/dist/lib/delivery/mqtt.js +112 -0
  72. package/dist/lib/delivery/outbox.d.ts +95 -0
  73. package/dist/lib/delivery/outbox.js +187 -0
  74. package/dist/lib/delivery/provenance.d.ts +129 -0
  75. package/dist/lib/delivery/provenance.js +93 -0
  76. package/dist/lib/delivery/reconciler.d.ts +151 -0
  77. package/dist/lib/delivery/reconciler.js +492 -0
  78. package/dist/lib/delivery/restore.d.ts +35 -0
  79. package/dist/lib/delivery/restore.js +134 -0
  80. package/dist/lib/delivery/store.d.ts +161 -0
  81. package/dist/lib/delivery/store.js +940 -0
  82. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  83. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  84. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  85. package/dist/lib/delivery/workers/macos.js +901 -0
  86. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  87. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  88. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  89. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  90. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  91. package/dist/lib/delivery/workers/windows.js +608 -0
  92. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  93. package/dist/lib/install/provider-wrappers.js +68 -3
  94. package/dist/utils/cognito-callback-port.d.ts +14 -0
  95. package/dist/utils/cognito-callback-port.js +24 -0
  96. package/dist/utils/cognito-session.js +3 -3
  97. package/dist/utils/deleted-company-notice.d.ts +59 -0
  98. package/dist/utils/deleted-company-notice.js +156 -0
  99. package/dist/utils/login-browser.d.ts +1 -1
  100. package/dist/utils/login-browser.js +7 -5
  101. package/dist/utils/resident-package-preload.js +30 -15
  102. package/dist/utils/vault-api.js +7 -0
  103. package/package.json +7 -7
@@ -0,0 +1,382 @@
1
+ import { assertJobTrust, injectCredentials, planCredentials, } from "./credentials.js";
2
+ import { authenticate, newSecret, secretDigest, secretMatches, trustAllows } from "./identity.js";
3
+ import { DeliveryStoreError, WORKER_CAPABILITIES, WORKER_TRUSTS, } from "./migrations.js";
4
+ import { sameEvent } from "./outbox.js";
5
+ import { notClaimant, openDeliveryController, } from "./reconciler.js";
6
+ export const MAX_READY_PAGE = 1000;
7
+ const NO_CREDENTIALS = {
8
+ resolve: () => {
9
+ throw new Error("no credential source");
10
+ },
11
+ };
12
+ function denied(found, expected, action) {
13
+ return new DeliveryStoreError("ACCESS_DENIED", { found, expected, action: `${action} Nothing was written.` });
14
+ }
15
+ function rejected(found, expected, action) {
16
+ return new DeliveryStoreError("PRIVILEGE_REJECTED", { found, expected, action: `${action} Nothing was written.` });
17
+ }
18
+ function invalid(found, expected) {
19
+ return new DeliveryStoreError("INVALID_RECORD", { found, expected, action: "Fix the input and retry. Nothing was written." });
20
+ }
21
+ function checkScope(scope) {
22
+ const s = scope;
23
+ const ok = typeof scope === "object" &&
24
+ scope !== null &&
25
+ Array.isArray(s.tenantIds) &&
26
+ s.tenantIds.length > 0 &&
27
+ s.tenantIds.every((t) => typeof t === "string" && t !== "") &&
28
+ WORKER_TRUSTS.includes(s.maxTrust);
29
+ if (!ok) {
30
+ throw denied("a missing or malformed admin scope", "tenantIds as a non-empty list and a known maxTrust", "Pass the admin's company scope.");
31
+ }
32
+ return s;
33
+ }
34
+ function checkRequest(input) {
35
+ const r = input;
36
+ if (typeof input !== "object" || input === null)
37
+ throw invalid("a missing enrollment request", "tenantId, workerId, capabilities and trust");
38
+ if (typeof r.tenantId !== "string" || r.tenantId === "")
39
+ throw invalid("tenantId that is not a non-empty string", "a tenantId");
40
+ if (typeof r.workerId !== "string" || r.workerId === "")
41
+ throw invalid("workerId that is not a non-empty string", "a workerId");
42
+ const caps = r.capabilities;
43
+ if (!Array.isArray(caps) ||
44
+ caps.length === 0 ||
45
+ !caps.every((c) => WORKER_CAPABILITIES.includes(c)) ||
46
+ new Set(caps).size !== caps.length) {
47
+ throw invalid(`capabilities ${JSON.stringify(caps)}`, `a non-empty list of distinct ${WORKER_CAPABILITIES.join(", ")}`);
48
+ }
49
+ if (!WORKER_TRUSTS.includes(r.trust))
50
+ throw invalid(`trust ${JSON.stringify(r.trust)}`, WORKER_TRUSTS.join(" or "));
51
+ return { tenantId: r.tenantId, workerId: r.workerId, capabilities: [...caps], trust: r.trust };
52
+ }
53
+ function inScope(scope, tenantId, workerId) {
54
+ if (!scope.tenantIds.includes(tenantId)) {
55
+ throw denied(`worker ${workerId} in a company outside the admin's scope`, `a company in the admin's scope: ${scope.tenantIds.join(", ")}`, "Ask an admin of that company.");
56
+ }
57
+ }
58
+ function view(w) {
59
+ return {
60
+ workerId: w.workerId,
61
+ tenantId: w.tenantId,
62
+ capabilities: [...w.capabilities],
63
+ trust: w.trust,
64
+ status: w.status,
65
+ issuedAt: w.issuedAt,
66
+ enrolledAt: w.enrolledAt,
67
+ revokedAt: w.revokedAt,
68
+ };
69
+ }
70
+ /** Open a store directory as its controller, with the worker access layer on top. */
71
+ export function openDeliveryAccess(opts) {
72
+ const { credentialPolicy, credentialSource, ...controllerOpts } = opts;
73
+ return new DeliveryAccess(openDeliveryController(controllerOpts), credentialPolicy, credentialSource);
74
+ }
75
+ export class DeliveryAccess {
76
+ /** The underlying controller, for accepting runs and admin reads. Worker operations go through this class. */
77
+ controller;
78
+ policy;
79
+ source;
80
+ constructor(controller, policy, source) {
81
+ this.controller = controller;
82
+ this.policy = policy;
83
+ this.source = source;
84
+ }
85
+ /** Issue a one-time enrollment ticket. The worker is pending until it enrolls. */
86
+ issueEnrollment(scope, request) {
87
+ this.controller.assertOwner();
88
+ const s = checkScope(scope);
89
+ const r = checkRequest(request);
90
+ inScope(s, r.tenantId, r.workerId);
91
+ if (!trustAllows(s.maxTrust, r.trust)) {
92
+ throw rejected(`a request for ${r.trust} trust`, `trust up to the admin's ${s.maxTrust}`, "Issue the ticket with lower trust, or ask an admin who may grant it.");
93
+ }
94
+ const ticket = newSecret("enrollment");
95
+ this.controller.commitWorkers((workers, at) => {
96
+ if (workers.some((w) => w.workerId === r.workerId)) {
97
+ throw new DeliveryStoreError("DUPLICATE_CONFLICT", {
98
+ found: `worker ${r.workerId} already exists`,
99
+ expected: "a new workerId",
100
+ action: "Use a new workerId, or revoke and replace the worker under a new id. Nothing was written.",
101
+ });
102
+ }
103
+ workers.push({
104
+ workerId: r.workerId,
105
+ tenantId: r.tenantId,
106
+ capabilities: [...r.capabilities],
107
+ trust: r.trust,
108
+ status: "pending",
109
+ secretSha256: secretDigest(ticket),
110
+ issuedAt: at.now,
111
+ issuedEpoch: at.epoch,
112
+ enrolledAt: null,
113
+ enrolledEpoch: null,
114
+ revokedAt: null,
115
+ revokedEpoch: null,
116
+ });
117
+ });
118
+ return { ...r, ticket };
119
+ }
120
+ /**
121
+ * Redeem a ticket for a worker token. The request must name the ticket's
122
+ * company and stay within its capabilities and trust.
123
+ */
124
+ enroll(input) {
125
+ const r = checkRequest(input);
126
+ const ticket = input.ticket;
127
+ const notFound = denied(`no pending enrollment for worker ${r.workerId} with the presented ticket`, "the tenantId, workerId and unused ticket from issueEnrollment", "Check the ticket, or ask an admin to issue a new one.");
128
+ const matchTicket = (workers) => {
129
+ const found = workers.filter((w) => w.workerId === r.workerId);
130
+ const w = found[0];
131
+ if (found.length !== 1 ||
132
+ !w ||
133
+ w.status !== "pending" ||
134
+ w.tenantId !== r.tenantId ||
135
+ typeof ticket !== "string" ||
136
+ ticket === "" ||
137
+ !secretMatches(ticket, w.secretSha256)) {
138
+ throw notFound;
139
+ }
140
+ return w;
141
+ };
142
+ const pending = matchTicket(this.ownedRecords());
143
+ const extra = r.capabilities.filter((c) => !pending.capabilities.includes(c));
144
+ if (extra.length > 0) {
145
+ throw rejected(`a request for capabilities ${extra.join(", ")} beyond the ticket`, `capabilities within ${pending.capabilities.join(", ")}`, "Enroll with the ticket's capabilities, or ask for a new ticket.");
146
+ }
147
+ if (!trustAllows(pending.trust, r.trust)) {
148
+ throw rejected(`a request for ${r.trust} trust`, `trust up to the ticket's ${pending.trust}`, "Enroll with the ticket's trust, or ask for a new ticket.");
149
+ }
150
+ const token = newSecret("worker");
151
+ this.controller.commitWorkers((workers, at) => {
152
+ // Re-check in the commit: a revocation or another redemption may have landed since.
153
+ const w = matchTicket(workers);
154
+ w.capabilities = [...r.capabilities];
155
+ w.trust = r.trust;
156
+ w.status = "active";
157
+ w.secretSha256 = secretDigest(token);
158
+ w.enrolledAt = at.now;
159
+ w.enrolledEpoch = at.epoch;
160
+ });
161
+ return { workerId: r.workerId, token };
162
+ }
163
+ /** Revoke a worker. It can no longer claim, read or report. Revoking twice is a no-op. */
164
+ revoke(scope, workerId) {
165
+ this.controller.assertOwner();
166
+ const s = checkScope(scope);
167
+ const find = (workers) => {
168
+ const found = workers.filter((w) => w.workerId === workerId);
169
+ const w = found[0];
170
+ if (found.length !== 1 || !w || !s.tenantIds.includes(w.tenantId)) {
171
+ throw denied(`no worker ${String(workerId)} in the admin's scope`, "a workerId in a company the admin manages", "Check the workerId and the admin's scope.");
172
+ }
173
+ return w;
174
+ };
175
+ const current = find(this.ownedRecords());
176
+ if (current.status === "revoked")
177
+ return view(current);
178
+ this.controller.commitWorkers((workers, at) => {
179
+ const w = find(workers);
180
+ if (w.status === "revoked")
181
+ return;
182
+ w.status = "revoked";
183
+ w.revokedAt = at.now;
184
+ w.revokedEpoch = at.epoch;
185
+ });
186
+ return view(find(this.ownedRecords()));
187
+ }
188
+ /** Workers in the admin's scope, without secret digests. */
189
+ workers(scope) {
190
+ this.controller.assertOwner();
191
+ const s = checkScope(scope);
192
+ return this.controller
193
+ .workerRecords()
194
+ .filter((w) => s.tenantIds.includes(w.tenantId))
195
+ .map(view);
196
+ }
197
+ /** Read a run of the worker's own company and its jobs. Needs "read". */
198
+ readRun(identity, runId) {
199
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "read" });
200
+ const run = this.controller.runs().find((r) => r.runId === runId);
201
+ if (!run) {
202
+ throw new DeliveryStoreError("UNKNOWN_RUN", {
203
+ found: `no accepted run ${runId}`,
204
+ expected: "an accepted runId",
205
+ action: "Check the runId. Nothing was written.",
206
+ });
207
+ }
208
+ this.sameTenant(worker, run.tenantId, `run ${runId}`);
209
+ return { run, jobs: this.controller.jobs(runId) };
210
+ }
211
+ /** Claim a ready job of the worker's own company. Needs "claim". */
212
+ claim(identity, jobId) {
213
+ const { worker, guard } = this.prepareClaim(identity, jobId);
214
+ return this.controller.claim(jobId, { guard, workerId: worker.workerId });
215
+ }
216
+ /** Report the outcome of an attempt of the worker's own company. Needs "report". */
217
+ recordOutcome(identity, attemptId, outcome) {
218
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "report" });
219
+ const attempt = this.controller.attempts().find((a) => a.attempt.attemptId === attemptId);
220
+ if (!attempt) {
221
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
222
+ found: `no attempt ${attemptId}`,
223
+ expected: "an attemptId returned by claim",
224
+ action: "Check the attemptId. Nothing was written.",
225
+ });
226
+ }
227
+ this.sameTenant(worker, attempt.attempt.tenantId, `attempt ${attemptId}`);
228
+ if (attempt.claimedBy !== worker.workerId)
229
+ throw notClaimant(worker.workerId, attemptId);
230
+ return this.controller.recordOutcome(attemptId, outcome, { guard: this.attemptGuard(identity, worker.tenantId, attemptId) });
231
+ }
232
+ /** US-007: return an open attempt of the worker's own company unfinished, so its job can be claimed again. Needs "report". */
233
+ returnAttempt(identity, attemptId) {
234
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "report" });
235
+ const attempt = this.controller.attempts().find((a) => a.attempt.attemptId === attemptId);
236
+ if (!attempt) {
237
+ throw new DeliveryStoreError("UNKNOWN_ATTEMPT", {
238
+ found: `no attempt ${attemptId}`,
239
+ expected: "an attemptId returned by claim",
240
+ action: "Check the attemptId. Nothing was written.",
241
+ });
242
+ }
243
+ this.sameTenant(worker, attempt.attempt.tenantId, `attempt ${attemptId}`);
244
+ if (attempt.claimedBy !== worker.workerId)
245
+ throw notClaimant(worker.workerId, attemptId);
246
+ return this.controller.returnAttempt(attemptId, { guard: this.attemptGuard(identity, worker.tenantId, attemptId) });
247
+ }
248
+ /**
249
+ * Claim a job and inject the credentials it may have. The request is planned
250
+ * first, so a rejected request looks nothing up; credentials are injected
251
+ * before the claim, so a lookup failure claims nothing.
252
+ */
253
+ dispatch(identity, jobId, request) {
254
+ const { worker, job, guard } = this.prepareClaim(identity, jobId);
255
+ const plan = planCredentials(this.policy, { job, workerTrust: worker.trust, requested: request?.credentials });
256
+ if (plan.refs.length > 0 && !this.source) {
257
+ throw new DeliveryStoreError("CREDENTIAL_UNAVAILABLE", {
258
+ found: `no credential source configured for ${plan.refs.join(", ")}`,
259
+ expected: "a credential source",
260
+ action: "Open the access layer with a credential source. Nothing was claimed.",
261
+ });
262
+ }
263
+ const credentials = injectCredentials(this.source ?? NO_CREDENTIALS, plan.refs);
264
+ const claim = this.controller.claim(jobId, { guard, workerId: worker.workerId });
265
+ return { claim, jobClass: plan.jobClass, credentials };
266
+ }
267
+ /** The company of an authenticated worker. Needs "claim". */
268
+ workerTenant(identity) {
269
+ return authenticate(this.ownedRecords(), identity, { capability: "claim" }).tenantId;
270
+ }
271
+ /**
272
+ * Ready jobs of the worker's own company after `after`, in ledger order, at
273
+ * most `limit`. An unknown cursor starts from the beginning. Needs "claim".
274
+ * Read only: it claims nothing and never removes a job.
275
+ */
276
+ readyWork(identity, page) {
277
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "claim" });
278
+ const limit = page?.limit;
279
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_READY_PAGE) {
280
+ throw invalid(`limit ${String(limit)}`, `an integer from 1 to ${MAX_READY_PAGE}`);
281
+ }
282
+ const own = this.controller.jobs().filter((j) => j.job.tenantId === worker.tenantId);
283
+ const at = page.after === null ? -1 : own.findIndex((j) => j.job.jobId === page.after);
284
+ const jobs = [];
285
+ for (const view of own.slice(at + 1)) {
286
+ if (view.state !== "ready")
287
+ continue;
288
+ jobs.push(view.job.jobId);
289
+ if (jobs.length === limit)
290
+ break;
291
+ }
292
+ return { jobs, cursor: jobs.length === limit ? jobs[jobs.length - 1] : null };
293
+ }
294
+ /**
295
+ * Check a notification against the committed ledger and return the jobs it
296
+ * may have made ready. A notification is a hint: it is accepted only when
297
+ * the ledger derives an event with the same id and the same values in every
298
+ * field, for the worker's own company. Needs "claim". Claims nothing.
299
+ *
300
+ * Another company's event is ACCESS_DENIED naming only the worker's company.
301
+ * Anything else that does not match is NOTIFICATION_UNVERIFIED, and the
302
+ * message does not repeat the presented ids.
303
+ */
304
+ verifyNotification(identity, event) {
305
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "claim" });
306
+ this.sameTenant(worker, event.tenantId, "a notification");
307
+ const derived = this.controller
308
+ .ledgerEvents()
309
+ .find((e) => e.tenantId === worker.tenantId && e.eventId === event.eventId);
310
+ if (!derived || !sameEvent(derived, event)) {
311
+ throw new DeliveryStoreError("NOTIFICATION_UNVERIFIED", {
312
+ found: `a notification for ${worker.tenantId} that no committed ledger record matches`,
313
+ expected: "a notification equal to an event derived from the committed ledger",
314
+ action: "Ignore it; reconciliation reads ready work from the ledger. Nothing was written.",
315
+ });
316
+ }
317
+ if (derived.type === "job.accepted")
318
+ return [derived.jobId];
319
+ const dependents = this.controller
320
+ .jobs(derived.runId)
321
+ .filter((j) => j.dependsOn.includes(derived.jobId))
322
+ .map((j) => j.job.jobId);
323
+ return [derived.jobId, ...dependents];
324
+ }
325
+ /** Release ownership of the store. Idempotent. */
326
+ close() {
327
+ this.controller.close();
328
+ }
329
+ prepareClaim(identity, jobId) {
330
+ const worker = authenticate(this.ownedRecords(), identity, { capability: "claim" });
331
+ // One job, not every job's view: building them all made each claim O(jobs x attempts).
332
+ const view = this.controller.job(jobId);
333
+ if (!view) {
334
+ throw new DeliveryStoreError("UNKNOWN_JOB", {
335
+ found: `no accepted job ${jobId}`,
336
+ expected: "an accepted jobId",
337
+ action: "Check the jobId. Nothing was written.",
338
+ });
339
+ }
340
+ this.sameTenant(worker, view.job.tenantId, `job ${jobId}`);
341
+ // The release-trust rule is checked here so claim() and dispatch() enforce it alike.
342
+ assertJobTrust(this.policy, view.job, worker.trust);
343
+ const job = view.job;
344
+ const guard = (state) => {
345
+ const current = authenticate(state.workers, identity, { capability: "claim", tenantId: worker.tenantId });
346
+ assertJobTrust(this.policy, job, current.trust);
347
+ };
348
+ return { worker, job, guard };
349
+ }
350
+ /**
351
+ * Worker records, only while this handle owns the store. A superseded or
352
+ * closed handle still holds its last state in memory, which may list a
353
+ * worker the current owner has revoked; it must not authenticate or serve
354
+ * anything from that state (FENCED or STORE_CLOSED, read only).
355
+ */
356
+ ownedRecords() {
357
+ this.controller.assertOwner();
358
+ return this.controller.workerRecords();
359
+ }
360
+ /** Re-authenticates against the state being committed, so a revocation in flight wins. */
361
+ guard(identity, capability, tenantId) {
362
+ return (state) => {
363
+ authenticate(state.workers, identity, { capability, tenantId });
364
+ };
365
+ }
366
+ /** Re-authenticates for "report" and re-checks, inside the commit, that the caller claimed the attempt. */
367
+ attemptGuard(identity, tenantId, attemptId) {
368
+ return (state) => {
369
+ const worker = authenticate(state.workers, identity, { capability: "report", tenantId });
370
+ const a = state.attempts.find((x) => x.record.attemptId === attemptId);
371
+ if (!a || a.claimedBy !== worker.workerId)
372
+ throw notClaimant(worker.workerId, attemptId);
373
+ };
374
+ }
375
+ /** Deny work of another company. The message names the worker and its own company only. */
376
+ sameTenant(worker, tenantId, what) {
377
+ if (worker.tenantId === tenantId)
378
+ return;
379
+ throw denied(`worker ${worker.workerId} of ${worker.tenantId} asked for ${what}, which belongs to another company`, `work of the worker's own company ${worker.tenantId}`, "Use a worker enrolled in the company that owns the work.");
380
+ }
381
+ }
382
+ //# sourceMappingURL=enrollment.js.map
@@ -0,0 +1,25 @@
1
+ import { type StoredWorker, type WorkerCapability, type WorkerTrust } from "./migrations.js";
2
+ export interface WorkerIdentity {
3
+ workerId: string;
4
+ token: string;
5
+ }
6
+ /** Check the shape of a presented identity. Exactly two non-empty strings, nothing else. */
7
+ export declare function parseIdentity(input: unknown): WorkerIdentity;
8
+ /** SHA-256 hex digest of a secret. The only form a secret is stored in. */
9
+ export declare function secretDigest(secret: string): string;
10
+ /** A new random secret: hqw_ for a worker token, hqe_ for an enrollment ticket. */
11
+ export declare function newSecret(kind: "worker" | "enrollment"): string;
12
+ /** Constant-time comparison of a presented secret with a stored digest. */
13
+ export declare function secretMatches(secret: string, storedSha256: string): boolean;
14
+ /** True when a worker with trust `have` may do what needs trust `want`. */
15
+ export declare function trustAllows(have: WorkerTrust, want: WorkerTrust): boolean;
16
+ /**
17
+ * Return the active worker for `input` when it may use `capability`, and,
18
+ * when tenantId is given, belongs to that tenant. Throws ACCESS_DENIED, or
19
+ * WORKER_REVOKED for a revoked worker with a valid token.
20
+ */
21
+ export declare function authenticate(workers: readonly StoredWorker[], input: unknown, need: {
22
+ capability: WorkerCapability;
23
+ tenantId?: string;
24
+ }): StoredWorker;
25
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Worker identity (US-004).
3
+ *
4
+ * A worker presents { workerId, token } on every operation. The store keeps
5
+ * only a SHA-256 digest of the token, so a store file or backup never holds a
6
+ * usable secret. authenticate checks the presented identity against the
7
+ * stored workers and the operation's capability and tenant, and fails closed:
8
+ * anything missing, malformed or ambiguous is ACCESS_DENIED. An unknown worker
9
+ * and a wrong token get the same denial, so a caller cannot probe which
10
+ * workerIds exist. Errors never carry the token.
11
+ */
12
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
13
+ import { DeliveryStoreError } from "./migrations.js";
14
+ const TRUST_RANK = { standard: 0, release: 1 };
15
+ function deny(found, expected, action) {
16
+ return new DeliveryStoreError("ACCESS_DENIED", { found, expected, action: `${action} Nothing was written.` });
17
+ }
18
+ /** Check the shape of a presented identity. Exactly two non-empty strings, nothing else. */
19
+ export function parseIdentity(input) {
20
+ const ok = typeof input === "object" &&
21
+ input !== null &&
22
+ !Array.isArray(input) &&
23
+ Object.keys(input).sort().join(",") === "token,workerId" &&
24
+ typeof input.workerId === "string" &&
25
+ typeof input.token === "string" &&
26
+ input.workerId !== "" &&
27
+ input.token !== "";
28
+ if (!ok) {
29
+ throw deny("a missing or malformed worker identity", "an object with exactly a non-empty workerId and token", "Pass the identity returned by enroll.");
30
+ }
31
+ const { workerId, token } = input;
32
+ return { workerId, token };
33
+ }
34
+ /** SHA-256 hex digest of a secret. The only form a secret is stored in. */
35
+ export function secretDigest(secret) {
36
+ return createHash("sha256").update(secret, "utf8").digest("hex");
37
+ }
38
+ /** A new random secret: hqw_ for a worker token, hqe_ for an enrollment ticket. */
39
+ export function newSecret(kind) {
40
+ return `${kind === "worker" ? "hqw" : "hqe"}_${randomBytes(32).toString("base64url")}`;
41
+ }
42
+ /** Constant-time comparison of a presented secret with a stored digest. */
43
+ export function secretMatches(secret, storedSha256) {
44
+ const a = Buffer.from(secretDigest(secret), "hex");
45
+ const b = Buffer.from(storedSha256, "hex");
46
+ return a.length === b.length && timingSafeEqual(a, b);
47
+ }
48
+ /** True when a worker with trust `have` may do what needs trust `want`. */
49
+ export function trustAllows(have, want) {
50
+ return TRUST_RANK[have] >= TRUST_RANK[want];
51
+ }
52
+ /**
53
+ * Return the active worker for `input` when it may use `capability`, and,
54
+ * when tenantId is given, belongs to that tenant. Throws ACCESS_DENIED, or
55
+ * WORKER_REVOKED for a revoked worker with a valid token.
56
+ */
57
+ export function authenticate(workers, input, need) {
58
+ const identity = parseIdentity(input);
59
+ const matches = workers.filter((w) => w.workerId === identity.workerId);
60
+ if (matches.length > 1) {
61
+ throw deny(`${matches.length} stored workers named ${identity.workerId}`, "one worker per workerId", "The store is ambiguous about this worker; ask an admin to revoke and re-enroll it.");
62
+ }
63
+ const worker = matches[0];
64
+ if (!worker || !secretMatches(identity.token, worker.secretSha256) || worker.status === "pending") {
65
+ throw deny(`no enrolled worker ${identity.workerId} with the presented token`, "the workerId and token returned by enroll", "Check the identity, or ask an admin for a new enrollment ticket.");
66
+ }
67
+ if (worker.status === "revoked") {
68
+ throw new DeliveryStoreError("WORKER_REVOKED", {
69
+ found: `worker ${worker.workerId} was revoked at epoch ${worker.revokedEpoch}`,
70
+ expected: "an active worker",
71
+ action: "This worker can no longer claim, read or report. Ask an admin to enroll a new worker. Nothing was written.",
72
+ });
73
+ }
74
+ if (need.tenantId !== undefined && worker.tenantId !== need.tenantId) {
75
+ throw deny(`worker ${worker.workerId} of ${worker.tenantId} asked for work of another company`, `work of the worker's own company ${worker.tenantId}`, "Use a worker enrolled in the company that owns the work.");
76
+ }
77
+ if (!worker.capabilities.includes(need.capability)) {
78
+ throw deny(`worker ${worker.workerId} has capabilities [${worker.capabilities.join(", ")}]`, `the ${need.capability} capability`, `Enroll a worker with ${need.capability}, or use one that has it.`);
79
+ }
80
+ return worker;
81
+ }
82
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1,116 @@
1
+ import type { DeliveryAccess } from "./enrollment.js";
2
+ import type { WorkerIdentity } from "./identity.js";
3
+ import { type NotificationBroker } from "./mqtt.js";
4
+ import { type BackoffPolicy } from "./outbox.js";
5
+ export type HandleOutcome = "claimed" | "ignored" | "duplicate" | "rejected" | "deferred";
6
+ export interface HandleResult {
7
+ /** The presented event id, or null when the payload did not parse. */
8
+ eventId: string | null;
9
+ outcome: HandleOutcome;
10
+ /** An error code when rejected or deferred, else null. Never repeats presented ids. */
11
+ reason: string | null;
12
+ /** Jobs this call claimed. */
13
+ claims: string[];
14
+ }
15
+ export interface InboxRecord {
16
+ key: string;
17
+ outcome: HandleOutcome;
18
+ reason: string | null;
19
+ at: number;
20
+ }
21
+ export interface ConsumerClaim {
22
+ attemptId: string;
23
+ jobId: string;
24
+ at: number;
25
+ }
26
+ export interface ReconcileReport {
27
+ claimed: string[];
28
+ /** Jobs this worker could not claim (for example a release job); backed off. */
29
+ deferred: string[];
30
+ /** Jobs still inside their backoff window. */
31
+ skipped: string[];
32
+ cursor: string | null;
33
+ }
34
+ export interface ReconcileOptions {
35
+ /** Most jobs to scan in this call, an integer from 1 to MAX_BATCH. */
36
+ batchSize: number;
37
+ /**
38
+ * Optional time budget in milliseconds, read from the consumer's clock. Once
39
+ * it is spent the call stops after the job in hand, saves the cursor at that
40
+ * job and returns; the next call resumes after it. Absent means no budget.
41
+ */
42
+ maxMs?: number;
43
+ }
44
+ export interface ConsumerOptions {
45
+ access: DeliveryAccess;
46
+ identity: WorkerIdentity;
47
+ /** Path of the consumer's inbox sqlite file. Not the ledger. */
48
+ path: string;
49
+ /** Credential refs requested on each dispatch. Default none. */
50
+ credentials?: string[];
51
+ clock?: () => number;
52
+ backoff?: BackoffPolicy;
53
+ /**
54
+ * Test-only crash barrier, inert unless passed. Called after a dispatch
55
+ * commits its claim to the ledger and before the inbox claim row is saved,
56
+ * which is also before the handler returns and the broker ack is sent.
57
+ * process-crash.test.ts uses it to SIGKILL a child at that point.
58
+ */
59
+ testBarrier?: (stage: "claimed", jobId: string, attemptId: string) => void;
60
+ }
61
+ export declare class NotificationConsumer {
62
+ private readonly access;
63
+ private readonly identity;
64
+ private readonly db;
65
+ private readonly credentials;
66
+ private readonly clock;
67
+ private readonly backoff;
68
+ private readonly testBarrier;
69
+ private results;
70
+ private detach;
71
+ private readonly statements;
72
+ private constructor();
73
+ static open(opts: ConsumerOptions): NotificationConsumer;
74
+ /**
75
+ * Handle one notification payload. Never throws: every outcome is returned.
76
+ * Only "deferred" leaves nothing recorded.
77
+ */
78
+ handle(payload: string): HandleResult;
79
+ private handleOnce;
80
+ /**
81
+ * Claim one job through the access layer. False when the ledger says it is
82
+ * not claimable now or this worker may not run it (left for reconciliation
83
+ * and its backoff). Throws on anything that means the handle cannot act.
84
+ */
85
+ private tryClaim;
86
+ /**
87
+ * Claim up to `batchSize` ready jobs of this worker's company from the
88
+ * ledger, continuing after the saved cursor and wrapping to the start.
89
+ * With `maxMs`, the clock is read after each scanned job; once that much
90
+ * time has passed the call stops, saving that job as the cursor. FENCED and STORE_CLOSED are thrown; nothing is
91
+ * claimed then.
92
+ */
93
+ reconcile(opts: ReconcileOptions): ReconcileReport;
94
+ /** Scan one ready job: skip it while its retry delay runs, else claim it or defer it. */
95
+ private reconcileOne;
96
+ /**
97
+ * Subscribe to this worker's company topic. A deferred result throws so the
98
+ * broker keeps the message; every other outcome acks it.
99
+ */
100
+ attach(broker: NotificationBroker): void;
101
+ /** Attempts this consumer claimed, in claim order. */
102
+ claims(): ConsumerClaim[];
103
+ /** True when a verified event with this id has been handled. */
104
+ seen(eventId: string): boolean;
105
+ records(): InboxRecord[];
106
+ /** Results of handle() since the last call, oldest first. */
107
+ lastResults(): HandleResult[];
108
+ close(): void;
109
+ private cursor;
110
+ private recorded;
111
+ private record;
112
+ /** A prepared statement, prepared once per consumer. */
113
+ private stmt;
114
+ private saveClaim;
115
+ }
116
+ //# sourceMappingURL=inbox.d.ts.map