@capybara-hq/kernel 0.1.0-rc.121 → 0.1.0-rc.123

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 (230) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/background/finish.d.ts +5 -1
  3. package/dist/background/finish.js +29 -18
  4. package/dist/background/launch.d.ts +0 -5
  5. package/dist/background/launch.js +1 -6
  6. package/dist/background/managed.js +1 -4
  7. package/dist/background/poll.job.d.ts +3 -25
  8. package/dist/background/poll.job.js +20 -112
  9. package/dist/background/render.d.ts +2 -8
  10. package/dist/background/render.js +3 -17
  11. package/dist/background/stop.d.ts +15 -16
  12. package/dist/background/stop.js +39 -76
  13. package/dist/background/store.d.ts +17 -45
  14. package/dist/background/store.js +60 -94
  15. package/dist/background/tasks.service.d.ts +2 -5
  16. package/dist/background/tasks.service.js +9 -20
  17. package/dist/background/wake.js +3 -2
  18. package/dist/catalog/admin-catalog.controller.d.ts +2 -18
  19. package/dist/catalog/admin-catalog.controller.js +2 -28
  20. package/dist/catalog/catalog-content.d.ts +1 -5
  21. package/dist/catalog/catalog-items.d.ts +2 -6
  22. package/dist/catalog/catalog-items.js +5 -26
  23. package/dist/catalog/catalog-scope.service.d.ts +1 -121
  24. package/dist/catalog/catalog-scope.service.js +12 -552
  25. package/dist/catalog/catalog.service.d.ts +4 -15
  26. package/dist/catalog/catalog.service.js +7 -35
  27. package/dist/catalog/job-ids.d.ts +0 -18
  28. package/dist/catalog/job-ids.js +0 -20
  29. package/dist/catalog/marketplaces.service.d.ts +1 -1
  30. package/dist/catalog/org-catalog.service.js +6 -20
  31. package/dist/catalog/org-plugin-uploads.controller.d.ts +4 -19
  32. package/dist/catalog/org-plugin-uploads.controller.js +6 -34
  33. package/dist/catalog/org-plugin-uploads.d.ts +3 -10
  34. package/dist/catalog/org-plugin-uploads.js +4 -18
  35. package/dist/catalog/org-plugin-uploads.schemas.js +0 -1
  36. package/dist/catalog/owned-items.d.ts +6 -11
  37. package/dist/catalog/owned-items.js +10 -20
  38. package/dist/catalog/ownership.d.ts +3 -29
  39. package/dist/catalog/ownership.js +4 -54
  40. package/dist/catalog/platform-components.d.ts +5 -11
  41. package/dist/catalog/platform-components.js +8 -15
  42. package/dist/catalog/plugin-import.d.ts +3 -42
  43. package/dist/catalog/plugin-import.js +26 -195
  44. package/dist/catalog/plugin-install.js +1 -6
  45. package/dist/catalog/plugin-package.d.ts +1 -0
  46. package/dist/catalog/plugin-package.js +5 -0
  47. package/dist/catalog/plugin-upgrade.d.ts +3 -26
  48. package/dist/catalog/plugin-upgrade.js +20 -103
  49. package/dist/catalog/request-rules.js +4 -6
  50. package/dist/catalog/scope-sync.js +2 -4
  51. package/dist/catalog/scope.d.ts +2 -5
  52. package/dist/channels/jobs.d.ts +3 -3
  53. package/dist/channels/jobs.js +4 -3
  54. package/dist/channels/outbound.d.ts +1 -0
  55. package/dist/channels/outbound.js +32 -8
  56. package/dist/config/load.d.ts +0 -25
  57. package/dist/config/load.js +0 -57
  58. package/dist/config/schema.js +2 -3
  59. package/dist/conversations/attachments.service.js +3 -5
  60. package/dist/conversations/conversations.service.d.ts +3 -3
  61. package/dist/conversations/conversations.service.js +3 -3
  62. package/dist/conversations/job-org.d.ts +3 -0
  63. package/dist/conversations/job-org.js +11 -0
  64. package/dist/conversations/prompt-suggestions.d.ts +2 -7
  65. package/dist/conversations/prompt-suggestions.js +29 -27
  66. package/dist/conversations/titles.d.ts +3 -4
  67. package/dist/conversations/titles.js +19 -30
  68. package/dist/db/kernel-schema.d.ts +6 -16
  69. package/dist/db/pool.js +7 -2
  70. package/dist/devices/devices.controller.d.ts +0 -5
  71. package/dist/devices/devices.controller.js +2 -20
  72. package/dist/devices/devices.service.d.ts +1 -17
  73. package/dist/devices/devices.service.js +0 -22
  74. package/dist/errors.d.ts +1 -5
  75. package/dist/errors.js +1 -5
  76. package/dist/evals/judge.d.ts +3 -0
  77. package/dist/evals/judge.js +1 -1
  78. package/dist/evals/run-replay.d.ts +1 -1
  79. package/dist/evals/run-replay.js +26 -29
  80. package/dist/evals/step-replay.d.ts +3 -1
  81. package/dist/evals/step-replay.js +10 -1
  82. package/dist/evals/worker.d.ts +3 -1
  83. package/dist/evals/worker.js +53 -21
  84. package/dist/extensions/deployment-config-store.js +18 -14
  85. package/dist/extensions/effective-config.d.ts +1 -5
  86. package/dist/extensions/effective-config.js +1 -5
  87. package/dist/extensions/hooks.d.ts +3 -1
  88. package/dist/extensions/hooks.js +7 -2
  89. package/dist/extensions/installs.d.ts +2 -14
  90. package/dist/extensions/installs.js +10 -32
  91. package/dist/extensions/org-config.d.ts +3 -4
  92. package/dist/extensions/org-config.js +3 -4
  93. package/dist/extensions/plugin-guides.d.ts +0 -1
  94. package/dist/extensions/plugin-guides.js +0 -1
  95. package/dist/extensions/plugin-icons.d.ts +0 -1
  96. package/dist/extensions/plugin-icons.js +0 -3
  97. package/dist/files/blob-sweep.job.d.ts +2 -11
  98. package/dist/files/blob-sweep.job.js +7 -21
  99. package/dist/files/hash-job.d.ts +5 -15
  100. package/dist/files/hash-job.js +14 -33
  101. package/dist/files/library-jobs.module.d.ts +1 -6
  102. package/dist/files/library-jobs.module.js +3 -9
  103. package/dist/identity/api-tokens.js +54 -40
  104. package/dist/identity/auth.guard.js +2 -2
  105. package/dist/identity/sessions.js +7 -3
  106. package/dist/identity/settings.js +5 -21
  107. package/dist/inbox/inbox.service.d.ts +2 -3
  108. package/dist/inbox/org-notices.d.ts +0 -14
  109. package/dist/inbox/platform-inbox.service.d.ts +1 -8
  110. package/dist/inbox/platform-inbox.service.js +2 -6
  111. package/dist/inbox/platform-notices.d.ts +3 -3
  112. package/dist/index.d.ts +0 -4
  113. package/dist/index.js +0 -3
  114. package/dist/infra/database/database.module.js +2 -1
  115. package/dist/infra/database/org-scope.d.ts +5 -3
  116. package/dist/infra/database/org-scope.js +7 -1
  117. package/dist/infra/database/scoped-dialect.d.ts +3 -1
  118. package/dist/infra/database/scoped-dialect.js +17 -5
  119. package/dist/infra/events/kernel-events.d.ts +2 -0
  120. package/dist/infra/outbox/outbox.service.d.ts +2 -0
  121. package/dist/infra/outbox/outbox.service.js +10 -0
  122. package/dist/infra/outbox/registry.d.ts +0 -41
  123. package/dist/infra/outbox/registry.js +0 -37
  124. package/dist/models/embeddings.d.ts +0 -5
  125. package/dist/models/embeddings.js +28 -35
  126. package/dist/models/images.d.ts +3 -8
  127. package/dist/models/images.js +19 -37
  128. package/dist/models/purposes.d.ts +7 -2
  129. package/dist/models/purposes.js +16 -3
  130. package/dist/orgs/device-network-setting.d.ts +0 -44
  131. package/dist/orgs/device-network-setting.js +0 -83
  132. package/dist/orgs/invitations.service.js +34 -30
  133. package/dist/orgs/offboarding.d.ts +2 -2
  134. package/dist/orgs/offboarding.js +2 -2
  135. package/dist/orgs/orgs.service.d.ts +1 -1
  136. package/dist/orgs/orgs.service.js +19 -15
  137. package/dist/orgs/settings.service.d.ts +19 -14
  138. package/dist/orgs/settings.service.js +12 -37
  139. package/dist/platform/exclusions.js +0 -11
  140. package/dist/platform/ops/catalog-admin.ops.js +0 -8
  141. package/dist/platform/ops/devices.ops.js +0 -28
  142. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  143. package/dist/platform/ops/inbox.ops.js +5 -22
  144. package/dist/platform/ops/org-plugins.ops.d.ts +1 -3
  145. package/dist/platform/ops/org-plugins.ops.js +11 -67
  146. package/dist/roles/worker.module.js +0 -9
  147. package/dist/runtime/hook-calls.d.ts +13 -6
  148. package/dist/runtime/hook-calls.js +26 -4
  149. package/dist/runtime/maintenance.d.ts +3 -12
  150. package/dist/runtime/maintenance.js +25 -55
  151. package/dist/runtime/model-call.d.ts +4 -2
  152. package/dist/runtime/model-call.js +59 -58
  153. package/dist/runtime/providers.d.ts +27 -1
  154. package/dist/runtime/providers.js +57 -0
  155. package/dist/runtime/run-jobs.d.ts +1 -1
  156. package/dist/runtime/run-processors.d.ts +3 -9
  157. package/dist/runtime/run-worker.d.ts +2 -0
  158. package/dist/runtime/run-worker.js +23 -8
  159. package/dist/runtime/subagents/deliveries.js +6 -1
  160. package/dist/runtime/subagents/dispatch.d.ts +3 -3
  161. package/dist/runtime/write-base.service.d.ts +2 -3
  162. package/dist/runtime/write-base.service.js +3 -5
  163. package/dist/sandbox/device-sandbox-settings.d.ts +38 -92
  164. package/dist/sandbox/device-sandbox-settings.js +19 -325
  165. package/dist/sandbox/jobs.d.ts +3 -14
  166. package/dist/sandbox/jobs.js +2 -20
  167. package/dist/sandbox/modes.d.ts +5 -45
  168. package/dist/sandbox/modes.js +3 -60
  169. package/dist/sandbox/operation-authority.js +0 -11
  170. package/dist/sandbox/operation-intents.d.ts +32 -9
  171. package/dist/sandbox/operation-intents.js +241 -32
  172. package/dist/sandbox/operation-intents.module.js +2 -1
  173. package/dist/sandbox/operation-reconcile.job.d.ts +9 -11
  174. package/dist/sandbox/operation-reconcile.job.js +119 -33
  175. package/dist/sandbox/operation-revoke.d.ts +20 -0
  176. package/dist/sandbox/operation-revoke.js +3 -0
  177. package/dist/sandbox/permission-ceiling-writes.d.ts +1 -2
  178. package/dist/sandbox/permission-ceiling-writes.js +3 -6
  179. package/dist/sandbox/permission-config-publication.d.ts +1 -28
  180. package/dist/sandbox/permission-config-publication.js +14 -211
  181. package/dist/sandbox/permission-facts.d.ts +4 -15
  182. package/dist/sandbox/permission-facts.js +7 -29
  183. package/dist/sandbox/permission-instance-writes.d.ts +1 -4
  184. package/dist/sandbox/permission-instance-writes.js +1 -55
  185. package/dist/sandbox/providers.d.ts +1 -6
  186. package/dist/sandbox/providers.js +1 -15
  187. package/dist/sandbox/review/classifier.js +12 -13
  188. package/dist/sandbox/sandbox.module.js +3 -6
  189. package/dist/sandbox/sandbox.service.d.ts +17 -123
  190. package/dist/sandbox/sandbox.service.js +239 -998
  191. package/dist/shares/liveness.d.ts +1 -2
  192. package/dist/shares/liveness.js +1 -2
  193. package/dist/shares/shares.module.d.ts +1 -2
  194. package/dist/shares/shares.module.js +2 -5
  195. package/dist/shares/shares.service.js +1 -2
  196. package/dist/tools/builtins/image/generate.js +7 -15
  197. package/dist/tools/builtins/sandbox/common.d.ts +0 -2
  198. package/dist/tools/builtins/sandbox/common.js +1 -27
  199. package/dist/tools/builtins/sandbox/task-list.js +10 -10
  200. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -10
  201. package/dist/tools/builtins/sandbox/task-output.js +13 -83
  202. package/dist/tools/builtins/sandbox/task-stop.js +18 -22
  203. package/dist/tools/builtins/vision/read-image.js +9 -10
  204. package/dist/tools/builtins/web/extract.js +9 -10
  205. package/package.json +3 -3
  206. package/src/migrations/0206_retire_org_extension_uploads.sql +125 -0
  207. package/src/migrations/0207_confirm_device_instance_destruction.sql +25 -0
  208. package/src/migrations/0208_convert_stored_permission_settings.sql +189 -0
  209. package/dist/background/retire-legacy-tasks.job.d.ts +0 -57
  210. package/dist/background/retire-legacy-tasks.job.js +0 -149
  211. package/dist/catalog/owned-plugin-cleanup.d.ts +0 -47
  212. package/dist/catalog/owned-plugin-cleanup.js +0 -140
  213. package/dist/config/permission-migration.d.ts +0 -34
  214. package/dist/config/permission-migration.js +0 -115
  215. package/dist/devices/legacy-cleanup.job.d.ts +0 -34
  216. package/dist/devices/legacy-cleanup.job.js +0 -147
  217. package/dist/files/library-backfill.d.ts +0 -63
  218. package/dist/files/library-backfill.js +0 -143
  219. package/dist/infra/cli/permission-cutover.d.ts +0 -59
  220. package/dist/infra/cli/permission-cutover.js +0 -107
  221. package/dist/sandbox/cloud-permission-snapshot.d.ts +0 -159
  222. package/dist/sandbox/cloud-permission-snapshot.js +0 -430
  223. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +0 -8
  224. package/dist/sandbox/cloud-permission-snapshot.module.js +0 -34
  225. package/dist/sandbox/legacy-retirement.d.ts +0 -284
  226. package/dist/sandbox/legacy-retirement.js +0 -1165
  227. package/dist/sandbox/legacy-retirement.module.d.ts +0 -8
  228. package/dist/sandbox/legacy-retirement.module.js +0 -25
  229. package/dist/shares/share-objects.d.ts +0 -47
  230. package/dist/shares/share-objects.js +0 -93
