@capybara-hq/kernel 0.1.0-rc.118 → 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 (52) hide show
  1. package/dist/automations/unattended.d.ts +2 -0
  2. package/dist/automations/unattended.js +10 -3
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/cards.d.ts +2 -4
  5. package/dist/channels/cards.js +11 -6
  6. package/dist/channels/phrases.d.ts +4 -0
  7. package/dist/channels/phrases.js +1 -0
  8. package/dist/conversations/conversations.service.js +2 -0
  9. package/dist/conversations/events.d.ts +26 -0
  10. package/dist/conversations/events.js +27 -4
  11. package/dist/ctx/create-ctx.d.ts +1 -1
  12. package/dist/ctx/create-ctx.js +4 -0
  13. package/dist/db/kernel-schema.d.ts +17 -1
  14. package/dist/device-access/device-access.module.js +2 -0
  15. package/dist/device-access/device-access.service.d.ts +16 -2
  16. package/dist/device-access/device-access.service.js +59 -2
  17. package/dist/device-access/site-access-request.d.ts +14 -0
  18. package/dist/device-access/site-access-request.js +35 -0
  19. package/dist/device-access/site-grants.d.ts +53 -0
  20. package/dist/device-access/site-grants.js +268 -0
  21. package/dist/device-access/site-grants.module.d.ts +2 -0
  22. package/dist/device-access/site-grants.module.js +14 -0
  23. package/dist/devices/devices.service.js +2 -0
  24. package/dist/extensions/admin-ops.js +7 -0
  25. package/dist/extensions/org-config.js +4 -0
  26. package/dist/extensions/permission-set.d.ts +3 -0
  27. package/dist/extensions/permission-set.js +5 -0
  28. package/dist/extensions/permission-view.d.ts +1 -1
  29. package/dist/extensions/permission-view.js +7 -1
  30. package/dist/orgs/offboarding.js +2 -0
  31. package/dist/roles/worker.module.js +2 -0
  32. package/dist/sandbox/loopback-expiry.job.d.ts +3 -1
  33. package/dist/sandbox/loopback-expiry.job.js +9 -3
  34. package/dist/sandbox/operation-authority.d.ts +1 -1
  35. package/dist/sandbox/operation-authority.js +14 -6
  36. package/dist/sandbox/permission-call-types.d.ts +2 -2
  37. package/dist/sandbox/review/classifier.d.ts +13 -4
  38. package/dist/sandbox/review/classifier.js +73 -22
  39. package/dist/sandbox/review/permission-candidate.d.ts +3 -3
  40. package/dist/sandbox/review/permission-candidate.js +10 -8
  41. package/dist/sandbox/review/review.service.d.ts +26 -19
  42. package/dist/sandbox/review/review.service.js +69 -15
  43. package/dist/tools/approvals.service.d.ts +30 -4
  44. package/dist/tools/approvals.service.js +143 -12
  45. package/dist/tools/call-scope.d.ts +3 -0
  46. package/dist/tools/call-scope.js +1 -0
  47. package/dist/tools/network-asks.js +7 -0
  48. package/dist/tools/pipeline.d.ts +16 -5
  49. package/dist/tools/pipeline.js +314 -11
  50. package/dist/tools/tools.module.js +2 -0
  51. package/package.json +2 -2
  52. package/src/migrations/0205_device_site_grants.sql +30 -0
@@ -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 };
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { pluginDescription, validateAllowHost, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { revokeSiteGrantsOfDevice } from "../device-access/site-grants.js";
14
15
  import { DialInHandlers } from "../dial-in/handlers.js";
15
16
  import { DialInMachines } from "../dial-in/machines.js";
16
17
  import { DialInRelay } from "../dial-in/relay.js";
@@ -678,6 +679,7 @@ let DevicesService = class DevicesService {
678
679
  await this.machines.revokeActive(id, "deleted");
679
680
  // its loopback port grants end with it (browser loopback port grants design §4)
680
681
  await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: id });
682
+ await revokeSiteGrantsOfDevice(this.db.db, { orgId, deviceId: id });
681
683
  await audit(this.db.db, {
682
684
  actorAccountId: accountId,
683
685
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -14,6 +14,7 @@ import semver from "semver";
14
14
  import { itemRemovedError } from "../catalog/ownership.js";
15
15
  import { oweDeployedExtensionSync } from "../catalog/scope-jobs.js";
16
16
  import { pluginSchemaName } from "../ctx/create-ctx.js";
17
+ import { revokeSiteGrantsOfExtensionEverywhere } from "../device-access/site-grants.js";
17
18
  import { ApiError } from "../errors.js";
18
19
  import { audit } from "../identity/audit.js";
19
20
  import { SuperAdminLock } from "../identity/super-admin.js";
@@ -282,6 +283,10 @@ let ExtensionAdminOps = class ExtensionAdminOps {
282
283
  updated_at: sql `now()`,
283
284
  }))
