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

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 (65) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/actions.js +2 -0
  3. package/dist/channels/cards.d.ts +4 -3
  4. package/dist/channels/cards.js +18 -3
  5. package/dist/channels/phrases.d.ts +15 -0
  6. package/dist/channels/phrases.js +9 -0
  7. package/dist/conversations/conversations.service.js +7 -0
  8. package/dist/conversations/events.d.ts +13 -0
  9. package/dist/conversations/events.js +24 -3
  10. package/dist/ctx/create-ctx.d.ts +1 -1
  11. package/dist/ctx/create-ctx.js +6 -1
  12. package/dist/db/kernel-schema.d.ts +26 -0
  13. package/dist/device-access/device-access.service.d.ts +74 -3
  14. package/dist/device-access/device-access.service.js +221 -7
  15. package/dist/devices/devices.service.js +3 -0
  16. package/dist/errors.d.ts +6 -0
  17. package/dist/errors.js +6 -0
  18. package/dist/extensions/permission-set.d.ts +11 -1
  19. package/dist/extensions/permission-set.js +15 -1
  20. package/dist/extensions/permission-view.d.ts +3 -2
  21. package/dist/extensions/permission-view.js +15 -2
  22. package/dist/infra/outbox/registry.d.ts +14 -0
  23. package/dist/infra/outbox/registry.js +14 -0
  24. package/dist/orgs/offboarding.js +5 -1
  25. package/dist/roles/worker.module.js +3 -0
  26. package/dist/runtime/maintenance.d.ts +4 -2
  27. package/dist/runtime/maintenance.js +14 -4
  28. package/dist/sandbox/device-sandbox.d.ts +12 -0
  29. package/dist/sandbox/device-sandbox.js +2 -0
  30. package/dist/sandbox/device-services.d.ts +42 -2
  31. package/dist/sandbox/device-services.js +74 -14
  32. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  33. package/dist/sandbox/loopback-expiry.job.js +50 -0
  34. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  35. package/dist/sandbox/loopback-grant-records.js +239 -0
  36. package/dist/sandbox/loopback-grants.d.ts +119 -0
  37. package/dist/sandbox/loopback-grants.js +454 -0
  38. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  39. package/dist/sandbox/loopback-live-ports.js +43 -0
  40. package/dist/sandbox/permission-call-types.d.ts +3 -2
  41. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  42. package/dist/sandbox/permission-facts.d.ts +4 -0
  43. package/dist/sandbox/permission-facts.js +4 -0
  44. package/dist/sandbox/review/classifier.d.ts +26 -4
  45. package/dist/sandbox/review/classifier.js +31 -4
  46. package/dist/sandbox/review/index.d.ts +3 -3
  47. package/dist/sandbox/review/index.js +2 -2
  48. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  49. package/dist/sandbox/review/permission-candidate.js +6 -5
  50. package/dist/sandbox/review/review.service.d.ts +69 -0
  51. package/dist/sandbox/review/review.service.js +117 -0
  52. package/dist/sandbox/sandbox.module.d.ts +1 -1
  53. package/dist/sandbox/sandbox.module.js +13 -2
  54. package/dist/tools/approvals.service.d.ts +82 -6
  55. package/dist/tools/approvals.service.js +233 -11
  56. package/dist/tools/call-scope.d.ts +9 -1
  57. package/dist/tools/loopback-asks.d.ts +52 -0
  58. package/dist/tools/loopback-asks.js +70 -0
  59. package/dist/tools/network-asks.d.ts +2 -1
  60. package/dist/tools/network-asks.js +10 -5
  61. package/dist/tools/pipeline.d.ts +59 -3
  62. package/dist/tools/pipeline.js +403 -40
  63. package/dist/tools/tools.module.js +3 -0
  64. package/package.json +2 -2
  65. package/src/migrations/0199_device_loopback_grants.sql +59 -0
