@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.133

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 (155) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +6 -5
  20. package/dist/catalog/plugin-import.js +69 -16
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.d.ts +1 -0
  28. package/dist/config/schema.js +9 -1
  29. package/dist/conversations/conversations.controller.js +4 -14
  30. package/dist/conversations/conversations.service.d.ts +14 -0
  31. package/dist/conversations/conversations.service.js +20 -2
  32. package/dist/ctx/create-ctx.d.ts +14 -4
  33. package/dist/ctx/create-ctx.js +131 -59
  34. package/dist/ctx/queue.js +7 -4
  35. package/dist/db/extension-db.d.ts +30 -0
  36. package/dist/db/extension-db.js +91 -0
  37. package/dist/db/extension-rls-predicate.d.ts +1 -0
  38. package/dist/db/extension-rls-predicate.js +8 -0
  39. package/dist/db/extension-schema-transfer.d.ts +6 -0
  40. package/dist/db/extension-schema-transfer.js +141 -0
  41. package/dist/db/kernel-schema.d.ts +50 -4
  42. package/dist/db/migrator.d.ts +6 -0
  43. package/dist/db/migrator.js +35 -7
  44. package/dist/db/pool.d.ts +6 -2
  45. package/dist/db/pool.js +37 -2
  46. package/dist/db/sql-statements.d.ts +3 -0
  47. package/dist/db/sql-statements.js +15 -5
  48. package/dist/device-access/device-access.module.js +12 -2
  49. package/dist/device-access/device-access.service.d.ts +30 -2
  50. package/dist/device-access/device-access.service.js +38 -4
  51. package/dist/device-access/host-gate.d.ts +45 -0
  52. package/dist/device-access/host-gate.js +92 -0
  53. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  54. package/dist/device-access/host-service-stop-sweep.js +112 -0
  55. package/dist/device-access/host-service-stop.d.ts +78 -0
  56. package/dist/device-access/host-service-stop.js +144 -0
  57. package/dist/device-access/host-services.d.ts +211 -0
  58. package/dist/device-access/host-services.js +803 -0
  59. package/dist/device-access/person-handles.d.ts +10 -0
  60. package/dist/device-access/person-handles.js +25 -0
  61. package/dist/device-access/service-events.d.ts +199 -0
  62. package/dist/device-access/service-events.js +704 -0
  63. package/dist/device-access/token.d.ts +5 -0
  64. package/dist/device-access/token.js +5 -0
  65. package/dist/devices/devices.service.js +3 -0
  66. package/dist/dial-in/access.d.ts +5 -5
  67. package/dist/dial-in/access.js +19 -12
  68. package/dist/dial-in/gateway.js +6 -2
  69. package/dist/dial-in/machines.d.ts +9 -2
  70. package/dist/dial-in/machines.js +27 -4
  71. package/dist/erasure/device-cleanup.js +12 -0
  72. package/dist/erasure/org-catalog.js +2 -2
  73. package/dist/erasure/org-rules.js +9 -0
  74. package/dist/errors.d.ts +2 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/extensions/admin-ops.d.ts +3 -1
  77. package/dist/extensions/admin-ops.js +19 -9
  78. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  79. package/dist/extensions/deployed-snapshots.js +7 -2
  80. package/dist/extensions/extensions.module.js +3 -0
  81. package/dist/extensions/host.d.ts +11 -3
  82. package/dist/extensions/host.js +40 -8
  83. package/dist/extensions/instance.d.ts +6 -0
  84. package/dist/extensions/instance.js +7 -1
  85. package/dist/extensions/ledger.d.ts +1 -1
  86. package/dist/extensions/lifecycle-hooks.js +3 -3
  87. package/dist/extensions/migrate-lock.d.ts +4 -1
  88. package/dist/extensions/migrate-lock.js +19 -2
  89. package/dist/extensions/org-config.js +6 -1
  90. package/dist/extensions/permission-set.d.ts +7 -0
  91. package/dist/extensions/permission-set.js +10 -0
  92. package/dist/extensions/permission-view.d.ts +1 -1
  93. package/dist/extensions/permission-view.js +10 -1
  94. package/dist/git/tickets.js +32 -27
  95. package/dist/http/app.js +5 -3
  96. package/dist/identity/accounts.d.ts +6 -1
  97. package/dist/identity/accounts.js +11 -2
  98. package/dist/identity/api-tokens.js +7 -6
  99. package/dist/identity/settings.d.ts +9 -1
  100. package/dist/identity/settings.js +16 -1
  101. package/dist/inbox/org-notices.js +3 -2
  102. package/dist/index.d.ts +1 -0
  103. package/dist/index.js +1 -0
  104. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  105. package/dist/infra/database/scoped-dialect.js +260 -72
  106. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  107. package/dist/infra/database/startup-activation-transaction.js +3 -2
  108. package/dist/infra/outbox/registry.d.ts +28 -14
  109. package/dist/infra/outbox/registry.js +30 -15
  110. package/dist/infra/queue/queue-names.d.ts +1 -1
  111. package/dist/infra/queue/queue-names.js +1 -0
  112. package/dist/infra/queue/run-job.d.ts +4 -1
  113. package/dist/infra/queue/run-job.js +10 -2
  114. package/dist/kernel.js +4 -0
  115. package/dist/kernel.module.js +3 -0
  116. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  117. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  118. package/dist/orgs/offboarding.js +18 -9
  119. package/dist/orgs/settings.service.js +3 -0
  120. package/dist/packages/npm-publish-keys.json +27 -0
  121. package/dist/packages/official-publisher.d.ts +19 -0
  122. package/dist/packages/official-publisher.js +152 -0
  123. package/dist/packages/provenance.d.ts +7 -0
  124. package/dist/packages/provenance.js +22 -19
  125. package/dist/packages/sigstore-trusted-root.json +126 -0
  126. package/dist/platform/ops/admin.ops.js +2 -1
  127. package/dist/platform/ops/orgs.ops.js +1 -0
  128. package/dist/roles/worker-role.d.ts +6 -3
  129. package/dist/roles/worker-role.js +12 -4
  130. package/dist/roles/worker.module.js +7 -6
  131. package/dist/runtime/maintenance.d.ts +5 -4
  132. package/dist/runtime/maintenance.js +16 -13
  133. package/dist/sandbox/device-reports.d.ts +4 -4
  134. package/dist/sandbox/device-reports.js +40 -30
  135. package/dist/sandbox/device-services.d.ts +2 -1
  136. package/dist/sandbox/device-services.js +5 -1
  137. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  138. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  139. package/dist/sandbox/permission-config-publication.js +5 -1
  140. package/dist/themes/theme-state.js +24 -13
  141. package/dist/tools/call-scope.d.ts +6 -0
  142. package/dist/tools/call-scope.js +22 -0
  143. package/dist/tools/registry.js +20 -2
  144. package/dist/ui/views.js +36 -8
  145. package/package.json +9 -4
  146. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  147. package/src/migrations/0220_require_event_org.sql +18 -0
  148. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  149. package/src/migrations/0222_device_host_services.sql +27 -0
  150. package/src/migrations/0223_device_service_events.sql +54 -0
  151. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  152. package/dist/conversations/event-org-backfill.d.ts +0 -111
  153. package/dist/conversations/event-org-backfill.js +0 -264
  154. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  155. package/dist/conversations/event-org-backfill.module.js +0 -18
