@capybara-hq/kernel 0.1.0-rc.132 → 0.1.0-rc.134

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 (173) 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/automations/events/trigger-events.service.d.ts +13 -1
  11. package/dist/automations/events/trigger-events.service.js +27 -14
  12. package/dist/catalog/catalog.service.d.ts +2 -0
  13. package/dist/catalog/catalog.service.js +28 -5
  14. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  15. package/dist/catalog/marketplace-fetch.js +15 -0
  16. package/dist/catalog/marketplaces.service.d.ts +4 -4
  17. package/dist/catalog/marketplaces.service.js +3 -2
  18. package/dist/catalog/owned-items.d.ts +2 -0
  19. package/dist/catalog/owned-items.js +30 -31
  20. package/dist/catalog/ownership.js +40 -38
  21. package/dist/catalog/plugin-import.d.ts +3 -4
  22. package/dist/catalog/plugin-import.js +50 -1
  23. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  24. package/dist/catalog/plugin-upgrade.js +95 -7
  25. package/dist/catalog/publisher-policy.d.ts +9 -0
  26. package/dist/catalog/publisher-policy.js +12 -0
  27. package/dist/catalog/unshare.js +66 -58
  28. package/dist/client/client-access.service.js +5 -3
  29. package/dist/config/schema.d.ts +1 -0
  30. package/dist/config/schema.js +8 -1
  31. package/dist/conversations/conversations.controller.js +4 -14
  32. package/dist/conversations/conversations.service.d.ts +14 -0
  33. package/dist/conversations/conversations.service.js +20 -2
  34. package/dist/ctx/create-ctx.d.ts +15 -2
  35. package/dist/ctx/create-ctx.js +195 -79
  36. package/dist/ctx/durable-cancellation.d.ts +3 -0
  37. package/dist/ctx/durable-cancellation.js +8 -0
  38. package/dist/ctx/durable-effects.service.d.ts +81 -0
  39. package/dist/ctx/durable-effects.service.js +316 -0
  40. package/dist/ctx/durable-envelope.d.ts +24 -0
  41. package/dist/ctx/durable-envelope.js +80 -0
  42. package/dist/ctx/durable-failure.d.ts +7 -0
  43. package/dist/ctx/durable-failure.js +32 -0
  44. package/dist/ctx/durable-job.d.ts +9 -0
  45. package/dist/ctx/durable-job.js +2 -0
  46. package/dist/ctx/durable-keys.d.ts +27 -0
  47. package/dist/ctx/durable-keys.js +138 -0
  48. package/dist/ctx/durable-relay.d.ts +29 -0
  49. package/dist/ctx/durable-relay.js +250 -0
  50. package/dist/ctx/queue.d.ts +2 -0
  51. package/dist/ctx/queue.js +25 -15
  52. package/dist/db/extension-db.js +2 -0
  53. package/dist/db/extension-handoff-schema.d.ts +6 -0
  54. package/dist/db/extension-handoff-schema.js +72 -0
  55. package/dist/db/extension-rls-predicate.d.ts +1 -0
  56. package/dist/db/extension-rls-predicate.js +8 -0
  57. package/dist/db/extension-schema-transfer.d.ts +1 -1
  58. package/dist/db/extension-schema-transfer.js +18 -6
  59. package/dist/db/kernel-schema.d.ts +64 -0
  60. package/dist/db/migrator.js +6 -13
  61. package/dist/db/pool.d.ts +2 -2
  62. package/dist/db/pool.js +2 -2
  63. package/dist/db/sql-statements.d.ts +3 -0
  64. package/dist/db/sql-statements.js +15 -5
  65. package/dist/device-access/device-access.module.js +12 -2
  66. package/dist/device-access/device-access.service.d.ts +30 -2
  67. package/dist/device-access/device-access.service.js +38 -4
  68. package/dist/device-access/host-gate.d.ts +45 -0
  69. package/dist/device-access/host-gate.js +92 -0
  70. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  71. package/dist/device-access/host-service-stop-sweep.js +112 -0
  72. package/dist/device-access/host-service-stop.d.ts +78 -0
  73. package/dist/device-access/host-service-stop.js +144 -0
  74. package/dist/device-access/host-services.d.ts +211 -0
  75. package/dist/device-access/host-services.js +803 -0
  76. package/dist/device-access/person-handles.d.ts +10 -0
  77. package/dist/device-access/person-handles.js +25 -0
  78. package/dist/device-access/service-events.d.ts +199 -0
  79. package/dist/device-access/service-events.js +704 -0
  80. package/dist/device-access/token.d.ts +5 -0
  81. package/dist/device-access/token.js +5 -0
  82. package/dist/devices/devices.service.js +3 -0
  83. package/dist/dial-in/access.d.ts +5 -5
  84. package/dist/dial-in/access.js +19 -12
  85. package/dist/dial-in/gateway.js +6 -2
  86. package/dist/dial-in/machines.d.ts +9 -2
  87. package/dist/dial-in/machines.js +27 -4
  88. package/dist/erasure/device-cleanup.js +12 -0
  89. package/dist/erasure/org-catalog.js +2 -2
  90. package/dist/erasure/org-rules.js +10 -0
  91. package/dist/errors.d.ts +2 -0
  92. package/dist/errors.js +2 -0
  93. package/dist/extensions/admin-ops.js +8 -2
  94. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  95. package/dist/extensions/deployed-snapshots.js +7 -2
  96. package/dist/extensions/extensions.module.js +10 -0
  97. package/dist/extensions/host.d.ts +12 -2
  98. package/dist/extensions/host.js +44 -22
  99. package/dist/extensions/instance.d.ts +5 -0
  100. package/dist/extensions/instance.js +10 -0
  101. package/dist/extensions/ledger.d.ts +1 -1
  102. package/dist/extensions/lifecycle-hooks.js +3 -3
  103. package/dist/extensions/org-config.js +6 -1
  104. package/dist/extensions/permission-set.d.ts +7 -0
  105. package/dist/extensions/permission-set.js +10 -0
  106. package/dist/extensions/permission-view.d.ts +1 -1
  107. package/dist/extensions/permission-view.js +10 -1
  108. package/dist/extensions/sources.d.ts +1 -0
  109. package/dist/extensions/sources.js +9 -0
  110. package/dist/git/tickets.js +32 -27
  111. package/dist/http/app.js +5 -3
  112. package/dist/identity/accounts.d.ts +6 -1
  113. package/dist/identity/accounts.js +11 -2
  114. package/dist/identity/api-tokens.js +7 -6
  115. package/dist/identity/settings.d.ts +9 -1
  116. package/dist/identity/settings.js +16 -1
  117. package/dist/inbox/inbox-items.service.d.ts +5 -0
  118. package/dist/inbox/inbox-items.service.js +57 -33
  119. package/dist/inbox/org-notices.js +3 -2
  120. package/dist/index.d.ts +1 -0
  121. package/dist/index.js +1 -0
  122. package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
  123. package/dist/infra/database/extension-effect-key-lock.js +69 -0
  124. package/dist/infra/database/extension-handoff.d.ts +27 -0
  125. package/dist/infra/database/extension-handoff.js +113 -0
  126. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  127. package/dist/infra/database/scoped-dialect.js +260 -72
  128. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  129. package/dist/infra/database/startup-activation-transaction.js +3 -2
  130. package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
  131. package/dist/infra/outbox/outbox.dispatcher.js +64 -4
  132. package/dist/infra/outbox/outbox.module.js +2 -0
  133. package/dist/infra/outbox/registry.d.ts +40 -0
  134. package/dist/infra/outbox/registry.js +42 -0
  135. package/dist/infra/queue/queue-names.d.ts +1 -1
  136. package/dist/infra/queue/queue-names.js +1 -0
  137. package/dist/infra/queue/run-job.d.ts +4 -1
  138. package/dist/infra/queue/run-job.js +10 -2
  139. package/dist/kernel.js +1 -0
  140. package/dist/kernel.module.js +3 -0
  141. package/dist/orgs/offboarding.js +18 -9
  142. package/dist/orgs/orgs.service.js +16 -0
  143. package/dist/orgs/settings.service.js +3 -0
  144. package/dist/packages/npm-publish-keys.json +27 -0
  145. package/dist/packages/official-publisher.d.ts +19 -0
  146. package/dist/packages/official-publisher.js +152 -0
  147. package/dist/packages/provenance.d.ts +7 -0
  148. package/dist/packages/provenance.js +22 -19
  149. package/dist/packages/sigstore-trusted-root.json +126 -0
  150. package/dist/platform/ops/admin.ops.js +2 -1
  151. package/dist/platform/ops/orgs.ops.js +1 -0
  152. package/dist/roles/worker-role.d.ts +6 -3
  153. package/dist/roles/worker-role.js +12 -4
  154. package/dist/roles/worker.module.js +9 -0
  155. package/dist/runtime/maintenance.d.ts +5 -2
  156. package/dist/runtime/maintenance.js +18 -4
  157. package/dist/sandbox/device-reports.d.ts +4 -4
  158. package/dist/sandbox/device-reports.js +40 -30
  159. package/dist/sandbox/device-services.d.ts +2 -1
  160. package/dist/sandbox/device-services.js +5 -1
  161. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  162. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  163. package/dist/sandbox/permission-config-publication.js +5 -1
  164. package/dist/themes/theme-state.js +24 -13
  165. package/dist/tools/call-scope.d.ts +6 -0
  166. package/dist/tools/call-scope.js +22 -0
  167. package/dist/tools/registry.js +20 -2
  168. package/dist/ui/views.js +36 -8
  169. package/package.json +9 -4
  170. package/src/migrations/0222_device_host_services.sql +27 -0
  171. package/src/migrations/0223_device_service_events.sql +54 -0
  172. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  173. package/src/migrations/0225_extension_effect_receipts.sql +25 -0
