@capybara-hq/kernel 0.1.0-rc.68 → 0.1.0-rc.69

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 (215) hide show
  1. package/dist/admin/admin.module.js +2 -0
  2. package/dist/admin/health.service.d.ts +11 -4
  3. package/dist/admin/health.service.js +33 -17
  4. package/dist/background/poll.job.js +2 -2
  5. package/dist/background/tasks.service.d.ts +5 -5
  6. package/dist/background/tasks.service.js +9 -8
  7. package/dist/catalog/marketplaces.service.d.ts +1 -1
  8. package/dist/catalog/requests.service.js +1 -1
  9. package/dist/config/schema.d.ts +1 -1
  10. package/dist/config/schema.js +9 -9
  11. package/dist/conversations/conversations.controller.d.ts +8 -3
  12. package/dist/conversations/conversations.controller.js +8 -3
  13. package/dist/conversations/conversations.service.d.ts +33 -15
  14. package/dist/conversations/conversations.service.js +60 -10
  15. package/dist/conversations/events.d.ts +21 -41
  16. package/dist/conversations/events.js +57 -31
  17. package/dist/conversations/permission-profiles.controller.d.ts +6 -4
  18. package/dist/conversations/permission-profiles.service.d.ts +6 -4
  19. package/dist/ctx/create-ctx.d.ts +20 -1
  20. package/dist/ctx/create-ctx.js +77 -6
  21. package/dist/ctx/device-provider-check.d.ts +6 -2
  22. package/dist/ctx/device-provider-check.js +17 -2
  23. package/dist/db/kernel-schema.d.ts +10 -48
  24. package/dist/devices/access.d.ts +3 -4
  25. package/dist/devices/access.js +3 -4
  26. package/dist/devices/conversation-devices.d.ts +1 -3
  27. package/dist/devices/conversation-devices.js +2 -7
  28. package/dist/devices/device-projects.service.js +24 -29
  29. package/dist/devices/device-provider-selection.d.ts +5 -6
  30. package/dist/devices/device-provider-selection.js +8 -9
  31. package/dist/devices/devices.controller.d.ts +8 -21
  32. package/dist/devices/devices.controller.js +9 -34
  33. package/dist/devices/devices.module.js +6 -4
  34. package/dist/devices/devices.schemas.d.ts +1 -5
  35. package/dist/devices/devices.schemas.js +1 -5
  36. package/dist/devices/devices.service.d.ts +84 -147
  37. package/dist/devices/devices.service.js +134 -229
  38. package/dist/devices/dto.d.ts +5 -32
  39. package/dist/devices/dto.js +5 -37
  40. package/dist/devices/errors.d.ts +6 -5
  41. package/dist/devices/errors.js +7 -8
  42. package/dist/devices/project-rules.d.ts +9 -11
  43. package/dist/devices/project-rules.js +7 -7
  44. package/dist/devices/working-root.d.ts +3 -6
  45. package/dist/devices/working-root.js +3 -8
  46. package/dist/dial-in/access.d.ts +23 -0
  47. package/dist/dial-in/access.js +64 -0
  48. package/dist/{local-devices/device-auth.controller.d.ts → dial-in/auth.controller.d.ts} +12 -6
  49. package/dist/{local-devices/device-auth.controller.js → dial-in/auth.controller.js} +30 -15
  50. package/dist/dial-in/auth.module.d.ts +7 -0
  51. package/dist/dial-in/auth.module.js +27 -0
  52. package/dist/{local-devices/device-auth.d.ts → dial-in/auth.service.d.ts} +42 -13
  53. package/dist/{local-devices/device-auth.js → dial-in/auth.service.js} +83 -32
  54. package/dist/dial-in/dial-in.module.d.ts +9 -0
  55. package/dist/dial-in/dial-in.module.js +37 -0
  56. package/dist/{local-devices → dial-in}/dto.d.ts +17 -2
  57. package/dist/{local-devices → dial-in}/dto.js +14 -2
  58. package/dist/dial-in/envelope.d.ts +95 -0
  59. package/dist/dial-in/envelope.js +89 -0
  60. package/dist/dial-in/gateway.d.ts +214 -0
  61. package/dist/{local-devices/local-device-gateway.js → dial-in/gateway.js} +337 -181
  62. package/dist/dial-in/handlers.d.ts +47 -0
  63. package/dist/dial-in/handlers.js +84 -0
  64. package/dist/dial-in/machines.d.ts +155 -0
  65. package/dist/dial-in/machines.js +383 -0
  66. package/dist/dial-in/relay.d.ts +135 -0
  67. package/dist/dial-in/relay.js +444 -0
  68. package/dist/dial-in/relay.module.d.ts +7 -0
  69. package/dist/dial-in/relay.module.js +24 -0
  70. package/dist/{local-devices/device-routes.d.ts → dial-in/routes.d.ts} +19 -11
  71. package/dist/{local-devices/device-routes.js → dial-in/routes.js} +45 -25
  72. package/dist/{local-devices → dial-in}/targets.d.ts +3 -18
  73. package/dist/{local-devices → dial-in}/targets.js +3 -48
  74. package/dist/errors.d.ts +8 -27
  75. package/dist/errors.js +8 -27
  76. package/dist/extensions/bootstrap.d.ts +5 -0
  77. package/dist/extensions/bootstrap.js +10 -1
  78. package/dist/extensions/extensions.module.js +6 -0
  79. package/dist/extensions/host.d.ts +6 -0
  80. package/dist/extensions/host.js +12 -2
  81. package/dist/extensions/permission-set.d.ts +15 -1
  82. package/dist/extensions/permission-set.js +11 -1
  83. package/dist/extensions/permission-view.d.ts +1 -1
  84. package/dist/extensions/permission-view.js +4 -1
  85. package/dist/http/api.module.js +4 -4
  86. package/dist/http/gateway-routes.d.ts +1 -1
  87. package/dist/http/gateway-routes.js +1 -1
  88. package/dist/http/meta.controller.js +1 -1
  89. package/dist/identity/settings.d.ts +1 -1
  90. package/dist/identity/settings.js +6 -8
  91. package/dist/infra/config/kernel-config.service.js +2 -2
  92. package/dist/infra/outbox/registry.d.ts +0 -14
  93. package/dist/infra/outbox/registry.js +0 -15
  94. package/dist/infra/throttler/named-throttlers.d.ts +1 -1
  95. package/dist/infra/throttler/named-throttlers.js +1 -1
  96. package/dist/kernel.module.js +0 -3
  97. package/dist/orgs/settings.service.js +5 -10
  98. package/dist/overrides.d.ts +0 -4
  99. package/dist/overrides.js +0 -2
  100. package/dist/platform/exclusions.js +5 -5
  101. package/dist/platform/ops/admin.ops.js +1 -1
  102. package/dist/platform/ops/conversations.ops.js +5 -2
  103. package/dist/platform/ops/devices.ops.js +11 -24
  104. package/dist/platform/ops/inbox.ops.js +1 -1
  105. package/dist/roles/gateway-role.d.ts +3 -3
  106. package/dist/roles/gateway-role.js +4 -4
  107. package/dist/roles/gateway.module.d.ts +1 -1
  108. package/dist/roles/gateway.module.js +5 -5
  109. package/dist/runtime/context/device-paths.d.ts +4 -1
  110. package/dist/runtime/context/permission-profile.js +5 -5
  111. package/dist/runtime/maintenance.d.ts +2 -5
  112. package/dist/runtime/maintenance.js +9 -19
  113. package/dist/runtime/project/knowledge.js +4 -5
  114. package/dist/runtime/project/knowledge.service.js +2 -1
  115. package/dist/sandbox/cloud-permission-snapshot.d.ts +1 -1
  116. package/dist/sandbox/cloud-permission-snapshot.js +1 -3
  117. package/dist/sandbox/device-reports.d.ts +74 -14
  118. package/dist/sandbox/device-reports.js +190 -33
  119. package/dist/sandbox/device-reports.module.d.ts +7 -0
  120. package/dist/sandbox/device-reports.module.js +25 -0
  121. package/dist/sandbox/device-sandbox.d.ts +39 -41
  122. package/dist/sandbox/device-sandbox.js +44 -83
  123. package/dist/sandbox/kernel-read.d.ts +2 -2
  124. package/dist/sandbox/legacy-retirement.d.ts +11 -59
  125. package/dist/sandbox/legacy-retirement.js +34 -186
  126. package/dist/sandbox/legacy-retirement.module.d.ts +2 -2
  127. package/dist/sandbox/legacy-retirement.module.js +2 -2
  128. package/dist/sandbox/managed-device-context.d.ts +16 -4
  129. package/dist/sandbox/managed-device-context.js +25 -8
  130. package/dist/sandbox/managed-device-context.module.js +4 -0
  131. package/dist/sandbox/modes.d.ts +3 -12
  132. package/dist/sandbox/modes.js +2 -14
  133. package/dist/{local-devices → sandbox}/network-grants.d.ts +2 -21
  134. package/dist/{local-devices → sandbox}/network-grants.js +4 -49
  135. package/dist/sandbox/operation-authority-types.d.ts +2 -1
  136. package/dist/sandbox/operation-authority.d.ts +6 -20
  137. package/dist/sandbox/operation-authority.js +43 -104
  138. package/dist/sandbox/operation-authority.module.js +1 -1
  139. package/dist/sandbox/operation-intents.d.ts +4 -1
  140. package/dist/sandbox/operation-intents.js +11 -2
  141. package/dist/sandbox/operation-reconcile.job.js +2 -4
  142. package/dist/sandbox/permission-availability.d.ts +6 -7
  143. package/dist/sandbox/permission-availability.js +7 -10
  144. package/dist/sandbox/permission-call-grants.d.ts +2 -1
  145. package/dist/sandbox/permission-call-grants.js +1 -7
  146. package/dist/sandbox/permission-call-types.d.ts +4 -4
  147. package/dist/sandbox/permission-ceiling-writes.d.ts +7 -23
  148. package/dist/sandbox/permission-ceiling-writes.js +8 -35
  149. package/dist/sandbox/permission-config-publication.d.ts +9 -1
  150. package/dist/sandbox/permission-config-publication.js +29 -21
  151. package/dist/sandbox/permission-context-types.d.ts +17 -10
  152. package/dist/sandbox/permission-facts.d.ts +98 -95
  153. package/dist/sandbox/permission-facts.js +160 -314
  154. package/dist/sandbox/permission-instance-writes.d.ts +23 -37
  155. package/dist/sandbox/permission-instance-writes.js +44 -121
  156. package/dist/sandbox/permission-runtime-reports.d.ts +38 -30
  157. package/dist/sandbox/permission-runtime-reports.js +105 -122
  158. package/dist/sandbox/providers.d.ts +26 -38
  159. package/dist/sandbox/providers.js +36 -18
  160. package/dist/sandbox/request-not-sent.d.ts +2 -13
  161. package/dist/sandbox/request-not-sent.js +2 -13
  162. package/dist/sandbox/review/permission-candidate.d.ts +13 -8
  163. package/dist/sandbox/review/permission-candidate.js +38 -48
  164. package/dist/sandbox/sandbox.module.js +7 -3
  165. package/dist/sandbox/sandbox.service.d.ts +49 -59
  166. package/dist/sandbox/sandbox.service.js +139 -259
  167. package/dist/schedules/fire.d.ts +15 -6
  168. package/dist/schedules/fire.js +27 -13
  169. package/dist/schedules/grant-rules.js +1 -1
  170. package/dist/schedules/scheduled-tasks.service.d.ts +0 -7
  171. package/dist/schedules/scheduled-tasks.service.js +1 -4
  172. package/dist/schedules/schedules.module.js +5 -3
  173. package/dist/skills/invoke.d.ts +1 -1
  174. package/dist/skills/invoke.js +2 -3
  175. package/dist/tools/approvals.service.d.ts +8 -5
  176. package/dist/tools/approvals.service.js +5 -5
  177. package/dist/tools/builtins/sandbox/bash.js +1 -2
  178. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  179. package/dist/tools/builtins/sandbox/common.js +37 -38
  180. package/dist/tools/network-asks.d.ts +19 -22
  181. package/dist/tools/network-asks.js +15 -21
  182. package/dist/tools/pipeline.d.ts +6 -7
  183. package/dist/tools/pipeline.js +17 -21
  184. package/dist/tools/tools.module.js +3 -7
  185. package/package.json +3 -4
  186. package/src/migrations/0177_dial_in_contract.sql +32 -0
  187. package/dist/local-devices/device-auth.module.d.ts +0 -7
  188. package/dist/local-devices/device-auth.module.js +0 -25
  189. package/dist/local-devices/device-policy.service.d.ts +0 -213
  190. package/dist/local-devices/device-policy.service.js +0 -605
  191. package/dist/local-devices/instance-bindings.d.ts +0 -82
  192. package/dist/local-devices/instance-bindings.js +0 -307
  193. package/dist/local-devices/local-device-gateway.d.ts +0 -153
  194. package/dist/local-devices/local-device-provider.d.ts +0 -122
  195. package/dist/local-devices/local-device-provider.js +0 -326
  196. package/dist/local-devices/local-devices.module.d.ts +0 -31
  197. package/dist/local-devices/local-devices.module.js +0 -100
  198. package/dist/local-devices/machines.d.ts +0 -211
  199. package/dist/local-devices/machines.js +0 -766
  200. package/dist/local-devices/owner-report.d.ts +0 -81
  201. package/dist/local-devices/owner-report.js +0 -150
  202. package/dist/local-devices/owner-reports.d.ts +0 -48
  203. package/dist/local-devices/owner-reports.js +0 -208
  204. package/dist/local-devices/policy-op-jobs.d.ts +0 -15
  205. package/dist/local-devices/policy-op-jobs.js +0 -12
  206. package/dist/local-devices/policy-summary.d.ts +0 -102
  207. package/dist/local-devices/policy-summary.js +0 -155
  208. package/dist/local-devices/relay.d.ts +0 -166
  209. package/dist/local-devices/relay.js +0 -559
  210. package/dist/tools/device-op-resolver.d.ts +0 -34
  211. package/dist/tools/device-op-resolver.js +0 -120
  212. /package/dist/{local-devices → dial-in}/keys.d.ts +0 -0
  213. /package/dist/{local-devices → dial-in}/keys.js +0 -0
  214. /package/dist/{local-devices → sandbox}/network-grants.module.d.ts +0 -0
  215. /package/dist/{local-devices → sandbox}/network-grants.module.js +0 -0
