@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
@@ -0,0 +1,47 @@
1
+ import type { DialInHandler } from "@capybara-hq/plugin-sdk";
2
+ import { DeviceProviderSelection } from "../devices/device-provider-selection.js";
3
+ import { ExtensionRegistry } from "../extensions/registry.js";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import { DeviceProviders } from "../sandbox/providers.js";
6
+ /** The provider serving a device over the dial-in channel, and the protocol its machines speak. */
7
+ export interface DialInServing {
8
+ plugin: string;
9
+ protocol: string;
10
+ handler: DialInHandler;
11
+ }
12
+ /**
13
+ * Why a device has no dial-in handler: its provider declares no `permissions.dialIn` (or the
14
+ * device has none), is off in the device's org, or is not loaded in this process.
15
+ */
16
+ export interface DialInUnavailable {
17
+ unavailable: "not-dial-in" | "off" | "unloaded";
18
+ }
19
+ /**
20
+ * The dial-in handlers of devices: the device's provider (`devices.provider`), the protocol its
21
+ * manifest declares (`permissions.dialIn.protocol`) and its `DeviceProvider.dialIn`, served only
22
+ * while the provider is on in the device's org ({@link DeviceProviderSelection.isOnInOrg}). Read
23
+ * at every call (PG and the process's extension registry; nothing cached).
24
+ */
25
+ export declare class DialInHandlers {
26
+ private readonly kdb;
27
+ private readonly providers;
28
+ private readonly selection;
29
+ private readonly registry;
30
+ constructor(kdb: KernelDb, providers: Pick<DeviceProviders, "forDevice">, selection: Pick<DeviceProviderSelection, "isOnInOrg" | "onInOrg">, registry: Pick<ExtensionRegistry, "current">);
31
+ forDevice(deviceId: string): Promise<DialInServing | DialInUnavailable>;
32
+ /**
33
+ * The dial-in providers that serve `orgId` now, each with the protocol its machines speak: the
34
+ * extensions {@link DeviceProviderSelection.onInOrg} lists that declare `permissions.dialIn` and
35
+ * implement `DeviceProvider.dialIn`, in extension-name order. Read at every call.
36
+ */
37
+ onInOrg(orgId: string): Promise<{
38
+ plugin: string;
39
+ protocol: string;
40
+ }[]>;
41
+ /**
42
+ * The protocol a provider's machines speak, when it serves devices over the dial-in channel:
43
+ * its manifest's `permissions.dialIn.protocol` and a `DeviceProvider.dialIn` handler (an
44
+ * in-process provider has no manifest, so none). Undefined otherwise.
45
+ */
46
+ private protocolOf;
47
+ }
@@ -0,0 +1,84 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { DeviceProviderSelection } from "../devices/device-provider-selection.js";
12
+ import { ExtensionRegistry } from "../extensions/registry.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { DeviceProviders } from "../sandbox/providers.js";
15
+ /**
16
+ * The dial-in handlers of devices: the device's provider (`devices.provider`), the protocol its
17
+ * manifest declares (`permissions.dialIn.protocol`) and its `DeviceProvider.dialIn`, served only
18
+ * while the provider is on in the device's org ({@link DeviceProviderSelection.isOnInOrg}). Read
19
+ * at every call (PG and the process's extension registry; nothing cached).
20
+ */
21
+ let DialInHandlers = class DialInHandlers {
22
+ kdb;
23
+ providers;
24
+ selection;
25
+ registry;
26
+ constructor(kdb, providers, selection, registry) {
27
+ this.kdb = kdb;
28
+ this.providers = providers;
29
+ this.selection = selection;
30
+ this.registry = registry;
31
+ }
32
+ async forDevice(deviceId) {
33
+ const row = await this.kdb.db
34
+ .selectFrom("devices")
35
+ .select(["org_id", "provider"])
36
+ .where("id", "=", deviceId)
37
+ .where("deleted_at", "is", null)
38
+ .executeTakeFirst();
39
+ if (!row || row.provider === null)
40
+ return { unavailable: "not-dial-in" };
41
+ const plugin = row.provider;
42
+ const entry = this.providers.forDevice(plugin);
43
+ if (!entry)
44
+ return { unavailable: "unloaded" };
45
+ const protocol = this.protocolOf(entry);
46
+ if (protocol === undefined)
47
+ return { unavailable: "not-dial-in" };
48
+ if (!(await this.selection.isOnInOrg(row.org_id, plugin)))
49
+ return { unavailable: "off" };
50
+ return { plugin, protocol, handler: entry.impl.dialIn };
51
+ }
52
+ /**
53
+ * The dial-in providers that serve `orgId` now, each with the protocol its machines speak: the
54
+ * extensions {@link DeviceProviderSelection.onInOrg} lists that declare `permissions.dialIn` and
55
+ * implement `DeviceProvider.dialIn`, in extension-name order. Read at every call.
56
+ */
57
+ async onInOrg(orgId) {
58
+ const out = [];
59
+ for (const e of await this.selection.onInOrg(orgId)) {
60
+ const protocol = this.protocolOf(e);
61
+ if (protocol !== undefined)
62
+ out.push({ plugin: e.plugin, protocol });
63
+ }
64
+ return out;
65
+ }
66
+ /**
67
+ * The protocol a provider's machines speak, when it serves devices over the dial-in channel:
68
+ * its manifest's `permissions.dialIn.protocol` and a `DeviceProvider.dialIn` handler (an
69
+ * in-process provider has no manifest, so none). Undefined otherwise.
70
+ */
71
+ protocolOf(entry) {
72
+ if (entry.impl.dialIn === undefined)
73
+ return undefined;
74
+ return this.registry.current(entry.plugin)?.manifest.permissions?.dialIn?.protocol;
75
+ }
76
+ };
77
+ DialInHandlers = __decorate([
78
+ Injectable(),
79
+ __param(0, Inject(KernelDb)),
80
+ __param(1, Inject(DeviceProviders)),
81
+ __param(2, Inject(DeviceProviderSelection)),
82
+ __param(3, Inject(ExtensionRegistry))
83
+ ], DialInHandlers);
84
+ export { DialInHandlers };
@@ -0,0 +1,155 @@
1
+ import type { ExtensionContext } 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 type { KernelLogger } from "../log.js";
5
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
6
+ import { DeviceProviders } from "../sandbox/providers.js";
7
+ import { DialInRelay } from "./relay.js";
8
+ /** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
9
+ export declare const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
10
+ /**
11
+ * Why a machine was revoked, for the machine and for the provider (`onClose`): `revoked`
12
+ * (disconnected, signed out, or a sign-in whose credential never reached its program) or `deleted`
13
+ * (its device was deleted), both told to stop first; `replaced` (the device signed in from
14
+ * another machine): no stop, which could reach the replacement instead, and its connection
15
+ * closes as replaced (4002).
16
+ */
17
+ export type MachineRevocationReason = "revoked" | "deleted" | "replaced";
18
+ /** The payload of `device.revoked.<deviceId>`. */
19
+ export interface MachineRevokedMessage {
20
+ machineId: string;
21
+ reason: MachineRevocationReason;
22
+ }
23
+ /** What a machine credential stands for. */
24
+ export interface MachineIdentity {
25
+ machineId: string;
26
+ orgId: string;
27
+ deviceId: string;
28
+ accountId: string;
29
+ }
30
+ /** The machine connected to a device (its unrevoked row). */
31
+ export interface ActiveMachine {
32
+ id: string;
33
+ orgId: string;
34
+ accountId: string;
35
+ name: string;
36
+ os: string;
37
+ arch: string;
38
+ programVersion: string | null;
39
+ lastSeenAt: Date | null;
40
+ createdAt: Date;
41
+ }
42
+ /**
43
+ * Connected machines and their credentials (environments spec §13.2). One active machine per
44
+ * dial-in device: issuing a credential revokes the device's previous machine. A
45
+ * credential is `cap_dev_` plus 32 random bytes; only its sha256 is stored. It is accepted only
46
+ * by the device connection route ({@link authenticate}), never by `/api`: it is no `Principal`.
47
+ *
48
+ * A revoked machine is told so after the commit: a `stop` relayed while a replica holds its
49
+ * connection (fire-and-forget, ruling R14) and `device.revoked.<deviceId>` published with
50
+ * {@link MachineRevokedMessage}, so the holder closes that machine's connection (and tells the
51
+ * provider why).
52
+ */
53
+ export declare class DialInMachines {
54
+ private readonly db;
55
+ readonly txHost: TransactionHost;
56
+ private readonly relay;
57
+ private readonly bus;
58
+ private readonly log;
59
+ private readonly ceilings;
60
+ private readonly providers;
61
+ constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites, providers: Pick<DeviceProviders, "forDevice">);
62
+ /**
63
+ * A new machine for the device and its credential (returned once). Revokes the
64
+ * device's active machine first. Joins the caller's transaction (the device confirmation),
65
+ * which has already checked the device is the person's own live dial-in device.
66
+ */
67
+ issue(input: {
68
+ orgId: string;
69
+ deviceId: string;
70
+ accountId: string;
71
+ name: string;
72
+ os: string;
73
+ arch: string;
74
+ programVersion: string;
75
+ }): Promise<{
76
+ machineId: string;
77
+ credential: string;
78
+ }>;
79
+ /**
80
+ * Ruling R23: the new machine may serve the device from another directory or mode (other
81
+ * roots), and a login recreates a directory that was lost (ruling R24). So the instance row
82
+ * forgets its instance (status `none`, no handle) and its files count as there again; the next
83
+ * use creates a fresh instance on the machine (with its roots: a new `device_paths` event
84
+ * follows). The fence moves on, so a lifecycle holder of the old instance fails its next write.
85
+ * The reset count (`fs_resets`) moves on when the files the next instance sees are not the old
86
+ * ones, so conversations that used the old files are told their files were reset, not that they
87
+ * were kept: lost files come back as an empty directory, and another machine (`moved`: name, OS
88
+ * or arch differ from the device's previous machine) has other files. Another directory on
89
+ * the same machine is known only to the provider (from the new machine's first hello).
90
+ */
91
+ private resetInstance;
92
+ /**
93
+ * Who a machine credential stands for, or null: the machine is not revoked, its device is
94
+ * live, the org is not deleted (ruling R12), and the person is an active account still a member
95
+ * of the org. Read live on every call (a connection re-checks it as it sees fit). Whether the
96
+ * device's provider takes its machines now (it declares the dial-in channel and is on in the
97
+ * org) is the connection's next check (`DialInHandlers.forDevice`).
98
+ */
99
+ authenticate(credential: string): Promise<MachineIdentity | null>;
100
+ /** Whether the device is deleted (soft-deleted, or gone): why its credential stopped working. */
101
+ isDeviceDeleted(deviceId: string): Promise<boolean>;
102
+ /**
103
+ * What a machine's hello envelope says about its program, recorded once the connection holds the
104
+ * device's lease (before the provider's `onHello`): its version, OS and architecture, and the
105
+ * host's boot identity (none clears the stored one). Marks the machine seen. A revoked machine
106
+ * is left alone.
107
+ */
108
+ recordConnect(machineId: string, program: {
109
+ version: string;
110
+ os: string;
111
+ arch: string;
112
+ bootId?: string;
113
+ }): Promise<void>;
114
+ /** Marks the machine seen (a ping); writes at most once every 60 seconds. */
115
+ touch(machineId: string): Promise<void>;
116
+ /**
117
+ * Disconnects the machine of one of the person's own live dial-in devices, whatever its
118
+ * provider (`DELETE /orgs/:orgId/devices/:id/machine`): revokes it and audits
119
+ * `device.machine_revoked`. Anyone else's device, a cloud one or a missing one →
120
+ * `device.not_found`; no machine connected is a no-op.
121
+ */
122
+ revoke(orgId: string, accountId: string, deviceId: string, actorTokenId?: string): Promise<void>;
123
+ /**
124
+ * Revokes the device's active machine, if any, in the caller's transaction, and after the
125
+ * commit tells it to stop (not when `replaced`) and closes its connection for `reason`. Returns
126
+ * the revoked machine's id. Used by {@link issue} (`replaced`), {@link revoke} (`revoked`) and
127
+ * the device's deletion (`deleted`).
128
+ */
129
+ revokeActive(deviceId: string, reason: MachineRevocationReason): Promise<string | null>;
130
+ /**
131
+ * Revokes one machine by id (a sign-in whose credential never reached the program), with the
132
+ * same post-commit disconnect as a replacement (no stop frame). True when it was active.
133
+ */
134
+ revokeMachine(machineId: string): Promise<boolean>;
135
+ /** Whether a machine ever signed in to the device (revoked or not). */
136
+ private everSignedIn;
137
+ /** The device's active machine, or null. */
138
+ activeFor(deviceId: string): Promise<ActiveMachine | null>;
139
+ /**
140
+ * After a revocation commits: `stop` is queued only while a replica holds the connection (an
141
+ * offline machine must not find it on the list later), then the revocation is published.
142
+ * Failures are logged; the revocation itself stands.
143
+ */
144
+ private disconnect;
145
+ }
146
+ /** Two machine rows (or a login) name the same machine: same name, OS and arch. */
147
+ export declare function sameMachine(a: {
148
+ name: string;
149
+ os: string;
150
+ arch: string;
151
+ }, b: {
152
+ name: string;
153
+ os: string;
154
+ arch: string;
155
+ }): boolean;
@@ -0,0 +1,383 @@
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 { randomBytes } from "node:crypto";
11
+ import { isDeviceBootId } from "@capybara-hq/plugin-sdk/device-protocol";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
14
+ import { audit } from "../identity/audit.js";
15
+ import { sha256Hex } from "../identity/hash.js";
16
+ import { afterCommit } from "../infra/database/after-commit.js";
17
+ import { KernelDb } from "../infra/database/kernel-db.js";
18
+ import { TransactionHost } from "../infra/database/transaction-host.js";
19
+ import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
21
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
22
+ import { DeviceProviders, servesDialIn } from "../sandbox/providers.js";
23
+ import { deviceNotFound } from "../sandbox/sandbox.service.js";
24
+ import { deviceRevokedTopic } from "./keys.js";
25
+ import { DialInRelay } from "./relay.js";
26
+ /** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
27
+ export const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
28
+ const CREDENTIAL_RE = /^cap_dev_[A-Za-z0-9_-]{43}$/;
29
+ /**
30
+ * Connected machines and their credentials (environments spec §13.2). One active machine per
31
+ * dial-in device: issuing a credential revokes the device's previous machine. A
32
+ * credential is `cap_dev_` plus 32 random bytes; only its sha256 is stored. It is accepted only
33
+ * by the device connection route ({@link authenticate}), never by `/api`: it is no `Principal`.
34
+ *
35
+ * A revoked machine is told so after the commit: a `stop` relayed while a replica holds its
36
+ * connection (fire-and-forget, ruling R14) and `device.revoked.<deviceId>` published with
37
+ * {@link MachineRevokedMessage}, so the holder closes that machine's connection (and tells the
38
+ * provider why).
39
+ */
40
+ let DialInMachines = class DialInMachines {
41
+ db;
42
+ txHost;
43
+ relay;
44
+ bus;
45
+ log;
46
+ ceilings;
47
+ providers;
48
+ constructor(db, txHost, relay, bus, log, ceilings, providers) {
49
+ this.db = db;
50
+ this.txHost = txHost;
51
+ this.relay = relay;
52
+ this.bus = bus;
53
+ this.log = log;
54
+ this.ceilings = ceilings;
55
+ this.providers = providers;
56
+ }
57
+ /**
58
+ * A new machine for the device and its credential (returned once). Revokes the
59
+ * device's active machine first. Joins the caller's transaction (the device confirmation),
60
+ * which has already checked the device is the person's own live dial-in device.
61
+ */
62
+ async issue(input) {
63
+ // the machine the device was last served from (revoked or not)
64
+ const prev = await this.db
65
+ .selectFrom("device_machines")
66
+ .select(["name", "os", "arch"])
67
+ .where("device_id", "=", input.deviceId)
68
+ .orderBy("created_at", "desc")
69
+ .orderBy("id", "desc")
70
+ .limit(1)
71
+ .executeTakeFirst();
72
+ // another machine has other files (maintainer decision 2026-11-08)
73
+ const moved = prev !== undefined && !sameMachine(prev, input);
74
+ // no stop frame: it would wait on the list and could reach the replacement machine instead
75
+ await this.revokeActive(input.deviceId, "replaced");
76
+ await this.resetInstance(input.deviceId, moved);
77
+ const credential = MACHINE_CREDENTIAL_PREFIX + randomBytes(32).toString("base64url");
78
+ const row = await this.db
79
+ .insertInto("device_machines")
80
+ .values({
81
+ org_id: input.orgId,
82
+ device_id: input.deviceId,
83
+ account_id: input.accountId,
84
+ credential_hash: sha256Hex(credential),
85
+ name: input.name,
86
+ os: input.os,
87
+ arch: input.arch,
88
+ program_version: input.programVersion,
89
+ })
90
+ .returning("id")
91
+ .executeTakeFirstOrThrow();
92
+ return { machineId: row.id, credential };
93
+ }
94
+ /**
95
+ * Ruling R23: the new machine may serve the device from another directory or mode (other
96
+ * roots), and a login recreates a directory that was lost (ruling R24). So the instance row
97
+ * forgets its instance (status `none`, no handle) and its files count as there again; the next
98
+ * use creates a fresh instance on the machine (with its roots: a new `device_paths` event
99
+ * follows). The fence moves on, so a lifecycle holder of the old instance fails its next write.
100
+ * The reset count (`fs_resets`) moves on when the files the next instance sees are not the old
101
+ * ones, so conversations that used the old files are told their files were reset, not that they
102
+ * were kept: lost files come back as an empty directory, and another machine (`moved`: name, OS
103
+ * or arch differ from the device's previous machine) has other files. Another directory on
104
+ * the same machine is known only to the provider (from the new machine's first hello).
105
+ */
106
+ async resetInstance(deviceId, moved) {
107
+ await this.db
108
+ .updateTable("device_instances")
109
+ .set((eb) => ({
110
+ status: "none",
111
+ handle: null,
112
+ fs_status: sql `CASE WHEN fs_handle IS NULL THEN 'none' ELSE 'ready' END`,
113
+ running_since: null,
114
+ suspended_at: null,
115
+ destroyed_at: sql `now()`,
116
+ generation: eb("generation", "+", 1),
117
+ fs_resets: moved
118
+ ? sql `fs_resets + 1`
119
+ : sql `CASE WHEN fs_status = 'lost' THEN fs_resets + 1 ELSE fs_resets END`,
120
+ }))
121
+ .where("device_id", "=", deviceId)
122
+ .execute();
123
+ }
124
+ /**
125
+ * Who a machine credential stands for, or null: the machine is not revoked, its device is
126
+ * live, the org is not deleted (ruling R12), and the person is an active account still a member
127
+ * of the org. Read live on every call (a connection re-checks it as it sees fit). Whether the
128
+ * device's provider takes its machines now (it declares the dial-in channel and is on in the
129
+ * org) is the connection's next check (`DialInHandlers.forDevice`).
130
+ */
131
+ async authenticate(credential) {
132
+ if (!CREDENTIAL_RE.test(credential))
133
+ return null;
134
+ const row = await this.db
135
+ .selectFrom("device_machines as m")
136
+ .innerJoin("devices as e", "e.id", "m.device_id")
137
+ .innerJoin("orgs as o", "o.id", "m.org_id")
138
+ .innerJoin("memberships as ms", (j) => j.onRef("ms.org_id", "=", "m.org_id").onRef("ms.account_id", "=", "m.account_id"))
139
+ .innerJoin("accounts as a", "a.id", "m.account_id")
140
+ .select(["m.id", "m.org_id", "m.device_id", "m.account_id"])
141
+ .where("m.credential_hash", "=", sha256Hex(credential))
142
+ .where("m.revoked_at", "is", null)
143
+ .whereRef("e.org_id", "=", "m.org_id")
144
+ .where("e.deleted_at", "is", null)
145
+ .where("o.deleted_at", "is", null)
146
+ .where("a.status", "=", "active")
147
+ .executeTakeFirst();
148
+ return row
149
+ ? {
150
+ machineId: row.id,
151
+ orgId: row.org_id,
152
+ deviceId: row.device_id,
153
+ accountId: row.account_id,
154
+ }
155
+ : null;
156
+ }
157
+ /** Whether the device is deleted (soft-deleted, or gone): why its credential stopped working. */
158
+ async isDeviceDeleted(deviceId) {
159
+ const row = await this.db
160
+ .selectFrom("devices")
161
+ .select("deleted_at")
162
+ .where("id", "=", deviceId)
163
+ .executeTakeFirst();
164
+ return row === undefined || row.deleted_at !== null;
165
+ }
166
+ /**
167
+ * What a machine's hello envelope says about its program, recorded once the connection holds the
168
+ * device's lease (before the provider's `onHello`): its version, OS and architecture, and the
169
+ * host's boot identity (none clears the stored one). Marks the machine seen. A revoked machine
170
+ * is left alone.
171
+ */
172
+ async recordConnect(machineId, program) {
173
+ await this.db
174
+ .updateTable("device_machines")
175
+ .set({
176
+ program_version: program.version,
177
+ os: program.os,
178
+ arch: program.arch,
179
+ boot_id: program.bootId !== undefined && isDeviceBootId(program.bootId) ? program.bootId : null,
180
+ last_seen_at: sql `now()`,
181
+ })
182
+ .where("id", "=", machineId)
183
+ .where("revoked_at", "is", null)
184
+ .execute();
185
+ }
186
+ /** Marks the machine seen (a ping); writes at most once every 60 seconds. */
187
+ async touch(machineId) {
188
+ await this.db
189
+ .updateTable("device_machines")
190
+ .set({ last_seen_at: sql `now()` })
191
+ .where("id", "=", machineId)
192
+ .where("revoked_at", "is", null)
193
+ .where((eb) => eb.or([
194
+ eb("last_seen_at", "is", null),
195
+ eb("last_seen_at", "<", sql `now() - interval '60 seconds'`),
196
+ ]))
197
+ .execute();
198
+ }
199
+ /**
200
+ * Disconnects the machine of one of the person's own live dial-in devices, whatever its
201
+ * provider (`DELETE /orgs/:orgId/devices/:id/machine`): revokes it and audits
202
+ * `device.machine_revoked`. Anyone else's device, a cloud one or a missing one →
203
+ * `device.not_found`; no machine connected is a no-op.
204
+ */
205
+ async revoke(orgId, accountId, deviceId, actorTokenId) {
206
+ const env = await this.db
207
+ .selectFrom("devices")
208
+ .select(["id", "provider"])
209
+ .where("id", "=", deviceId)
210
+ .where("org_id", "=", orgId)
211
+ .where("owner_kind", "=", "personal")
212
+ .where("owner_account_id", "=", accountId)
213
+ .where("deleted_at", "is", null)
214
+ .forNoKeyUpdate()
215
+ .executeTakeFirst();
216
+ if (!env)
217
+ throw deviceNotFound();
218
+ // a dial-in device: its provider serves the dial-in channel, or a machine signed in to it
219
+ // (its provider may be unloaded here, and the person disconnects anyway)
220
+ const p = this.providers.forDevice(env.provider);
221
+ if (!(p !== undefined && servesDialIn(p)) && !(await this.everSignedIn(deviceId)))
222
+ throw deviceNotFound();
223
+ const machineId = await this.revokeActive(deviceId, "revoked");
224
+ if (machineId === null)
225
+ return;
226
+ await audit(this.db.db, {
227
+ actorAccountId: accountId,
228
+ ...(actorTokenId !== undefined && { actorTokenId }),
229
+ orgId,
230
+ action: "device.machine_revoked",
231
+ target: deviceId,
232
+ detail: { machineId },
233
+ });
234
+ }
235
+ /**
236
+ * Revokes the device's active machine, if any, in the caller's transaction, and after the
237
+ * commit tells it to stop (not when `replaced`) and closes its connection for `reason`. Returns
238
+ * the revoked machine's id. Used by {@link issue} (`replaced`), {@link revoke} (`revoked`) and
239
+ * the device's deletion (`deleted`).
240
+ */
241
+ async revokeActive(deviceId, reason) {
242
+ const device = await this.db
243
+ .selectFrom("devices")
244
+ .select("org_id")
245
+ .where("id", "=", deviceId)
246
+ .executeTakeFirstOrThrow();
247
+ await this.ceilings.lock({ orgId: device.org_id, deviceId }, "device");
248
+ await this.ceilings.publishLocked({ orgId: device.org_id, deviceId }, "device", true, true);
249
+ const row = await this.db
250
+ .updateTable("device_machines")
251
+ .set({ revoked_at: sql `now()` })
252
+ .where("device_id", "=", deviceId)
253
+ .where("revoked_at", "is", null)
254
+ .returning("id")
255
+ .executeTakeFirst();
256
+ if (!row)
257
+ return null;
258
+ const machineId = row.id;
259
+ afterCommit(() => this.disconnect(deviceId, machineId, reason));
260
+ return machineId;
261
+ }
262
+ /**
263
+ * Revokes one machine by id (a sign-in whose credential never reached the program), with the
264
+ * same post-commit disconnect as a replacement (no stop frame). True when it was active.
265
+ */
266
+ async revokeMachine(machineId) {
267
+ const machine = await this.db
268
+ .selectFrom("device_machines")
269
+ .select(["org_id", "device_id"])
270
+ .where("id", "=", machineId)
271
+ .executeTakeFirst();
272
+ if (!machine)
273
+ return false;
274
+ await this.ceilings.lock({ orgId: machine.org_id, deviceId: machine.device_id }, "device");
275
+ await this.ceilings.publishLocked({ orgId: machine.org_id, deviceId: machine.device_id }, "device", true, true);
276
+ const row = await this.db
277
+ .updateTable("device_machines")
278
+ .set({ revoked_at: sql `now()` })
279
+ .where("id", "=", machineId)
280
+ .where("revoked_at", "is", null)
281
+ .returning("device_id")
282
+ .executeTakeFirst();
283
+ if (!row)
284
+ return false;
285
+ const deviceId = row.device_id;
286
+ afterCommit(() => this.disconnect(deviceId, machineId, "revoked", { stop: false }));
287
+ return true;
288
+ }
289
+ /** Whether a machine ever signed in to the device (revoked or not). */
290
+ async everSignedIn(deviceId) {
291
+ const row = await this.db
292
+ .selectFrom("device_machines")
293
+ .select("id")
294
+ .where("device_id", "=", deviceId)
295
+ .limit(1)
296
+ .executeTakeFirst();
297
+ return row !== undefined;
298
+ }
299
+ /** The device's active machine, or null. */
300
+ async activeFor(deviceId) {
301
+ const r = await this.db
302
+ .selectFrom("device_machines")
303
+ .select([
304
+ "id",
305
+ "org_id",
306
+ "account_id",
307
+ "name",
308
+ "os",
309
+ "arch",
310
+ "program_version",
311
+ "last_seen_at",
312
+ "created_at",
313
+ ])
314
+ .where("device_id", "=", deviceId)
315
+ .where("revoked_at", "is", null)
316
+ .executeTakeFirst();
317
+ return r
318
+ ? {
319
+ id: r.id,
320
+ orgId: r.org_id,
321
+ accountId: r.account_id,
322
+ name: r.name,
323
+ os: r.os,
324
+ arch: r.arch,
325
+ programVersion: r.program_version,
326
+ lastSeenAt: r.last_seen_at,
327
+ createdAt: r.created_at,
328
+ }
329
+ : null;
330
+ }
331
+ /**
332
+ * After a revocation commits: `stop` is queued only while a replica holds the connection (an
333
+ * offline machine must not find it on the list later), then the revocation is published.
334
+ * Failures are logged; the revocation itself stands.
335
+ */
336
+ async disconnect(deviceId, machineId, reason, opts = {}) {
337
+ try {
338
+ // fenced to this machine; queued only while a replica holds its connection
339
+ if (reason !== "replaced" && opts.stop !== false)
340
+ await this.relay.stop(deviceId, "stop", { machineId });
341
+ }
342
+ catch (err) {
343
+ this.log.warn("could not tell a revoked machine to stop", { deviceId, machineId, err });
344
+ }
345
+ try {
346
+ const message = { machineId, reason };
347
+ await this.bus.publish(deviceRevokedTopic(deviceId), message);
348
+ }
349
+ catch (err) {
350
+ this.log.warn("could not publish a machine revocation", { deviceId, machineId, err });
351
+ }
352
+ }
353
+ };
354
+ __decorate([
355
+ Transactional()
356
+ ], DialInMachines.prototype, "issue", null);
357
+ __decorate([
358
+ Transactional()
359
+ ], DialInMachines.prototype, "recordConnect", null);
360
+ __decorate([
361
+ Transactional()
362
+ ], DialInMachines.prototype, "revoke", null);
363
+ __decorate([
364
+ Transactional()
365
+ ], DialInMachines.prototype, "revokeActive", null);
366
+ __decorate([
367
+ Transactional()
368
+ ], DialInMachines.prototype, "revokeMachine", null);
369
+ DialInMachines = __decorate([
370
+ Injectable(),
371
+ __param(0, Inject(KernelDb)),
372
+ __param(1, Inject(TransactionHost)),
373
+ __param(2, Inject(DialInRelay)),
374
+ __param(3, Inject(KERNEL_BUS)),
375
+ __param(4, Inject(KERNEL_LOGGER)),
376
+ __param(5, Inject(PermissionCeilingWrites)),
377
+ __param(6, Inject(DeviceProviders))
378
+ ], DialInMachines);
379
+ export { DialInMachines };
380
+ /** Two machine rows (or a login) name the same machine: same name, OS and arch. */
381
+ export function sameMachine(a, b) {
382
+ return a.name === b.name && a.os === b.os && a.arch === b.arch;
383
+ }