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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +3 -4
  20. package/dist/catalog/plugin-import.js +50 -1
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.js +1 -1
  28. package/dist/conversations/conversations.controller.js +4 -14
  29. package/dist/conversations/conversations.service.d.ts +14 -0
  30. package/dist/conversations/conversations.service.js +20 -2
  31. package/dist/ctx/create-ctx.d.ts +11 -2
  32. package/dist/ctx/create-ctx.js +121 -52
  33. package/dist/ctx/queue.js +7 -4
  34. package/dist/db/extension-rls-predicate.d.ts +1 -0
  35. package/dist/db/extension-rls-predicate.js +8 -0
  36. package/dist/db/kernel-schema.d.ts +48 -0
  37. package/dist/db/migrator.js +6 -13
  38. package/dist/db/pool.d.ts +2 -2
  39. package/dist/db/pool.js +2 -2
  40. package/dist/db/sql-statements.d.ts +3 -0
  41. package/dist/db/sql-statements.js +15 -5
  42. package/dist/device-access/device-access.module.js +12 -2
  43. package/dist/device-access/device-access.service.d.ts +30 -2
  44. package/dist/device-access/device-access.service.js +38 -4
  45. package/dist/device-access/host-gate.d.ts +45 -0
  46. package/dist/device-access/host-gate.js +92 -0
  47. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  48. package/dist/device-access/host-service-stop-sweep.js +112 -0
  49. package/dist/device-access/host-service-stop.d.ts +78 -0
  50. package/dist/device-access/host-service-stop.js +144 -0
  51. package/dist/device-access/host-services.d.ts +211 -0
  52. package/dist/device-access/host-services.js +803 -0
  53. package/dist/device-access/person-handles.d.ts +10 -0
  54. package/dist/device-access/person-handles.js +25 -0
  55. package/dist/device-access/service-events.d.ts +199 -0
  56. package/dist/device-access/service-events.js +704 -0
  57. package/dist/device-access/token.d.ts +5 -0
  58. package/dist/device-access/token.js +5 -0
  59. package/dist/devices/devices.service.js +3 -0
  60. package/dist/dial-in/access.d.ts +5 -5
  61. package/dist/dial-in/access.js +19 -12
  62. package/dist/dial-in/gateway.js +6 -2
  63. package/dist/dial-in/machines.d.ts +9 -2
  64. package/dist/dial-in/machines.js +27 -4
  65. package/dist/erasure/device-cleanup.js +12 -0
  66. package/dist/erasure/org-catalog.js +2 -2
  67. package/dist/erasure/org-rules.js +9 -0
  68. package/dist/errors.d.ts +2 -0
  69. package/dist/errors.js +2 -0
  70. package/dist/extensions/admin-ops.js +8 -2
  71. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  72. package/dist/extensions/deployed-snapshots.js +7 -2
  73. package/dist/extensions/host.d.ts +7 -2
  74. package/dist/extensions/host.js +11 -2
  75. package/dist/extensions/instance.d.ts +3 -0
  76. package/dist/extensions/instance.js +4 -0
  77. package/dist/extensions/ledger.d.ts +1 -1
  78. package/dist/extensions/lifecycle-hooks.js +3 -3
  79. package/dist/extensions/org-config.js +6 -1
  80. package/dist/extensions/permission-set.d.ts +7 -0
  81. package/dist/extensions/permission-set.js +10 -0
  82. package/dist/extensions/permission-view.d.ts +1 -1
  83. package/dist/extensions/permission-view.js +10 -1
  84. package/dist/git/tickets.js +32 -27
  85. package/dist/http/app.js +5 -3
  86. package/dist/identity/accounts.d.ts +6 -1
  87. package/dist/identity/accounts.js +11 -2
  88. package/dist/identity/api-tokens.js +7 -6
  89. package/dist/identity/settings.d.ts +9 -1
  90. package/dist/identity/settings.js +16 -1
  91. package/dist/inbox/org-notices.js +3 -2
  92. package/dist/index.d.ts +1 -0
  93. package/dist/index.js +1 -0
  94. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  95. package/dist/infra/database/scoped-dialect.js +260 -72
  96. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  97. package/dist/infra/database/startup-activation-transaction.js +3 -2
  98. package/dist/infra/outbox/registry.d.ts +28 -0
  99. package/dist/infra/outbox/registry.js +30 -0
  100. package/dist/infra/queue/queue-names.d.ts +1 -1
  101. package/dist/infra/queue/queue-names.js +1 -0
  102. package/dist/infra/queue/run-job.d.ts +4 -1
  103. package/dist/infra/queue/run-job.js +10 -2
  104. package/dist/kernel.module.js +3 -0
  105. package/dist/orgs/offboarding.js +18 -9
  106. package/dist/orgs/settings.service.js +3 -0
  107. package/dist/packages/npm-publish-keys.json +27 -0
  108. package/dist/packages/official-publisher.d.ts +19 -0
  109. package/dist/packages/official-publisher.js +152 -0
  110. package/dist/packages/provenance.d.ts +7 -0
  111. package/dist/packages/provenance.js +22 -19
  112. package/dist/packages/sigstore-trusted-root.json +126 -0
  113. package/dist/platform/ops/admin.ops.js +2 -1
  114. package/dist/platform/ops/orgs.ops.js +1 -0
  115. package/dist/roles/worker-role.d.ts +6 -3
  116. package/dist/roles/worker-role.js +12 -4
  117. package/dist/roles/worker.module.js +7 -0
  118. package/dist/runtime/maintenance.d.ts +5 -2
  119. package/dist/runtime/maintenance.js +18 -4
  120. package/dist/sandbox/device-reports.d.ts +4 -4
  121. package/dist/sandbox/device-reports.js +40 -30
  122. package/dist/sandbox/device-services.d.ts +2 -1
  123. package/dist/sandbox/device-services.js +5 -1
  124. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  125. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  126. package/dist/sandbox/permission-config-publication.js +5 -1
  127. package/dist/themes/theme-state.js +24 -13
  128. package/dist/tools/call-scope.d.ts +6 -0
  129. package/dist/tools/call-scope.js +22 -0
  130. package/dist/tools/registry.js +20 -2
  131. package/dist/ui/views.js +36 -8
  132. package/package.json +9 -4
  133. package/src/migrations/0222_device_host_services.sql +27 -0
  134. package/src/migrations/0223_device_service_events.sql +54 -0
  135. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