@@ -0,0 +1,239 @@
1
+ import { DeviceAccessError, LOOPBACK_DATABASE_PORTS, LOOPBACK_MAX_PORTS_PER_SERVICE, } from "@capybara-hq/plugin-sdk";
2
+ import { sql } from "kysely";
3
+ import { audit } from "../identity/audit.js";
4
+ import { asPlatform } from "../infra/database/org-scope.js";
5
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
6
+ /**
7
+ * Loopback port grants (browser loopback port grants design §4, §6): one device service of a
8
+ * person's own device may reach one loopback port of that device for one conversation tree. The
9
+ * records in `device_loopback_grants` are the live set; every change to it (a grant, a revoke, an
10
+ * expiry, a conversation's deletion, a narrowing ceiling) owes a `device-loopback-refresh` job per
11
+ * affected (device, service), which sends the whole live set to an `ifRunning` ensure of the
12
+ * service. A ceiling narrows by revocation: the refresh job revokes (`outside-sandbox-off`) when
13
+ * the device refuses loopback grants now.
14
+ */
15
+ /** A grant's lifetime from issue. */
16
+ export const LOOPBACK_GRANT_TTL_HOURS = 24;
17
+ /** The refresh of one (device, service)'s live set (outbox job on the maintenance queue). */
18
+ export const LOOPBACK_REFRESH_JOB = "device-loopback-refresh";
19
+ /**
20
+ * The most follow-ups one change owes after failed sends, about a day at
21
+ * {@link LOOPBACK_FOLLOW_UP_MAX_DELAY_MS}: a device the kernel records as running keeps getting
22
+ * the live set until one send lands, so a narrowing never stays on the machine because a send
23
+ * failed.
24
+ */
25
+ export const LOOPBACK_MAX_FOLLOW_UPS = 300;
26
+ /** The first follow-up's delay; it doubles up to {@link LOOPBACK_FOLLOW_UP_MAX_DELAY_MS}. */
27
+ export const LOOPBACK_FOLLOW_UP_DELAY_MS = 30_000;
28
+ export const LOOPBACK_FOLLOW_UP_MAX_DELAY_MS = 300_000;
29
+ /**
30
+ * Owes the follow-up of a refresh whose send failed (`-t<n>` after its change), delayed with a
31
+ * doubling backoff; false past {@link LOOPBACK_MAX_FOLLOW_UPS}.
32
+ */
33
+ export async function oweLoopbackFollowUp(outbox, data) {
34
+ const n = (data.followUp ?? 0) + 1;
35
+ if (n > LOOPBACK_MAX_FOLLOW_UPS)
36
+ return false;
37
+ const change = data.change ?? "x";
38
+ const delay = Math.min(LOOPBACK_FOLLOW_UP_DELAY_MS * 2 ** (n - 1), LOOPBACK_FOLLOW_UP_MAX_DELAY_MS);
39
+ const next = {
40
+ orgId: data.orgId,
41
+ deviceId: data.deviceId,
42
+ serviceId: data.serviceId,
43
+ change,
44
+ followUp: n,
45
+ };
46
+ await outbox.add({
47
+ queue: MAINTENANCE_QUEUE_NAME,
48
+ name: LOOPBACK_REFRESH_JOB,
49
+ jobId: loopbackRefreshJobId(data.deviceId, data.serviceId, `${change}-t${n}`),
50
+ data: next,
51
+ runAt: new Date(Date.now() + delay),
52
+ orgId: data.orgId,
53
+ });
54
+ return true;
55
+ }
56
+ /**
57
+ * The deterministic job id of a refresh (no `:`). `change` names what owed it: `g<grantId>` (a
58
+ * grant), `r<grantId>` (a revoke, an expiry or a deletion), `c<level>-<subjectId>-<epoch>` (a
59
+ * ceiling publication, the epoch after its bump).
60
+ */
61
+ export const loopbackRefreshJobId = (deviceId, serviceId, change) => `dlr-${deviceId}-${serviceId}-${change}`;
62
+ /** The budget of one refresh job's device calls. */
63
+ export const LOOPBACK_REFRESH_TIMEOUT_MS = 30_000;
64
+ /** A grant past {@link LOOPBACK_MAX_PORTS_PER_SERVICE} live ports of one (device, service). */
65
+ export class LoopbackLimitError extends DeviceAccessError {
66
+ constructor() {
67
+ super("loopback_limit", `This device service already has ${LOOPBACK_MAX_PORTS_PER_SERVICE} local ports open; revoke one in the browser panel before granting another.`);
68
+ this.name = "LoopbackLimitError";
69
+ }
70
+ }
71
+ /**
72
+ * Why a loopback grant is refused on this device now, in the note's words; null when grantable.
73
+ * `escalationRefusal` is why a call could not run outside the sandbox here (the ceiling, an
74
+ * unattended run), null or undefined when it could.
75
+ */
76
+ export function loopbackRefusal(box, support, escalationRefusal) {
77
+ if (escalationRefusal !== null && escalationRefusal !== undefined)
78
+ return `running outside the sandbox is not possible here (${escalationRefusal})`;
79
+ if (support?.network.loopbackPorts !== true &&
80
+ support?.limitedBy?.loopbackPorts === "device-update")
81
+ return "capybara-device on this device is too old; update capybara-device to let the browser reach local ports";
82
+ if (support?.network.loopbackPorts !== true || !box.loopbackPorts)
83
+ return "this device's provider cannot open a local port to a device service";
84
+ return null;
85
+ }
86
+ /**
87
+ * Whether the device refuses loopback grants now, as far as that is known: a ceiling layer keeps
88
+ * running outside the sandbox off (`ceiling`), or a known, usable support lacks loopback ports
89
+ * (`provider-support`: no `network.loopbackPorts`, an old capybara-device, or nothing run outside
90
+ * the sandbox). A support not known (none stored, a failed read, or a closed one naming an
91
+ * `unavailableReason`, as while a device re-binds) refuses nothing: grants are consents and are
92
+ * kept until the support is known again. Null when nothing known refuses.
93
+ */
94
+ export function knownLoopbackRefusal(facts) {
95
+ const { box, support } = facts;
96
+ // no run here: only the device's ceiling decides whether a call could run outside now
97
+ if (!box.outsideSandbox && box.layer.outsideSandbox !== "provider")
98
+ return "ceiling";
99
+ if (support === null || support.unavailableReason !== undefined)
100
+ return null;
101
+ const refusal = loopbackRefusal(box, support, box.outsideSandbox ? null : "the provider runs nothing outside the sandbox");
102
+ return refusal === null ? null : "provider-support";
103
+ }
104
+ export const rowOf = (r) => ({
105
+ id: r.id,
106
+ port: r.port,
107
+ source: r.source,
108
+ expiresAt: new Date(r.expires_at).toISOString(),
109
+ runId: r.run_id,
110
+ callId: r.call_id,
111
+ attempt: r.attempt,
112
+ });
113
+ export const isDatabasePort = (port) => LOOPBACK_DATABASE_PORTS.includes(port);
114
+ /** Owes the refresh of one (device, service). */
115
+ export async function oweRefresh(outbox, target, change) {
116
+ const data = {
117
+ orgId: target.orgId,
118
+ deviceId: target.deviceId,
119
+ serviceId: target.serviceId,
120
+ change,
121
+ };
122
+ await outbox.add({
123
+ queue: MAINTENANCE_QUEUE_NAME,
124
+ name: LOOPBACK_REFRESH_JOB,
125
+ jobId: loopbackRefreshJobId(target.deviceId, target.serviceId, change),
126
+ data,
127
+ orgId: target.orgId,
128
+ });
129
+ }
130
+ /**
131
+ * Owes one refresh per (device, service) with live grants under the subject, in the caller's
132
+ * transaction (a ceiling publication, `PermissionCeilingWrites.publishLocked`): every org at the
133
+ * platform level, the org's, the device's, or the root conversation's grants. Returns how many it
134
+ * owed. The job decides whether the ceiling now refuses and revokes then.
135
+ */
136
+ export async function oweLoopbackRefreshes(db, outbox, under, change) {
137
+ const need = (v) => {
138
+ if (!v)
139
+ throw new Error(`A ${under.level} loopback refresh needs its subject`);
140
+ return v;
141
+ };
142
+ // RLS phase 5: the platform level reads every org's grants under asPlatform, but owes their
143
+ // outbox rows in the caller's scope; once RLS is enabled, those inserts must run under
144
+ // asPlatform too (or per row in its own org), or the policy refuses other orgs' rows
145
+ const rows = under.level === "platform"
146
+ ? await asPlatform("platform ceiling publication: loopback grants of every org", () => {
147
+ // org-filter: deployment-wide platform-level writer under the exclusive platform lock:
148
+ // the live grants it may narrow lie in every org; each refresh runs in its own org
149
+ return db
150
+ .selectFrom("device_loopback_grants")
151
+ .select(["org_id", "device_id", "service_id"])
152
+ .distinct()
153
+ .where("revoked_at", "is", null)
154
+ .orderBy("org_id")
155
+ .orderBy("device_id")
156
+ .orderBy("service_id")
157
+ .execute();
158
+ })
159
+ : await db
160
+ .selectFrom("device_loopback_grants")
161
+ .select(["org_id", "device_id", "service_id"])
162
+ .distinct()
163
+ .where("org_id", "=", need(under.orgId))
164
+ .where("revoked_at", "is", null)
165
+ .$if(under.level === "device", (q) => q.where("device_id", "=", need(under.deviceId)))
166
+ .$if(under.level === "root", (q) => q.where("conversation_id", "=", need(under.rootConversationId)))
167
+ .orderBy("device_id")
168
+ .orderBy("service_id")
169
+ .execute();
170
+ for (const r of rows)
171
+ await oweRefresh(outbox, { orgId: r.org_id, deviceId: r.device_id, serviceId: r.service_id }, change);
172
+ return rows.length;
173
+ }
174
+ /**
175
+ * Revokes a deleted device's live grants (reason `revoked`, audited with `cause: "device-deleted"`)
176
+ * and owes their refreshes, in the caller's transaction (the device's deletion or its owner's
177
+ * offboarding).
178
+ */
179
+ export async function revokeLoopbackGrantsOfDevice(db, outbox, target) {
180
+ const rows = await db
181
+ .updateTable("device_loopback_grants")
182
+ .set({ revoked_at: sql `now()`, revoke_reason: "revoked" })
183
+ .where("org_id", "=", target.orgId)
184
+ .where("device_id", "=", target.deviceId)
185
+ .where("revoked_at", "is", null)
186
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
187
+ .execute();
188
+ await endedGrants(db, outbox, rows, "revoked", null, "device-deleted");
189
+ }
190
+ /**
191
+ * Revokes a deleted root's live grants (reason `conversation-deleted`, audited) and owes their
192
+ * refreshes, in the caller's transaction (the conversation's deletion). A sub-agent's
193
+ * conversation holds no grant, so its id finds none.
194
+ */
195
+ export async function revokeLoopbackGrantsOfConversation(db, outbox, target) {
196
+ const rows = await db
197
+ .updateTable("device_loopback_grants")
198
+ .set({ revoked_at: sql `now()`, revoke_reason: "conversation-deleted" })
199
+ .where("org_id", "=", target.orgId)
200
+ .where("conversation_id", "=", target.rootConversationId)
201
+ .where("revoked_at", "is", null)
202
+ .returning(["id", "org_id", "device_id", "service_id", "conversation_id", "port"])
203
+ .execute();
204
+ await endedGrants(db, outbox, rows, "conversation-deleted", null);
205
+ }
206
+ /**
207
+ * Audits ended grants (`device.loopback_revoked`) and owes one refresh per (device, service),
208
+ * named by its first grant.
209
+ */
210
+ export async function endedGrants(db, outbox, rows, reason, actorAccountId,
211
+ /** What ended them when the reason alone does not say (`device-deleted`, `provider-support`). */
212
+ cause) {
213
+ const owed = new Map();
214
+ for (const r of [...rows].sort((a, b) => a.id.localeCompare(b.id))) {
215
+ await audit(db, {
216
+ actorAccountId,
217
+ orgId: r.org_id,
218
+ action: "device.loopback_revoked",
219
+ target: r.device_id,
220
+ detail: {
221
+ grantId: r.id,
222
+ deviceId: r.device_id,
223
+ serviceId: r.service_id,
224
+ conversationId: r.conversation_id,
225
+ port: r.port,
226
+ reason,
227
+ ...(cause !== undefined && { cause }),
228
+ },
229
+ });
230
+ const key = `${r.device_id}\n${r.service_id}`;
231
+ if (!owed.has(key))
232
+ owed.set(key, {
233
+ target: { orgId: r.org_id, deviceId: r.device_id, serviceId: r.service_id },
234
+ grantId: r.id,
235
+ });
236
+ }
237
+ for (const { target, grantId } of owed.values())
238
+ await oweRefresh(outbox, target, `r${grantId}`);
239
+ }
@@ -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
+ }