@@ -4,18 +4,10 @@ import { join } from "node:path";
4
4
  import { sql } from "kysely";
5
5
  import pg from "pg";
6
6
  import { assertExtensionSchemaOwner, assertExtensionSession } from "./extension-db.js";
7
+ import { EXTENSION_RLS_PREDICATE } from "./extension-rls-predicate.js";
7
8
  import { pgConnectOptions } from "./pool.js";
8
9
  /** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
9
10
  export const MIGRATION_FILE_RE = /^\d{4}_[a-z0-9_]+\.sql$/;
10
- // Keep this local to each extension schema so its login never needs USAGE on capybara.
11
- const extensionRlsPredicate = `
12
- create or replace function rls_admits(row_org text) returns boolean
13
- language sql stable parallel safe as $$
14
- select coalesce(pg_catalog.current_setting('capybara.rls', true), '') <> 'enforce'
15
- or pg_catalog.current_setting('capybara.scope', true) = 'platform'
16
- or row_org = pg_catalog.current_setting('capybara.org_id', true)
17
- $$
18
- `;
19
11
  const ident = (s) => `"${s.replaceAll('"', '""')}"`;
20
12
  const num = (name) => Number.parseInt(name.slice(0, 4), 10);
21
13
  export async function lockMigrationSchema(client, schema, scope) {
@@ -41,9 +33,10 @@ async function migrationFiles(dir) {
41
33
  }));
42
34
  }
43
35
  // Use the effective login on the actual connection, including when a URL sets a role.
36
+ // Roles are cluster-wide, so the schema owner in this database identifies a split installation.
44
37
  const kernelMigrationPrivileges = `
45
38
  select pg_catalog.has_database_privilege(current_user, current_database(), 'CREATE') as can_create,
46
- exists (select from pg_catalog.pg_roles where rolname = 'capybara_owner') as has_owner_role,
39
+ coalesce(n.nspowner = pg_catalog.to_regrole('capybara_owner'), false) as split_identity,
47
40
  current_user = pg_catalog.pg_get_userbyid(n.nspowner) as owns_schema
48
41
  from (values ('capybara'::name)) as target(schema_name)
49
42
  left join pg_catalog.pg_namespace n on n.nspname = target.schema_name
@@ -52,7 +45,7 @@ export async function canMigrateKernel(db) {
52
45
  const { rows: [privileges], } = await sql.raw(kernelMigrationPrivileges).execute(db);
53
46
  if (privileges === undefined)
54
47
  throw new Error("Could not read kernel migration privileges");
55
- return privileges.can_create && (privileges.owns_schema ?? !privileges.has_owner_role);
48
+ return privileges.can_create && (privileges.owns_schema ?? true);
56
49
  }
57
50
  const migrateHint = "Run capybara migrate with CAPYBARA_DB__MIGRATION_URL set to the schema owner URL for split roles.";
58
51
  /** Verify the files expected by this binary without taking a migration lock or writing the journal.
@@ -160,7 +153,7 @@ export async function migrate(connectionString, owner, opts = {}) {
160
153
  }
161
154
  if (schema === "capybara") {
162
155
  const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
163
- if (privileges?.has_owner_role && !privileges.owns_schema) {
156
+ if (privileges?.split_identity && !privileges.owns_schema) {
164
157
  throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
165
158
  }
166
159
  }
@@ -196,7 +189,7 @@ export async function migrate(connectionString, owner, opts = {}) {
196
189
  pg_catalog.set_config('capybara.org_id', '', true),
197
190
  pg_catalog.set_config('capybara.rls', 'off', true)`);
198
191
  if (applied.length === 0)
199
- await client.query(extensionRlsPredicate);
192
+ await client.query(EXTENSION_RLS_PREDICATE);
200
193
  }
201
194
  await client.query(f.content);
202
195
  await client.query(`insert into ${table} (name, checksum) values ($1, $2)`, [
package/dist/db/pool.d.ts CHANGED
@@ -31,8 +31,8 @@ export declare function createDb(url: string, poolMax: number, onError?: (err: E
31
31
  */