284
285
  .execute();
286
+ if (leftDisabled !== undefined ||
287
+ target.section.manifest.permissions?.deviceAccess?.siteAccess !== true) {
288
+ await revokeSiteGrantsOfExtensionEverywhere(db, name);
289
+ }
285
290
  await this.audit(actor, actorTokenId, "extension.installed", name, pkg.version, sha256, {
286
291
  catalogItemId,
287
292
  ...ownerDetail(opts.owner),
@@ -401,6 +406,8 @@ let ExtensionAdminOps = class ExtensionAdminOps {
401
406
  })
402
407
  .where("name", "=", name)
403
408
  .execute();
409
+ if (state === "disabled")
410
+ await revokeSiteGrantsOfExtensionEverywhere(db, name);
404
411
  await this.audit(actor, actorTokenId, state === "enabled" ? "extension.enabled" : "extension.disabled", name, row.version, row.sha256, { ...ownerDetail(owner), ...auditDetail });
405
412
  afterCommit(() => this.notify(name));
406
413
  // The enable is the deploy: it owes its plugin's scope sync, which installs it where its scope
@@ -11,6 +11,7 @@ import { EXTENSION_POINTS, parseExtensionPoint, } from "@capybara-hq/plugin-sdk"
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { assertItemInstallable, assertPluginSourcesInstallable, disabledPluginItems, pluginItemDisabled, } from "../catalog/request-rules.js";
13
13
  import { oweTemplateConnectors } from "../catalog/template-connector-jobs.js";
14
+ import { revokeSiteGrantsOfExtension } from "../device-access/site-grants.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { audit } from "../identity/audit.js";
16
17
  import { afterCommit } from "../infra/database/after-commit.js";
@@ -262,6 +263,8 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
262
263
  updated_at: new Date(),
263
264
  }))
264
265
  .execute();
266
+ if (!enabled)
267
+ await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
265
268
  // Switched on: it may provide the connector kind of a template whose plugin is installed in
266
269
  // the org without its connector; a worker creates the connectors it never had, once the
267
270
  // extension is loaded there (ruling R27)
