@capybara-hq/kernel 0.1.0-rc.113 → 0.1.0-rc.115

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 (96) hide show
  1. package/bootstrap.json +7 -7
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/actions.js +2 -0
  5. package/dist/channels/cards.d.ts +4 -3
  6. package/dist/channels/cards.js +18 -3
  7. package/dist/channels/phrases.d.ts +15 -0
  8. package/dist/channels/phrases.js +9 -0
  9. package/dist/conversations/conversations.service.js +7 -0
  10. package/dist/conversations/events.d.ts +21 -0
  11. package/dist/conversations/events.js +35 -3
  12. package/dist/ctx/create-ctx.d.ts +1 -1
  13. package/dist/ctx/create-ctx.js +6 -1
  14. package/dist/db/kernel-schema.d.ts +29 -0
  15. package/dist/device-access/device-access.service.d.ts +74 -3
  16. package/dist/device-access/device-access.service.js +221 -7
  17. package/dist/devices/devices.service.js +3 -0
  18. package/dist/errors.d.ts +6 -0
  19. package/dist/errors.js +6 -0
  20. package/dist/extensions/permission-set.d.ts +11 -1
  21. package/dist/extensions/permission-set.js +15 -1
  22. package/dist/extensions/permission-view.d.ts +3 -2
  23. package/dist/extensions/permission-view.js +15 -2
  24. package/dist/identity/settings.d.ts +5 -0
  25. package/dist/identity/settings.js +4 -0
  26. package/dist/infra/outbox/registry.d.ts +14 -0
  27. package/dist/infra/outbox/registry.js +14 -0
  28. package/dist/models/purposes.js +5 -0
  29. package/dist/orgs/offboarding.js +5 -1
  30. package/dist/orgs/settings.service.d.ts +2 -0
  31. package/dist/platform/ops/org-settings.ops.js +1 -1
  32. package/dist/roles/worker.module.js +3 -0
  33. package/dist/runtime/compaction-model.d.ts +57 -0
  34. package/dist/runtime/compaction-model.js +87 -0
  35. package/dist/runtime/compaction.service.d.ts +23 -8
  36. package/dist/runtime/compaction.service.js +15 -10
  37. package/dist/runtime/context/compaction.d.ts +19 -2
  38. package/dist/runtime/context/compaction.js +23 -2
  39. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  40. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  41. package/dist/runtime/idle-arm.d.ts +12 -2
  42. package/dist/runtime/idle-arm.js +66 -18
  43. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  44. package/dist/runtime/idle-compaction.d.ts +11 -3
  45. package/dist/runtime/idle-compaction.js +61 -30
  46. package/dist/runtime/maintenance.d.ts +4 -2
  47. package/dist/runtime/maintenance.js +14 -4
  48. package/dist/runtime/model-call.d.ts +52 -16
  49. package/dist/runtime/model-call.js +71 -24
  50. package/dist/runtime/run-finish.d.ts +12 -3
  51. package/dist/runtime/run-finish.js +14 -7
  52. package/dist/runtime/run-queue.d.ts +5 -2
  53. package/dist/runtime/run-queue.js +7 -4
  54. package/dist/runtime/run-steps.d.ts +4 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.js +4 -2
  57. package/dist/runtime/runtime.module.js +3 -0
  58. package/dist/sandbox/device-sandbox.d.ts +12 -0
  59. package/dist/sandbox/device-sandbox.js +2 -0
  60. package/dist/sandbox/device-services.d.ts +42 -2
  61. package/dist/sandbox/device-services.js +74 -14
  62. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  63. package/dist/sandbox/loopback-expiry.job.js +50 -0
  64. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  65. package/dist/sandbox/loopback-grant-records.js +239 -0
  66. package/dist/sandbox/loopback-grants.d.ts +119 -0
  67. package/dist/sandbox/loopback-grants.js +454 -0
  68. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  69. package/dist/sandbox/loopback-live-ports.js +43 -0
  70. package/dist/sandbox/permission-call-types.d.ts +3 -2
  71. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  72. package/dist/sandbox/permission-facts.d.ts +4 -0
  73. package/dist/sandbox/permission-facts.js +4 -0
  74. package/dist/sandbox/review/classifier.d.ts +26 -4
  75. package/dist/sandbox/review/classifier.js +31 -4
  76. package/dist/sandbox/review/index.d.ts +3 -3
  77. package/dist/sandbox/review/index.js +2 -2
  78. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  79. package/dist/sandbox/review/permission-candidate.js +6 -5
  80. package/dist/sandbox/review/review.service.d.ts +69 -0
  81. package/dist/sandbox/review/review.service.js +117 -0
  82. package/dist/sandbox/sandbox.module.d.ts +1 -1
  83. package/dist/sandbox/sandbox.module.js +13 -2
  84. package/dist/tools/approvals.service.d.ts +82 -6
  85. package/dist/tools/approvals.service.js +233 -11
  86. package/dist/tools/call-scope.d.ts +9 -1
  87. package/dist/tools/loopback-asks.d.ts +52 -0
  88. package/dist/tools/loopback-asks.js +70 -0
  89. package/dist/tools/network-asks.d.ts +2 -1
  90. package/dist/tools/network-asks.js +10 -5
  91. package/dist/tools/pipeline.d.ts +59 -3
  92. package/dist/tools/pipeline.js +403 -40
  93. package/dist/tools/tools.module.js +3 -0
  94. package/package.json +2 -2
  95. package/src/migrations/0199_device_loopback_grants.sql +59 -0
  96. package/src/migrations/0200_runs_idle_mode.sql +4 -0