@@ -1,430 +0,0 @@
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 { isSandboxScopeDeniedError } from "@capybara-hq/plugin-sdk";
11
- import { Inject, Injectable } from "@nestjs/common";
12
- import { sql } from "kysely";
13
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
- import { KernelDb } from "../infra/database/kernel-db.js";
15
- import { TransactionHost } from "../infra/database/transaction-host.js";
16
- import { Transactional } from "../infra/database/transactional.decorator.js";
17
- import { readOrgSettings } from "../orgs/settings.service.js";
18
- import { SandboxLeases } from "./leases.js";
19
- import { LegacyRetirementStore } from "./legacy-retirement.js";
20
- import { appliedOf, cloudChosenMode, cloudSnapshotOf, coversHost, effectiveDevicePolicy, normalizeNetwork, readDeploymentDevicePolicy, readInstanceLimits, sameAppliedExactly, } from "./modes.js";
21
- import { isExecutionMethod } from "./operation-authority-types.js";
22
- import { PermissionAuthorityLock } from "./permission-authority-lock.js";
23
- import { needsFullCeiling, PermissionCeilingWrites } from "./permission-ceiling-writes.js";
24
- import { PermissionConfigPublication } from "./permission-config-publication.js";
25
- import { PermissionFacts } from "./permission-facts.js";
26
- import { DeviceProviders } from "./providers.js";
27
- /** How long the writer waits for the device's exclusive lifecycle lease (running commands). */
28
- const LEASE_WAIT_MS = 120_000;
29
- /** Devices the driver reads per page. */
30
- const DRIVER_PAGE = 100;
31
- const liveCloud = (db) => db
32
- .selectFrom("devices as d")
33
- .innerJoin("orgs as g", "g.id", "d.org_id")
34
- .where("d.deleted_at", "is", null)
35
- .where("g.deleted_at", "is", null);
36
- /** Reads the cloud snapshot's progress; no lock, no lease (a report). */
37
- export async function readCloudSnapshotProgress(db) {
38
- const counts = await liveCloud(db)
39
- .select((eb) => [
40
- eb.fn.countAll().as("n"),
41
- eb.fn.count(sql `CASE WHEN d.owner_full_access IS NULL THEN 1 END`).as("pending"),
42
- ])
43
- .executeTakeFirstOrThrow();
44
- const marked = await liveCloud(db)
45
- .select("d.id")
46
- .where("d.permission_reconcile_required", "=", true)
47
- .orderBy("d.id")
48
- .execute();
49
- return {
50
- cloudDevices: Number(counts.n),
51
- pending: Number(counts.pending),
52
- reconcileRequired: marked.map((r) => r.id),
53
- };
54
- }
55
- /**
56
- * The B1 cloud per-device authority writer: replaces the old daily mode of a cloud device by an
57
- * explicit owner Full ceiling and outer network, computed from the device's OLD effective
58
- * authority (platform switch with its configured / stored precedence, the org's switch and cloud
59
- * network, the device's narrowing switch, `egress: none`), narrowed by what its instance is known
60
- * to run, never widened. Each device: the exclusive lifecycle lease outside the transaction, then
61
- * the device authority write lock (platform -> org -> device order) before the row locks. Written
62
- * once: a snapshot is never recomputed (a later false stays explicit after a widening). A device
63
- * whose applied limits are not exactly the desired ones keeps a durable marker that blocks
64
- * admission ({@link PermissionFacts.assertCloudReconciled}) until {@link reconcile} finds them
65
- * established: after a file reset (the next create applies them exactly), or once a provider
66
- * `update` under the lifecycle lease applied the reconcile target (B-12,
67
- * `SandboxService.reconcileLimits`). Reconciling keeps any stricter boundary the instance is
68
- * known to run by intersection: the owner ceiling and outer network are narrowed to it (a real
69
- * narrowing, published like the snapshot's), never the instance widened to the authority.
70
- */
71
- let CloudPermissionSnapshots = class CloudPermissionSnapshots {
72
- db;
73
- txHost;
74
- leases;
75
- locks;
76
- config;
77
- facts;
78
- publication;
79
- ceilings;
80
- retirement;
81
- providers;
82
- constructor(db, txHost, leases, locks, config, facts, publication, ceilings, retirement,
83
- /** Whether a device's provider fixes limits at its file system (B-12 intersection). */
84
- providers) {
85
- this.db = db;
86
- this.txHost = txHost;
87
- this.leases = leases;
88
- this.locks = locks;
89
- this.config = config;
90
- this.facts = facts;
91
- this.publication = publication;
92
- this.ceilings = ceilings;
93
- this.retirement = retirement;
94
- this.providers = providers;
95
- }
96
- /**
97
- * The production driver (B-10, `capybara permissions cutover snapshot`): snapshots every live
98
- * cloud device that has none yet, one device at a time, each under its exclusive lifecycle
99
- * lease and in its own transaction ({@link snapshot}).
100
- *
101
- * - **Barrier.** Refuses unless legacy admission is closed (the freeze published and enumerated,
102
- * {@link LegacyRetirementStore.assertCutoverBarrier}) and this replica's permission
103
- * configuration is the published one; each device re-checks the latter under the platform
104
- * lock, and a failure there stops the run.
105
- * - **Idempotent.** Only devices without a snapshot are visited, and {@link snapshot} keeps an
106
- * existing one under the row lock, so a rerun takes no lease and publishes nothing.
107
- * - **Resumable.** A device's snapshot, its narrowing publication (epoch, Full consent reset,
108
- * exact revocation) and its marker commit together or not at all; a crash or a failed device
109
- * leaves it without a snapshot for the next run, never half written or published twice.
110
- * - Devices whose applied limits are not established keep `permission_reconcile_required`
111
- * (listed in the answer) until a file reset reconciles them.
112
- */
113
- async snapshotAll(opts = {}) {
114
- await this.retirement.assertCutoverBarrier();
115
- await this.publication.assertCurrent();
116
- const results = [];
117
- const failed = [];
118
- let after = "";
119
- for (;;) {
120
- opts.signal?.throwIfAborted();
121
- const page = await liveCloud(this.db)
122
- .select(["d.id", "d.org_id"])
123
- .where("d.owner_full_access", "is", null)
124
- .where(sql `d.id COLLATE "C" > ${after}`)
125
- .orderBy(sql `d.id COLLATE "C"`)
126
- .limit(DRIVER_PAGE)
127
- .execute();
128
- for (const d of page) {
129
- opts.signal?.throwIfAborted();
130
- const wait = AbortSignal.timeout(opts.leaseWaitMs ?? LEASE_WAIT_MS);
131
- const signal = opts.signal ? AbortSignal.any([opts.signal, wait]) : wait;
132
- try {
133
- const outcome = await this.snapshot(d.org_id, d.id, signal);
134
- results.push({ deviceId: d.id, orgId: d.org_id, ...outcome });
135
- }
136
- catch (e) {
137
- // a replica that is not (or no longer) current stops the whole run; the caller's abort too
138
- if (isSandboxScopeDeniedError(e) || opts.signal?.aborted)
139
- throw e;
140
- failed.push({
141
- deviceId: d.id,
142
- orgId: d.org_id,
143
- error: e instanceof Error ? e.message : String(e),
144
- });
145
- }
146
- }
147
- if (page.length < DRIVER_PAGE)
148
- break;
149
- after = page.at(-1).id;
150
- }
151
- const progress = await readCloudSnapshotProgress(this.db);
152
- return {
153
- results,
154
- failed,
155
- pending: progress.pending,
156
- reconcileRequired: progress.reconcileRequired,
157
- };
158
- }
159
- /** Snapshots one device under its exclusive lifecycle lease. */
160
- async snapshot(orgId, deviceId, signal = AbortSignal.timeout(LEASE_WAIT_MS)) {
161
- return this.underLease(deviceId, signal, () => this.snapshotLocked(orgId, deviceId));
162
- }
163
- /** Re-checks a device carrying the marker; clears it once its limits are established. */
164
- async reconcile(orgId, deviceId, signal = AbortSignal.timeout(LEASE_WAIT_MS)) {
165
- return this.underLease(deviceId, signal, () => this.reconcileLocked(orgId, deviceId));
166
- }
167
- /**
168
- * {@link reconcile} for a caller that already holds the device's exclusive lifecycle lease
169
- * (`SandboxService.reconcileLimits`): the same transaction, no lease taken here.
170
- */
171
- async reconcileHeld(orgId, deviceId) {
172
- return this.txHost.run(() => this.reconcileLocked(orgId, deviceId), {
173
- propagation: "requires_new",
174
- });
175
- }
176
- /** {@link reconcile} by device id alone (after a file reset); nothing for an unknown device. */
177
- async reconcileDevice(deviceId) {
178
- // org-filter: reads the device's own org to scope the reconcile; the id comes from the
179
- // kernel-enqueued reset-files job, not caller input
180
- const row = await this.db
181
- .selectFrom("devices")
182
- .select(["org_id", "permission_reconcile_required"])
183
- .where("id", "=", deviceId)
184
- .executeTakeFirst();
185
- if (!row?.permission_reconcile_required)
186
- return { state: "existing" };
187
- return this.reconcile(row.org_id, deviceId);
188
- }
189
- async underLease(deviceId, signal, fn) {
190
- // the lease is a distributed lock: taken outside the transaction, released after the commit
191
- const lease = await this.leases.acquireExclusive(deviceId, signal, undefined, {
192
- intent: true,
193
- });
194
- try {
195
- return await this.txHost.run(fn, { propagation: "requires_new" });
196
- }
197
- finally {
198
- await lease.release();
199
- }
200
- }
201
- async snapshotLocked(orgId, deviceId) {
202
- const device = await this.lockedDevice(orgId, deviceId);
203
- if (device === undefined)
204
- return { state: "skipped" };
205
- if (device.owner_full_access !== null)
206
- return { state: "existing" };
207
- // under the platform shared lock: proves this replica reads the converted (current) inputs
208
- await this.publication.assertCurrent();
209
- const [deployment, settings] = await Promise.all([
210
- readDeploymentDevicePolicy(this.db.db, this.config),
211
- readOrgSettings(this.db.db, orgId),
212
- ]);
213
- // the OLD algorithm on the old inputs: the snapshot columns are still empty here
214
- const old = effectiveDevicePolicy(deployment, settings, cloudChosenMode(device));
215
- const instance = await this.lockedInstance(orgId, deviceId);
216
- const rec = instance === null ? null : readInstanceLimits(instance.instance_limits);
217
- // what the instance really runs narrows the snapshot even when a newer value is pending
218
- const known = rec?.applied ?? null;
219
- const snap = cloudSnapshotOf(old, known);
220
- const desired = this.desired(snap.fullAccess, snap.outerNetwork);
221
- const state = instance === null
222
- ? "unprobed"
223
- : rec?.unapplied === null && sameAppliedExactly(known, desired)
224
- ? "bound"
225
- : "reconcile-required";
226
- await this.db
227
- .updateTable("devices")
228
- .set({
229
- owner_full_access: snap.fullAccess,
230
- outer_network: JSON.stringify(snap.outerNetwork),
231
- // the device's own sandbox network carries an allowlist snapshot (never wider): the
232
- // device sandbox reads it, not `outer_network`
233
- ...(device.network_mode === null && ownNetworkOf(snap.outerNetwork)),
234
- permission_migration: JSON.stringify({
235
- from: "auto-mode",
236
- old: { mode: old.mode, network: old.network },
237
- instance: instance === null ? null : { generation: instance.generation, applied: known, state },
238
- }),
239
- permission_reconcile_required: state === "reconcile-required",
240
- })
241
- .where("id", "=", deviceId)
242
- .where("org_id", "=", orgId)
243
- .execute();
244
- // A snapshot narrowed by what the instance really runs changes the device's authority: it
245
- // goes through the device ceiling writer (epoch, Full consent, exact revocation) in this
246
- // transaction, under the device write lock already held.
247
- const fullNarrowed = old.mode === "auto" && !snap.fullAccess;
248
- const networkNarrowed = JSON.stringify(normalizeNetwork(old.network)) !== JSON.stringify(snap.outerNetwork);
249
- if (fullNarrowed || networkNarrowed)
250
- await this.publishNarrowing(orgId, deviceId, snap, fullNarrowed);
251
- return state === "reconcile-required" ? { state, action: "reset-files" } : { state };
252
- }
253
- /**
254
- * A narrowed owner ceiling or outer network changes the device's authority: it goes through the
255
- * device ceiling writer (epoch, Full consent, exact revocation) in the caller's transaction,
256
- * under the device write lock already held.
257
- */
258
- async publishNarrowing(orgId, deviceId, snap, fullNarrowed) {
259
- const outer = snap.outerNetwork;
260
- await this.ceilings.publishLocked({ orgId, deviceId }, "device", (scope, row) => {
261
- if (needsFullCeiling(scope))
262
- return !snap.fullAccess;
263
- if (outer.kind !== "allowlist" || !("network" in scope) || !isExecutionMethod(row.method))
264
- return false;
265
- // an execution outside any allowlist (environment networking, the open public network)
266
- // is wider than the outer allowlist; `none` is narrower; an allowlist must be covered
267
- // host by host
268
- if (scope.network.kind === "environment" || scope.network.kind === "open-public")
269
- return true;
270
- if (scope.network.kind !== "allowlist")
271
- return false;
272
- return scope.network.hosts.some((h) => !outer.hosts.some((p) => coversHost(p, h)));
273
- }, fullNarrowed);
274
- }
275
- /**
276
- * Re-checks a marked device under its write lock. With an instance whose applied limits are
277
- * known (in force, even with a newer value pending a reset), the device's authority is first
278
- * narrowed to them by intersection (B-12): Full only where the instance runs auto, the outer
279
- * network cut to the applied network; a real narrowing is published. Then the marker clears
280
- * when the applied limits are exactly the (narrowed) effective ones with nothing pending;
281
- * otherwise it stays, with the target that would establish them: the effective limits, which
282
- * are now never wider than the instance in any dimension, so applying them only narrows.
283
- */
284
- async reconcileLocked(orgId, deviceId) {
285
- const device = await this.lockedDevice(orgId, deviceId);
286
- if (device === undefined)
287
- return { state: "skipped" };
288
- if (!device.permission_reconcile_required)
289
- return { state: "existing" };
290
- const instance = await this.lockedInstance(orgId, deviceId);
291
- let state = "unprobed";
292
- let target;
293
- if (instance !== null) {
294
- const rec = readInstanceLimits(instance.instance_limits);
295
- // only a record in force narrows: a live instance's, or the file system's of a provider
296
- // that fixes limits there; a destroyed instance's record is stale (the next create applies
297
- // the desired limits)
298
- const inForce = (instance.handle !== null &&
299
- (instance.status === "running" || instance.status === "suspended")) ||
300
- this.providers.forDevice(device.provider)?.impl.limitsApplyAt === "fileSystem";
301
- if (inForce && rec.applied !== null && device.owner_full_access !== null) {
302
- const outer = device.outer_network ?? { kind: "open-public", hosts: [] };
303
- const narrowed = cloudSnapshotOf({ mode: device.owner_full_access ? "auto" : "sandbox", network: outer }, rec.applied);
304
- const fullNarrowed = device.owner_full_access && !narrowed.fullAccess;
305
- const networkNarrowed = JSON.stringify(normalizeNetwork(outer)) !== JSON.stringify(narrowed.outerNetwork);
306
- if (fullNarrowed || networkNarrowed) {
307
- await this.db
308
- .updateTable("devices")
309
- .set({
310
- owner_full_access: narrowed.fullAccess,
311
- outer_network: JSON.stringify(narrowed.outerNetwork),
312
- // a narrower instance narrows the device's own network choice too
313
- ...ownNetworkOf(narrowed.outerNetwork),
314
- })
315
- .where("id", "=", deviceId)
316
- .where("org_id", "=", orgId)
317
- .execute();
318
- await this.publishNarrowing(orgId, deviceId, narrowed, fullNarrowed);
319
- }
320
- }
321
- // what the instance must run with now: the snapshot as the current effective policy
322
- const policy = await this.facts.devicePolicy({ orgId, deviceId });
323
- const effective = appliedOf({ mode: policy.mode, network: policy.network });
324
- const known = rec.unapplied !== null ? null : rec.applied;
325
- state = sameAppliedExactly(known, effective) ? "bound" : "reconcile-required";
326
- target = effective;
327
- }
328
- if (state !== "reconcile-required")
329
- await this.db
330
- .updateTable("devices")
331
- .set({ permission_reconcile_required: false })
332
- .where("id", "=", deviceId)
333
- .where("org_id", "=", orgId)
334
- .execute();
335
- return state === "reconcile-required"
336
- ? { state, action: "reset-files", ...(target !== undefined && { target }) }
337
- : { state };
338
- }
339
- desired(fullAccess, outer) {
340
- return { mode: fullAccess ? "auto" : "sandbox", network: outer };
341
- }
342
- /**
343
- * The device row under the device authority write lock, or undefined (not a live cloud one). The
344
- * row is locked first (`FOR NO KEY UPDATE`: only non-key columns change), then the permission
345
- * lock, the order the device writers take (`DevicesService.lockOwn`, the device project writes),
346
- * then the row is read again under both.
347
- */
348
- async lockedDevice(orgId, deviceId) {
349
- const exists = await this.db
350
- .selectFrom("devices")
351
- .select("org_id")
352
- .where("id", "=", deviceId)
353
- .where("org_id", "=", orgId)
354
- .forNoKeyUpdate()
355
- .executeTakeFirst();
356
- if (exists === undefined)
357
- return undefined;
358
- await this.locks.acquire({ orgId, deviceId }, { kind: "write", level: "device" });
359
- const device = await this.db
360
- .selectFrom("devices")
361
- .select([
362
- "provider",
363
- "mode",
364
- "owner_full_access",
365
- "outer_network",
366
- "network_mode",
367
- "permission_reconcile_required",
368
- "deleted_at",
369
- ])
370
- .where("id", "=", deviceId)
371
- .where("org_id", "=", orgId)
372
- .forNoKeyUpdate()
373
- .executeTakeFirst();
374
- if (device === undefined || device.deleted_at !== null)
375
- return undefined;
376
- return device;
377
- }
378
- /**
379
- * The device's instance row when an instance or a file system exists (their limits are in
380
- * force); null when neither does (the next create applies the desired limits exactly).
381
- */
382
- async lockedInstance(orgId, deviceId) {
383
- const row = await this.db
384
- .selectFrom("device_instances")
385
- .select(["handle", "status", "fs_status", "instance_limits", "generation"])
386
- .where("device_id", "=", deviceId)
387
- .where("org_id", "=", orgId)
388
- .forUpdate()
389
- .executeTakeFirst();
390
- if (row === undefined)
391
- return null;
392
- // a create that may have acted (creating, even without a handle yet) or any file system left
393
- // counts: its limits are not established
394
- const live = row.status === "creating" ||
395
- (row.handle !== null && (row.status === "running" || row.status === "suspended"));
396
- return live || row.fs_status !== "none" ? row : null;
397
- }
398
- };
399
- __decorate([
400
- Transactional({ propagation: "mandatory" })
401
- ], CloudPermissionSnapshots.prototype, "snapshotLocked", null);
402
- __decorate([
403
- Transactional({ propagation: "mandatory" })
404
- ], CloudPermissionSnapshots.prototype, "reconcileLocked", null);
405
- CloudPermissionSnapshots = __decorate([
406
- Injectable(),
407
- __param(0, Inject(KernelDb)),
408
- __param(1, Inject(TransactionHost)),
409
- __param(2, Inject(SandboxLeases)),
410
- __param(3, Inject(PermissionAuthorityLock)),
411
- __param(4, Inject(KernelConfigService)),
412
- __param(5, Inject(PermissionFacts)),
413
- __param(6, Inject(PermissionConfigPublication)),
414
- __param(7, Inject(PermissionCeilingWrites)),
415
- __param(8, Inject(LegacyRetirementStore)),
416
- __param(9, Inject(DeviceProviders))
417
- ], CloudPermissionSnapshots);
418
- export { CloudPermissionSnapshots };
419
- /**
420
- * The device's own sandbox network columns for an allowlist snapshot, as migrations 0165 and 0167
421
- * copy them: its hosts as an allowlist, or `none` (closed) for an empty one; nothing for an open
422
- * one, which follows the org.
423
- */
424
- function ownNetworkOf(outer) {
425
- if (outer.kind !== "allowlist")
426
- return {};
427
- return outer.hosts.length === 0
428
- ? { network_mode: "none", network_hosts: "[]" }
429
- : { network_mode: "allowlist", network_hosts: JSON.stringify([...outer.hosts]) };
430
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * The cloud snapshot writer (permission runtime cutover B1) and its driver (B-10), with the
3
- * sandbox leases it takes: the one {@link SandboxLeases} of the application (the sandbox service
4
- * uses it through {@link SandboxModule}'s import). Small enough for a CLI context
5
- * (`capybara permissions cutover snapshot`), which has Redis but no extension host.
6
- */
7
- export declare class CloudPermissionSnapshotsModule {
8
- }
@@ -1,34 +0,0 @@
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
- import { Module } from "@nestjs/common";
8
- import { CloudPermissionSnapshots } from "./cloud-permission-snapshot.js";
9
- import { SandboxLeases } from "./leases.js";
10
- import { LegacyRetirementModule } from "./legacy-retirement.module.js";
11
- import { PermissionAuthorityModule } from "./permission-authority.module.js";
12
- import { PermissionFactsModule } from "./permission-facts.module.js";
13
- import { SandboxProviderRegistryModule } from "./providers.module.js";
14
- /**
15
- * The cloud snapshot writer (permission runtime cutover B1) and its driver (B-10), with the
16
- * sandbox leases it takes: the one {@link SandboxLeases} of the application (the sandbox service
17
- * uses it through {@link SandboxModule}'s import). Small enough for a CLI context
18
- * (`capybara permissions cutover snapshot`), which has Redis but no extension host.
19
- */
20
- let CloudPermissionSnapshotsModule = class CloudPermissionSnapshotsModule {
21
- };
22
- CloudPermissionSnapshotsModule = __decorate([
23
- Module({
24
- imports: [
25
- PermissionAuthorityModule,
26
- PermissionFactsModule,
27
- LegacyRetirementModule,
28
- SandboxProviderRegistryModule,
29
- ],
30
- providers: [SandboxLeases, CloudPermissionSnapshots],
31
- exports: [SandboxLeases, CloudPermissionSnapshots],
32
- })
33
- ], CloudPermissionSnapshotsModule);
34
- export { CloudPermissionSnapshotsModule };