@@ -380,6 +383,7 @@ let OrgExtensionConfigs = class OrgExtensionConfigs {
380
383
  .executeTakeFirst();
381
384
  if (!r)
382
385
  return false;
386
+ await revokeSiteGrantsOfExtension(t, { orgId, extensionName: plugin });
383
387
  await audit(t, {
384
388
  actorAccountId,
385
389
  orgId,
@@ -80,6 +80,7 @@ export interface PermissionSet {
80
80
  deviceAccess?: {
81
81
  services: string[];
82
82
  loopbackPorts?: true;
83
+ siteAccess?: true;
83
84
  };
84
85
  /**
85
86
  * The event types the extension may emit (`permissions.triggers.emit`, collaboration spec
@@ -187,6 +188,8 @@ export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
187
188
  * upgrade without approval again. Recorded only when declared.
188
189
  */
189
190
  export declare const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
191
+ /** Blocking permission for profile decisions on non-loopback site actions. */
192
+ export declare const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
190
193
  /**
191
194
  * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
192
195
  * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
@@ -123,6 +123,7 @@ export function buildPermissionSet(input) {
123
123
  deviceAccess: {
124
124
  services: sortedUnique(p.deviceAccess.services),
125
125
  ...(p.deviceAccess.loopbackPorts === true && { loopbackPorts: true }),
126
+ ...(p.deviceAccess.siteAccess === true && { siteAccess: true }),
126
127
  },
127
128
  }
128
129
  : {}),
@@ -197,6 +198,8 @@ export function permissionKeys(set) {
197
198
  keys.push(`${DEVICE_ACCESS_KEY_PREFIX}${svc}`);
198
199
  if (p.deviceAccess?.loopbackPorts === true)
199
200
  keys.push(DEVICE_LOOPBACK_PORTS_KEY);
201
+ if (p.deviceAccess?.siteAccess === true)
202
+ keys.push(DEVICE_SITE_ACCESS_KEY);
200
203
  for (const t of p.triggers?.emit ?? [])
201
204
  keys.push(`${TRIGGERS_KEY_PREFIX}${t}`);
202
205
  if (p.inbox === true)
@@ -238,6 +241,8 @@ export const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
238
241
  * upgrade without approval again. Recorded only when declared.
239
242
  */
240
243
  export const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
244
+ /** Blocking permission for profile decisions on non-loopback site actions. */
245
+ export const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
241
246
  /**
242
247
  * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
243
248
  * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
@@ -34,7 +34,7 @@ export interface PermissionGroup {
34
34
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
35
35
  * `-` replaced by `_`).
36
36
  */
37
- export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "device_loopback_ports" | "migration_warnings";
37
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "device_provider" | "object_store" | "context" | "push_provider" | "device_access" | "device_loopback_ports" | "device_site_access" | "migration_warnings";
38
38
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
39
39
  export interface PermissionItem {
40
40
  value: string;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { pluginSchemaName } from "../ctx/create-ctx.js";
3
3
  import { isDestructiveSql, splitSqlStatements } from "../db/sql-statements.js";
4
- import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
4
+ import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_LOOPBACK_PORTS_KEY, DEVICE_SITE_ACCESS_KEY, DIAL_IN_KEY_PREFIX, INBOX_KEY, PEOPLE_KEY, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
5
5
  /**
6
6
  * Review digest: the first 16 hex digits of `sha256(permissionKeys(set).join("\n"))`; with migration
7
7
  * warnings their digest (kind, file, line and statement) is folded in, without warnings it equals the
@@ -42,6 +42,7 @@ export const SENSITIVE_EXTENSION_POINTS = [
42
42
  const CLIENT_ITEM = "client code";
43
43
  /** The "deviceAccess" group's item of loopback port grants (`permissions.deviceAccess.loopbackPorts`). */
44
44
  const LOOPBACK_PORTS_ITEM = "local ports on the device (loopback)";
45
+ const SITE_ACCESS_ITEM = "profile-approved actions on websites";
45
46
  /** The one item of the "inbox" group (collaboration spec §4.9). */
46
47
  const INBOX_ITEM = "personal inbox items";
47
48
  /** The items of the read-only org fact groups. */
@@ -89,6 +90,8 @@ function itemReason(category, item) {
89
90
  }
90
91
  if (category === "deviceAccess" && item === LOOPBACK_PORTS_ITEM)
91
92
  return "device_loopback_ports";
93
+ if (category === "deviceAccess" && item === SITE_ACCESS_ITEM)
94
+ return "device_site_access";
92
95
  return ALWAYS_SENSITIVE.has(category) ? CATEGORY_REASON[category] : undefined;
93
96
  }
94
97
  /** Routes of the `http` group: member and admin (the kernel authenticates a person). */
@@ -109,6 +112,8 @@ function keyItem(key) {
109
112
  return { category: "inbox", item: INBOX_ITEM };
110
113
  if (key === DEVICE_LOOPBACK_PORTS_KEY)
111
114
  return { category: "deviceAccess", item: LOOPBACK_PORTS_ITEM };
115
+ if (key === DEVICE_SITE_ACCESS_KEY)
116
+ return { category: "deviceAccess", item: SITE_ACCESS_ITEM };
112
117
  if (key === AGENTS_KEY)
113
118
  return { category: "agents", item: AGENTS_ITEM };
114
119
  if (key === CONVERSATIONS_KEY)
@@ -214,6 +219,7 @@ export function permissionGroups(set) {
214
219
  items: [
215
220
  ...(p.deviceAccess?.services ?? []),
216
221
  ...(p.deviceAccess?.loopbackPorts === true ? [LOOPBACK_PORTS_ITEM] : []),
222
+ ...(p.deviceAccess?.siteAccess === true ? [SITE_ACCESS_ITEM] : []),
217
223
  ],
218
224
  },
219
225
  // the event types it emits for the orgs' event automations (not sensitive)
@@ -13,6 +13,7 @@ import { sql } from "kysely";
13
13
  import { retargetSetupRequests } from "../agents/pending-connector-requests.js";
14
14
  import { EventLog } from "../conversations/event-log.js";
15
15
  import { lockConversationTrees } from "../conversations/tree.js";
16
+ import { revokeSiteGrantsOfDevice } from "../device-access/site-grants.js";
16
17
  import { ApiError } from "../errors.js";
17
18
  import { enabledExtensionsQuery } from "../extensions/enabled.js";
18
19
  import { LifecycleHooks } from "../extensions/lifecycle-hooks.js";
@@ -319,6 +320,7 @@ let Offboarding = class Offboarding {
319
320
  await oweDeviceDestroy(this.outbox, d.id, orgId);
320
321
  // its loopback port grants end with it (browser loopback port grants design §4)
321
322
  await revokeLoopbackGrantsOfDevice(this.db.db, this.outbox, { orgId, deviceId: d.id });
323
+ await revokeSiteGrantsOfDevice(this.db.db, { orgId, deviceId: d.id });
322
324
  }
323
325
  await this.db
324
326
  .deleteFrom("device_defaults")
@@ -24,6 +24,7 @@ import { EventLogModule } from "../conversations/event-log.js";
24
24
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
25
25
  import { TitlesModule } from "../conversations/titles.js";
26
26
  import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
27
+ import { DeviceSiteGrantsModule } from "../device-access/site-grants.module.js";
27
28
  import { LegacySandboxCleanupJob } from "../devices/legacy-cleanup.job.js";
28
29
  import { EvalWorkersModule } from "../evals/evals.module.js";
29
30
  import { ExtensionsModule } from "../extensions/extensions.module.js";
@@ -75,6 +76,7 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
75
76
  return {
76
77
  module: WorkerModule_1,
77
78
  imports: [
79
+ DeviceSiteGrantsModule,
78
80
  KernelScheduleModule,
79
81
  // the outbox relay (`@LockedInterval`): delivers what the fast path did not
80
82
  OutboxRelayModule,
@@ -1,3 +1,4 @@
1
+ import { DeviceSiteGrants } from "../device-access/site-grants.js";
1
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
3
  import { LockService } from "../infra/lock/lock.service.js";
3
4
  import type { KernelLogger } from "../log.js";
@@ -16,6 +17,7 @@ export declare class LoopbackExpiryJob {
16
17
  readonly config: KernelConfigService;
17
18
  readonly lockService: LockService;
18
19
  readonly log: KernelLogger;
19
- constructor(grants: Pick<LoopbackGrants, "expireDue">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
20
+ private readonly site?;
21
+ constructor(grants: Pick<LoopbackGrants, "expireDue">, config: KernelConfigService, lockService: LockService, log: KernelLogger, site?: DeviceSiteGrants | undefined);
20
22
  expire(): Promise<void>;
21
23
  }
@@ -7,7 +7,8 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Inject, Injectable } from "@nestjs/common";
10
+ import { Inject, Injectable, Optional } from "@nestjs/common";
11
+ import { DeviceSiteGrants } from "../device-access/site-grants.js";
11
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
13
  import { LockService } from "../infra/lock/lock.service.js";
13
14
  import { LockedInterval } from "../infra/schedule/locked-interval.js";
@@ -27,14 +28,17 @@ let LoopbackExpiryJob = class LoopbackExpiryJob {
27
28
  config;
28
29
  lockService;
29
30
  log;
30
- constructor(grants, config, lockService, log) {
31
+ site;
32
+ constructor(grants, config, lockService, log, site) {
31
33
  this.grants = grants;
32
34
  this.config = config;
33
35
  this.lockService = lockService;
34
36
  this.log = log;
37
+ this.site = site;
35
38
  }
36
39
  async expire() {
37
40
  await this.grants.expireDue();
41
+ await this.site?.purgeEnded();
38
42
  }
39
43
  };
40
44
  __decorate([
@@ -45,6 +49,8 @@ LoopbackExpiryJob = __decorate([
45
49
  __param(0, Inject(LoopbackGrants)),
46
50
  __param(1, Inject(KernelConfigService)),
47
51
  __param(2, Inject(LockService)),
48
- __param(3, Inject(KERNEL_LOGGER))
52
+ __param(3, Inject(KERNEL_LOGGER)),
53
+ __param(4, Optional()),
54
+ __param(4, Inject(DeviceSiteGrants))
49
55
  ], LoopbackExpiryJob);
50
56
  export { LoopbackExpiryJob };
@@ -91,7 +91,7 @@ export declare class SandboxOperationAuthority {
91
91
  deviceId: string;
92
92
  rootConversationId: string;
93
93
  }>;
94
- previewCall(ctx: SandboxUseContext, call: PermissionCallRef, signal: AbortSignal): Promise<PermissionReviewSnapshot>;
94
+ previewCall(ctx: SandboxUseContext, call: PermissionCallRef, signal: AbortSignal, crossing?: "site-access"): Promise<PermissionReviewSnapshot>;
95
95
  private previewLocked;
96
96
  resolve(ctx: SandboxUseContext, operation: SandboxAuthorityOperation, signal: AbortSignal): Promise<SandboxOperationScope>;
97
97
  resolveInvocation(ctx: SandboxUseContext, operation: SandboxAuthorityOperation, call: PermissionCallRef, signal: AbortSignal): Promise<{
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { instanceSupported, parseSandboxBrowseScope, parseSandboxOperationScope, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
+ import { hasUnattendedTaskRun } from "../automations/unattended.js";
14
15
  import { ACTOR_DEVICE_ACCESS_REASON, ACTOR_NOT_DEVICE_OWNER_REASON, PermissionContextV2Schema, permissionCodePointCompare, } from "../conversations/events.js";
15
16
  import { PermissionProfileStore, } from "../conversations/permission-profile-store.js";
16
17
  import { canonicalRoot, workingRootOf as reviewWorkingRootOf } from "../devices/working-root.js";
@@ -201,12 +202,12 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
201
202
  const root = await this.profiles.readOwnedRoot(ctx.orgId, ctx.holderConversationId, ctx.actor.accountId);
202
203
  return { orgId: ctx.orgId, deviceId: ctx.deviceId, rootConversationId: root.id };
203
204
  }
204
- async previewCall(ctx, call, signal) {
205
+ async previewCall(ctx, call, signal, crossing) {
205
206
  const subject = await this.subjectFor(ctx);
206
- return withTransactionFencePrelude(() => this.locks.acquire(subject, { kind: "admit" }), () => this.previewLocked(ctx, call, signal));
207
+ return withTransactionFencePrelude(() => this.locks.acquire(subject, { kind: "admit" }), () => this.previewLocked(ctx, call, signal, crossing));
207
208
  }
208
- async previewLocked(ctx, call, signal) {
209
- const snapshot = await this.snapshot(ctx, call, signal);
209
+ async previewLocked(ctx, call, signal, crossing) {
210
+ const snapshot = await this.snapshot(ctx, call, signal, undefined, crossing === undefined ? {} : { crossing });
210
211
  const messages = await this.db
211
212
  .selectFrom("conversation_events")
212
213
  .select("payload")
@@ -472,8 +473,15 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
472
473
  throw new ApiError("device.not_found", "The conversation is not bound to this device");
473
474
  await this.facts.preview(ctx.orgId, ctx.actor.accountId, ctx.deviceId, root.project_name ?? undefined);
474
475
  let unattended = root.automation_id !== null;
475
- if (ctx.actor.runId)
476
- unattended ||= await this.runScheduledLocked(ctx.holderConversationId, ctx.actor.accountId, ctx.actor.runId);
476
+ if (ctx.actor.runId && !unattended) {
477
+ const scheduled = await this.runScheduledLocked(ctx.holderConversationId, ctx.actor.accountId, ctx.actor.runId);
478
+ // Attended site actions use the root's profile even after a person joins a scheduled run.
479
+ // Sandbox operation admission keeps its stricter scheduled-run policy.
480
+ unattended =
481
+ scheduled &&
482
+ (opts.crossing !== "site-access" ||
483
+ (await hasUnattendedTaskRun(this.db.db, ctx.actor.runId)));
484
+ }
477
485
  const base = await this.baseScopeLocked({
478
486
  orgId: ctx.orgId,
479
487
  deviceId: ctx.deviceId,
@@ -57,9 +57,9 @@ export type PermissionGrantSource = PermissionGrantDecision["source"];
57
57
  /**
58
58
  * The kind of one boundary crossing, as `ReviewRecord.crossing` records it: a directory outside the
59
59
  * scope, a new host on an allowlist, running one call outside the sandbox, a sensitive command, or
60
- * a device service (the browser) reaching one loopback port on the person's own device.
60
+ * a device service reaching one loopback port or acting on a site using the person's browser session.
61
61
  */
62
- export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive" | "loopback-port";
62
+ export type PermissionCrossingKind = "directory" | "host" | "outside-sandbox" | "sensitive" | "loopback-port" | "site-access";
63
63
  /**
64
64
  * What a call grant authorizes: an exact directory and host expansion of the restricted scope, or
65
65
  * one Bash call run outside the OS sandbox (per-call sandbox escalation: full execution for that