@@ -1,4 +1,4 @@
1
- import { type DeviceAccessScope, type DeviceProjectReach, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, type ServiceBlockedHost, type SiteAccessAction, type SiteAccessAsk, type SiteGrantView, type ToolCallContext } from "@capybara-hq/plugin-sdk";
1
+ import { DeviceAccessError, type DeviceAccessScope, type DevicePersonScope, type DeviceProjectReach, type DeviceServiceSpec, type DeviceServiceStatus, type DeviceToolScope, type Logger, type LoopbackGrantView, type PersonalDeviceView, type ServiceBlockedHost, type SiteAccessAction, type SiteAccessAsk, type SiteGrantView, type ToolCallContext } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { DeviceAccess } from "../devices/access.js";
4
4
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -13,6 +13,7 @@ import { DeviceProviders } from "../sandbox/providers.js";
13
13
  import { CommandReviewService } from "../sandbox/review/review.service.js";
14
14
  import { ApprovalsService } from "../tools/approvals.service.js";
15
15
  import { QuestionsService } from "../tools/questions.service.js";
16
+ import { HostServiceAccess } from "./host-services.js";
16
17
  import { DeviceSiteGrants } from "./site-grants.js";
17
18
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
18
19
  export declare const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
@@ -51,6 +52,11 @@ export interface DeviceAccessCaller {
51
52
  */
52
53
  loopbackPorts: boolean;
53
54
  siteAccess?: boolean;
55
+ /**
56
+ * The approved manifest's `permissions.deviceAccess.hostServices`: the services that may run on
57
+ * the owner's machine outside the device sandbox ({@link HostServiceAccess}).
58
+ */
59
+ hostServices?: readonly string[];
54
60
  }
55
61
  /**
56
62
  * `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
@@ -81,9 +87,29 @@ export declare class DeviceAccessService {
81
87
  /** A panel grant settles the agent's pending ask for the same port. */
82
88
  private readonly approvals;
83
89
  private readonly site;