32
32
  onClientError?: ((err: Error) => void) | undefined;
33
33
  /**
34
- * `db.rls`: whether every connection carries the org scope of its caller (RLS spec §5.2;
35
- * `scoped-dialect.ts`). Unset = `off`, a plain pool.
34
+ * `db.rls` controls the scope carried by each PostgreSQL transaction (RLS spec §5.2).
35
+ * Unset uses a plain pool.
36
36
  */
37
37
  rls?: RlsMode | undefined;
38
38
  onConnect?: (client: pg.ClientBase) => Promise<void>;
package/dist/db/pool.js CHANGED
@@ -20,6 +20,7 @@ export function pgConnectOptions(cfg) {
20
20
  * `opts.connectTimeoutMs` 为建立连接的超时(不设则 pg 无限等待)。
21
21
  */
22
22
  export function createDb(url, poolMax, onError = (err) => console.error("[db] idle client error:", err), opts = {}) {
23
+ const rls = opts.rls ?? "off";
23
24
  const pool = new pg.Pool({
24
25
  connectionString: url,
25
26
  max: poolMax,
@@ -31,11 +32,10 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
31
32
  });
32
33
  pool.on("error", onError);
33
34
  pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
34
- const rls = opts.rls ?? "off";
35
35
  return new Kysely({
36
36
  dialect: new ScopedPostgresDialect({
37
37
  pool: opts.closeActiveOnDestroy ? disposablePool(pool) : pool,
38
- }, rls),
38
+ }, rls, rls !== "off"),
39
39
  plugins: rls !== "off" && unscopedQueryCheck() ? [captureUnscopedQueryOrigins] : [],
40
40
  });