@@ -124,6 +124,9 @@ export function buildPermissionSet(input) {
124
124
  services: sortedUnique(p.deviceAccess.services),
125
125
  ...(p.deviceAccess.loopbackPorts === true && { loopbackPorts: true }),
126
126
  ...(p.deviceAccess.siteAccess === true && { siteAccess: true }),
127
+ ...(p.deviceAccess.hostServices && p.deviceAccess.hostServices.length > 0
128
+ ? { hostServices: sortedUnique(p.deviceAccess.hostServices) }
129
+ : {}),
127
130
  },
128
131
  }
129
132
  : {}),
@@ -200,6 +203,8 @@ export function permissionKeys(set) {
200
203
  keys.push(DEVICE_LOOPBACK_PORTS_KEY);
201
204
  if (p.deviceAccess?.siteAccess === true)
202
205
  keys.push(DEVICE_SITE_ACCESS_KEY);
206
+ for (const svc of p.deviceAccess?.hostServices ?? [])
207
+ keys.push(`${DEVICE_HOST_KEY_PREFIX}${svc}`);
203
208
  for (const t of p.triggers?.emit ?? [])
204
209
  keys.push(`${TRIGGERS_KEY_PREFIX}${t}`);
205
210
  if (p.inbox === true)
@@ -241,6 +246,11 @@ export const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
241
246
  * upgrade without approval again. Recorded only when declared.
242
247
  */
243
248
  export const DEVICE_LOOPBACK_PORTS_KEY = "permissions.deviceaccess.loopbackports";
249
+ /**
250
+ * Key prefix of a host service (`permissions.deviceAccess.hostServices`): the service runs on the
251
+ * owner's machine outside the sandbox; sensitive and blocking like any device service key.
252
+ */
253
+ export const DEVICE_HOST_KEY_PREFIX = "permissions.deviceaccess.host:";
244
254
  /** Blocking permission for profile decisions on non-loopback site actions. */
245
255
  export const DEVICE_SITE_ACCESS_KEY = "permissions.deviceaccess.siteaccess";
246
256
  /**
@@ -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" | "device_site_access" | "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" | "device_host_service" | "migration_warnings";
38
38
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
39
39
  export interface PermissionItem {
40
40
  value: string;
@@ -1,7 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { pluginSchemaName } from "../ctx/create-ctx.js";
3
+ import { EXTENSION_RLS_PREDICATE } from "../db/extension-rls-predicate.js";
3
4
  import { isDestructiveSql, splitSqlStatements } from "../db/sql-statements.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
+ import { AGENTS_KEY, CLIENT_KEY, CONVERSATIONS_KEY, DEVICE_ACCESS_KEY_PREFIX, DEVICE_HOST_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
6
  /**
6
7
  * Review digest: the first 16 hex digits of `sha256(permissionKeys(set).join("\n"))`; with migration
7
8
  * warnings their digest (kind, file, line and statement) is folded in, without warnings it equals the
@@ -43,6 +44,8 @@ const CLIENT_ITEM = "client code";
43
44
  /** The "deviceAccess" group's item of loopback port grants (`permissions.deviceAccess.loopbackPorts`). */
44
45
  const LOOPBACK_PORTS_ITEM = "local ports on the device (loopback)";
45
46
  const SITE_ACCESS_ITEM = "profile-approved actions on websites";
47
+ /** Item prefix of a host service (`permissions.deviceAccess.hostServices`): `host:<service>`. */
48
+ const HOST_ITEM_PREFIX = "host:";
46
49
  /** The one item of the "inbox" group (collaboration spec §4.9). */
47
50
  const INBOX_ITEM = "personal inbox items";
48
51
  /** The items of the read-only org fact groups. */
@@ -92,6 +95,8 @@ function itemReason(category, item) {
92
95
  return "device_loopback_ports";
93
96
  if (category === "deviceAccess" && item === SITE_ACCESS_ITEM)
94
97
  return "device_site_access";
98
+ if (category === "deviceAccess" && item.startsWith(HOST_ITEM_PREFIX))
99
+ return "device_host_service";
95
100
  return ALWAYS_SENSITIVE.has(category) ? CATEGORY_REASON[category] : undefined;
96
101
  }
97
102
  /** Routes of the `http` group: member and admin (the kernel authenticates a person). */
@@ -134,6 +139,7 @@ function keyItem(key) {
134
139
  ["ui.view:", "ui", "view:"],
135
140
  [DIAL_IN_KEY_PREFIX, "dialIn", ""],
136
141
  [DEVICE_ACCESS_KEY_PREFIX, "deviceAccess", ""],
142
+ [DEVICE_HOST_KEY_PREFIX, "deviceAccess", HOST_ITEM_PREFIX],
137
143
  [TRIGGERS_KEY_PREFIX, "triggers", ""],
138
144
  ];
139
145
  for (const [prefix, category, itemPrefix] of table) {
@@ -220,6 +226,7 @@ export function permissionGroups(set) {
220
226
  ...(p.deviceAccess?.services ?? []),
221
227
  ...(p.deviceAccess?.loopbackPorts === true ? [LOOPBACK_PORTS_ITEM] : []),
222
228
  ...(p.deviceAccess?.siteAccess === true ? [SITE_ACCESS_ITEM] : []),
229
+ ...(p.deviceAccess?.hostServices ?? []).map((s) => `${HOST_ITEM_PREFIX}${s}`),
223
230
  ],
224
231
  },
225
232
  // the event types it emits for the orgs' event automations (not sensitive)
@@ -287,6 +294,8 @@ export function deriveExtensionStatus(i) {
287
294
  export function migrationWarnings(files, plugin) {
288
295
  const own = pluginSchemaName(plugin);
289
296
  return files.flatMap((m) => splitSqlStatements(m.sql).flatMap((st) => {
297
+ if (m.sql.slice(st.startOffset, st.endOffset) === EXTENSION_RLS_PREDICATE)
298
+ return [];
290
299
  const base = { sensitive: true, file: m.file, line: st.line, statement: st.text };
291
300
  if (/^DO\b/i.test(st.text))
292
301
  return [{ kind: "dynamic_sql", ...base }];
@@ -12,6 +12,7 @@ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { withOrgScope } from "../infra/database/org-scope.js";
15
16
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
16
17
  import { readOrgSettings } from "../orgs/settings.service.js";
17
18
  const BindingSchema = z.object({
@@ -110,33 +111,37 @@ let GitTickets = class GitTickets {
110
111
  const binding = parseBinding(stored);
111
112
  if (binding === null)
112
113
  return refuse("invalid binding");
113
- const run = await this.db
114
- .selectFrom("runs")
115
- .innerJoin("conversations", "conversations.id", "runs.conversation_id")
116
- .innerJoin("orgs", "orgs.id", "conversations.org_id")
117
- .select(["runs.status", "conversations.org_id"])
118
- .where("runs.id", "=", binding.runId)
119
- .where("orgs.deleted_at", "is", null)
120
- .executeTakeFirst();
121
- if (run === undefined || run.org_id !== binding.orgId)
122
- return refuse("run not in org");
123
- if (!ACTIVE_RUN_STATUSES.includes(run.status)) {
124
- return refuse("run not active");
125
- }
126
- const member = await this.db
127
- .selectFrom("memberships")
128
- .innerJoin("accounts", "accounts.id", "memberships.account_id")
129
- .select("memberships.account_id")
130
- .where("memberships.org_id", "=", binding.orgId)
131
- .where("memberships.account_id", "=", binding.accountId)
132
- .where("accounts.status", "=", "active")
133
- .executeTakeFirst();
134
- if (member === undefined)
135
- return refuse("not an active member");
136
- const settings = await readOrgSettings(this.db.db, binding.orgId);
137
- if (settings.gitGateway?.enabled === false)
138
- return refuse("gateway off for the org");
139
- return binding;
114
+ // The binding is issued by the kernel. Re-check its run and membership under that org's scope.
115
+ return withOrgScope(binding.orgId, async () => {
116
+ const run = await this.db
117
+ .selectFrom("runs")
118
+ .innerJoin("conversations", "conversations.id", "runs.conversation_id")
119
+ .innerJoin("orgs", "orgs.id", "conversations.org_id")
120
+ .select("runs.status")
121
+ .where("runs.id", "=", binding.runId)
122
+ .where("conversations.org_id", "=", binding.orgId)
123
+ .where("orgs.deleted_at", "is", null)
124
+ .executeTakeFirst();
125
+ if (run === undefined)
126
+ return refuse("run not in org");
127
+ if (!ACTIVE_RUN_STATUSES.includes(run.status)) {
128
+ return refuse("run not active");
129
+ }
130
+ const member = await this.db
131
+ .selectFrom("memberships")
132
+ .innerJoin("accounts", "accounts.id", "memberships.account_id")
133
+ .select("memberships.account_id")
134
+ .where("memberships.org_id", "=", binding.orgId)
135
+ .where("memberships.account_id", "=", binding.accountId)
136
+ .where("accounts.status", "=", "active")
137
+ .executeTakeFirst();
138
+ if (member === undefined)
139
+ return refuse("not an active member");
140
+ const settings = await readOrgSettings(this.db.db, binding.orgId);
141
+ if (settings.gitGateway?.enabled === false)
142
+ return refuse("gateway off for the org");
143
+ return binding;
144
+ });
140
145
  }
141
146
  /**
142
147
  * Deletes every ticket of the run (run end, abort, offboarding) in one Lua script, so a ticket
package/dist/http/app.js CHANGED
@@ -7,7 +7,7 @@ import { ApiTokenService } from "../identity/api-tokens.js";
7
7
  import { authenticateOrgUploader, authorizeSuperAdmin, } from "../identity/auth.guard.js";
8
8
  import { SessionService } from "../identity/sessions.js";
9
9
  import { KernelDb } from "../infra/database/kernel-db.js";
10
- import { withRequestScopeSlot } from "../infra/database/org-scope.js";
10
+ import { withOrgScope, withRequestScopeSlot } from "../infra/database/org-scope.js";
11
11
  import { withLogContext } from "../log-context.js";
12
12
  import { authorizeOrgAction } from "../orgs/org.guard.js";
13
13
  import { redactPath } from "./error.filter.js";
@@ -158,8 +158,10 @@ export async function createHttpApp(opts, app) {
158
158
  // the org admin role before the body (ruling P3-29): no one else makes the kernel buffer
159
159
  // a package-sized body
160
160
  const principal = await authenticateOrgUploader(req, services());
161
- const orgId = req.params.orgId ?? "";
162
- await authorizeOrgAction(app.get(KernelDb, { strict: false }).db, principal, orgId, "catalog.upload");
161
+ const orgId = req.params.orgId;
162
+ if (!orgId)
163
+ throw new ApiError("org.not_found", "Organization not found");
164
+ await withOrgScope(orgId, () => authorizeOrgAction(app.get(KernelDb, { strict: false }).db, principal, orgId, "catalog.upload"));
163
165
  }
164
166
  catch (e) {
165
167
  return sendError(reply, e, req.method, req.url);
@@ -3,6 +3,7 @@ import { SetupLock } from "../admin/setup-lock.js";
3
3
  import type { AccountsTable } from "../db/kernel-schema.js";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
5
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
6
7
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
7
8
  import { type AccountAvatar, type AccountView } from "./account-avatar.js";
8
9
  import type { Preferences } from "./me.schemas.js";
@@ -73,7 +74,11 @@ export declare class AccountsService {
73
74
  private readonly adminLock;
74
75
  private readonly setupLock;
75
76
  private readonly ceilings;
76
- constructor(db: KernelDb, txHost: TransactionHost, adminLock: SuperAdminLock, setupLock: SetupLock, ceilings: PermissionCeilingWrites);
77
+ /** The owed stops of a disabled account's host services. */
78
+ private readonly outbox;
79
+ constructor(db: KernelDb, txHost: TransactionHost, adminLock: SuperAdminLock, setupLock: SetupLock, ceilings: PermissionCeilingWrites,
80
+ /** The owed stops of a disabled account's host services. */
81
+ outbox: Pick<OutboxService, "add">);
77
82
  /** Checks the password length and hashes it (scrypt, slow): for callers that hash before their transaction opens. */
78
83
  hashNewPassword(password: string): Promise<string>;
79
84
  /**
@@ -11,11 +11,13 @@ import { randomUUID } from "node:crypto";
11
11
  import { Inject, Injectable, Module } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { SetupLock, SetupLockModule } from "../admin/setup-lock.js";
14
+ import { oweHostServicesStopOfAccount } from "../device-access/host-service-stop.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { KernelDb } from "../infra/database/kernel-db.js";
16
17
  import { asPlatform } from "../infra/database/org-scope.js";
17
18
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
19
21
  import { deletePushRegistrationsForSessions } from "../push/registration-cleanup.js";
20
22
  import { PermissionCeilingWritesModule } from "../sandbox/permission-authority.module.js";
21
23
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
@@ -86,12 +88,16 @@ let AccountsService = class AccountsService {
86
88
  adminLock;
87
89
  setupLock;
88
90
  ceilings;
89
- constructor(db, txHost, adminLock, setupLock, ceilings) {
91
+ outbox;
92
+ constructor(db, txHost, adminLock, setupLock, ceilings,
93
+ /** The owed stops of a disabled account's host services. */
94
+ outbox) {
90
95
  this.db = db;
91
96
  this.txHost = txHost;
92
97
  this.adminLock = adminLock;
93
98
  this.setupLock = setupLock;
94
99
  this.ceilings = ceilings;
100
+ this.outbox = outbox;
95
101
  }
96
102
  /** Checks the password length and hashes it (scrypt, slow): for callers that hash before their transaction opens. */
97
103
  async hashNewPassword(password) {
@@ -644,6 +650,8 @@ let AccountsService = class AccountsService {
644
650
  revokedSessionIds = sessions.map((r) => r.id);
645
651
  // a registration follows its session (push plan decision 3): a disabled account loses all
646
652
  await deletePushRegistrationsForSessions(this.db.db, revokedSessionIds);
653
+ // its host services stop on every machine of theirs (local agents spec, call 5)
654
+ await oweHostServicesStopOfAccount(this.db.db, this.outbox, id);
647
655
  }
648
656
  return { account: toAccount(row), revokedSessionIds };
649
657
  }
@@ -687,7 +695,8 @@ AccountsService = __decorate([
687
695
  __param(1, Inject(TransactionHost)),
688
696
  __param(2, Inject(SuperAdminLock)),
689
697
  __param(3, Inject(SetupLock)),
690
- __param(4, Inject(PermissionCeilingWrites))
698
+ __param(4, Inject(PermissionCeilingWrites)),
699
+ __param(5, Inject(OutboxService))
691
700
  ], AccountsService);
692
701
  export { AccountsService };
693
702
  /**
@@ -27,6 +27,7 @@ export const FutureIsoDate = z.iso
27
27
  .refine((s) => new Date(s).getTime() > Date.now(), "must be in the future")
28
28
  .transform((s) => new Date(s));
29
29
  const PREFIX = { personal: "cap_pat_", service: "cap_svc_" };
30
+ const tokenTouchDue = sql `(last_used_at is null or last_used_at < now() - interval '5 minutes')`;
30
31
  function toRecord(r) {
31
32
  return {
32
33
  id: r.id,
@@ -141,6 +142,7 @@ let ApiTokenService = class ApiTokenService {
141
142
  const row = await this.db
142
143
  .selectFrom("api_tokens")
143
144
  .selectAll()
145
+ .select(tokenTouchDue.as("touch_due"))
144
146
  .where("token_hash", "=", sha256Hex(token))
145
147
  .where("kind", "=", kind)
146
148
  .where("revoked_at", "is", null)
@@ -148,19 +150,18 @@ let ApiTokenService = class ApiTokenService {
148
150
  .executeTakeFirst();
149
151
  if (!row)
150
152
  return null;
151
- // Touch the token at most once every five minutes.
153
+ const record = toRecord(row);
154
+ // Skip the usual no-op write. The write also checks the deadline for concurrent callers.
155
+ if (!row.touch_due)
156
+ return record;
152
157
  // org-filter: deployment-wide update by primary key of the token authenticated above.
153
158
  const touched = await this.db
154
159
  .updateTable("api_tokens")
155
160
  .set({ last_used_at: sql `now()` })
156
161
  .where("id", "=", row.id)
157
- .where((eb) => eb.or([
158
- eb("last_used_at", "is", null),
159
- eb("last_used_at", "<", sql `now() - interval '5 minutes'`),
160
- ]))
162
+ .where(tokenTouchDue)
161
163
  .returning("last_used_at")
162
164
  .executeTakeFirst();
163
- const record = toRecord(row);
164
165
  if (touched)
165
166
  record.lastUsedAt = touched.last_used_at;
166
167
  return record;
@@ -203,6 +203,10 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
203
203
  }, z.core.$strict>>;
204
204
  }, z.core.$strict>>;
205
205
  }, z.core.$strict>>;
206
+ officialPublisherProof: z.ZodDefault<z.ZodEnum<{
207
+ "pin-only": "pin-only";
208
+ require: "require";
209
+ }>>;
206
210
  priceCurrency: z.ZodDefault<z.ZodString>;
207
211
  sandboxLimitOverrides: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
208
212
  cpu: z.ZodOptional<z.ZodNumber>;
@@ -329,6 +333,10 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
329
333
  }, z.core.$strict>>;
330
334
  }, z.core.$strict>>;
331
335
  }, z.core.$strict>>>;
336
+ officialPublisherProof: z.ZodOptional<z.ZodEnum<{
337
+ "pin-only": "pin-only";
338
+ require: "require";
339
+ }>>;
332
340
  priceCurrency: z.ZodOptional<z.ZodString>;
333
341
  sandboxLimitOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodObject<{
334
342
  cpu: z.ZodOptional<z.ZodNumber>;
@@ -542,7 +550,7 @@ export declare class SettingsService {
542
550
  * `onlyNarrows` (an API token, the Platform tool): `devicesOutsideSandbox` may only turn it off,
543
551
  * `devicesNetwork` may only narrow to the allowlist,
544
552
  * `externalSharing` may only turn external sharing off, `shareMaxExpiryDays` may only decrease and
545
- * `htmlRenderCdnAllowlist` may only shrink.
553
+ * `htmlRenderCdnAllowlist` may only shrink. Only a web session may choose pin-only publisher proof.
546
554
  */
547
555
  update(patch: DeploymentSettingsPatch, actorAccountId: string, actorTokenId?: string,
548
556
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
@@ -11,6 +11,7 @@ import { EXTENSION_NAME_RE, narrowerProjectReach } from "@capybara-hq/plugin-sdk
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { applyPlatformAttributionPatch, PLATFORM_ATTRIBUTION_FIELDS, PLATFORM_ATTRIBUTION_PATCH, PLATFORM_ATTRIBUTION_SETTING, readStoredPlatformAttribution, resolvePlatformAttribution, } from "../attribution/platform-attribution.js";
14
+ import { OfficialPublisherProofMode, officialPublisherProofMode, } from "../catalog/publisher-policy.js";
14
15
  import { productName } from "../config/product-name.js";
15
16
  import { DEVICES_DEFAULT_PROVIDER_PATCH, DEVICES_DEFAULT_PROVIDER_SETTING, readPlatformDefaultProvider, } from "../devices/default-provider-setting.js";
16
17
  import { ApiError } from "../errors.js";
@@ -208,6 +209,7 @@ export const DEPLOYMENT_SETTINGS = z.object({
208
209
  runConcurrencyOverrides: z.record(z.string().min(1), z.number().int().positive()).default({}),
209
210
  retention: StoredPlatformRetentionSchema.default(OFF_RETENTION),
210
211
  modelBudgets: PlatformModelBudgetsSchema.default({}),
212
+ officialPublisherProof: OfficialPublisherProofMode.default("require"),
211
213
  /** The currency of model prices used for cost estimates, without conversion. */
212
214
  priceCurrency: PriceCurrency.default(DEFAULT_PRICE_CURRENCY),
213
215
  /** 按组织覆盖沙箱 cpu / 内存(orgId → 覆盖,C19);只对之后新建的沙箱生效。组织管理员只读。 */
@@ -297,6 +299,7 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
297
299
  retention: PlatformRetentionSchema.partial().optional(),
298
300
  confirmRetentionShortening: z.literal(true).optional(),
299
301
  modelBudgets: PlatformModelBudgetsSchema.nullable().optional(),
302
+ officialPublisherProof: OfficialPublisherProofMode.optional(),
300
303
  priceCurrency: PriceCurrency.optional(),
301
304
  sandboxLimitOverrides: z
302
305
  .record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE.nullable())
@@ -793,7 +796,7 @@ let SettingsService = class SettingsService {
793
796
  * `onlyNarrows` (an API token, the Platform tool): `devicesOutsideSandbox` may only turn it off,
794
797
  * `devicesNetwork` may only narrow to the allowlist,
795
798
  * `externalSharing` may only turn external sharing off, `shareMaxExpiryDays` may only decrease and
796
- * `htmlRenderCdnAllowlist` may only shrink.
799
+ * `htmlRenderCdnAllowlist` may only shrink. Only a web session may choose pin-only publisher proof.
797
800
  */
798
801
  async update(patch, actorAccountId, actorTokenId,
799
802
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
@@ -881,6 +884,14 @@ let SettingsService = class SettingsService {
881
884
  }
882
885
  if (patch.orgCreation !== undefined)
883
886
  next.orgCreation = patch.orgCreation;
887
+ let officialPublisherProofPrevious;
888
+ if (patch.officialPublisherProof !== undefined) {
889
+ if (opts.onlyNarrows && patch.officialPublisherProof === "pin-only") {
890
+ throw new ApiError("deployment.publisher_policy_requires_session", "Switch to pin-only from the admin console in a super admin session");
891
+ }
892
+ officialPublisherProofPrevious = await officialPublisherProofMode(this.db.db);
893
+ next.officialPublisherProof = patch.officialPublisherProof;
894
+ }
884
895
  if (patch.priceCurrency !== undefined)
885
896
  next.priceCurrency = patch.priceCurrency;
886
897
  if (patch.customConnectors !== undefined)
@@ -1006,6 +1017,9 @@ let SettingsService = class SettingsService {
1006
1017
  (r.before.outsideSandbox.permission === "off" &&
1007
1018
  r.after.outsideSandbox.permission === "allowed") ||
1008
1019
  widened(r.before.network, r.after.network), reachTightened, r.after.allowedProfiles.value);
1020
+ // running outside the sandbox switched off closes the host gate on every device
1021
+ if (outsideOff)
1022
+ await this.ceilings.oweHostServiceStopsLocked({}, "platform");
1009
1023
  if (reachChanged && !reachTightened)
1010
1024
  await this.ceilings.invalidateProjectReachWideningLocked(r.before.projectReach.ceiling, r.after.projectReach.ceiling, r.after.allowedProfiles.value);
1011
1025
  }
@@ -1071,6 +1085,7 @@ let SettingsService = class SettingsService {
1071
1085
  detail: {
1072
1086
  ...patch,
1073
1087
  ...retentionAudit,
1088
+ ...(officialPublisherProofPrevious !== undefined && { officialPublisherProofPrevious }),
1074
1089
  ...(deviceSandboxChange !== undefined && { deviceSandboxEffective: deviceSandboxChange }),
1075
1090
  ...auditDetail,
1076
1091
  },
@@ -3,6 +3,7 @@
3
3
  // caller's transaction, so a notice exists exactly when its change does.
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { orgsUsing, ownerOf, ownersOf } from "../catalog/ownership.js";
6
+ import { withOrgScope } from "../infra/database/org-scope.js";
6
7
  /** An owned ref's display name: a plugin's (skills and agent templates have none). */
7
8
  const refDisplayName = (db, ref) => ref.kind === "plugin" ? itemDisplayName(db, ref.id) : Promise.resolve(null);
8
9
  /** A catalog item's display name for an upload notice (null without one, or for an unknown id). */
@@ -78,14 +79,14 @@ export async function notifySharedUpdate(db, ref, change) {
78
79
  const using = await orgsUsing(db, ref, { except: row.owner_org_id });
79
80
  const displayName = await refDisplayName(db, ref);
80
81
  for (const o of using) {
81
- await addOrgNotice(db, o.id, "shared_item_updated", {
82
+ await withOrgScope(o.id, () => addOrgNotice(db, o.id, "shared_item_updated", {
82
83
  ref,
83
84
  name: change.name,
84
85
  displayName,
85
86
  from: change.from,
86
87
  to: change.to,
87
88
  owner,
88
- });
89
+ }));
89
90
  }
90
91
  return using.length;
91
92
  }
package/dist/index.d.ts CHANGED
@@ -71,6 +71,7 @@ export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWr
71
71
  export { type Org, OrgsService } from "./orgs/orgs.service.js";
72
72
  export type { KernelOverride } from "./overrides.js";
73
73
  export { fetchNpmPackage, IntegrityMismatchError, type NpmFetchConfig, NpmFetchError, PackageTooLargeError, } from "./packages/npm.js";
74
+ export { fetchOfficialPublisher } from "./packages/official-publisher.js";
74
75
  export { packPackageTgz } from "./packages/tgz.js";
75
76
  export { checkInputParity, inputParity, type ParityFinding, type ParityOperation, } from "./platform/parity.js";
76
77
  export { PLATFORM_OPERATION_PROVIDERS } from "./platform/platform-ops.module.js";
package/dist/index.js CHANGED
@@ -67,6 +67,7 @@ export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js
67
67
  export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
68
68
  export { OrgsService } from "./orgs/orgs.service.js";
69
69
  export { fetchNpmPackage, IntegrityMismatchError, NpmFetchError, PackageTooLargeError, } from "./packages/npm.js";
70
+ export { fetchOfficialPublisher } from "./packages/official-publisher.js";
70
71
  // The canonical tgz of a package tree; `capybara-plugin bootstrap` pins git entries with it.
71
72
  export { packPackageTgz } from "./packages/tgz.js";
72
73
  // Test seam: the Platform input-parity test in tools/checks (no runtime caller).
@@ -2,7 +2,7 @@ import { type Driver, type KyselyPlugin, PostgresDialect, type PostgresDialectCo
2
2
  /**
3
3
  * `db.rls`: how the kernel pool carries the org scope to Postgres (RLS spec §5.2, §7).
4
4
  * - `off`: nothing is sent; the pool is a plain Kysely pool (no extra round trip).
5
- * - `scoped`: every connection carries the scope, with `capybara.rls = off`, so the policies admit
5
+ * - `scoped`: every transaction carries the scope, with `capybara.rls = off`, so the policies admit
6
6
  * every row; for measuring the round-trip cost (§8) and for the unscoped-query check.
7
7
  * - `enforce`: the same with `capybara.rls = enforce`: the policies filter by the scope.
8
8
  */
@@ -15,6 +15,7 @@ export declare const captureUnscopedQueryOrigins: KyselyPlugin;
15
15
  */
16
16
  export declare class ScopedPostgresDialect extends PostgresDialect {
17
17
  private readonly rls;
18
- constructor(config: PostgresDialectConfig, rls: RlsMode);
18
+ private readonly standaloneScope;
19
+ constructor(config: PostgresDialectConfig, rls: RlsMode, extendedProtocol?: boolean);
19
20
  createDriver(): Driver;
20
21
  }