90
+ /** Host services (`ensureHostService` and the rest): their own admission. */
91
+ private readonly host;
84
92
  constructor(kdb: KernelDb, redis: Redis, config: Pick<KernelConfigService, "get">, services: DeviceServices, review: Pick<CommandReviewService, "review">, devices: Pick<ConversationDevices, "forTool" | "reviewFacts">, access: Pick<DeviceAccess, "usable">, deviceWrites: Pick<DevicesService, "addNetworkHostsIn">, questions: Pick<QuestionsService, "answer">, providers: Pick<DeviceProviders, "forDevice">, log: Logger, registry: Pick<ExtensionRegistry, "current">, txHost: TransactionHost, loopback: Pick<LoopbackGrants, "grantIn" | "revoke" | "liveForRoot" | "refusalNow">,
85
93
  /** A panel grant settles the agent's pending ask for the same port. */
86
- approvals: Pick<ApprovalsService, "settleLoopbackAsks">, site: DeviceSiteGrants);
94
+ approvals: Pick<ApprovalsService, "settleLoopbackAsks">, site: DeviceSiteGrants,
95
+ /** Host services (`ensureHostService` and the rest): their own admission. */
96
+ host: HostServiceAccess);
97
+ /** `ctx.deviceAccess.ensureHostService` ({@link HostServiceAccess.ensure}). */
98
+ ensureHostService(caller: DeviceAccessCaller, at: DeviceToolScope | DevicePersonScope, spec: DeviceServiceSpec): Promise<DeviceServiceStatus>;
99
+ /** `ctx.deviceAccess.hostRequest` ({@link HostServiceAccess.request}). */
100
+ hostRequest(caller: DeviceAccessCaller, at: DeviceToolScope | DevicePersonScope, req: {
101
+ service: string;
102
+ body: Uint8Array;
103
+ timeoutMs: number;
104
+ ifRunning?: boolean;
105
+ }): Promise<Uint8Array>;
106
+ /** `ctx.deviceAccess.stopHostService` ({@link HostServiceAccess.stop}). */
107
+ stopHostService(caller: DeviceAccessCaller, at: DeviceToolScope | DevicePersonScope, service: string): Promise<void>;
108
+ /** `ctx.deviceAccess.personalDevices` ({@link HostServiceAccess.personalDevices}). */
109
+ personalDevices(caller: DeviceAccessCaller, args: {
110
+ orgId: string;
111
+ accountId: string;
112
+ }): Promise<PersonalDeviceView[]>;
87
113
  private get db();
88
114
  private recordAuthorizedServiceLaunch;
89
115
  /**
@@ -274,3 +300,5 @@ export declare class DeviceAccessService {
274
300
  private scopedDevice;
275
301
  private rootOf;
276
302
  }
303
+ /** What the ordinary service path refuses a host spec with. */
304
+ export declare function hostSpecRefused(name: string): DeviceAccessError;
@@ -34,6 +34,7 @@ import { ApprovalsService } from "../tools/approvals.service.js";
34
34
  import { mapSandboxError } from "../tools/builtins/sandbox/common.js";
35
35
  import { attachCallScope, callScopeOf, serviceHostKey, strongerLayer, whileDeviceStarting, } from "../tools/call-scope.js";
36
36
  import { QuestionsService } from "../tools/questions.service.js";
37
+ import { HostServiceAccess } from "./host-services.js";
37
38
  import { assertSiteAccessAction, siteAccessInstallActive } from "./site-access-request.js";
38
39
  import { DeviceSiteGrants } from "./site-grants.js";
39
40
  /** The layers a service may report a refused host with (`ServiceBlockedHost.layer`). */
