@capybara-hq/kernel 0.1.0-rc.117 → 0.1.0-rc.119

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 (106) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/automations/unattended.d.ts +2 -0
  4. package/dist/automations/unattended.js +10 -3
  5. package/dist/catalog/component-scope.service.js +2 -1
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-install.d.ts +1 -0
  8. package/dist/catalog/plugin-install.js +11 -1
  9. package/dist/channels/cards.d.ts +2 -4
  10. package/dist/channels/cards.js +11 -6
  11. package/dist/channels/phrases.d.ts +4 -0
  12. package/dist/channels/phrases.js +1 -0
  13. package/dist/conversations/conversations.controller.d.ts +1 -1
  14. package/dist/conversations/conversations.controller.js +1 -1
  15. package/dist/conversations/conversations.service.d.ts +4 -2
  16. package/dist/conversations/conversations.service.js +19 -3
  17. package/dist/conversations/events.d.ts +35 -1
  18. package/dist/conversations/events.js +29 -4
  19. package/dist/ctx/create-ctx.d.ts +1 -1
  20. package/dist/ctx/create-ctx.js +4 -0
  21. package/dist/db/kernel-schema.d.ts +31 -1
  22. package/dist/device-access/device-access.module.js +2 -0
  23. package/dist/device-access/device-access.service.d.ts +16 -2
  24. package/dist/device-access/device-access.service.js +59 -2
  25. package/dist/device-access/site-access-request.d.ts +14 -0
  26. package/dist/device-access/site-access-request.js +35 -0
  27. package/dist/device-access/site-grants.d.ts +53 -0
  28. package/dist/device-access/site-grants.js +268 -0
  29. package/dist/device-access/site-grants.module.d.ts +2 -0
  30. package/dist/device-access/site-grants.module.js +14 -0
  31. package/dist/devices/devices.controller.d.ts +5 -0
  32. package/dist/devices/devices.controller.js +20 -2
  33. package/dist/devices/devices.service.d.ts +3 -1
  34. package/dist/devices/devices.service.js +6 -0
  35. package/dist/evals/plan.d.ts +3 -1
  36. package/dist/evals/plan.js +25 -5
  37. package/dist/evals/runs.service.js +3 -2
  38. package/dist/evals/trajectory.js +1 -0
  39. package/dist/extensions/admin-ops.js +7 -0
  40. package/dist/extensions/org-config.js +4 -0
  41. package/dist/extensions/permission-set.d.ts +3 -0
  42. package/dist/extensions/permission-set.js +5 -0
  43. package/dist/extensions/permission-view.d.ts +1 -1
  44. package/dist/extensions/permission-view.js +7 -1
  45. package/dist/files/blob-references.d.ts +8 -0
  46. package/dist/files/blob-references.js +19 -0
  47. package/dist/files/blob-sweep.job.js +5 -23
  48. package/dist/files/library-files.service.js +8 -4
  49. package/dist/models/cache-write-usage.d.ts +3 -0
  50. package/dist/models/cache-write-usage.js +26 -0
  51. package/dist/models/images.js +5 -1
  52. package/dist/models/prices.d.ts +8 -6
  53. package/dist/models/prices.js +28 -3
  54. package/dist/orgs/offboarding.js +2 -0
  55. package/dist/orgs/settings.controller.d.ts +4 -17
  56. package/dist/orgs/settings.controller.js +5 -9
  57. package/dist/orgs/settings.service.d.ts +12 -0
  58. package/dist/orgs/settings.service.js +24 -0
  59. package/dist/platform/exclusions.js +6 -0
  60. package/dist/platform/ops/admin.ops.js +2 -2
  61. package/dist/platform/ops/conversations.ops.js +1 -1
  62. package/dist/platform/ops/devices.ops.js +7 -0
  63. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  64. package/dist/platform/ops/org-settings.ops.js +10 -10
  65. package/dist/roles/worker.module.js +2 -0
  66. package/dist/runtime/context/build.d.ts +2 -0
  67. package/dist/runtime/context/build.js +9 -1
  68. package/dist/runtime/usage-report.js +3 -0
  69. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  70. package/dist/sandbox/legacy-retirement.js +243 -3
  71. package/dist/sandbox/loopback-expiry.job.d.ts +3 -1
  72. package/dist/sandbox/loopback-expiry.job.js +9 -3
  73. package/dist/sandbox/operation-authority.d.ts +1 -1
  74. package/dist/sandbox/operation-authority.js +14 -6
  75. package/dist/sandbox/permission-call-types.d.ts +2 -2
  76. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  77. package/dist/sandbox/permission-instance-writes.js +55 -1
  78. package/dist/sandbox/providers.d.ts +6 -1
  79. package/dist/sandbox/providers.js +15 -1
  80. package/dist/sandbox/review/classifier.d.ts +13 -4
  81. package/dist/sandbox/review/classifier.js +73 -22
  82. package/dist/sandbox/review/permission-candidate.d.ts +3 -3
  83. package/dist/sandbox/review/permission-candidate.js +10 -8
  84. package/dist/sandbox/review/review.service.d.ts +26 -19
  85. package/dist/sandbox/review/review.service.js +69 -15
  86. package/dist/sandbox/sandbox.service.d.ts +6 -3
  87. package/dist/sandbox/sandbox.service.js +116 -5
  88. package/dist/tools/approvals.service.d.ts +30 -4
  89. package/dist/tools/approvals.service.js +143 -12
  90. package/dist/tools/builtins/sandbox/common.js +10 -6
  91. package/dist/tools/call-scope.d.ts +3 -0
  92. package/dist/tools/call-scope.js +1 -0
  93. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  94. package/dist/tools/connectors.service.d.ts +3 -1
  95. package/dist/tools/connectors.service.js +64 -12
  96. package/dist/tools/drift.d.ts +1 -1
  97. package/dist/tools/drift.js +13 -13
  98. package/dist/tools/network-asks.js +7 -0
  99. package/dist/tools/pipeline.d.ts +16 -5
  100. package/dist/tools/pipeline.js +314 -11
  101. package/dist/tools/tools.module.js +2 -0
  102. package/package.json +2 -2
  103. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  104. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  105. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
  106. package/src/migrations/0205_device_site_grants.sql +30 -0