@@ -0,0 +1,119 @@
1
+ import { type LoopbackGrantSource } from "@capybara-hq/plugin-sdk";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { XactLock } from "../infra/database/xact-lock.js";
5
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
6
+ import type { KernelLogger } from "../log.js";
7
+ import { DeviceServices } from "./device-services.js";
8
+ import { type LoopbackGrantKey, type LoopbackGrantRow, type LoopbackRefreshJobData } from "./loopback-grant-records.js";
9
+ import { LoopbackLivePorts } from "./loopback-live-ports.js";
10
+ import { PermissionFacts } from "./permission-facts.js";
11
+ export * from "./loopback-grant-records.js";
12
+ /** How long an ended grant row is kept before the expiry pass deletes it (the audit log stays). */
13
+ export declare const LOOPBACK_ENDED_RETENTION_DAYS = 30;
14
+ /** The rows one retention batch deletes. */
15
+ export declare const LOOPBACK_PURGE_BATCH = 500;
16
+ /** The retention batches one expiry pass runs at most. */
17
+ export declare const LOOPBACK_PURGE_MAX_BATCHES = 20;
18
+ /**
19
+ * The lock of one (device, service)'s live set (decision R9: one provider per
20
+ * transaction-scoped lock): serializes grants of the service, so the count of its live ports
21
+ * checked against {@link LOOPBACK_MAX_PORTS_PER_SERVICE} and the insert are one step. Joins the
22
+ * caller's transaction (`mandatory`), which holds it until it ends.
23
+ */
24
+ export declare class LoopbackGrantLock {
25
+ private readonly xactLock;
26
+ readonly txHost: TransactionHost;
27
+ constructor(xactLock: XactLock, txHost: TransactionHost);
28
+ lock(deviceId: string, serviceId: string): Promise<void>;
29
+ }
30
+ /** The grant records: issue, revoke, read, refresh and expiry (see the file header). */
31
+ export declare class LoopbackGrants {
32
+ private readonly db;
33
+ readonly txHost: TransactionHost;
34
+ private readonly outbox;
35
+ private readonly locks;
36
+ private readonly live;
37
+ private readonly facts;
38
+ private readonly services;
39
+ private readonly log;
40
+ constructor(db: KernelDb, txHost: TransactionHost, outbox: OutboxService, locks: LoopbackGrantLock, live: LoopbackLivePorts, facts: Pick<PermissionFacts, "deviceSandboxFacts">, services: Pick<DeviceServices, "refreshLoopback">, log: Pick<KernelLogger, "warn">);
41
+ /**
42
+ * In the caller's transaction (`propagation: "mandatory"`): expires stale rows of the key,
43
+ * inserts the grant (or returns the live row, with no second audit or refresh), audits
44
+ * `device.loopback_granted` and owes the refresh. Throws {@link LoopbackLimitError} when the
45
+ * port would be the service's 33rd live one. The caller checked the person, the device and the
46
+ * ceilings ({@link loopbackRefusal}).
47
+ */
48
+ grantIn(key: LoopbackGrantKey, by: {
49
+ source: LoopbackGrantSource;
50
+ actorAccountId: string | null;
51
+ approvalId?: string;
52
+ call?: {
53
+ runId: string;
54
+ callId: string;
55
+ attempt: number;
56
+ };
57
+ }): Promise<LoopbackGrantRow>;
58
+ /**
59
+ * Revokes the key's live grant (reason `revoked`, audited `device.loopback_revoked`) and owes the
60
+ * refresh; false when there was none.
61
+ */
62
+ revoke(key: LoopbackGrantKey, actorAccountId: string): Promise<boolean>;
63
+ /** The live ports of one (device, service): sorted, unique, not revoked, not expired. */
64
+ livePorts(orgId: string, deviceId: string, serviceId: string): Promise<number[]>;
65
+ /**
66
+ * In the caller's transaction (`propagation: "mandatory"`): the key's live grant read
67
+ * `FOR SHARE`, or null. A revoke committed first is not seen; one that comes later waits for the
68
+ * caller's transaction.
69
+ */
70
+ liveLockedIn(key: LoopbackGrantKey): Promise<LoopbackGrantRow | null>;
71
+ /** The live grants of one (device, service) held by the root, by port. */
72
+ liveForRoot(orgId: string, deviceId: string, serviceId: string, rootConversationId: string): Promise<LoopbackGrantRow[]>;
73
+ /**
74
+ * The live grant the call made (a rerun after a crash resumes from it), or null when it made
75
+ * none or the grant ended since.
76
+ */
77
+ forCall(runId: string, callId: string): Promise<LoopbackGrantRow | null>;
78
+ /**
79
+ * Why a loopback grant on the device is refused now for an attended decision (a person's click
80
+ * or approval; an unattended run is refused before), in the note's words ({@link loopbackRefusal});
81
+ * null when grantable. The escalation refusal is previewCall's for an attended call: the runtime
82
+ * cannot run anything outside its sandbox now, else the device's outside-sandbox ceiling. Read
83
+ * outside the grant's transaction: a ceiling switched off meanwhile owes a refresh whose job
84
+ * revokes the grant ({@link refresh}), so the window is bounded.
85
+ */
86
+ refusalNow(orgId: string, deviceId: string): Promise<string | null>;
87
+ /**
88
+ * The refresh job. First it revokes the (device, service)'s live grants (reason
89
+ * `outside-sandbox-off`, audited) when the device refuses loopback grants now: a ceiling layer
90
+ * keeps running outside the sandbox off, or the provider's known support lacks
91
+ * `network.loopbackPorts` (a provider that lost it; {@link knownLoopbackRefusal}). A support
92
+ * not known (none stored, a failed read, or a closed one with an `unavailableReason`, as while a
93
+ * device re-binds) revokes nothing: grants are consents, and new ones are refused meanwhile.
94
+ * Then it sends the live set to an `ifRunning` ensure of the service
95
+ * (`DeviceServices.refreshLoopback`), always, so a revocation already recorded reaches the
96
+ * machine whatever the support says. A stopped service or instance needs nothing: its
97
+ * next ensure sends the set. A failed send owes a delayed follow-up
98
+ * ({@link oweLoopbackFollowUp}), so a narrowing never stays on a machine the kernel records as
99
+ * running because one send failed.
100
+ */
101
+ refresh(data: LoopbackRefreshJobData, signal: AbortSignal): Promise<void>;
102
+ private followUp;
103
+ private revokeRefused;
104
+ /**
105
+ * The expiry pass: marks every live grant past its `expires_at` revoked (reason `expired`,
106
+ * audited) and owes one refresh per (device, service). Returns how many it ended. Then it
107
+ * deletes the grant rows that ended more than {@link LOOPBACK_ENDED_RETENTION_DAYS} days ago
108
+ * ({@link purgeEnded}; the audit log keeps every grant and its end).
109
+ */
110
+ expireDue(): Promise<number>;
111
+ /**
112
+ * Deletes ended grant rows older than the retention, in batches of
113
+ * {@link LOOPBACK_PURGE_BATCH} (each its own transaction), at most
114
+ * {@link LOOPBACK_PURGE_MAX_BATCHES} per pass: the next pass takes the rest. Returns how many.
115
+ */
116
+ purgeEnded(): Promise<number>;
117
+ private purgeEndedBatch;
118
+ private expireDueIn;
119
+ }
@@ -0,0 +1,454 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomUUID } from "node:crypto";
11
+ import { DeviceAccessError, LOOPBACK_MAX_PORTS_PER_SERVICE, } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
14
+ import { ApiError } from "../errors.js";
15
+ import { audit } from "../identity/audit.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { asPlatform } from "../infra/database/org-scope.js";
18
+ import { TransactionHost } from "../infra/database/transaction-host.js";
19
+ import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { XactLock } from "../infra/database/xact-lock.js";
21
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
22
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
23
+ import { DeviceServices } from "./device-services.js";
24
+ import { endedGrants, isDatabasePort, knownLoopbackRefusal, LOOPBACK_GRANT_TTL_HOURS, LoopbackLimitError, loopbackRefusal, oweLoopbackFollowUp, oweRefresh, rowOf, } from "./loopback-grant-records.js";
25
+ import { LoopbackLivePorts } from "./loopback-live-ports.js";
26
+ import { runtimeReportVerdict } from "./permission-availability.js";
27
+ import { PermissionFacts } from "./permission-facts.js";
28
+ import { escalationCeilingWhy, escalationRuntimeWhy } from "./review/permission-candidate.js";
29
+ // the constants, types and plain functions live in a leaf module (no services imported), so
30
+ // conversation deletion and ceiling writes import them without an import cycle
31
+ export * from "./loopback-grant-records.js";
32
+ /** How long an ended grant row is kept before the expiry pass deletes it (the audit log stays). */
33
+ export const LOOPBACK_ENDED_RETENTION_DAYS = 30;
34
+ /** The rows one retention batch deletes. */
35
+ export const LOOPBACK_PURGE_BATCH = 500;
36
+ /** The retention batches one expiry pass runs at most. */
37
+ export const LOOPBACK_PURGE_MAX_BATCHES = 20;
38
+ /**
39
+ * The lock of one (device, service)'s live set (decision R9: one provider per
40
+ * transaction-scoped lock): serializes grants of the service, so the count of its live ports
41
+ * checked against {@link LOOPBACK_MAX_PORTS_PER_SERVICE} and the insert are one step. Joins the
42
+ * caller's transaction (`mandatory`), which holds it until it ends.
43
+ */
44
+ let LoopbackGrantLock = class LoopbackGrantLock {
45
+ xactLock;
46
+ txHost;
47
+ constructor(xactLock, txHost) {
48
+ this.xactLock = xactLock;
49
+ this.txHost = txHost;
50
+ }
51
+ async lock(deviceId, serviceId) {
52
+ await this.xactLock.lock(`capybara.loopback-grants:${deviceId}:${serviceId}`);
53
+ }
54
+ };
55
+ __decorate([
56
+ Transactional({ propagation: "mandatory" })
57
+ ], LoopbackGrantLock.prototype, "lock", null);
58
+ LoopbackGrantLock = __decorate([
59
+ Injectable(),
60
+ __param(0, Inject(XactLock)),
61
+ __param(1, Inject(TransactionHost))
62
+ ], LoopbackGrantLock);
63
+ export { LoopbackGrantLock };
64
+ /** The grant records: issue, revoke, read, refresh and expiry (see the file header). */
65
+ let LoopbackGrants = class LoopbackGrants {
66
+ db;
67
+ txHost;
68
+ outbox;
69
+ locks;
70
+ live;
71
+ facts;
72
+ services;
73
+ log;
74
+ constructor(db, txHost, outbox, locks, live, facts, services, log) {
75
+ this.db = db;
76
+ this.txHost = txHost;
77
+ this.outbox = outbox;
78
+ this.locks = locks;
79
+ this.live = live;
80
+ this.facts = facts;
81
+ this.services = services;
82
+ this.log = log;
83
+ }
84
+ /**
85
+ * In the caller's transaction (`propagation: "mandatory"`): expires stale rows of the key,
86
+ * inserts the grant (or returns the live row, with no second audit or refresh), audits
87
+ * `device.loopback_granted` and owes the refresh. Throws {@link LoopbackLimitError} when the
88
+ * port would be the service's 33rd live one. The caller checked the person, the device and the
89
+ * ceilings ({@link loopbackRefusal}).
90
+ */
91
+ async grantIn(key, by) {
92
+ if ((by.source === "owner-panel") !== (by.call === undefined))
93
+ throw new Error("A loopback grant names its call unless the owner's panel made it");
94
+ const db = this.db.db;
95
+ // the root must be a live root conversation, read FOR SHARE: a deletion that commits first is
96
+ // seen here (the row is re-checked after its lock), and one that comes later waits for this
97
+ // transaction and then revokes the grant with the conversation's other grants
98
+ const root = await db
99
+ .selectFrom("conversations")
100
+ .select("id")
101
+ .where("id", "=", key.rootConversationId)
102
+ .where("org_id", "=", key.orgId)
103
+ .where("deleted_at", "is", null)
104
+ .where("parent_conversation_id", "is", null)
105
+ .forShare()
106
+ .executeTakeFirst();
107
+ if (!root)
108
+ throw new ApiError("conversation.not_found", "The conversation was deleted or is not a root conversation; a loopback port is granted to a live root conversation");
109
+ await this.locks.lock(key.deviceId, key.serviceId);
110
+ const stale = await db
111
+ .updateTable("device_loopback_grants")
112
+ .set({ revoked_at: sql `now()`, revoke_reason: "expired" })
113
+ .where("org_id", "=", key.orgId)
114
+ .where("device_id", "=", key.deviceId)
115
+ .where("service_id", "=", key.serviceId)
116
+ .where("conversation_id", "=", key.rootConversationId)
117
+ .where("port", "=", key.port)
118
+ .where("revoked_at", "is", null)
119
+ .where("expires_at", "<=", sql `now()`)
120
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
121
+ .execute();
122
+ for (const r of stale)
123
+ await audit(db, {
124
+ actorAccountId: null,
125
+ orgId: r.org_id,
126
+ action: "device.loopback_revoked",
127
+ target: r.device_id,
128
+ detail: {
129
+ grantId: r.id,
130
+ deviceId: r.device_id,
131
+ serviceId: r.service_id,
132
+ conversationId: r.conversation_id,
133
+ port: r.port,
134
+ reason: "expired",
135
+ },
136
+ });
137
+ const existing = await db
138
+ .selectFrom("device_loopback_grants")
139
+ .selectAll()
140
+ .where("org_id", "=", key.orgId)
141
+ .where("device_id", "=", key.deviceId)
142
+ .where("service_id", "=", key.serviceId)
143
+ .where("conversation_id", "=", key.rootConversationId)
144
+ .where("port", "=", key.port)
145
+ .where("revoked_at", "is", null)
146
+ .executeTakeFirst();
147
+ if (existing)
148
+ return rowOf(existing);
149
+ const ports = await this.live.livePorts(key.orgId, key.deviceId, key.serviceId);
150
+ if (!ports.includes(key.port) && ports.length >= LOOPBACK_MAX_PORTS_PER_SERVICE)
151
+ throw new LoopbackLimitError();
152
+ const inserted = await db
153
+ .insertInto("device_loopback_grants")
154
+ .values({
155
+ id: randomUUID(),
156
+ org_id: key.orgId,
157
+ device_id: key.deviceId,
158
+ service_id: key.serviceId,
159
+ conversation_id: key.rootConversationId,
160
+ port: key.port,
161
+ source: by.source,
162
+ ...(by.approvalId !== undefined && { approval_id: by.approvalId }),
163
+ ...(by.call !== undefined && {
164
+ run_id: by.call.runId,
165
+ call_id: by.call.callId,
166
+ attempt: by.call.attempt,
167
+ }),
168
+ expires_at: sql `now() + make_interval(hours => ${LOOPBACK_GRANT_TTL_HOURS})`,
169
+ })
170
+ .returningAll()
171
+ .executeTakeFirstOrThrow();
172
+ const row = rowOf(inserted);
173
+ await audit(db, {
174
+ actorAccountId: by.actorAccountId,
175
+ orgId: key.orgId,
176
+ action: "device.loopback_granted",
177
+ target: key.deviceId,
178
+ detail: {
179
+ grantId: row.id,
180
+ deviceId: key.deviceId,
181
+ serviceId: key.serviceId,
182
+ conversationId: key.rootConversationId,
183
+ port: key.port,
184
+ database: isDatabasePort(key.port),
185
+ source: by.source,
186
+ expiresAt: row.expiresAt,
187
+ ...(by.approvalId !== undefined && { approvalId: by.approvalId }),
188
+ ...(by.call !== undefined && { ...by.call }),
189
+ },
190
+ });
191
+ await oweRefresh(this.outbox, { orgId: key.orgId, deviceId: key.deviceId, serviceId: key.serviceId }, `g${row.id}`);
192
+ return row;
193
+ }
194
+ /**
195
+ * Revokes the key's live grant (reason `revoked`, audited `device.loopback_revoked`) and owes the
196
+ * refresh; false when there was none.
197
+ */
198
+ async revoke(key, actorAccountId) {
199
+ const rows = await this.db
200
+ .updateTable("device_loopback_grants")
201
+ .set({ revoked_at: sql `now()`, revoke_reason: "revoked" })
202
+ .where("org_id", "=", key.orgId)
203
+ .where("device_id", "=", key.deviceId)
204
+ .where("service_id", "=", key.serviceId)
205
+ .where("conversation_id", "=", key.rootConversationId)
206
+ .where("port", "=", key.port)
207
+ .where("revoked_at", "is", null)
208
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
209
+ .execute();
210
+ await endedGrants(this.db.db, this.outbox, rows, "revoked", actorAccountId);
211
+ return rows.length > 0;
212
+ }
213
+ /** The live ports of one (device, service): sorted, unique, not revoked, not expired. */
214
+ livePorts(orgId, deviceId, serviceId) {
215
+ return this.live.livePorts(orgId, deviceId, serviceId);
216
+ }
217
+ /**
218
+ * In the caller's transaction (`propagation: "mandatory"`): the key's live grant read
219
+ * `FOR SHARE`, or null. A revoke committed first is not seen; one that comes later waits for the
220
+ * caller's transaction.
221
+ */
222
+ async liveLockedIn(key) {
223
+ const row = await this.db
224
+ .selectFrom("device_loopback_grants")
225
+ .selectAll()
226
+ .where("org_id", "=", key.orgId)
227
+ .where("device_id", "=", key.deviceId)
228
+ .where("service_id", "=", key.serviceId)
229
+ .where("conversation_id", "=", key.rootConversationId)
230
+ .where("port", "=", key.port)
231
+ .where("revoked_at", "is", null)
232
+ .where("expires_at", ">", sql `now()`)
233
+ .forShare()
234
+ .executeTakeFirst();
235
+ return row === undefined ? null : rowOf(row);
236
+ }
237
+ /** The live grants of one (device, service) held by the root, by port. */
238
+ async liveForRoot(orgId, deviceId, serviceId, rootConversationId) {
239
+ const rows = await this.db
240
+ .selectFrom("device_loopback_grants")
241
+ .selectAll()
242
+ .where("org_id", "=", orgId)
243
+ .where("device_id", "=", deviceId)
244
+ .where("service_id", "=", serviceId)
245
+ .where("conversation_id", "=", rootConversationId)
246
+ .where("revoked_at", "is", null)
247
+ .where("expires_at", ">", sql `now()`)
248
+ .orderBy("port")
249
+ .execute();
250
+ return rows.map(rowOf);
251
+ }
252
+ /**
253
+ * The live grant the call made (a rerun after a crash resumes from it), or null when it made
254
+ * none or the grant ended since.
255
+ */
256
+ async forCall(runId, callId) {
257
+ // org-filter: the runtime's own run and call ids name the grant; the run was claimed under its
258
+ // org, and run ids are unique across orgs
259
+ const row = await this.db
260
+ .selectFrom("device_loopback_grants")
261
+ .selectAll()
262
+ .where("run_id", "=", runId)
263
+ .where("call_id", "=", callId)
264
+ .where("revoked_at", "is", null)
265
+ .where("expires_at", ">", sql `now()`)
266
+ .orderBy("created_at", "desc")
267
+ .limit(1)
268
+ .executeTakeFirst();
269
+ return row ? rowOf(row) : null;
270
+ }
271
+ /**
272
+ * Why a loopback grant on the device is refused now for an attended decision (a person's click
273
+ * or approval; an unattended run is refused before), in the note's words ({@link loopbackRefusal});
274
+ * null when grantable. The escalation refusal is previewCall's for an attended call: the runtime
275
+ * cannot run anything outside its sandbox now, else the device's outside-sandbox ceiling. Read
276
+ * outside the grant's transaction: a ceiling switched off meanwhile owes a refresh whose job
277
+ * revokes the grant ({@link refresh}), so the window is bounded.
278
+ */
279
+ async refusalNow(orgId, deviceId) {
280
+ const facts = await this.facts.deviceSandboxFacts(orgId, deviceId);
281
+ const runtime = runtimeWhy(facts.availability);
282
+ const escalation = runtime !== null
283
+ ? escalationRuntimeWhy(runtime)
284
+ : facts.box.outsideSandbox
285
+ ? null
286
+ : escalationCeilingWhy({
287
+ layer: facts.box.layer.outsideSandbox,
288
+ boundary: facts.box.boundary,
289
+ description: facts.description,
290
+ changeHint: facts.changeHint,
291
+ });
292
+ return loopbackRefusal(facts.box, facts.support, escalation);
293
+ }
294
+ /**
295
+ * The refresh job. First it revokes the (device, service)'s live grants (reason
296
+ * `outside-sandbox-off`, audited) when the device refuses loopback grants now: a ceiling layer
297
+ * keeps running outside the sandbox off, or the provider's known support lacks
298
+ * `network.loopbackPorts` (a provider that lost it; {@link knownLoopbackRefusal}). A support
299
+ * not known (none stored, a failed read, or a closed one with an `unavailableReason`, as while a
300
+ * device re-binds) revokes nothing: grants are consents, and new ones are refused meanwhile.
301
+ * Then it sends the live set to an `ifRunning` ensure of the service
302
+ * (`DeviceServices.refreshLoopback`), always, so a revocation already recorded reaches the
303
+ * machine whatever the support says. A stopped service or instance needs nothing: its
304
+ * next ensure sends the set. A failed send owes a delayed follow-up
305
+ * ({@link oweLoopbackFollowUp}), so a narrowing never stays on a machine the kernel records as
306
+ * running because one send failed.
307
+ */
308
+ async refresh(data, signal) {
309
+ const refused = knownLoopbackRefusal(await this.facts.deviceSandboxFacts(data.orgId, data.deviceId));
310
+ if (refused !== null)
311
+ await this.revokeRefused(data, refused);
312
+ signal.throwIfAborted();
313
+ try {
314
+ await this.services.refreshLoopback(data.orgId, data.deviceId, data.serviceId, signal);
315
+ }
316
+ catch (err) {
317
+ // a provider without services runs none, so nothing holds a port there
318
+ if (err instanceof DeviceAccessError && err.code === "capability_missing")
319
+ return;
320
+ const owed = await this.followUp(data);
321
+ this.log.warn("loopback refresh failed", {
322
+ deviceId: data.deviceId,
323
+ serviceId: data.serviceId,
324
+ followUp: owed ? (data.followUp ?? 0) + 1 : null,
325
+ err,
326
+ });
327
+ }
328
+ }
329
+ followUp(data) {
330
+ return oweLoopbackFollowUp(this.outbox, data);
331
+ }
332
+ async revokeRefused(data, cause) {
333
+ const rows = await this.db
334
+ .updateTable("device_loopback_grants")
335
+ .set({ revoked_at: sql `now()`, revoke_reason: "outside-sandbox-off" })
336
+ .where("org_id", "=", data.orgId)
337
+ .where("device_id", "=", data.deviceId)
338
+ .where("service_id", "=", data.serviceId)
339
+ .where("revoked_at", "is", null)
340
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
341
+ .execute();
342
+ // audited only: this job is the refresh their revocation would owe
343
+ for (const r of rows)
344
+ await audit(this.db.db, {
345
+ actorAccountId: null,
346
+ orgId: r.org_id,
347
+ action: "device.loopback_revoked",
348
+ target: r.device_id,
349
+ detail: {
350
+ grantId: r.id,
351
+ deviceId: r.device_id,
352
+ serviceId: r.service_id,
353
+ conversationId: r.conversation_id,
354
+ port: r.port,
355
+ reason: "outside-sandbox-off",
356
+ cause,
357
+ },
358
+ });
359
+ }
360
+ /**
361
+ * The expiry pass: marks every live grant past its `expires_at` revoked (reason `expired`,
362
+ * audited) and owes one refresh per (device, service). Returns how many it ended. Then it
363
+ * deletes the grant rows that ended more than {@link LOOPBACK_ENDED_RETENTION_DAYS} days ago
364
+ * ({@link purgeEnded}; the audit log keeps every grant and its end).
365
+ */
366
+ async expireDue() {
367
+ const ended = await asPlatform("loopback grant expiry sweep over every org", () => this.expireDueIn());
368
+ await this.purgeEnded();
369
+ return ended;
370
+ }
371
+ /**
372
+ * Deletes ended grant rows older than the retention, in batches of
373
+ * {@link LOOPBACK_PURGE_BATCH} (each its own transaction), at most
374
+ * {@link LOOPBACK_PURGE_MAX_BATCHES} per pass: the next pass takes the rest. Returns how many.
375
+ */
376
+ async purgeEnded() {
377
+ let total = 0;
378
+ for (let i = 0; i < LOOPBACK_PURGE_MAX_BATCHES; i++) {
379
+ const n = await asPlatform("loopback grant retention sweep over every org", () => this.purgeEndedBatch());
380
+ total += n;
381
+ if (n < LOOPBACK_PURGE_BATCH)
382
+ break;
383
+ }
384
+ return total;
385
+ }
386
+ async purgeEndedBatch() {
387
+ // org-filter: the retention sweep over every org's ended grants, entered under asPlatform by
388
+ // purgeEnded; nothing live is touched
389
+ const r = await this.db
390
+ .deleteFrom("device_loopback_grants")
391
+ .where("id", "in", this.db
392
+ .selectFrom("device_loopback_grants")
393
+ .select("id")
394
+ .where("revoked_at", "is not", null)
395
+ .where("revoked_at", "<", sql `now() - make_interval(days => ${LOOPBACK_ENDED_RETENTION_DAYS})`)
396
+ .limit(LOOPBACK_PURGE_BATCH))
397
+ .executeTakeFirst();
398
+ return Number(r.numDeletedRows);
399
+ }
400
+ async expireDueIn() {
401
+ // org-filter: the expiry sweep over every org's grants, entered under asPlatform by
402
+ // expireDue; each row keeps its org
403
+ const rows = await this.db
404
+ .updateTable("device_loopback_grants")
405
+ .set({ revoked_at: sql `now()`, revoke_reason: "expired" })
406
+ .where("revoked_at", "is", null)
407
+ .where("expires_at", "<=", sql `now()`)
408
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
409
+ .execute();
410
+ await endedGrants(this.db.db, this.outbox, rows, "expired", null);
411
+ return rows.length;
412
+ }
413
+ };
414
+ __decorate([
415
+ Transactional({ propagation: "mandatory" })
416
+ ], LoopbackGrants.prototype, "grantIn", null);
417
+ __decorate([
418
+ Transactional()
419
+ ], LoopbackGrants.prototype, "revoke", null);
420
+ __decorate([
421
+ Transactional({ propagation: "mandatory" })
422
+ ], LoopbackGrants.prototype, "liveLockedIn", null);
423
+ __decorate([
424
+ Transactional()
425
+ ], LoopbackGrants.prototype, "followUp", null);
426
+ __decorate([
427
+ Transactional()
428
+ ], LoopbackGrants.prototype, "revokeRefused", null);
429
+ __decorate([
430
+ Transactional()
431
+ ], LoopbackGrants.prototype, "purgeEndedBatch", null);
432
+ __decorate([
433
+ Transactional()
434
+ ], LoopbackGrants.prototype, "expireDueIn", null);
435
+ LoopbackGrants = __decorate([
436
+ Injectable(),
437
+ __param(0, Inject(KernelDb)),
438
+ __param(1, Inject(TransactionHost)),
439
+ __param(2, Inject(OutboxService)),
440
+ __param(3, Inject(LoopbackGrantLock)),
441
+ __param(4, Inject(LoopbackLivePorts)),
442
+ __param(5, Inject(PermissionFacts)),
443
+ __param(6, Inject(DeviceServices)),
444
+ __param(7, Inject(KERNEL_LOGGER))
445
+ ], LoopbackGrants);
446
+ export { LoopbackGrants };
447
+ /** Why the device's runtime cannot run anything outside its sandbox now; null when it can. */
448
+ function runtimeWhy(availability) {
449
+ if (availability.state === "unsupported")
450
+ return availability.reason;
451
+ if (availability.state === "supported")
452
+ return runtimeReportVerdict(availability.report);
453
+ return null;
454
+ }
@@ -0,0 +1,12 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ /**
3
+ * The live ports of one (device, service): what every ensure of the service sends its provider.
4
+ * A provider of its own so `DeviceServices` reads it without depending on `LoopbackGrants`
5
+ * (`sandbox/loopback-grants.ts`, whose refresh calls `DeviceServices`).
6
+ */
7
+ export declare class LoopbackLivePorts {
8
+ private readonly db;
9
+ constructor(db: KernelDb);
10
+ /** Sorted, unique, not revoked and not expired. */
11
+ livePorts(orgId: string, deviceId: string, serviceId: string): Promise<number[]>;
12
+ }
@@ -0,0 +1,43 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ /**
14
+ * The live ports of one (device, service): what every ensure of the service sends its provider.
15
+ * A provider of its own so `DeviceServices` reads it without depending on `LoopbackGrants`
16
+ * (`sandbox/loopback-grants.ts`, whose refresh calls `DeviceServices`).
17
+ */
18
+ let LoopbackLivePorts = class LoopbackLivePorts {
19
+ db;
20
+ constructor(db) {
21
+ this.db = db;
22
+ }
23
+ /** Sorted, unique, not revoked and not expired. */
24
+ async livePorts(orgId, deviceId, serviceId) {
25
+ const rows = await this.db
26
+ .selectFrom("device_loopback_grants")
27
+ .select("port")
28
+ .distinct()
29
+ .where("org_id", "=", orgId)
30
+ .where("device_id", "=", deviceId)
31
+ .where("service_id", "=", serviceId)
32
+ .where("revoked_at", "is", null)
33
+ .where("expires_at", ">", sql `now()`)
34
+ .orderBy("port")
35
+ .execute();
36
+ return rows.map((r) => r.port);
37
+ }
38
+ };
39
+ LoopbackLivePorts = __decorate([
40
+ Injectable(),
41
+ __param(0, Inject(KernelDb))
42
+ ], LoopbackLivePorts);
43
+ export { LoopbackLivePorts };
@@ -56,9 +56,10 @@ export type PermissionFullAccessGrantDecision = {
56
56
  export type PermissionGrantSource = PermissionGrantDecision["source"];
57
57
  /**
58
58
  * The kind of one boundary crossing, as `ReviewRecord.crossing` records it: a directory outside the
59
- * scope, a new host on an allowlist, running one call outside the sandbox, or a sensitive command.
59
+ * scope, a new host on an allowlist, running one call outside the sandbox, a sensitive command, or
60
+ * a device service (the browser) reaching one loopback port on the person's own device.
60
61
  */
61
- export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive";
62
+ export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive" | "loopback-port";
62
63
  /**
63
64
  * What a call grant authorizes: an exact directory and host expansion of the restricted scope, or
64
65
  * one Bash call run outside the OS sandbox (per-call sandbox escalation: full execution for that