41
41
  }
@@ -5,6 +5,9 @@
5
5
  export type SqlStatement = {
6
6
  text: string;
7
7
  line: number;
8
+ /** Source range from the first token through the terminator, if present. */
9
+ startOffset: number;
10
+ endOffset: number;
8
11
  /** 语句里美元引用字符串的原文(不含定界符),按出现顺序;`DO $$ … $$` 的块体在这里。 */
9
12
  bodies: string[];
10
13
  /**
@@ -13,17 +13,27 @@ export function splitSqlStatements(src) {
13
13
  let text = "";
14
14
  let line = 1;
15
15
  let startLine = 0;
16
+ let startOffset = 0;
16
17
  let bodies = [];
17
18
  let quoted = [];
18
19
  let i = 0;
19
20
  const push = (chunk) => {
20
- if (startLine === 0 && chunk.trim() !== "")
21
+ if (startLine === 0 && chunk.trim() !== "") {
21
22
  startLine = line;
23
+ startOffset = i;
24
+ }
22
25
  text += chunk;
23
26
  };
24
- const flush = () => {
27
+ const flush = (endOffset) => {
25
28
  if (text.trim() !== "") {
26
- out.push({ text: text.replace(/\s+/g, " ").trim(), line: startLine, bodies, quoted });
29
+ out.push({
30
+ text: text.replace(/\s+/g, " ").trim(),
31
+ line: startLine,
32
+ startOffset,
33
+ endOffset,
34
+ bodies,
35
+ quoted,
36
+ });
27
37
  }
28
38
  text = "";
29
39
  startLine = 0;
@@ -113,7 +123,7 @@ export function splitSqlStatements(src) {
113
123
  }
114
124
  }
115
125
  if (c === ";") {
116
- flush();
126
+ flush(i + 1);
117
127
  i++;
118
128
  continue;
119
129
  }
@@ -122,7 +132,7 @@ export function splitSqlStatements(src) {
122
132
  line++;
123
133
  i++;
124
134
  }
125
- flush();
135
+ flush(src.length);
126
136
  return out;
127
137
  }
128
138
  /**
@@ -7,10 +7,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  import { Module } from "@nestjs/common";
8
8
  import { DevicesModule } from "../devices/devices.module.js";
9
9
  import { ExtensionRegistryModule } from "../extensions/registry.js";
10
+ import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
11
+ import { PermissionFactsModule } from "../sandbox/permission-facts.module.js";
10
12
  import { SandboxProviderRegistryModule } from "../sandbox/providers.module.js";
11
13
  import { SandboxModule } from "../sandbox/sandbox.module.js";
12
14
  import { ToolsModule } from "../tools/tools.module.js";
13
15
  import { DeviceAccessService } from "./device-access.service.js";
16
+ import { HostServiceGate } from "./host-gate.js";
17
+ import { HostServiceAccess } from "./host-services.js";
14
18
  import { DeviceSiteGrantsModule } from "./site-grants.module.js";
15
19
  import { DEVICE_ACCESS_BACKEND } from "./token.js";
16
20
  /**
@@ -24,7 +28,9 @@ ExtensionDeviceAccessModule = __decorate([
24
28
  Module({
25
29
  // SandboxModule: device services and the command review; DevicesModule: the conversation's
26
30
  // device, who may use it and its allowlist write; ToolsModule: the questions;
27
- // ExtensionRegistryModule: an extension's approved manifest when a viewer opens
31
+ // ExtensionRegistryModule: an extension's approved manifest when a viewer opens;
32
+ // PermissionFactsModule: the host gate's device sandbox; PermissionAuthorityModule: the locks and
33
+ // the published config its admission reads under
28
34
  imports: [
29
35
  SandboxModule,
30
36
  SandboxProviderRegistryModule,
@@ -32,12 +38,16 @@ ExtensionDeviceAccessModule = __decorate([
32
38
  ToolsModule,
33
39
  ExtensionRegistryModule,
34
40
  DeviceSiteGrantsModule,
41
+ PermissionFactsModule,
42
+ PermissionAuthorityModule,
35
43
  ],
36
44
  providers: [
45
+ HostServiceGate,
46
+ HostServiceAccess,
37
47
  DeviceAccessService,
38
48
  { provide: DEVICE_ACCESS_BACKEND, useExisting: DeviceAccessService },
39
49
  ],
40
- exports: [DeviceAccessService, DEVICE_ACCESS_BACKEND],
50
+ exports: [DeviceAccessService, HostServiceAccess, DEVICE_ACCESS_BACKEND],
41
51
  })
42
52
  ], ExtensionDeviceAccessModule);
43
53
  export { ExtensionDeviceAccessModule };
@@ -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 };