@@ -1,605 +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 { randomUUID } from "node:crypto";
11
- import { ToolError, validateAllowHost, } from "@capybara-hq/plugin-sdk";
12
- import { Inject, Injectable, Optional } from "@nestjs/common";
13
- import { sql } from "kysely";
14
- import { ApiError } from "../errors.js";
15
- import { audit } from "../identity/audit.js";
16
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
- import { KernelDb } from "../infra/database/kernel-db.js";
18
- import { currentStore, TransactionHost } from "../infra/database/transaction-host.js";
19
- import { Transactional } from "../infra/database/transactional.decorator.js";
20
- import { OutboxService } from "../infra/outbox/outbox.service.js";
21
- import { KERNEL_LOGGER } from "../infra/tokens.js";
22
- import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
- import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
24
- import { deviceNotFound } from "../sandbox/sandbox.service.js";
25
- import { MachinesService } from "./machines.js";
26
- import { ownerFactsOf } from "./owner-report.js";
27
- import { OwnerReports } from "./owner-reports.js";
28
- import { DEVICE_OP_RESOLVE_JOB, deviceOpResolveJobId } from "./policy-op-jobs.js";
29
- import { localPolicyOf, ownerPolicyRevokes, pendingPolicyOpsOf, } from "./policy-summary.js";
30
- import { LIST_TTL_MARGIN_MS, LocalDeviceRelay, ON_MACHINE_PREFIX, wasDeviceRequestNotSent, } from "./relay.js";
31
- /** How long the machine may take to apply a policy change. */
32
- export const POLICY_DEADLINE_MS = 30_000;
33
- /** How long the machine may take to answer a `policyStatus` (it only reads its op log). */
34
- const STATUS_DEADLINE_MS = 10_000;
35
- /** How long an op left `unknown` waits for the machine's hello to report it (from its intent). */
36
- export const UNKNOWN_OP_MS = 24 * 3_600_000;
37
- /** The prefix the relay puts before a machine's `policy`-kind refusal. */
38
- const REFUSED_PREFIX = "Refused by the machine's local policy: ";
39
- /**
40
- * Test seam (`KernelOverride`): called by {@link DevicePolicyService.send} right after the `policy`
41
- * op's call returned, before its outcome is recorded (by `apply` or a network ask's decision);
42
- * throwing stands for a crash between the call and the resolve transaction.
43
- * The kernel never provides it.
44
- */
45
- export const DEVICE_POLICY_AFTER_CALL = Symbol("DEVICE_POLICY_AFTER_CALL");
46
- const OFFLINE_MESSAGE = "The device's machine is offline, so its policy was not changed. Start capybara-device on it.";
47
- const UNSUPPORTED_MESSAGE = "The device's capybara-device program cannot change its policy from the platform. Update capybara-device on the machine.";
48
- const UNCONFIRMED_MESSAGE = "The device's machine did not confirm the policy change; the platform checks it again shortly.";
49
- const INTERRUPTED_MESSAGE = "capybara-device stopped while applying the policy change, and the change is not in the device's policy now.";
50
- /** The longest text of the machine's own error the caller is told (as its op log keeps it). */
51
- const MAX_MACHINE_MESSAGE = 500;
52
- const NOT_RECEIVED_MESSAGE = "The device's machine never received the policy change.";
53
- const OWNER_CEILING_UNSUPPORTED_MESSAGE = "The device's capybara-device program cannot narrow its owner ceiling from the platform. Update capybara-device on the machine, or run capybara-device ceiling set there.";
54
- const errMsg = (e) => (e instanceof Error ? e.message : String(e));
55
- /**
56
- * Narrows a local device's policy on its machine (approval-only profiles design, "Settings model":
57
- * hosts removed, the network to the allowlist, no running outside the sandbox, the workspace
58
- * reach): the kernel→device `policy`
59
- * op over the {@link LocalDeviceRelay}. The machine is the authority: it refuses what its owner
60
- * forbids, validates every host and answers with the policy as written, which the kernel then
61
- * keeps on the active machine's row (§5.4).
62
- *
63
- * Intent first (transactional outbox spec §7): {@link begin} writes the intent in a transaction
64
- * before anything is sent (the entry on the machine row's `pending_policy_ops`, the audit
65
- * `device.policy_requested` and the `device-op-resolve` job owed for when the op can no longer
66
- * reach the machine); the call sends the op with its id (no transaction open); {@link settleIn}
67
- * records the outcome: `device.policy_changed` (applied), `device.policy_failed` (refused, never
68
- * received) or `device.policy_unknown` (no answer: the entry stays, `unknown`, for the machine's
69
- * next hello or the resolver). A crash between the call and the resolve transaction leaves the
70
- * intent and its owed job, whose resolver asks the machine what became of the op (never sends it
71
- * again). Callers decide who may change a device's policy (the device owner, in a signed-in
72
- * session); this service checks only that the device is a live device of the org.
73
- */
74
- let DevicePolicyService = class DevicePolicyService {
75
- db;
76
- txHost;
77
- relay;
78
- machines;
79
- outbox;
80
- config;
81
- log;
82
- ceilings;
83
- owners;
84
- afterCall;
85
- constructor(db, txHost, relay, machines, outbox, config, log, ceilings, owners, afterCall = () => { }) {
86
- this.db = db;
87
- this.txHost = txHost;
88
- this.relay = relay;
89
- this.machines = machines;
90
- this.outbox = outbox;
91
- this.config = config;
92
- this.log = log;
93
- this.ceilings = ceilings;
94
- this.owners = owners;
95
- this.afterCall = afterCall;
96
- }
97
- /**
98
- * Changes the policy: {@link begin}, the call, then the outcome recorded in its own transaction
99
- * (no transaction may be open). Never throws for an offline machine, a refusal or a program
100
- * without the `policyOpId` feature (nothing is sent to it); a device that is not a live device
101
- * of `orgId` is `device.not_found`.
102
- */
103
- async apply(input) {
104
- const begun = await this.begin(input);
105
- if ("outcome" in begun)
106
- return begun.outcome;
107
- const { intent } = begun;
108
- const sent = await this.send(intent);
109
- const out = await this.settle(intent, sent.result);
110
- if (sent.notFound)
111
- throw deviceNotFound();
112
- // unknown: the caller is told what the call saw (offline, or an answer the machine did not
113
- // confirm), not the recorded state's generic text
114
- return sent.result.outcome === "unknown" ? sent.outcome : (out ?? sent.outcome);
115
- }
116
- /**
117
- * Checks the device and its machine, then records the intent in its own transaction: the entry
118
- * (`sent`) on the machine's row, the audit `device.policy_requested` and the `device-op-resolve`
119
- * job owed for when the op can no longer reach the machine. No transaction may be open (the
120
- * call follows). Returns the intent, or why nothing will be sent (offline, unsupported).
121
- */
122
- async begin(input) {
123
- if (currentStore()) {
124
- throw new Error("DevicePolicyService.begin() must not run inside a transaction: the intent is recorded " +
125
- "first, the policy op sent, then the outcome recorded in a transaction.");
126
- }
127
- assertHosts(input.change);
128
- const device = await this.db
129
- .selectFrom("devices as e")
130
- .innerJoin("orgs as o", "o.id", "e.org_id")
131
- .select("e.source")
132
- .where("e.id", "=", input.deviceId)
133
- .where("e.org_id", "=", input.orgId)
134
- .where("e.deleted_at", "is", null)
135
- .where("o.deleted_at", "is", null)
136
- .executeTakeFirst();
137
- if (!device)
138
- throw deviceNotFound();
139
- if (device.source !== "local")
140
- return { outcome: unsupported() };
141
- const machine = await this.machines.activeFor(input.deviceId);
142
- if (machine === null)
143
- return { outcome: offline() };
144
- // only a program that logs op outcomes under their ids can tell what became of a lost answer
145
- if (!machine.features.includes("policyOpId"))
146
- return { outcome: unsupported() };
147
- // not connected: nothing is sent (a queued op would wait for a reconnect nobody watches)
148
- if (!(await this.relay.holderLive(input.deviceId)))
149
- return { outcome: offline() };
150
- // the codec follows the connection the protocol gate accepted: a staged one takes v3 ops
151
- let connection;
152
- try {
153
- connection = (await this.relay.stagedTransport(input.deviceId)) ?? undefined;
154
- }
155
- catch (e) {
156
- // the gate is open and the connection went away or is not ready: nothing is sent
157
- if (e instanceof ApiError && e.code === "device.not_found")
158
- throw e;
159
- return { outcome: offline() };
160
- }
161
- const change = wireChange(input.change);
162
- // B2: an owner-ceiling narrowing needs a program that reports authenticated owner facts over
163
- // a staged connection
164
- if (change.ownerCeiling !== undefined) {
165
- const row = connection
166
- ? await this.db
167
- .selectFrom("device_machines")
168
- .select(["owner_report"])
169
- .where("id", "=", machine.id)
170
- .executeTakeFirst()
171
- : undefined;
172
- if (!row || ownerFactsOf(row).state !== "report")
173
- return {
174
- outcome: {
175
- applied: false,
176
- reason: "unsupported",
177
- message: OWNER_CEILING_UNSUPPORTED_MESSAGE,
178
- },
179
- };
180
- }
181
- const opId = randomUUID();
182
- const args = { ...change, opId, source: input.source };
183
- const recorded = await this.recordIntent({ ...input, change, machineId: machine.id, opId });
184
- if (!recorded)
185
- return { outcome: offline() };
186
- return {
187
- intent: {
188
- orgId: input.orgId,
189
- deviceId: input.deviceId,
190
- machineId: machine.id,
191
- opId,
192
- args,
193
- ...(connection && { connection }),
194
- },
195
- };
196
- }
197
- /**
198
- * Sends the intent's `policy` op (no transaction may be open) and classifies the answer:
199
- * applied; refused (the machine's local policy refused it: its message); anything else is
200
- * `unknown`, left to the resolver's `policyStatus`: no answer, and an answer the kernel cannot
201
- * trust to mean "not applied" (a result it cannot read, the machine's own error). `notFound`:
202
- * the device was deleted meanwhile (recorded as unknown; the caller throws `device.not_found`).
203
- */
204
- async send(intent) {
205
- if (currentStore()) {
206
- throw new Error("DevicePolicyService.send() must not run inside a transaction: the outcome is recorded " +
207
- "afterwards, in its own transaction.");
208
- }
209
- const sent = await this.call(intent);
210
- this.afterCall(intent.opId);
211
- return sent;
212
- }
213
- /** The `policy` op's call and its classification ({@link send}). */
214
- async call(intent) {
215
- try {
216
- const { connection } = intent;
217
- const connectionId = connection
218
- ? connection.connectionId
219
- : await this.connectionIdOf(intent.deviceId);
220
- const opts = {
221
- deadlineMs: POLICY_DEADLINE_MS,
222
- // the relay gives up by itself (deadline plus the reconnect grace)
223
- signal: new AbortController().signal,
224
- };
225
- // a staged connection takes a v3 `policy` request fenced to it; its answer carries the
226
- // owner report issued for the change
227
- const answer = (connection
228
- ? await this.relay.callV3(intent.deviceId, "policy", intent.args, { ...opts, connection })
229
- : await this.relay.call(intent.deviceId, "policy", intent.args, opts));
230
- const { policy } = answer;
231
- return {
232
- result: {
233
- outcome: "applied",
234
- policy,
235
- // a staged (v3) answer's owner report, recorded with the connection it came on
236
- ...(answer.ownerCeiling !== undefined && { ownerCeiling: answer.ownerCeiling }),
237
- connectionId,
238
- },
239
- outcome: { applied: true, policy },
240
- };
241
- }
242
- catch (e) {
243
- // the gateway (or the relay before queuing) says it never reached the machine: definite
244
- if (wasDeviceRequestNotSent(e))
245
- return {
246
- result: { outcome: "not_received" },
247
- outcome: { applied: false, reason: "offline", message: NOT_RECEIVED_MESSAGE },
248
- };
249
- if (e instanceof ApiError) {
250
- // device.offline (the wait ran out: the machine may still apply it), device.forbidden
251
- // (the machine was disconnected meanwhile), device.not_found (the device was deleted)
252
- return {
253
- result: { outcome: "unknown" },
254
- outcome: offline(),
255
- ...(e.code === "device.not_found" && { notFound: true }),
256
- };
257
- }
258
- if (e instanceof ToolError && e.message.startsWith(REFUSED_PREFIX)) {
259
- const message = e.message.slice(REFUSED_PREFIX.length);
260
- return {
261
- result: { outcome: "refused", message },
262
- outcome: { applied: false, reason: "refused", message },
263
- };
264
- }
265
- // an unreadable result (the machine may have applied it) or the machine's own error (it may
266
- // have failed after the write): what the machine logged under the op id tells
267
- this.log.warn("a device policy change was not confirmed by the machine", {
268
- deviceId: intent.deviceId,
269
- opId: intent.opId,
270
- error: errMsg(e),
271
- });
272
- const raw = errMsg(e);
273
- const message = (raw.startsWith(ON_MACHINE_PREFIX) ? raw.slice(ON_MACHINE_PREFIX.length) : raw).slice(0, MAX_MACHINE_MESSAGE);
274
- return {
275
- result: { outcome: "unknown" },
276
- outcome: {
277
- applied: false,
278
- reason: "offline",
279
- message: `${UNCONFIRMED_MESSAGE} ${message}`,
280
- },
281
- };
282
- }
283
- }
284
- /** The authenticated connection a call goes to now, or null when unknown (M4). */
285
- async connectionIdOf(deviceId) {
286
- try {
287
- return (await this.relay.connection(deviceId)).connectionId;
288
- }
289
- catch {
290
- return null;
291
- }
292
- }
293
- /**
294
- * What the machine says became of the op `opId` (a read-only `policyStatus`), or `offline` when
295
- * no replica holds its connection or it does not answer. Never sends the change.
296
- */
297
- async outcomeOf(deviceId, opId) {
298
- if (!(await this.relay.holderLive(deviceId)))
299
- return { outcome: "offline" };
300
- try {
301
- const opts = { deadlineMs: STATUS_DEADLINE_MS, signal: new AbortController().signal };
302
- const connection = await this.relay.stagedTransport(deviceId);
303
- if (connection) {
304
- // a staged connection answers in v3: an applied outcome carries the owner report
305
- const status = (await this.relay.callV3(deviceId, "policyStatus", { opId }, { ...opts, connection }));
306
- return { ...status, connectionId: connection.connectionId };
307
- }
308
- const connectionId = await this.connectionIdOf(deviceId);
309
- const status = await this.relay.call(deviceId, "policyStatus", { opId }, opts);
310
- return { ...status, connectionId };
311
- }
312
- catch (e) {
313
- this.log.warn("could not ask a machine what became of a policy op", {
314
- deviceId,
315
- opId,
316
- error: errMsg(e),
317
- });
318
- return { outcome: "offline" };
319
- }
320
- }
321
- /**
322
- * Records what became of the op `opId` of machine `machineId`, in the caller's transaction (the
323
- * machine's row locked): `applied` → the policy the machine wrote (when given) kept on the row,
324
- * the entry removed, `device.policy_changed` (`late` when the op was left `unknown`); `refused`,
325
- * `not_received` or `interrupted` → the entry removed, `device.policy_failed` (`reason` the
326
- * outcome); `unknown` → the entry kept, `unknown` until a day after its intent,
327
- * `device.policy_unknown` (once; ignored once a hello reported the op). Returns the outcome for
328
- * the caller, or null when the op has no live entry (resolved already, or expired: a no-op).
329
- */
330
- async settleIn(ref, result) {
331
- const subject = await this.db
332
- .selectFrom("device_machines")
333
- .select(["org_id", "device_id"])
334
- .where("id", "=", ref.machineId)
335
- .executeTakeFirst();
336
- if (!subject)
337
- return null;
338
- // a caller that locked the machine's device first ({@link lockMachineDevice}, before the rows
339
- // its transaction locks later) must have locked this one: a machine that moved since is retried
340
- const held = currentStore()?.permissionLocks;
341
- if (held?.size && !held.has(`permission-authority-device-${subject.device_id}`))
342
- throw new ApiError("conflict", "The machine's device changed; retry");
343
- await this.ceilings.lock({ orgId: subject.org_id, deviceId: subject.device_id }, "device");
344
- const row = await this.db
345
- .selectFrom("device_machines")
346
- .select(["org_id", "device_id", "local_policy", "pending_policy_ops", "revoked_at"])
347
- .where("id", "=", ref.machineId)
348
- .where("org_id", "=", subject.org_id)
349
- .where("device_id", "=", subject.device_id)
350
- .forUpdate()
351
- .executeTakeFirst();
352
- const op = pendingPolicyOpsOf(row?.pending_policy_ops).find((o) => o.id === ref.opId);
353
- // an expired entry no longer explains the machine's own reports (they are audited as the
354
- // owner's): recording the op too would list the change twice
355
- if (row === undefined || op === undefined || op.until <= Date.now())
356
- return null;
357
- const auditOp = (action, extra) => audit(this.db.db, {
358
- actorAccountId: op.source.accountId,
359
- ...(op.actorTokenId !== undefined && { actorTokenId: op.actorTokenId }),
360
- orgId: row.org_id,
361
- action,
362
- target: row.device_id,
363
- detail: { ...changeDetail(op), ...extra },
364
- });
365
- // B2: an applied answer carrying an owner report is accepted only once that report is
366
- // committed by the common owner writer; an out-of-order report leaves the op unknown
367
- let v3Report = false;
368
- if (result.outcome === "applied" && result.ownerCeiling !== undefined) {
369
- const recorded = await this.owners.recordLocked(ref.machineId, result.ownerCeiling, {
370
- connectionId: result.connectionId ?? null,
371
- via: "policy-result",
372
- // the op explains the owner change: audited once, as the op's source made it
373
- explainedBy: {
374
- accountId: op.source.accountId,
375
- via: op.source.via,
376
- opId: op.id,
377
- ...(op.actorTokenId !== undefined && { actorTokenId: op.actorTokenId }),
378
- },
379
- });
380
- // a lower sequence is a late delivery (ignored by the writer), the op still applied; only
381
- // a conflicting report or a revoked machine leaves it unknown
382
- if (recorded === "conflict" || recorded === "revoked")
383
- result = { outcome: "unknown" };
384
- else
385
- v3Report = true;
386
- }
387
- if (result.outcome === "unknown") {
388
- // a hello reported the op meanwhile (its job records it), or it is unknown already
389
- if (op.reported !== undefined || op.status === "unknown")
390
- return { applied: false, reason: "offline", message: OFFLINE_MESSAGE };
391
- await this.db
392
- .updateTable("device_machines")
393
- .set({
394
- pending_policy_ops: withOp(op.id, {
395
- status: "unknown",
396
- until: op.sentAt + UNKNOWN_OP_MS,
397
- }),
398
- })
399
- .where("id", "=", ref.machineId)
400
- .execute();
401
- await auditOp("device.policy_unknown", {});
402
- return offline();
403
- }
404
- const live = row.revoked_at === null;
405
- const policy = result.outcome === "applied" ? result.policy : undefined;
406
- await this.db
407
- .updateTable("device_machines")
408
- .set({
409
- // resolved: the op no longer explains a summary the machine reports
410
- pending_policy_ops: withoutOp(op.id),
411
- ...(policy !== undefined && live && { local_policy: JSON.stringify(policy) }),
412
- })
413
- .where("id", "=", ref.machineId)
414
- .execute();
415
- if (!v3Report &&
416
- policy !== undefined &&
417
- live &&
418
- JSON.stringify(policy) !== JSON.stringify(localPolicyOf(row.local_policy)))
419
- await this.ceilings.publishLocked({ orgId: row.org_id, deviceId: row.device_id }, "device", (scope, intent) => ownerPolicyRevokes(policy, scope, intent.method, intent.granted_hosts), false);
420
- if (result.outcome === "applied") {
421
- if (op.remove.length > 0) {
422
- await auditOp("device.policy_changed", {
423
- ...(op.status === "unknown" && { late: true }),
424
- });
425
- }
426
- // the owner ceiling's change is the owner report's, audited once by its writer
427
- // (`device.owner_ceiling_changed`)
428
- const stored = policy ?? (await this.machines.activeFor(row.device_id))?.localPolicy;
429
- return stored
430
- ? { applied: true, policy: stored }
431
- : { applied: false, reason: "offline", message: OFFLINE_MESSAGE };
432
- }
433
- const message = result.outcome === "refused"
434
- ? result.message
435
- : result.outcome === "interrupted"
436
- ? INTERRUPTED_MESSAGE
437
- : NOT_RECEIVED_MESSAGE;
438
- await auditOp("device.policy_failed", { reason: result.outcome, message });
439
- return result.outcome === "refused"
440
- ? { applied: false, reason: "refused", message }
441
- : offline();
442
- }
443
- /** The active machine's features and policy summary (null when no machine is connected). */
444
- async summary(deviceId) {
445
- const m = await this.machines.activeFor(deviceId);
446
- return m === null ? null : { features: m.features, policy: m.localPolicy };
447
- }
448
- /**
449
- * How long after its intent an op can no longer reach the machine: the call's deadline, the
450
- * reconnect grace and the request list's margin (the relay's list TTL), plus 5 s. A machine
451
- * that does not know the op id by then never will.
452
- */
453
- resolveDelayMs() {
454
- const graceMs = this.config.get().devices.local.reconnectGraceSeconds * 1000;
455
- return POLICY_DEADLINE_MS + graceMs + LIST_TTL_MARGIN_MS + 5_000;
456
- }
457
- /**
458
- * The ordered prelude of a transaction that records an op's outcome ({@link settleIn}) after it
459
- * locked other rows (a network ask's conversation, its approval, its run): the permission
460
- * authority lock of the machine's device, read without a lock first. The global order puts it
461
- * before every conversation row (`withOrderedLocks`); {@link settleIn} re-reads the machine
462
- * under it. A machine that is gone locks nothing (its settle is a no-op).
463
- */
464
- async lockMachineDevice(machineId) {
465
- const subject = await this.db
466
- .selectFrom("device_machines")
467
- .select(["org_id", "device_id"])
468
- .where("id", "=", machineId)
469
- .executeTakeFirst();
470
- if (!subject)
471
- return;
472
- await this.ceilings.lock({ orgId: subject.org_id, deviceId: subject.device_id }, "device");
473
- }
474
- /** {@link settleIn} in its own transaction (the {@link apply} path). */
475
- settle(intent, result) {
476
- return this.settleIn(intent, result);
477
- }
478
- /**
479
- * The intent transaction: locks the machine's row (still the device's active machine), appends
480
- * the entry (dropping the expired ones), audits `device.policy_requested` and owes the
481
- * `device-op-resolve` job. False when the machine was revoked meanwhile (nothing written).
482
- */
483
- async recordIntent(input) {
484
- const locked = await this.db
485
- .selectFrom("device_machines")
486
- .select("id")
487
- .where("id", "=", input.machineId)
488
- .where("revoked_at", "is", null)
489
- .forUpdate()
490
- .executeTakeFirst();
491
- if (locked === undefined)
492
- return false;
493
- const now = Date.now();
494
- const resolveAt = now + this.resolveDelayMs();
495
- const { change, source } = input;
496
- const op = {
497
- id: input.opId,
498
- remove: change.remove ?? [],
499
- ...(change.ownerCeiling !== undefined && { ownerCeiling: change.ownerCeiling }),
500
- source: { accountId: source.accountId, via: source.via },
501
- ...(input.actorTokenId !== undefined && { actorTokenId: input.actorTokenId }),
502
- status: "sent",
503
- sentAt: now,
504
- resolveAt,
505
- // a summary the machine reports by itself may be this op's until it is resolved
506
- until: now + UNKNOWN_OP_MS,
507
- };
508
- await this.db
509
- .updateTable("device_machines")
510
- .set({
511
- pending_policy_ops: sql `(
512
- SELECT coalesce(jsonb_agg(e), '[]'::jsonb) FROM jsonb_array_elements(pending_policy_ops) e
513
- WHERE (e->>'until')::bigint > ${now}
514
- ) || jsonb_build_array(${JSON.stringify(op)}::jsonb)`,
515
- })
516
- .where("id", "=", input.machineId)
517
- .execute();
518
- await audit(this.db.db, {
519
- actorAccountId: source.accountId,
520
- ...(input.actorTokenId !== undefined && { actorTokenId: input.actorTokenId }),
521
- orgId: input.orgId,
522
- action: "device.policy_requested",
523
- target: input.deviceId,
524
- detail: changeDetail(op),
525
- });
526
- await this.outbox.add({
527
- queue: MAINTENANCE_QUEUE_NAME,
528
- name: DEVICE_OP_RESOLVE_JOB,
529
- jobId: deviceOpResolveJobId(input.opId),
530
- data: { machineId: input.machineId, opId: input.opId },
531
- runAt: new Date(resolveAt),
532
- orgId: input.orgId,
533
- });
534
- return true;
535
- }
536
- };
537
- __decorate([
538
- Transactional({ propagation: "mandatory" })
539
- ], DevicePolicyService.prototype, "settleIn", null);
540
- __decorate([
541
- Transactional({ propagation: "mandatory" })
542
- ], DevicePolicyService.prototype, "lockMachineDevice", null);
543
- __decorate([
544
- Transactional()
545
- ], DevicePolicyService.prototype, "settle", null);
546
- __decorate([
547
- Transactional()
548
- ], DevicePolicyService.prototype, "recordIntent", null);
549
- DevicePolicyService = __decorate([
550
- Injectable(),
551
- __param(0, Inject(KernelDb)),
552
- __param(1, Inject(TransactionHost)),
553
- __param(2, Inject(LocalDeviceRelay)),
554
- __param(3, Inject(MachinesService)),
555
- __param(4, Inject(OutboxService)),
556
- __param(5, Inject(KernelConfigService)),
557
- __param(6, Inject(KERNEL_LOGGER)),
558
- __param(7, Inject(PermissionCeilingWrites)),
559
- __param(8, Inject(OwnerReports)),
560
- __param(9, Optional()),
561
- __param(9, Inject(DEVICE_POLICY_AFTER_CALL))
562
- ], DevicePolicyService);
563
- export { DevicePolicyService };
564
- /**
565
- * A change as the machine takes it (protocol 4): the hosts to remove and the owner-ceiling
566
- * narrowing. Never wider: only narrowings come out of it (the frame parser refuses anything else).
567
- */
568
- function wireChange(change) {
569
- return {
570
- ...(change.remove !== undefined && { remove: change.remove }),
571
- ...(change.ownerCeiling !== undefined && { ownerCeiling: change.ownerCeiling }),
572
- };
573
- }
574
- const offline = () => ({
575
- applied: false,
576
- reason: "offline",
577
- message: OFFLINE_MESSAGE,
578
- });
579
- const unsupported = () => ({
580
- applied: false,
581
- reason: "unsupported",
582
- message: UNSUPPORTED_MESSAGE,
583
- });
584
- /** The audit detail of an op's change and source (every `device.policy_*` row). */
585
- function changeDetail(op) {
586
- return { opId: op.id, remove: op.remove, by: op.source.accountId, via: op.source.via };
587
- }
588
- /** The machine's pending ops with the fields `patch` merged into the op `opId`. */
589
- const withOp = (opId, patch) => sql `(
590
- SELECT coalesce(jsonb_agg(CASE WHEN e->>'id' = ${opId} THEN e || ${JSON.stringify(patch)}::jsonb ELSE e END), '[]'::jsonb)
591
- FROM jsonb_array_elements(pending_policy_ops) e
592
- )`;
593
- /** The machine's pending ops without `opId` (an expired one left for the next intent to drop). */
594
- const withoutOp = (opId) => sql `(
595
- SELECT coalesce(jsonb_agg(e), '[]'::jsonb) FROM jsonb_array_elements(pending_policy_ops) e
596
- WHERE e->>'id' <> ${opId}
597
- )`;
598
- /** Hosts the platform may send: `remove` takes any valid entry (narrowing, a wildcard too). */
599
- function assertHosts(change) {
600
- const bad = (h) => typeof h !== "string" || validateAllowHost(h).length > 0;
601
- for (const h of change.remove ?? []) {
602
- if (bad(h))
603
- throw new Error(`not a host to remove from a device policy: ${JSON.stringify(h)}`);
604
- }
605
- }