@@ -116,9 +117,12 @@ let DeviceAccessService = class DeviceAccessService {
116
117
  loopback;
117
118
  approvals;
118
119
  site;
120
+ host;
119
121
  constructor(kdb, redis, config, services, review, devices, access, deviceWrites, questions, providers, log, registry, txHost, loopback,
120
122
  /** A panel grant settles the agent's pending ask for the same port. */
121
- approvals, site) {
123
+ approvals, site,
124
+ /** Host services (`ensureHostService` and the rest): their own admission. */
125
+ host) {
122
126
  this.kdb = kdb;
123
127
  this.redis = redis;
124
128
  this.config = config;
@@ -135,6 +139,23 @@ let DeviceAccessService = class DeviceAccessService {
135
139
  this.loopback = loopback;
136
140
  this.approvals = approvals;
137
141
  this.site = site;
142
+ this.host = host;
143
+ }
144
+ /** `ctx.deviceAccess.ensureHostService` ({@link HostServiceAccess.ensure}). */
145
+ ensureHostService(caller, at, spec) {
146
+ return this.host.ensure(caller, at, spec);
147
+ }
148
+ /** `ctx.deviceAccess.hostRequest` ({@link HostServiceAccess.request}). */
149
+ hostRequest(caller, at, req) {
150
+ return this.host.request(caller, at, req);
151
+ }
152
+ /** `ctx.deviceAccess.stopHostService` ({@link HostServiceAccess.stop}). */
153
+ stopHostService(caller, at, service) {
154
+ return this.host.stop(caller, at, service);
155
+ }
156
+ /** `ctx.deviceAccess.personalDevices` ({@link HostServiceAccess.personalDevices}). */
157
+ personalDevices(caller, args) {
158
+ return this.host.personalDevices(caller, args);
138
159
  }
139
160
  get db() {
140
161
  return this.kdb.db;
@@ -162,6 +183,9 @@ let DeviceAccessService = class DeviceAccessService {
162
183
  }
163
184
  async ensureServiceNow(caller, call, spec) {
164
185
  assertDeclared(caller, spec.name);
186
+ // a host spec goes through ensureHostService's admission, never this path
187
+ if (spec.host !== undefined)
188
+ throw hostSpecRefused(spec.name);
165
189
  assertCallOwner(call);
166
190
  // a watcher only looks: it never starts or resumes anything (browser long waits spec §5.3)
167
191
  if (callScopeOf(call)?.watch === true)
@@ -944,7 +968,8 @@ DeviceAccessService = __decorate([
944
968
  __param(12, Inject(TransactionHost)),
945
969
  __param(13, Inject(LoopbackGrants)),
946
970
  __param(14, Inject(ApprovalsService)),
947
- __param(15, Inject(DeviceSiteGrants))
971
+ __param(15, Inject(DeviceSiteGrants)),
972
+ __param(16, Inject(HostServiceAccess))
948
973
  ], DeviceAccessService);
949
974
  export { DeviceAccessService };
950
975
  /** A grant record as the extension sees it. */
@@ -961,18 +986,27 @@ function viewOf(row) {
961
986
  * service when it names none, else null.
962
987
  */
963
988
  function reportedService(caller, named) {
989
+ // host services have no sandbox network: never a loopback grant's service
990
+ const sandboxed = caller.services.filter((s) => !(caller.hostServices ?? []).includes(s));
964
991
  if (named !== undefined)
965
- return caller.services.includes(named) ? named : null;
966
- return caller.services.length === 1 ? caller.services[0] : null;
992
+ return sandboxed.includes(named) ? named : null;
993
+ return sandboxed.length === 1 ? sandboxed[0] : null;
967
994
  }
968
995
  /** A provider's status under the extension's own service name (the provider names the id). */
969
996
  function asNamed(status, name) {
970
997
  return { ...status, name };
971
998
  }
972
999
  function assertDeclared(caller, service) {
1000
+ // a host service is reached only through the host methods and their admission
1001
+ if ((caller.hostServices ?? []).includes(service))
1002
+ throw new DeviceAccessError("host_not_declared", `The device service ${JSON.stringify(service)} is a host service of ${caller.extension}: use ensureHostService, hostRequest and stopHostService.`);
973
1003
  if (!caller.services.includes(service))
974
1004
  throw new DeviceAccessError("service_not_declared", `The device service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.services of ${caller.extension}.`);
975
1005
  }
1006
+ /** What the ordinary service path refuses a host spec with. */
1007
+ export function hostSpecRefused(name) {
1008
+ return new DeviceAccessError("host_not_declared", `The device service spec ${JSON.stringify(name)} sets host: a host service starts only through ensureHostService.`);
1009
+ }
976
1010
  function assertSiteAccessCaller(caller, service) {
977
1011
  if (caller.siteAccess !== true || caller.superseded?.()) {
978
1012
  throw new DeviceAccessError("site_access_not_declared", "This extension does not have an active site access permission.");
@@ -0,0 +1,45 @@
1
+ import { TransactionHost } from "../infra/database/transaction-host.js";
2
+ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
3
+ import { PermissionConfigPublication } from "../sandbox/permission-config-publication.js";
4
+ import { PermissionFacts } from "../sandbox/permission-facts.js";
5
+ /** Why the host gate is closed for a device ({@link HostServiceGate.refusal}). */
6
+ export type HostGateRefusal = "outside_sandbox_off" | "reach_capped";
7
+ /**
8
+ * The host gate (local agents spec, call 1): a host service runs on the whole machine, outside the
9
+ * device sandbox, so it is admitted only where
10
+ * - the platform's and the org's project reach caps (#1194) are both `machine` (`reach_capped`
11
+ * otherwise; the owner's own sandboxed read reach on the machine is not part of the gate), and
12
+ * - running outside the sandbox is allowed for the device: the platform and org ceilings and the
13
+ * provider's support (the owner's own setting on the machine) all allow it
14
+ * (`box.outsideSandbox` of the effective device sandbox; `outside_sandbox_off` otherwise).
15
+ * Read live on every admission (PG, no cache), under the shared permission authority locks of
16
+ * the device ({@link admit}): a ceiling writer narrowing a cap holds its level's lock exclusively
17
+ * while it marks the running host services owed (`PermissionCeilingWrites.publishLocked`), so an
18
+ * admission either waits that write out and sees the narrowed cap, or is dispatched before the
19
+ * writer marks the placement the admission's start wrote first.
20
+ */
21
+ export declare class HostServiceGate {
22
+ private readonly facts;
23
+ private readonly transactions;
24
+ private readonly authority;
25
+ private readonly publication;
26
+ constructor(facts: Pick<PermissionFacts, "deviceSandboxFacts">, transactions: Pick<TransactionHost, "run">, authority: Pick<PermissionAuthorityLock, "acquire">, publication: Pick<PermissionConfigPublication, "assertCurrent">);
27
+ /** Null when host services may run on the device now; otherwise why not. */
28
+ refusal(orgId: string, deviceId: string): Promise<HostGateRefusal | null>;
29
+ /**
30
+ * Admits one call to the machine's host services: in a short transaction of its own that holds
31
+ * the shared authority locks of the device (platform, org, device) and checks this replica runs
32
+ * the published permission config, reads {@link refusal} and, when the gate is open, dispatches
33
+ * `send` before the locks are released (the PG transaction is never carried into the provider);
34
+ * its outcome is awaited after. A closed gate calls `onClosed` (which throws) instead.
35
+ */
36
+ admit<T>(orgId: string, deviceId: string, onClosed: (why: HostGateRefusal) => never, send: () => Promise<T>): Promise<T>;
37
+ /**
38
+ * Whether the gate is open as far as known now, for display (`personalDevices`): true when
39
+ * open; false when a ceiling of the platform, the org or the device keeps it shut (a project
40
+ * reach cap included: it sets the outside-sandbox layer), or the machine's known setting does;
41
+ * null while the provider's support (the machine owner's setting) is not known yet: it is read
42
+ * once the device has run.
43
+ */
44
+ known(orgId: string, deviceId: string): Promise<boolean | null>;
45
+ }
@@ -0,0 +1,92 @@
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 { runOutsideTransaction, TransactionHost } from "../infra/database/transaction-host.js";
12
+ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
13
+ import { PermissionConfigPublication } from "../sandbox/permission-config-publication.js";
14
+ import { PermissionFacts } from "../sandbox/permission-facts.js";
15
+ /**
16
+ * The host gate (local agents spec, call 1): a host service runs on the whole machine, outside the
17
+ * device sandbox, so it is admitted only where
18
+ * - the platform's and the org's project reach caps (#1194) are both `machine` (`reach_capped`
19
+ * otherwise; the owner's own sandboxed read reach on the machine is not part of the gate), and
20
+ * - running outside the sandbox is allowed for the device: the platform and org ceilings and the
21
+ * provider's support (the owner's own setting on the machine) all allow it
22
+ * (`box.outsideSandbox` of the effective device sandbox; `outside_sandbox_off` otherwise).
23
+ * Read live on every admission (PG, no cache), under the shared permission authority locks of
24
+ * the device ({@link admit}): a ceiling writer narrowing a cap holds its level's lock exclusively
25
+ * while it marks the running host services owed (`PermissionCeilingWrites.publishLocked`), so an
26
+ * admission either waits that write out and sees the narrowed cap, or is dispatched before the
27
+ * writer marks the placement the admission's start wrote first.
28
+ */
29
+ let HostServiceGate = class HostServiceGate {
30
+ facts;
31
+ transactions;
32
+ authority;
33
+ publication;
34
+ constructor(facts, transactions, authority, publication) {
35
+ this.facts = facts;
36
+ this.transactions = transactions;
37
+ this.authority = authority;
38
+ this.publication = publication;
39
+ }
40
+ /** Null when host services may run on the device now; otherwise why not. */
41
+ async refusal(orgId, deviceId) {
42
+ const { box } = await this.facts.deviceSandboxFacts(orgId, deviceId);
43
+ // `box.projectReach` is the narrower of the platform and org caps, absent at `machine`
44
+ if (box.projectReach !== undefined)
45
+ return "reach_capped";
46
+ return box.outsideSandbox ? null : "outside_sandbox_off";
47
+ }
48
+ /**
49
+ * Admits one call to the machine's host services: in a short transaction of its own that holds
50
+ * the shared authority locks of the device (platform, org, device) and checks this replica runs
51
+ * the published permission config, reads {@link refusal} and, when the gate is open, dispatches
52
+ * `send` before the locks are released (the PG transaction is never carried into the provider);
53
+ * its outcome is awaited after. A closed gate calls `onClosed` (which throws) instead.
54
+ */
55
+ async admit(orgId, deviceId, onClosed, send) {
56
+ const { pending } = await runOutsideTransaction(() => this.transactions.run(async () => {
57
+ await this.authority.acquire({ orgId, deviceId }, { kind: "admit" });
58
+ await this.publication.assertCurrent();
59
+ const closed = await this.refusal(orgId, deviceId);
60
+ if (closed !== null)
61
+ onClosed(closed);
62
+ const sent = runOutsideTransaction(send);
63
+ void sent.catch(() => { });
64
+ return { pending: sent };
65
+ }, { propagation: "requires_new" }));
66
+ return pending;
67
+ }
68
+ /**
69
+ * Whether the gate is open as far as known now, for display (`personalDevices`): true when
70
+ * open; false when a ceiling of the platform, the org or the device keeps it shut (a project
71
+ * reach cap included: it sets the outside-sandbox layer), or the machine's known setting does;
72
+ * null while the provider's support (the machine owner's setting) is not known yet: it is read
73
+ * once the device has run.
74
+ */
75
+ async known(orgId, deviceId) {
76
+ const facts = await this.facts.deviceSandboxFacts(orgId, deviceId);
77
+ if (facts.box.outsideSandbox)
78
+ return true;
79
+ const layer = facts.box.layer.outsideSandbox;
80
+ if (layer === "platform" || layer === "org" || layer === "device")
81
+ return false;
82
+ return facts.support === null ? null : false;
83
+ }
84
+ };
85
+ HostServiceGate = __decorate([
86
+ Injectable(),
87
+ __param(0, Inject(PermissionFacts)),
88
+ __param(1, Inject(TransactionHost)),
89
+ __param(2, Inject(PermissionAuthorityLock)),
90
+ __param(3, Inject(PermissionConfigPublication))
91
+ ], HostServiceGate);
92
+ export { HostServiceGate };
@@ -0,0 +1,33 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { LockService } from "../infra/lock/lock.service.js";
4
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
5
+ import type { KernelLogger } from "../log.js";
6
+ /** The name of the owed host service stop sweep (`@LockedCron`). */
7
+ export declare const HOST_SERVICES_STOP_SWEEP_JOB = "device-host-services-stop-sweep";
8
+ /**
9
+ * How old an owed stop is before the sweep owes its delivery again; also the window of the sweep's
10
+ * job ids (one delivery per device and window).
11
+ */
12
+ export declare const HOST_STOP_REOWE_AFTER_MS: number;
13
+ /**
14
+ * The owed host service stop sweep, every 5 minutes (a `@LockedCron`, once per tick across
15
+ * replicas, under `WorkerModule`): owes the delivery again of every device whose stop has been
16
+ * owed longer than {@link HOST_STOP_REOWE_AFTER_MS} while its machine stays connected (a delivery
17
+ * job that ran out of retries, or a reconnect's delivery folded into a job still kept) and of
18
+ * every deleted device that still has an owed stop (its delivery settles it: the device's program
19
+ * stopped its host services when its machine was closed or refused). A machine that is
20
+ * away gets its delivery on its next connect (`DialInMachines.recordConnect`).
21
+ */
22
+ export declare class HostServiceStopSweepJob {
23
+ private readonly kdb;
24
+ private readonly outbox;
25
+ readonly txHost: TransactionHost;
26
+ readonly lockService: LockService;
27
+ readonly log: KernelLogger;
28
+ constructor(kdb: KernelDb, outbox: Pick<OutboxService, "add">, txHost: TransactionHost, lockService: LockService, log: KernelLogger);
29
+ sweep(signal?: AbortSignal): Promise<void>;
30
+ /** One sweep (the test seam): the number of devices whose delivery was owed again. */
31
+ runOnce(signal?: AbortSignal): Promise<number>;
32
+ private oweAgain;
33
+ }
@@ -0,0 +1,112 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
14
+ import { TransactionHost } from "../infra/database/transaction-host.js";
15
+ import { Transactional } from "../infra/database/transactional.decorator.js";
16
+ import { LockService } from "../infra/lock/lock.service.js";
17
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
18
+ import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
19
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
20
+ import { oweHostServicesDelivery } from "./host-service-stop.js";
21
+ /** The name of the owed host service stop sweep (`@LockedCron`). */
22
+ export const HOST_SERVICES_STOP_SWEEP_JOB = "device-host-services-stop-sweep";
23
+ /**
24
+ * How old an owed stop is before the sweep owes its delivery again; also the window of the sweep's
25
+ * job ids (one delivery per device and window).
26
+ */
27
+ export const HOST_STOP_REOWE_AFTER_MS = 10 * 60_000;
28
+ /**
29
+ * How recently a machine was seen for the sweep to count it connected (`device_machines`
30
+ * `last_seen_at`, written at most once a minute while its connection carries traffic or pings).
31
+ */
32
+ const CONNECTED_SEEN_MS = 3 * 60_000;
33
+ /** The devices one sweep owes again at most. */
34
+ const SWEEP_BATCH = 500;
35
+ /**
36
+ * The owed host service stop sweep, every 5 minutes (a `@LockedCron`, once per tick across
37
+ * replicas, under `WorkerModule`): owes the delivery again of every device whose stop has been
38
+ * owed longer than {@link HOST_STOP_REOWE_AFTER_MS} while its machine stays connected (a delivery
39
+ * job that ran out of retries, or a reconnect's delivery folded into a job still kept) and of
40
+ * every deleted device that still has an owed stop (its delivery settles it: the device's program
41
+ * stopped its host services when its machine was closed or refused). A machine that is
42
+ * away gets its delivery on its next connect (`DialInMachines.recordConnect`).
43
+ */
44
+ let HostServiceStopSweepJob = class HostServiceStopSweepJob {
45
+ kdb;
46
+ outbox;
47
+ txHost;
48
+ lockService;
49
+ log;
50
+ constructor(kdb, outbox, txHost, lockService, log) {
51
+ this.kdb = kdb;
52
+ this.outbox = outbox;
53
+ this.txHost = txHost;
54
+ this.lockService = lockService;
55
+ this.log = log;
56
+ }
57
+ async sweep(signal) {
58
+ const n = await this.runOnce(signal);
59
+ // debug only: a stop the device's provider cannot deliver (`capability_missing`) stays owed
60
+ // and is owed again every window while its machine stays connected; each delivery logs its
61
+ // own failure (a warning the first time for such a stop)
62
+ if (n > 0)
63
+ this.log.debug("owed host service stops owed again", { devices: n });
64
+ }
65
+ /** One sweep (the test seam): the number of devices whose delivery was owed again. */
66
+ async runOnce(signal) {
67
+ // org-filter: deployment-wide scan for owed host service stops, in every org; each delivery is
68
+ // owed again in its own org's scope
69
+ const rows = await asPlatform("find owed host service stops to deliver again", () => this.kdb.db
70
+ .selectFrom("device_host_services as h")
71
+ .innerJoin("devices as d", (j) => j.onRef("d.id", "=", "h.device_id").onRef("d.org_id", "=", "h.org_id"))
72
+ .select(["h.org_id", "h.device_id"])
73
+ .distinct()
74
+ .where("h.stop_owed_at", "is not", null)
75
+ .where("h.stop_owed_at", "<", sql `now() - make_interval(secs => ${HOST_STOP_REOWE_AFTER_MS / 1000})`)
76
+ .where((eb) => eb.or([
77
+ eb("d.deleted_at", "is not", null),
78
+ eb.exists(eb
79
+ .selectFrom("device_machines as m")
80
+ .select(sql `1`.as("one"))
81
+ .whereRef("m.device_id", "=", "h.device_id")
82
+ .where("m.revoked_at", "is", null)
83
+ .where("m.last_seen_at", ">", sql `now() - make_interval(secs => ${CONNECTED_SEEN_MS / 1000})`)),
84
+ ]))
85
+ .limit(SWEEP_BATCH)
86
+ .execute());
87
+ const window = `w${Math.floor(Date.now() / HOST_STOP_REOWE_AFTER_MS)}`;
88
+ for (const r of rows) {
89
+ signal?.throwIfAborted();
90
+ await withOrgScope(r.org_id, () => this.oweAgain(r.org_id, r.device_id, window));
91
+ }
92
+ return rows.length;
93
+ }
94
+ async oweAgain(orgId, deviceId, window) {
95
+ await oweHostServicesDelivery(this.outbox, { orgId, deviceId }, window);
96
+ }
97
+ };
98
+ __decorate([
99
+ LockedCron("*/5 * * * *", { name: HOST_SERVICES_STOP_SWEEP_JOB })
100
+ ], HostServiceStopSweepJob.prototype, "sweep", null);
101
+ __decorate([
102
+ Transactional()
103
+ ], HostServiceStopSweepJob.prototype, "oweAgain", null);
104
+ HostServiceStopSweepJob = __decorate([
105
+ Injectable(),
106
+ __param(0, Inject(KernelDb)),
107
+ __param(1, Inject(OutboxService)),
108
+ __param(2, Inject(TransactionHost)),
109
+ __param(3, Inject(LockService)),
110
+ __param(4, Inject(KERNEL_LOGGER))
111
+ ], HostServiceStopSweepJob);
112
+ export { HostServiceStopSweepJob };
@@ -0,0 +1,78 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
3
+ /**
4
+ * The stops of host services the kernel owes (local agents spec, calls 1 and 5: a host service
5
+ * ends when its extension is switched off in the org, disabled on the deployment or uninstalled;
6
+ * when the host gate closes: a platform or org project reach cap narrows below `machine`, or
7
+ * running outside the sandbox is switched off there; and when its person or device goes: the
8
+ * device is deleted, the person is removed from the org, or their account is disabled). The owed
9
+ * stop is state, `device_host_services.stop_owed_at`, set in the transaction that makes the change
10
+ * and cleared only when the machine confirms the stop (or, for a deleted device, when the delivery
11
+ * finds the device gone: its machine is closed with 4003 or refused with 401, and `capybara-device`
12
+ * stops every host service it runs at that terminal end before it exits; a disabled account's
13
+ * devices stay owed until a machine confirms). The delivery is an
14
+ * outbox job on the maintenance queue (`HostServiceAccess.deliverOwedStops`), owed by the same
15
+ * transaction, again by every connect of a machine that still has owed stops
16
+ * (`DialInMachines.recordConnect`), so a machine offline at the change gets the stop when it comes
17
+ * back, and again by the periodic sweep (`HostServiceStopSweepJob`) for a machine that stayed
18
+ * connected while a delivery job ran out of retries. A file of its own (no Nest, no device graph),
19
+ * so the extension, identity, org and dial-in modules can owe it without importing the device
20
+ * access module.
21
+ */
22
+ export declare const HOST_SERVICES_STOP_JOB = "device-host-services-stop";
23
+ /**
24
+ * The data of {@link HOST_SERVICES_STOP_JOB}: which owed stops to deliver, narrowed by extension,
25
+ * org and device (`orgId` gives the job its org scope, `runJob`); none of them: every owed stop.
26
+ */
27
+ export interface HostServicesStopJobData {
28
+ extension?: string;
29
+ orgId?: string;
30
+ deviceId?: string;
31
+ }
32
+ /**
33
+ * The mark of an owed stop as a job id part: `stop_owed_at` in microseconds since the epoch (the
34
+ * owing transaction's `now()`), selected with {@link owedMarkMicros}.
35
+ */
36
+ export declare const owedMarkMicros: import("kysely").RawBuilder<string>;
37
+ /**
38
+ * The deterministic job id (no `:`): one delivery per narrowing and per mark, `mark` being the
39
+ * latest `stop_owed_at` it delivers ({@link owedMarkMicros}). A mark made while an earlier
40
+ * delivery of the same narrowing runs (or is still kept by the queue) gets a job of its own, so
41
+ * the queue never folds it into a delivery that already read its rows; owing the same mark again
42
+ * (a machine's reconnects) stays one job.
43
+ */
44
+ export declare const hostServicesStopJobId: (data: HostServicesStopJobData, mark: string) => string;
45
+ /**
46
+ * Owes one delivery of the owed stops `data` narrows to, in the caller's transaction, under the
47
+ * latest mark among them (`mark`, {@link owedMarkMicros}).
48
+ */
49
+ export declare function oweHostServicesDelivery(outbox: Pick<OutboxService, "add">, data: HostServicesStopJobData, mark: string): Promise<void>;
50
+ /** The latest of the marks `rows` returned, or null when no placement was marked. */
51
+ export declare function latestMark(rows: readonly {
52
+ mark: string;
53
+ }[]): string | null;
54
+ /**
55
+ * Owes the stop of host services, in the caller's transaction (`db`): marks every placement of
56
+ * `extension` (of every extension when absent: the host gate closed, a project reach cap narrowed
57
+ * below `machine` or running outside the sandbox switched off,
58
+ * `PermissionCeilingWrites.oweHostServiceStopsLocked`) in `orgId` (every org when absent) as
59
+ * owed, and owes their delivery. Nothing is owed where no placement was marked.
60
+ */
61
+ export declare function oweHostServicesStop(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, data: {
62
+ extension?: string;
63
+ orgId?: string;
64
+ }): Promise<void>;
65
+ /**
66
+ * Owes the stop of every host service on `deviceIds` of `orgId`, in the caller's transaction
67
+ * (`db`): the devices are deleted, or their person leaves the org. Marks their placements owed and
68
+ * owes one delivery per device that had one.
69
+ */
70
+ export declare function oweHostServicesStopOnDevices(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, data: {
71
+ orgId: string;
72
+ deviceIds: readonly string[];
73
+ }): Promise<void>;
74
+ /**
75
+ * Owes the stop of every host service on the personal devices of `accountId`, in every org, in the
76
+ * caller's transaction (`db`): the account is disabled. One delivery per device that had one.
77
+ */
78
+ export declare function oweHostServicesStopOfAccount(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, accountId: string): Promise<void>;