@@ -1,4 +1,4 @@
1
- import type { ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
1
+ import type { CacheWriteByTtl, ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SiteAccessAction, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
2
2
  import type { ColumnType, Generated, Kysely } from "kysely";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import type { AutomationChat, AutomationEventMarker, AutomationMode, AutomationOrigin, AutomationPauseReason, AutomationPrincipal, AutomationStatus, AutomationTrigger, AutomationUnattendedAsk, ScheduleMarker, TaskRunSkipReason, TaskRunStatus } from "../automations/types.js";
@@ -648,6 +648,8 @@ export interface ConnectorsTable {
648
648
  deleted_at: TsNullable;
649
649
  /** 0015:最近一次成功拿到工具清单的时间;为空 = 从未拍过快照(首个快照按安装处理)。 */
650
650
  tools_synced_at: TsNullable;
651
+ /** When the current endpoint was first written. Null for rows from before migration 0202. */
652
+ endpoint_changed_at: TsNullable;
651
653
  /**
652
654
  * 0037, renamed in 0042: the source item (an app's template records the app item) and version
653
655
  * when installed from a catalog template.
@@ -1321,6 +1323,21 @@ export interface DeviceLoopbackGrantsTable {
1321
1323
  revoked_at: TsNullable;
1322
1324
  revoke_reason: Generated<"revoked" | "expired" | "conversation-deleted" | "outside-sandbox-off" | null>;
1323
1325
  }
1326
+ /** Durable, human-approved consent for one origin and action in a conversation tree. */
1327
+ export interface DeviceSiteGrantsTable {
1328
+ id: string;
1329
+ org_id: string;
1330
+ device_id: string;
1331
+ service_id: string;
1332
+ /** The root conversation. */
1333
+ conversation_id: string;
1334
+ origin: string;
1335
+ action: SiteAccessAction;
1336
+ approval_id: ColumnType<string | null, string, string | null>;
1337
+ created_at: Ts;
1338
+ expires_at: ColumnType<Date, Date | string, Date | string>;
1339
+ revoked_at: TsNullable;
1340
+ }
1324
1341
  /** 0088_environments.sql, renamed in 0105: the device a member's new conversations use by default. */
1325
1342
  export interface DeviceDefaultsTable {
1326
1343
  org_id: string;
@@ -1339,6 +1356,7 @@ export interface ModelPricesTable {
1339
1356
  output_per_mtok: Numeric;
1340
1357
  cache_read_per_mtok: NumericNullable;
1341
1358
  cache_write_per_mtok: NumericNullable;
1359
+ cache_write_per_mtok_by_ttl: Json<Record<string, number>>;
1342
1360
  updated_by: string | null;
1343
1361
  updated_at: Ts;
1344
1362
  }
@@ -1564,6 +1582,7 @@ export interface ModelUsageTable {
1564
1582
  cache_read_tokens: Generated<number>;
1565
1583
  /** 0160: the answer's cache write tokens (0 for an embedding call). */
1566
1584
  cache_write_tokens: Generated<number>;
1585
+ cache_write_by_ttl: Json<CacheWriteByTtl[] | null>;
1567
1586
  occurred_at: Ts;
1568
1587
  reported_at: TsNullable;
1569
1588
  /** Set when the row's `usage.report` job gave up after its last attempt. */
@@ -1956,6 +1975,15 @@ export interface DeviceRetirementMembersTable {
1956
1975
  settled: ColumnType<boolean, boolean | undefined, boolean>;
1957
1976
  created_at: Generated<Date>;
1958
1977
  }
1978
+ /** 0204: the exact local provider identity of a committed kernel incarnation. */
1979
+ export interface DeviceInstanceRetirementIdentitiesTable {
1980
+ org_id: string;
1981
+ device_id: string;
1982
+ provider: string;
1983
+ instance_generation: string;
1984
+ provider_generation: string;
1985
+ attested_at: TsNullable;
1986
+ }
1959
1987
  export interface DeviceInstanceDestructionsTable {
1960
1988
  device_id: string;
1961
1989
  provider: string;
@@ -1989,6 +2017,7 @@ export interface KernelDatabase {
1989
2017
  device_retirement_members: DeviceRetirementMembersTable;
1990
2018
  /** Migration 0157: provider-confirmed destruction of a cloud instance incarnation. */
1991
2019
  device_instance_destructions: DeviceInstanceDestructionsTable;
2020
+ device_instance_retirement_identities: DeviceInstanceRetirementIdentitiesTable;
1992
2021
  sandbox_operation_intents: SandboxOperationIntentsTable;
1993
2022
  sandbox_operation_payload_chunks: SandboxOperationPayloadChunksTable;
1994
2023
  permission_config_publication: PermissionConfigPublicationTable;
@@ -2053,6 +2082,7 @@ export interface KernelDatabase {
2053
2082
  device_projects: DeviceProjectsTable;
2054
2083
  device_conversation_notices: DeviceConversationNoticesTable;
2055
2084
  device_loopback_grants: DeviceLoopbackGrantsTable;
2085
+ device_site_grants: DeviceSiteGrantsTable;
2056
2086
  background_tasks: BackgroundTasksTable;
2057
2087
  automations: AutomationsTable;
2058
2088
  automation_runs: AutomationRunsTable;
@@ -11,6 +11,7 @@ import { SandboxProviderRegistryModule } from "../sandbox/providers.module.js";
11
11
  import { SandboxModule } from "../sandbox/sandbox.module.js";
12
12
  import { ToolsModule } from "../tools/tools.module.js";
13
13
  import { DeviceAccessService } from "./device-access.service.js";
14
+ import { DeviceSiteGrantsModule } from "./site-grants.module.js";
14
15
  import { DEVICE_ACCESS_BACKEND } from "./token.js";
15
16
  /**
16
17
  * `ctx.deviceAccess` (browser use spec §7): {@link DeviceAccessService}. The extension host finds
@@ -30,6 +31,7 @@ ExtensionDeviceAccessModule = __decorate([
30
31
  DevicesModule,
31
32
  ToolsModule,
32
33
  ExtensionRegistryModule,
34
+ DeviceSiteGrantsModule,
33
35
  ],
34
36
  providers: [
35
37
  DeviceAccessService,
@@ -1,4 +1,4 @@
1
- import { type DeviceAccessScope, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, type ServiceBlockedHost, type ToolCallContext } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceAccessScope, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, 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 { DeviceSiteGrants } from "./site-grants.js";
16
17
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
17
18
  export declare const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
18
19
  /** A viewer ticket's key prefix (`capk:device-stream-ticket:<id>`, single use, GETDEL). */
@@ -47,6 +48,7 @@ export interface DeviceAccessCaller {
47
48
  * be granted local ports of the device (browser loopback port grants design).
48
49
  */
49
50
  loopbackPorts: boolean;
51
+ siteAccess?: boolean;
50
52
  }
51
53
  /**
52
54
  * `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
@@ -76,9 +78,10 @@ export declare class DeviceAccessService {
76
78
  private readonly loopback;
77
79
  /** A panel grant settles the agent's pending ask for the same port. */
78
80
  private readonly approvals;
81
+ private readonly site;
79
82
  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">,
80
83
  /** A panel grant settles the agent's pending ask for the same port. */
81
- approvals: Pick<ApprovalsService, "settleLoopbackAsks">);
84
+ approvals: Pick<ApprovalsService, "settleLoopbackAsks">, site: DeviceSiteGrants);
82
85
  private get db();
83
86
  /**
84
87
  * Starts the service in the call's device, or finds it running. An `ifRunning` ensure first
@@ -135,6 +138,17 @@ export declare class DeviceAccessService {
135
138
  url?: string;
136
139
  service?: string;
137
140
  }): void;
141
+ /** Report the daemon's refusal in the currently executing, owner-bound tool scope. */
142
+ requestSiteAccess(caller: DeviceAccessCaller, call: ToolCallContext, ask: SiteAccessAsk): void;
143
+ siteGrants(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
144
+ service: string;
145
+ }): Promise<SiteGrantView[]>;
146
+ revokeSiteGrant(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
147
+ service: string;
148
+ origin: string;
149
+ action: SiteAccessAction;
150
+ }): Promise<void>;
151
+ private siteGrantScope;
138
152
  /**
139
153
  * Grants the scope conversation's root a local port of its device for one service (the owner's
140
154
  * click in the panel, source `owner-panel`): owner only, refused with `loopback_unavailable`
@@ -34,6 +34,8 @@ 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 { assertSiteAccessAction, siteAccessInstallActive } from "./site-access-request.js";
38
+ import { DeviceSiteGrants } from "./site-grants.js";
37
39
  /** The layers a service may report a refused host with (`ServiceBlockedHost.layer`). */
38
40
  const BLOCK_LAYERS = ["device", "org", "address", "unknown"];
39
41
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
@@ -113,9 +115,10 @@ let DeviceAccessService = class DeviceAccessService {
113
115
  txHost;
114
116
  loopback;
115
117
  approvals;
118
+ site;
116
119
  constructor(kdb, redis, config, services, review, devices, access, deviceWrites, questions, providers, log, registry, txHost, loopback,
117
120
  /** A panel grant settles the agent's pending ask for the same port. */
118
- approvals) {
121
+ approvals, site) {
119
122
  this.kdb = kdb;
120
123
  this.redis = redis;
121
124
  this.config = config;
@@ -131,6 +134,7 @@ let DeviceAccessService = class DeviceAccessService {
131
134
  this.txHost = txHost;
132
135
  this.loopback = loopback;
133
136
  this.approvals = approvals;
137
+ this.site = site;
134
138
  }
135
139
  get db() {
136
140
  return this.kdb.db;
@@ -457,6 +461,52 @@ let DeviceAccessService = class DeviceAccessService {
457
461
  port: entry.port,
458
462
  };
459
463
  }
464
+ /** Report the daemon's refusal in the currently executing, owner-bound tool scope. */
465
+ requestSiteAccess(caller, call, ask) {
466
+ assertCallOwner(call);
467
+ assertSiteAccessCaller(caller, ask?.service);
468
+ assertSiteAccessAction(ask.action, ask.origin);
469
+ if (typeof ask.detail !== "string" || ask.detail.length === 0 || ask.detail.length > 20_000) {
470
+ throw new DeviceAccessError("invalid_request", "Describe the site action within 20,000 characters.");
471
+ }
472
+ const scope = callScopeOf(call);
473
+ if (scope?.facts === undefined || scope.watch || scope.device === null)
474
+ return;
475
+ scope.siteAccess = {
476
+ service: ask.service,
477
+ serviceId: deviceServiceId(caller.extension, ask.service),
478
+ extension: caller.extension,
479
+ deviceId: scope.device,
480
+ origin: ask.origin,
481
+ action: ask.action,
482
+ detail: ask.detail,
483
+ };
484
+ }
485
+ async siteGrants(caller, scope) {
486
+ const { d, key } = await this.siteGrantScope(caller, scope);
487
+ if ((await this.unattendedTree(d)) ||
488
+ !(await siteAccessInstallActive(this.db, caller.extension, caller.sha256 ?? null)))
489
+ return [];
490
+ return this.site.liveForRoot(key);
491
+ }
492
+ async revokeSiteGrant(caller, scope) {
493
+ assertSiteAccessAction(scope.action, scope.origin);
494
+ const { key } = await this.siteGrantScope(caller, scope);
495
+ await this.site.revoke({ ...key, origin: scope.origin, action: scope.action }, scope.accountId);
496
+ }
497
+ async siteGrantScope(caller, scope) {
498
+ assertSiteAccessCaller(caller, scope.service);
499
+ const d = await this.scopedDevice(caller, scope);
500
+ return {
501
+ d,
502
+ key: {
503
+ orgId: d.orgId,
504
+ deviceId: d.deviceId,
505
+ rootConversationId: d.rootConversationId,
506
+ serviceId: deviceServiceId(caller.extension, scope.service),
507
+ },
508
+ };
509
+ }
460
510
  /**
461
511
  * Grants the scope conversation's root a local port of its device for one service (the owner's
462
512
  * click in the panel, source `owner-panel`): owner only, refused with `loopback_unavailable`
@@ -874,7 +924,8 @@ DeviceAccessService = __decorate([
874
924
  __param(11, Inject(ExtensionRegistry)),
875
925
  __param(12, Inject(TransactionHost)),
876
926
  __param(13, Inject(LoopbackGrants)),
877
- __param(14, Inject(ApprovalsService))
927
+ __param(14, Inject(ApprovalsService)),
928
+ __param(15, Inject(DeviceSiteGrants))
878
929
  ], DeviceAccessService);
879
930
  export { DeviceAccessService };
880
931
  /** A grant record as the extension sees it. */
@@ -903,6 +954,12 @@ function assertDeclared(caller, service) {
903
954
  if (!caller.services.includes(service))
904
955
  throw new DeviceAccessError("service_not_declared", `The device service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.services of ${caller.extension}.`);
905
956
  }
957
+ function assertSiteAccessCaller(caller, service) {
958
+ if (caller.siteAccess !== true || caller.superseded?.()) {
959
+ throw new DeviceAccessError("site_access_not_declared", "This extension does not have an active site access permission.");
960
+ }
961
+ assertDeclared(caller, service);
962
+ }
906
963
  function assertCallOwner(call) {
907
964
  if (call.ownerAccountId === undefined || call.accountId !== call.ownerAccountId)
908
965
  throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT);
@@ -0,0 +1,14 @@
1
+ import { type SiteAccessAction, type SiteAccessAsk } from "@capybara-hq/plugin-sdk";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ /** The request reported from a particular device service, bound to the call that sent it. */
4
+ export interface ReportedSiteAccess extends SiteAccessAsk {
5
+ extension: string;
6
+ serviceId: string;
7
+ deviceId: string;
8
+ }
9
+ export declare function isSiteAccessOrigin(origin: unknown): origin is string;
10
+ /** Refuse malformed requests before retaining any detail in the call or the approval. */
11
+ export declare function assertSiteAccessAction(action: SiteAccessAction, origin: string): void;
12
+ export declare const siteAccessDetailHash: (detail: string) => string;
13
+ /** Installed code can still be loaded after a deployment update. Bind to the desired package. */
14
+ export declare function siteAccessInstallActive(db: KernelSchemaDb, extension: string, sha256: string | null, lock?: boolean): Promise<boolean>;
@@ -0,0 +1,35 @@
1
+ import { createHash } from "node:crypto";
2
+ import { DeviceAccessError, isLoopbackGrantHost, SITE_ACCESS_ACTIONS, } from "@capybara-hq/plugin-sdk";
3
+ export function isSiteAccessOrigin(origin) {
4
+ if (typeof origin !== "string" || origin.length > 300)
5
+ return false;
6
+ try {
7
+ const parsed = new URL(origin);
8
+ return ((parsed.protocol === "https:" || parsed.protocol === "http:") &&
9
+ parsed.origin === origin &&
10
+ !isLoopbackGrantHost(parsed.hostname.replace(/^\[(.*)\]$/, "$1")));
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ /** Refuse malformed requests before retaining any detail in the call or the approval. */
17
+ export function assertSiteAccessAction(action, origin) {
18
+ if (!SITE_ACCESS_ACTIONS.includes(action) || !isSiteAccessOrigin(origin)) {
19
+ throw new DeviceAccessError("invalid_request", "Use a canonical HTTP(S) site origin and action.");
20
+ }
21
+ }
22
+ export const siteAccessDetailHash = (detail) => createHash("sha256").update(detail, "utf8").digest("hex");
23
+ /** Installed code can still be loaded after a deployment update. Bind to the desired package. */
24
+ export async function siteAccessInstallActive(db, extension, sha256, lock = false) {
25
+ let q = db
26
+ .selectFrom("extension_installs")
27
+ .select(["sha256", "desired_state"])
28
+ .where("name", "=", extension);
29
+ if (lock)
30
+ q = q.forShare();
31
+ const row = await q.executeTakeFirst();
32
+ return row === undefined
33
+ ? sha256 === null
34
+ : row.desired_state === "enabled" && row.sha256 === sha256;
35
+ }
@@ -0,0 +1,53 @@
1
+ import type { SiteAccessAction, SiteGrantView } from "@capybara-hq/plugin-sdk";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ export interface SiteGrantScope {
6
+ orgId: string;
7
+ deviceId: string;
8
+ /** The service id is `<extension>.<name>`. */
9
+ serviceId: string;
10
+ rootConversationId: string;
11
+ }
12
+ export interface SiteGrantKey extends SiteGrantScope {
13
+ origin: string;
14
+ action: SiteAccessAction;
15
+ }
16
+ /** Call in the deleting transaction, after locking the conversation. */
17
+ export declare function revokeSiteGrantsOfConversation(db: KernelSchemaDb, scope: {
18
+ orgId: string;
19
+ rootConversationId: string;
20
+ }): Promise<void>;
21
+ /** Call in the transaction that deletes the device, including its owner's offboarding. */
22
+ export declare function revokeSiteGrantsOfDevice(db: KernelSchemaDb, scope: {
23
+ orgId: string;
24
+ deviceId: string;
25
+ }): Promise<void>;
26
+ /** Call in the transaction disabling the extension in the org or removing its permission. */
27
+ export declare function revokeSiteGrantsOfExtension(db: KernelSchemaDb, scope: {
28
+ orgId: string;
29
+ extensionName: string;
30
+ }): Promise<void>;
31
+ /** Revoke an extension's grants when deployment state or its approved capability changes. */
32
+ export declare function revokeSiteGrantsOfExtensionEverywhere(db: KernelSchemaDb, extensionName: string): Promise<void>;
33
+ /** PostgreSQL is the only grant store. A device gets the live set with one request. */
34
+ export declare class DeviceSiteGrants {
35
+ private readonly db;
36
+ readonly txHost: TransactionHost;
37
+ constructor(db: KernelDb, txHost: TransactionHost);
38
+ /** Callers resolve the root and check the owner, service permission and attended status. */
39
+ liveForRoot(scope: SiteGrantScope): Promise<SiteGrantView[]>;
40
+ /** Advisory offer for an approval card; issuance rechecks the cap under the root row lock. */
41
+ canGrant(key: SiteGrantKey): Promise<boolean>;
42
+ /** Joins the human approval transaction. A full root can still approve the current call once. */
43
+ grantIn(key: SiteGrantKey, by: {
44
+ approvalId: string;
45
+ actorAccountId: string;
46
+ }): Promise<SiteGrantView | null>;
47
+ revoke(key: SiteGrantKey, actorAccountId: string): Promise<void>;
48
+ /** Expiry is enforced on reads; maintenance only removes old records. */
49
+ purgeEnded(): Promise<number>;
50
+ private purgeEndedIn;
51
+ private liveRootQuery;
52
+ private lockOwnedRoot;
53
+ }
@@ -0,0 +1,268 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomUUID } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { ApiError } from "../errors.js";
14
+ import { audit } from "../identity/audit.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { asPlatform } from "../infra/database/org-scope.js";
17
+ import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ const MAX_SITE_GRANTS_PER_ROOT = 20;
20
+ const SITE_GRANT_TTL_HOURS = 24;
21
+ const ENDED_RETENTION_DAYS = 30;
22
+ const PURGE_BATCH = 500;
23
+ function viewOf(row) {
24
+ return {
25
+ origin: row.origin,
26
+ action: row.action,
27
+ source: "human",
28
+ expiresAt: row.expires_at.toISOString(),
29
+ };
30
+ }
31
+ function tupleOf(key) {
32
+ return {
33
+ org_id: key.orgId,
34
+ device_id: key.deviceId,
35
+ service_id: key.serviceId,
36
+ conversation_id: key.rootConversationId,
37
+ origin: key.origin,
38
+ action: key.action,
39
+ };
40
+ }
41
+ /** Call in the deleting transaction, after locking the conversation. */
42
+ export function revokeSiteGrantsOfConversation(db, scope) {
43
+ return revokeGrants(db, { ...scope, reason: "conversation-deleted" });
44
+ }
45
+ /** Call in the transaction that deletes the device, including its owner's offboarding. */
46
+ export function revokeSiteGrantsOfDevice(db, scope) {
47
+ return revokeGrants(db, { ...scope, reason: "device-deleted" });
48
+ }
49
+ /** Call in the transaction disabling the extension in the org or removing its permission. */
50
+ export function revokeSiteGrantsOfExtension(db, scope) {
51
+ return revokeGrants(db, { ...scope, reason: "extension-unavailable" });
52
+ }
53
+ /** Revoke an extension's grants when deployment state or its approved capability changes. */
54
+ export async function revokeSiteGrantsOfExtensionEverywhere(db, extensionName) {
55
+ await asPlatform("revoke site grants for a deployment extension change", async () => {
56
+ // org-filter: deployment-wide extension changes affect its grants in every organization
57
+ const orgs = await db
58
+ .selectFrom("device_site_grants")
59
+ .select("org_id")
60
+ .distinct()
61
+ .where(sql `starts_with(service_id, ${`${extensionName}.`})`)
62
+ .where("revoked_at", "is", null)
63
+ .execute();
64
+ for (const { org_id: orgId } of orgs) {
65
+ await revokeSiteGrantsOfExtension(db, { orgId, extensionName });
66
+ }
67
+ });
68
+ }
69
+ async function revokeGrants(db, change) {
70
+ let update = db
71
+ .updateTable("device_site_grants")
72
+ .set({ revoked_at: sql `now()` })
73
+ .where("org_id", "=", change.orgId)
74
+ .where("revoked_at", "is", null)
75
+ .where("expires_at", ">", sql `now()`);
76
+ switch (change.reason) {
77
+ case "conversation-deleted":
78
+ update = update.where("conversation_id", "=", change.rootConversationId);
79
+ break;
80
+ case "device-deleted":
81
+ update = update.where("device_id", "=", change.deviceId);
82
+ break;
83
+ case "extension-unavailable":
84
+ update = update.where(sql `starts_with(service_id, ${`${change.extensionName}.`})`);
85
+ break;
86
+ case "owner-revoked":
87
+ update = update.where((eb) => eb.and(tupleOf(change.key)));
88
+ break;
89
+ }
90
+ const rows = await update
91
+ .returning(["id", "device_id", "service_id", "conversation_id", "origin", "action"])
92
+ .execute();
93
+ for (const row of rows) {
94
+ await audit(db, {
95
+ actorAccountId: change.reason === "owner-revoked" ? change.actorAccountId : null,
96
+ orgId: change.orgId,
97
+ action: "device.site_revoked",
98
+ target: row.device_id,
99
+ detail: {
100
+ grantId: row.id,
101
+ deviceId: row.device_id,
102
+ serviceId: row.service_id,
103
+ conversationId: row.conversation_id,
104
+ origin: row.origin,
105
+ action: row.action,
106
+ reason: change.reason,
107
+ },
108
+ });
109
+ }
110
+ }
111
+ /** PostgreSQL is the only grant store. A device gets the live set with one request. */
112
+ let DeviceSiteGrants = class DeviceSiteGrants {
113
+ db;
114
+ txHost;
115
+ constructor(db, txHost) {
116
+ this.db = db;
117
+ this.txHost = txHost;
118
+ }
119
+ /** Callers resolve the root and check the owner, service permission and attended status. */
120
+ async liveForRoot(scope) {
121
+ const rows = await this.liveRootQuery(scope)
122
+ .where("device_id", "=", scope.deviceId)
123
+ .where("service_id", "=", scope.serviceId)
124
+ .select(["origin", "action", "expires_at"])
125
+ .orderBy("origin")
126
+ .orderBy("action")
127
+ .execute();
128
+ return rows.map(viewOf);
129
+ }
130
+ /** Advisory offer for an approval card; issuance rechecks the cap under the root row lock. */
131
+ async canGrant(key) {
132
+ const rows = await this.liveRootQuery(key)
133
+ .select(["device_id", "service_id", "origin", "action"])
134
+ .execute();
135
+ return (rows.length < MAX_SITE_GRANTS_PER_ROOT ||
136
+ rows.some((row) => row.device_id === key.deviceId &&
137
+ row.service_id === key.serviceId &&
138
+ row.origin === key.origin &&
139
+ row.action === key.action));
140
+ }
141
+ /** Joins the human approval transaction. A full root can still approve the current call once. */
142
+ async grantIn(key, by) {
143
+ await this.lockOwnedRoot(key, by.actorAccountId);
144
+ const existing = await this.liveRootQuery(key)
145
+ .where((eb) => eb.and(tupleOf(key)))
146
+ .select(["origin", "action", "expires_at"])
147
+ .executeTakeFirst();
148
+ if (existing)
149
+ return viewOf(existing);
150
+ if (!(await this.canGrant(key)))
151
+ return null;
152
+ // Retire an expired row of this tuple to free its partial unique index entry.
153
+ await this.db
154
+ .updateTable("device_site_grants")
155
+ .set({ revoked_at: sql `expires_at` })
156
+ .where("org_id", "=", key.orgId)
157
+ .where((eb) => eb.and(tupleOf(key)))
158
+ .where("revoked_at", "is", null)
159
+ .where("expires_at", "<=", sql `now()`)
160
+ .execute();
161
+ const row = await this.db
162
+ .insertInto("device_site_grants")
163
+ .values({
164
+ ...tupleOf(key),
165
+ id: randomUUID(),
166
+ approval_id: by.approvalId,
167
+ expires_at: sql `now() + make_interval(hours => ${SITE_GRANT_TTL_HOURS})`,
168
+ })
169
+ .onConflict((oc) => oc.column("approval_id").doNothing())
170
+ .returning(["id", "origin", "action", "expires_at"])
171
+ .executeTakeFirst();
172
+ if (!row)
173
+ return null;
174
+ const view = viewOf(row);
175
+ await audit(this.db.db, {
176
+ actorAccountId: by.actorAccountId,
177
+ orgId: key.orgId,
178
+ action: "device.site_granted",
179
+ target: key.deviceId,
180
+ detail: {
181
+ ...view,
182
+ grantId: row.id,
183
+ deviceId: key.deviceId,
184
+ serviceId: key.serviceId,
185
+ conversationId: key.rootConversationId,
186
+ approvalId: by.approvalId,
187
+ },
188
+ });
189
+ return view;
190
+ }
191
+ async revoke(key, actorAccountId) {
192
+ await this.lockOwnedRoot(key, actorAccountId);
193
+ await revokeGrants(this.db.db, {
194
+ orgId: key.orgId,
195
+ key,
196
+ actorAccountId,
197
+ reason: "owner-revoked",
198
+ });
199
+ }
200
+ /** Expiry is enforced on reads; maintenance only removes old records. */
201
+ purgeEnded() {
202
+ return asPlatform("site grant retention sweep", () => this.purgeEndedIn());
203
+ }
204
+ async purgeEndedIn() {
205
+ const ended = sql `least(expires_at, revoked_at)`;
206
+ // org-filter: the retention sweep over every org's ended grants, entered under asPlatform by
207
+ // purgeEnded; the rows are already excluded from authorization reads
208
+ const { numDeletedRows } = await this.db
209
+ .deleteFrom("device_site_grants")
210
+ .where("id", "in", (qb) => qb
211
+ .selectFrom("device_site_grants")
212
+ .select("id")
213
+ .where(ended, "<=", sql `now() - make_interval(days => ${ENDED_RETENTION_DAYS})`)
214
+ .orderBy(ended)
215
+ .orderBy("id")
216
+ .limit(PURGE_BATCH)
217
+ .forUpdate()
218
+ .skipLocked())
219
+ .executeTakeFirstOrThrow();
220
+ return Number(numDeletedRows);
221
+ }
222
+ liveRootQuery(scope) {
223
+ return this.db
224
+ .selectFrom("device_site_grants")
225
+ .where("org_id", "=", scope.orgId)
226
+ .where("conversation_id", "=", scope.rootConversationId)
227
+ .where("revoked_at", "is", null)
228
+ .where("expires_at", ">", sql `now()`);
229
+ }
230
+ async lockOwnedRoot(scope, actorAccountId) {
231
+ // The run fence and deletion also take the root row before touching grants. This serializes
232
+ // the live count across services, and a root deleted while issuance waited is refused.
233
+ const root = await this.db
234
+ .selectFrom("conversations")
235
+ .innerJoin("devices", (join) => join
236
+ .onRef("devices.id", "=", "conversations.device_id")
237
+ .onRef("devices.org_id", "=", "conversations.org_id"))
238
+ .select("conversations.id")
239
+ .where("conversations.org_id", "=", scope.orgId)
240
+ .where("conversations.id", "=", scope.rootConversationId)
241
+ .where("conversations.device_id", "=", scope.deviceId)
242
+ .where("conversations.account_id", "=", actorAccountId)
243
+ .where("conversations.parent_conversation_id", "is", null)
244
+ .where("conversations.deleted_at", "is", null)
245
+ .where("devices.owner_kind", "=", "personal")
246
+ .where("devices.owner_account_id", "=", actorAccountId)
247
+ .where("devices.deleted_at", "is", null)
248
+ .forNoKeyUpdate("conversations")
249
+ .executeTakeFirst();
250
+ if (!root)
251
+ throw new ApiError("conversation.not_found", "The owner's conversation or personal device is unavailable");
252
+ }
253
+ };
254
+ __decorate([
255
+ Transactional({ propagation: "mandatory" })
256
+ ], DeviceSiteGrants.prototype, "grantIn", null);
257
+ __decorate([
258
+ Transactional()
259
+ ], DeviceSiteGrants.prototype, "revoke", null);
260
+ __decorate([
261
+ Transactional()
262
+ ], DeviceSiteGrants.prototype, "purgeEndedIn", null);
263
+ DeviceSiteGrants = __decorate([
264
+ Injectable(),
265
+ __param(0, Inject(KernelDb)),
266
+ __param(1, Inject(TransactionHost))
267
+ ], DeviceSiteGrants);
268
+ export { DeviceSiteGrants };
@@ -0,0 +1,2 @@
1
+ export declare class DeviceSiteGrantsModule {
2
+ }
@@ -0,0 +1,14 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { DeviceSiteGrants } from "./site-grants.js";
9
+ let DeviceSiteGrantsModule = class DeviceSiteGrantsModule {
10
+ };
11
+ DeviceSiteGrantsModule = __decorate([
12
+ Module({ providers: [DeviceSiteGrants], exports: [DeviceSiteGrants] })
13
+ ], DeviceSiteGrantsModule);
14
+ export { DeviceSiteGrantsModule };