@capybara-hq/kernel 0.1.0-rc.142 → 0.1.0-rc.144

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 (238) hide show
  1. package/dist/admin/admin-agents.controller.d.ts +3 -5
  2. package/dist/admin/admin-agents.controller.js +1 -1
  3. package/dist/admin/admin-connectors.controller.d.ts +3 -5
  4. package/dist/admin/admin-connectors.controller.js +1 -1
  5. package/dist/admin/admin-items.schemas.d.ts +6 -6
  6. package/dist/admin/admin-items.schemas.js +5 -9
  7. package/dist/admin/admin.controller.d.ts +18 -12
  8. package/dist/admin/admin.controller.js +29 -15
  9. package/dist/admin/admin.schemas.d.ts +12 -3
  10. package/dist/admin/admin.schemas.js +17 -6
  11. package/dist/agents/admin-agents.d.ts +10 -8
  12. package/dist/agents/admin-agents.js +13 -9
  13. package/dist/agents/agents.module.js +3 -0
  14. package/dist/agents/agents.service.js +1 -1
  15. package/dist/agents/org-templates.d.ts +3 -1
  16. package/dist/agents/org-templates.js +7 -3
  17. package/dist/agents/pending-connector-requests.d.ts +10 -4
  18. package/dist/agents/pending-connector-requests.js +29 -7
  19. package/dist/automations/automations.controller.d.ts +9 -5
  20. package/dist/automations/automations.controller.js +21 -4
  21. package/dist/automations/automations.schemas.d.ts +19 -0
  22. package/dist/automations/automations.schemas.js +9 -0
  23. package/dist/automations/automations.service.d.ts +25 -8
  24. package/dist/automations/automations.service.js +40 -34
  25. package/dist/automations/events/acceptance.d.ts +6 -1
  26. package/dist/automations/events/acceptance.js +30 -11
  27. package/dist/automations/store.d.ts +17 -0
  28. package/dist/automations/store.js +35 -0
  29. package/dist/catalog/admin-catalog.controller.d.ts +64 -2
  30. package/dist/catalog/admin-catalog.controller.js +17 -0
  31. package/dist/catalog/catalog-import.module.js +3 -0
  32. package/dist/catalog/catalog-scope.service.d.ts +3 -1
  33. package/dist/catalog/catalog-scope.service.js +11 -7
  34. package/dist/catalog/catalog.module.js +3 -0
  35. package/dist/catalog/catalog.service.d.ts +3 -1
  36. package/dist/catalog/catalog.service.js +8 -4
  37. package/dist/catalog/cli.js +2 -2
  38. package/dist/catalog/component-promotion.d.ts +3 -1
  39. package/dist/catalog/component-promotion.js +7 -3
  40. package/dist/catalog/component-scope.service.d.ts +3 -1
  41. package/dist/catalog/component-scope.service.js +7 -3
  42. package/dist/catalog/enable-requests.d.ts +10 -8
  43. package/dist/catalog/enable-requests.js +40 -21
  44. package/dist/catalog/marketplaces.service.d.ts +1 -1
  45. package/dist/catalog/owned-items.d.ts +3 -1
  46. package/dist/catalog/owned-items.js +13 -9
  47. package/dist/catalog/platform-components.d.ts +6 -1
  48. package/dist/catalog/platform-components.js +9 -3
  49. package/dist/catalog/plugin-connectors.d.ts +8 -4
  50. package/dist/catalog/plugin-connectors.js +12 -6
  51. package/dist/catalog/plugin-import.d.ts +3 -1
  52. package/dist/catalog/plugin-import.js +14 -5
  53. package/dist/catalog/plugin-install.d.ts +3 -1
  54. package/dist/catalog/plugin-install.js +8 -4
  55. package/dist/catalog/plugin-package.js +2 -1
  56. package/dist/catalog/plugin-upgrade.d.ts +3 -1
  57. package/dist/catalog/plugin-upgrade.js +8 -4
  58. package/dist/catalog/request-hints.d.ts +19 -0
  59. package/dist/catalog/request-hints.js +34 -0
  60. package/dist/catalog/request-rules.d.ts +9 -5
  61. package/dist/catalog/request-rules.js +16 -9
  62. package/dist/catalog/requests.service.d.ts +3 -1
  63. package/dist/catalog/requests.service.js +28 -9
  64. package/dist/catalog/scope-orgs.d.ts +2 -1
  65. package/dist/catalog/scope-orgs.js +2 -2
  66. package/dist/catalog/scope-sync.d.ts +3 -1
  67. package/dist/catalog/scope-sync.js +12 -2
  68. package/dist/catalog/scope-writer.d.ts +6 -3
  69. package/dist/catalog/scope-writer.js +28 -10
  70. package/dist/catalog/unshare.d.ts +3 -2
  71. package/dist/catalog/unshare.js +4 -4
  72. package/dist/client/client-access.service.js +29 -1
  73. package/dist/config/schema.d.ts +12 -0
  74. package/dist/config/schema.js +56 -0
  75. package/dist/ctx/create-ctx.d.ts +2 -19
  76. package/dist/ctx/create-ctx.js +3 -93
  77. package/dist/ctx/durable-relay.d.ts +2 -5
  78. package/dist/ctx/durable-relay.js +56 -29
  79. package/dist/db/extension-handoff-schema.js +5 -0
  80. package/dist/db/kernel-schema.d.ts +74 -0
  81. package/dist/db/migrator.js +36 -0
  82. package/dist/erasure/account-batches.js +2 -0
  83. package/dist/erasure/account-residual.js +1 -0
  84. package/dist/erasure/org-catalog.js +8 -3
  85. package/dist/erasure/org-rules.js +1 -0
  86. package/dist/evals/evals.schemas.d.ts +15 -5
  87. package/dist/evals/evals.schemas.js +17 -10
  88. package/dist/evals/runs.controller.d.ts +4 -12
  89. package/dist/evals/runs.controller.js +14 -11
  90. package/dist/evals/runs.service.d.ts +29 -25
  91. package/dist/evals/runs.service.js +73 -61
  92. package/dist/evals/trajectory.controller.d.ts +10 -6
  93. package/dist/evals/trajectory.controller.js +11 -4
  94. package/dist/evals/trajectory.service.d.ts +17 -9
  95. package/dist/evals/trajectory.service.js +52 -35
  96. package/dist/extensions/admin-ops.d.ts +6 -1
  97. package/dist/extensions/admin-ops.js +21 -7
  98. package/dist/extensions/blobs.d.ts +2 -0
  99. package/dist/extensions/blobs.js +11 -0
  100. package/dist/extensions/deployment-config.d.ts +6 -1
  101. package/dist/extensions/deployment-config.js +13 -2
  102. package/dist/extensions/enabled.d.ts +5 -0
  103. package/dist/extensions/extensions.module.js +3 -0
  104. package/dist/extensions/grant-epoch.d.ts +108 -0
  105. package/dist/extensions/grant-epoch.js +214 -0
  106. package/dist/extensions/host.d.ts +29 -9
  107. package/dist/extensions/host.js +148 -42
  108. package/dist/extensions/instance.d.ts +3 -3
  109. package/dist/extensions/instance.js +1 -1
  110. package/dist/extensions/isolated/authorization.d.ts +54 -2
  111. package/dist/extensions/isolated/authorization.js +148 -35
  112. package/dist/extensions/isolated/child-session.js +0 -1
  113. package/dist/extensions/isolated/revision.js +1 -1
  114. package/dist/extensions/org-config.d.ts +3 -1
  115. package/dist/extensions/org-config.js +13 -4
  116. package/dist/extensions/org-overrides.d.ts +6 -1
  117. package/dist/extensions/org-overrides.js +13 -2
  118. package/dist/extensions/package-digest.job.d.ts +34 -0
  119. package/dist/extensions/package-digest.job.js +121 -0
  120. package/dist/extensions/package.js +10 -6
  121. package/dist/extensions/permission-set.d.ts +14 -78
  122. package/dist/extensions/permission-set.js +17 -143
  123. package/dist/extensions/permission-view.d.ts +13 -1
  124. package/dist/extensions/permission-view.js +20 -0
  125. package/dist/extensions/registry.js +4 -1
  126. package/dist/extensions/resolve.d.ts +7 -8
  127. package/dist/extensions/resolve.js +7 -8
  128. package/dist/extensions/revision-approvals.d.ts +167 -0
  129. package/dist/extensions/revision-approvals.js +353 -0
  130. package/dist/extensions/revision-grants.d.ts +197 -0
  131. package/dist/extensions/revision-grants.js +584 -0
  132. package/dist/extensions/state.module.js +12 -1
  133. package/dist/identity/accounts.d.ts +10 -4
  134. package/dist/identity/accounts.js +18 -5
  135. package/dist/inbox/inbox-items.service.d.ts +6 -1
  136. package/dist/inbox/inbox-items.service.js +29 -10
  137. package/dist/inbox/inbox.module.js +3 -0
  138. package/dist/inbox/inbox.service.d.ts +3 -1
  139. package/dist/inbox/inbox.service.js +9 -2
  140. package/dist/inbox/org-notices.d.ts +4 -3
  141. package/dist/inbox/org-notices.js +9 -6
  142. package/dist/inbox/platform-inbox.service.d.ts +3 -1
  143. package/dist/inbox/platform-inbox.service.js +11 -3
  144. package/dist/inbox/platform-notices.d.ts +3 -2
  145. package/dist/inbox/platform-notices.js +10 -4
  146. package/dist/infra/config/kernel-config.service.js +4 -1
  147. package/dist/infra/database/extension-effect-key-lock.js +7 -0
  148. package/dist/infra/paging/paged-read.d.ts +34 -4
  149. package/dist/infra/paging/paged-read.js +38 -1
  150. package/dist/invalidation/audiences.d.ts +32 -0
  151. package/dist/invalidation/audiences.js +43 -0
  152. package/dist/invalidation/hints.d.ts +6 -0
  153. package/dist/invalidation/hints.js +7 -1
  154. package/dist/invalidation/invalidation-hints.d.ts +12 -1
  155. package/dist/invalidation/invalidation-hints.js +46 -5
  156. package/dist/invalidation/invalidation-hints.module.d.ts +2 -0
  157. package/dist/invalidation/invalidation-hints.module.js +4 -1
  158. package/dist/invalidation/me-stream.d.ts +1 -11
  159. package/dist/invalidation/me-stream.js +12 -41
  160. package/dist/invalidation/org-intent-bridge.d.ts +18 -0
  161. package/dist/invalidation/org-intent-bridge.js +46 -0
  162. package/dist/models/enablement.d.ts +3 -1
  163. package/dist/models/enablement.js +25 -5
  164. package/dist/orgs/invitations.controller.d.ts +4 -7
  165. package/dist/orgs/invitations.controller.js +8 -5
  166. package/dist/orgs/invitations.service.d.ts +17 -3
  167. package/dist/orgs/invitations.service.js +35 -13
  168. package/dist/orgs/members.service.d.ts +35 -0
  169. package/dist/orgs/members.service.js +52 -3
  170. package/dist/orgs/offboarding.d.ts +3 -1
  171. package/dist/orgs/offboarding.js +7 -3
  172. package/dist/orgs/orgs.controller.d.ts +11 -4
  173. package/dist/orgs/orgs.controller.js +25 -5
  174. package/dist/orgs/orgs.module.js +3 -0
  175. package/dist/orgs/orgs.schemas.d.ts +14 -0
  176. package/dist/orgs/orgs.schemas.js +19 -2
  177. package/dist/orgs/orgs.service.d.ts +24 -2
  178. package/dist/orgs/orgs.service.js +47 -4
  179. package/dist/orgs/security-settings.service.d.ts +14 -6
  180. package/dist/orgs/security-settings.service.js +18 -13
  181. package/dist/orgs/settings.controller.d.ts +7 -4
  182. package/dist/platform/exclusions.js +15 -0
  183. package/dist/platform/ops/accounts.ops.js +7 -16
  184. package/dist/platform/ops/admin-items.ops.js +7 -7
  185. package/dist/platform/ops/automations.ops.js +6 -4
  186. package/dist/platform/ops/evals.ops.js +30 -15
  187. package/dist/platform/ops/org-settings.ops.js +2 -2
  188. package/dist/platform/ops/orgs.ops.js +44 -27
  189. package/dist/push/delivery.d.ts +3 -1
  190. package/dist/push/delivery.js +7 -3
  191. package/dist/push/push-processor.js +8 -1
  192. package/dist/roles/worker.module.js +3 -0
  193. package/dist/runtime/step-log.d.ts +1 -1
  194. package/dist/runtime/step-log.js +5 -4
  195. package/dist/runtime/stream-limit.d.ts +13 -0
  196. package/dist/runtime/stream-limit.js +40 -0
  197. package/dist/runtime/stream.controller.d.ts +2 -0
  198. package/dist/runtime/stream.controller.js +2 -0
  199. package/dist/runtime/stream.d.ts +1 -0
  200. package/dist/runtime/stream.js +15 -6
  201. package/dist/sandbox/permission-authority.module.js +6 -1
  202. package/dist/sandbox/permission-transitions.d.ts +3 -1
  203. package/dist/sandbox/permission-transitions.js +17 -2
  204. package/dist/setup/kernel-checks.d.ts +3 -3
  205. package/dist/setup/kernel-checks.js +4 -4
  206. package/dist/setup/setup-check-registry.d.ts +16 -5
  207. package/dist/setup/setup-check-registry.js +11 -3
  208. package/dist/setup/setup-checks.service.d.ts +1 -2
  209. package/dist/setup/setup-checks.service.js +7 -6
  210. package/dist/skills/agent-skills.service.d.ts +6 -1
  211. package/dist/skills/agent-skills.service.js +12 -3
  212. package/dist/skills/changes.service.d.ts +6 -1
  213. package/dist/skills/changes.service.js +11 -3
  214. package/dist/skills/conversation-catalog.d.ts +3 -0
  215. package/dist/skills/conversation-catalog.js +2 -0
  216. package/dist/skills/skills.module.js +3 -0
  217. package/dist/skills/skills.service.d.ts +3 -1
  218. package/dist/skills/skills.service.js +8 -4
  219. package/dist/tools/admin-connectors.d.ts +10 -8
  220. package/dist/tools/admin-connectors.js +12 -10
  221. package/dist/tools/approvals.service.d.ts +12 -1
  222. package/dist/tools/approvals.service.js +36 -9
  223. package/dist/tools/builtins/automations.d.ts +1 -1
  224. package/dist/tools/builtins/automations.js +1 -1
  225. package/dist/tools/connectors.service.d.ts +3 -1
  226. package/dist/tools/connectors.service.js +29 -7
  227. package/dist/tools/tools.module.js +3 -0
  228. package/dist/ui/admin-ui.controller.d.ts +3 -1
  229. package/dist/ui/admin-ui.controller.js +3 -1
  230. package/dist/ui/ui-stream.d.ts +2 -0
  231. package/dist/ui/ui-stream.js +20 -6
  232. package/dist/ui/views.controller.d.ts +4 -2
  233. package/dist/ui/views.controller.js +4 -2
  234. package/package.json +3 -3
  235. package/src/migrations/0234_extension_grant_epoch.sql +141 -0
  236. package/src/migrations/0235_extension_revision_grants.sql +166 -0
  237. package/src/migrations/0236_paged_table_idx.sql +33 -0
  238. package/src/migrations/0237_extension_handoff_health.sql +18 -0
@@ -0,0 +1,584 @@
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 { createHash } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { asPlatform } from "../infra/database/org-scope.js";
15
+ import { TransactionHost } from "../infra/database/transaction-host.js";
16
+ import { Transactional } from "../infra/database/transactional.decorator.js";
17
+ import { canonicalJson } from "../tools/canonical-json.js";
18
+ export const EXECUTION_REALMS = ["server", "browser", "device"];
19
+ /** The kernel-generated permission key of full access in one realm, revocable on its own. */
20
+ export function fullAccessKey(realm) {
21
+ return `execution.full-access:${realm}`;
22
+ }
23
+ /** The serving surface of a live grant: its keys minus the revoked and the retired ones. */
24
+ export function effectiveKeys(grant) {
25
+ const gone = new Set([...grant.disabledKeys, ...grant.retiredKeys]);
26
+ return grant.keys.filter((key) => !gone.has(key));
27
+ }
28
+ /**
29
+ * The full-access realms a live grant still covers, each with its remaining forcing keys: a realm
30
+ * whose key was revoked or retired, or whose forcing keys were all retired, is gone.
31
+ */
32
+ export function effectiveRealms(grant) {
33
+ const keys = new Set(effectiveKeys(grant));
34
+ const realms = {};
35
+ for (const realm of EXECUTION_REALMS) {
36
+ const forcing = grant.realms[realm];
37
+ if (!forcing || !keys.has(fullAccessKey(realm)))
38
+ continue;
39
+ const retired = new Set(grant.retiredForcing[realm] ?? []);
40
+ const remaining = forcing.filter((key) => !retired.has(key));
41
+ if (remaining.length > 0)
42
+ realms[realm] = remaining;
43
+ }
44
+ return realms;
45
+ }
46
+ export function isLive(state) {
47
+ return state === "approved" || state === "partially_revoked";
48
+ }
49
+ export class RevisionGrantError extends Error {
50
+ code;
51
+ constructor(code, message) {
52
+ super(message);
53
+ this.code = code;
54
+ this.name = "RevisionGrantError";
55
+ }
56
+ }
57
+ const SHA512_HEX = /^[0-9a-f]{128}$/;
58
+ const FULL_ACCESS_PREFIX = "execution.full-access:";
59
+ const SOURCE_AUTHORITY = {
60
+ review: "super_admin",
61
+ operator_config: "operator",
62
+ operator_cli: "operator",
63
+ auto: "auto",
64
+ };
65
+ /** sha256 hex of the canonical encoding of the purpose rows, sorted by key. */
66
+ export function purposesDigest(purposes) {
67
+ return createHash("sha256")
68
+ .update(canonicalJson(sortPurposes(purposes)))
69
+ .digest("hex");
70
+ }
71
+ function sortPurposes(purposes) {
72
+ return [...purposes]
73
+ .map(({ key, zh, en }) => ({ key, zh, en }))
74
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
75
+ }
76
+ function checkRevision({ plugin, version, sha512 }) {
77
+ if (!plugin || !version || !SHA512_HEX.test(sha512)) {
78
+ throw new RevisionGrantError("invalid", "A revision needs a plugin, a version and a hex sha512");
79
+ }
80
+ }
81
+ function normalize(input) {
82
+ checkRevision(input.revision);
83
+ const purposes = sortPurposes(input.purposes);
84
+ for (const [index, row] of purposes.entries()) {
85
+ if (!row.key || !row.zh.trim() || !row.en.trim()) {
86
+ throw new RevisionGrantError("invalid", `Purpose of ${row.key || "a key"} needs zh and en`);
87
+ }
88
+ if (index > 0 && purposes[index - 1]?.key === row.key) {
89
+ throw new RevisionGrantError("invalid", `Duplicate purpose row for ${row.key}`);
90
+ }
91
+ }
92
+ const keys = purposes.map((row) => row.key);
93
+ const realms = {};
94
+ for (const [realm, forcing] of Object.entries(input.realms ?? {})) {
95
+ if (!EXECUTION_REALMS.includes(realm) || !forcing || forcing.length === 0) {
96
+ throw new RevisionGrantError("invalid", `Full access for ${realm} needs its forcing keys`);
97
+ }
98
+ realms[realm] = [...new Set(forcing)].sort();
99
+ }
100
+ for (const key of keys) {
101
+ if (!key.startsWith(FULL_ACCESS_PREFIX))
102
+ continue;
103
+ if (!(key.slice(FULL_ACCESS_PREFIX.length) in realms)) {
104
+ throw new RevisionGrantError("invalid", `${key} needs the forcing keys of its realm`);
105
+ }
106
+ }
107
+ for (const realm of Object.keys(realms)) {
108
+ if (!keys.includes(fullAccessKey(realm))) {
109
+ throw new RevisionGrantError("invalid", `Full access for ${realm} needs ${fullAccessKey(realm)}`);
110
+ }
111
+ }
112
+ if (!input.reviewHash)
113
+ throw new RevisionGrantError("invalid", "A grant needs its review hash");
114
+ if (input.approvalScope.mode === "named" && input.approvalScope.orgs.length === 0) {
115
+ throw new RevisionGrantError("invalid", "A named approval scope needs at least one org");
116
+ }
117
+ if ((input.source === "continuity") !== (input.continuedFrom !== undefined)) {
118
+ throw new RevisionGrantError("invalid", "Only a continuity grant names the grant it continues");
119
+ }
120
+ if (input.continuedFrom) {
121
+ checkRevision(input.continuedFrom);
122
+ if (input.continuedFrom.plugin !== input.revision.plugin) {
123
+ throw new RevisionGrantError("invalid", "Continuity stays within one plugin");
124
+ }
125
+ }
126
+ return { purposes, realms, keys };
127
+ }
128
+ function toGrant(row, orgs) {
129
+ return {
130
+ revision: { plugin: row.plugin, version: row.version, sha512: row.sha512 },
131
+ generation: row.generation,
132
+ keys: row.keys,
133
+ purposes: row.purposes,
134
+ purposesDigest: row.purposes_digest,
135
+ realms: row.realms,
136
+ reviewHash: row.review_hash,
137
+ approvalScope: row.approval_scope === "named"
138
+ ? { mode: "named", orgs: [...orgs].sort() }
139
+ : { mode: row.approval_scope },
140
+ source: row.source,
141
+ authority: row.authority,
142
+ publisher: row.publisher,
143
+ publisherEvidence: row.publisher_evidence,
144
+ continuedFrom: row.continued_version !== null &&
145
+ row.continued_sha512 !== null &&
146
+ row.continued_generation !== null
147
+ ? {
148
+ plugin: row.plugin,
149
+ version: row.continued_version,
150
+ sha512: row.continued_sha512,
151
+ generation: row.continued_generation,
152
+ }
153
+ : null,
154
+ state: row.state,
155
+ disabledKeys: row.disabled_keys,
156
+ retiredKeys: row.retired_keys,
157
+ retiredForcing: row.retired_forcing,
158
+ approvedBy: row.approved_by,
159
+ approvedAt: row.approved_at,
160
+ stateChangedBy: row.state_changed_by,
161
+ stateChangedAt: row.state_changed_at,
162
+ };
163
+ }
164
+ const LIVE_STATES = ["approved", "partially_revoked"];
165
+ /** The sources that may open a new generation after a revocation or retirement: human review. */
166
+ const REVIVING_SOURCES = new Set(["review", "operator_cli"]);
167
+ const SCOPE_BREADTH = { named: 0, optional: 1, all: 2 };
168
+ /**
169
+ * The spec's continuity conditions against a live source grant; the reason the candidate is not a
170
+ * continuation, or undefined when it is. The continued surface is a subset of what still serves,
171
+ * with identical purposes, no wider org scope, full access only where the source still covers it,
172
+ * and the same verified publisher. A partially revoked source never resurrects its revoked or
173
+ * retired keys. The store checks it under the source's share lock; the shadow decisions use it to
174
+ * report why a revision would wait for review.
175
+ */
176
+ export function continuityProblem(source, candidate) {
177
+ const serving = new Set(effectiveKeys(source));
178
+ const reviewed = new Map(source.purposes.map((row) => [row.key, row]));
179
+ for (const row of candidate.purposes) {
180
+ if (!serving.has(row.key))
181
+ return `${row.key} is not served by the grant it continues`;
182
+ const before = reviewed.get(row.key);
183
+ if (before?.zh !== row.zh || before?.en !== row.en)
184
+ return `the purpose of ${row.key} changed`;
185
+ }
186
+ const scope = candidate.approvalScope;
187
+ if (SCOPE_BREADTH[scope.mode] > SCOPE_BREADTH[source.approvalScope.mode]) {
188
+ return `the ${scope.mode} scope is wider than ${source.approvalScope.mode}`;
189
+ }
190
+ if (scope.mode === "named" && source.approvalScope.mode === "named") {
191
+ const allowed = new Set(source.approvalScope.orgs);
192
+ if (scope.orgs.some((org) => !allowed.has(org)))
193
+ return "the named scope adds orgs";
194
+ }
195
+ const covered = effectiveRealms(source);
196
+ for (const realm of Object.keys(candidate.realms)) {
197
+ const still = new Set(covered[realm] ?? []);
198
+ if ((candidate.realms[realm] ?? []).some((key) => !still.has(key))) {
199
+ return `full access for ${realm} is not covered by the grant it continues`;
200
+ }
201
+ }
202
+ if (candidate.publisher.evidence !== "verified" ||
203
+ source.publisherEvidence !== "verified" ||
204
+ canonicalJson(candidate.publisher.identity) !== canonicalJson(source.publisher)) {
205
+ return "continuity needs the same verified publisher";
206
+ }
207
+ return undefined;
208
+ }
209
+ const sortedUnion = (a, b) => [...new Set([...a, ...b])].sort();
210
+ /** The revision grants and the approved / candidate revision of each install (PG). */
211
+ let ExtensionRevisionGrants = class ExtensionRevisionGrants {
212
+ kdb;
213
+ txHost;
214
+ constructor(kdb, txHost) {
215
+ this.kdb = kdb;
216
+ this.txHost = txHost;
217
+ }
218
+ get db() {
219
+ return this.kdb.db;
220
+ }
221
+ /**
222
+ * Records an approval for one exact revision as a new generation. Recording the same review
223
+ * while that grant is approved returns it; any other review while a grant is live is a
224
+ * conflict. After a revocation or retirement a new review opens the next generation. Two
225
+ * replicas recording at once end in the same outcome: the loser re-reads the winner's row.
226
+ */
227
+ async record(input) {
228
+ const { purposes, realms, keys } = normalize(input);
229
+ const { revision } = input;
230
+ const live = await this.liveRow(revision, "update");
231
+ if (live)
232
+ return this.sameReview(live, input.reviewHash);
233
+ const newest = await this.get(revision);
234
+ if (newest && !REVIVING_SOURCES.has(input.source)) {
235
+ // A revoked or retired revision comes back only through a fresh human review, never
236
+ // through a preseed, automatic approval or continuity re-running.
237
+ throw new RevisionGrantError("terminal", `The grant of ${revision.plugin}@${revision.version} is ${newest.state}; only a new review restores it`);
238
+ }
239
+ let authority;
240
+ let continued;
241
+ if (input.continuedFrom) {
242
+ // A shared lock: continuations from one source don't queue behind each other, and a
243
+ // revocation of the source waits for this transaction.
244
+ continued = await this.liveRow(input.continuedFrom, "share");
245
+ if (!continued) {
246
+ throw new RevisionGrantError("not_live", "Continuity needs a live grant to continue");
247
+ }
248
+ const problem = continuityProblem(await this.withOrgs(continued), {
249
+ purposes,
250
+ realms,
251
+ approvalScope: input.approvalScope,
252
+ publisher: input.publisher,
253
+ });
254
+ if (problem)
255
+ throw new RevisionGrantError("not_continuous", `Not a continuation: ${problem}`);
256
+ authority = continued.authority;
257
+ }
258
+ else {
259
+ authority = SOURCE_AUTHORITY[input.source];
260
+ }
261
+ const { next } = await this.db
262
+ .selectFrom("extension_revision_grants")
263
+ .select(sql `coalesce(max(generation), 0) + 1`.as("next"))
264
+ .where(revisionIs(revision))
265
+ .executeTakeFirstOrThrow();
266
+ const inserted = await this.db
267
+ .insertInto("extension_revision_grants")
268
+ .values({
269
+ plugin: revision.plugin,
270
+ version: revision.version,
271
+ sha512: revision.sha512,
272
+ generation: next,
273
+ keys: JSON.stringify(keys),
274
+ purposes: JSON.stringify(purposes),
275
+ purposes_digest: purposesDigest(purposes),
276
+ realms: JSON.stringify(realms),
277
+ review_hash: input.reviewHash,
278
+ approval_scope: input.approvalScope.mode,
279
+ source: input.source,
280
+ authority,
281
+ publisher: input.publisher.evidence === "verified" ? JSON.stringify(input.publisher.identity) : null,
282
+ publisher_evidence: input.publisher.evidence,
283
+ continued_version: continued?.version ?? null,
284
+ continued_sha512: continued?.sha512 ?? null,
285
+ continued_generation: continued?.generation ?? null,
286
+ approved_by: input.approvedBy,
287
+ })
288
+ .onConflict((conflict) => conflict.doNothing())
289
+ .returning("generation")
290
+ .executeTakeFirst();
291
+ if (!inserted) {
292
+ // Another transaction recorded this revision first (its commit released our insert).
293
+ const winner = await this.liveRow(revision, "update");
294
+ if (!winner) {
295
+ throw new RevisionGrantError("conflict", "The revision changed while recording its grant");
296
+ }
297
+ return this.sameReview(winner, input.reviewHash);
298
+ }
299
+ if (input.approvalScope.mode === "named") {
300
+ const orgs = [...new Set(input.approvalScope.orgs)];
301
+ // org-filter: deployment-wide: a platform approval lists the orgs of its named scope.
302
+ await asPlatform("record the named approval scope of a revision grant", () => this.db
303
+ .insertInto("extension_revision_grant_orgs")
304
+ .values(orgs.map((orgId) => ({ ...revision, generation: next, org_id: orgId })))
305
+ .execute());
306
+ }
307
+ const stored = await this.liveRow(revision, "update");
308
+ if (!stored)
309
+ throw new RevisionGrantError("not_found", "The recorded grant is missing");
310
+ return this.withOrgs(stored);
311
+ }
312
+ /** The newest generation of a revision's grant in any state, or undefined. */
313
+ async get(revision) {
314
+ const row = (await this.select()
315
+ .where(revisionIs(revision))
316
+ .orderBy("generation", "desc")
317
+ .limit(1)
318
+ .executeTakeFirst());
319
+ return row ? this.withOrgs(row) : undefined;
320
+ }
321
+ /** The live (approved or partially revoked) grant of a revision, or undefined. */
322
+ async live(revision) {
323
+ const row = await this.liveRow(revision);
324
+ return row ? this.withOrgs(row) : undefined;
325
+ }
326
+ /** Every generation of a revision's grant, oldest first. */
327
+ async history(revision) {
328
+ const rows = (await this.select()
329
+ .where(revisionIs(revision))
330
+ .orderBy("generation")
331
+ .execute());
332
+ return Promise.all(rows.map((row) => this.withOrgs(row)));
333
+ }
334
+ /** Every grant of a plugin, newest approval first. */
335
+ async forPlugin(plugin) {
336
+ const rows = (await this.select()
337
+ .where("plugin", "=", plugin)
338
+ .orderBy("approved_at", "desc")
339
+ .orderBy("generation", "desc")
340
+ .execute());
341
+ return Promise.all(rows.map((row) => this.withOrgs(row)));
342
+ }
343
+ /**
344
+ * Revokes keys of a live grant (partial revocation; `execution.full-access:<realm>` revokes one
345
+ * realm). Revoking every key that is not retired revokes the grant. The reviewed rows stay;
346
+ * only `disabled_keys` grows.
347
+ */
348
+ async revokeKeys(revision, keys, actor) {
349
+ const row = await this.requireLive(revision);
350
+ this.checkKeys(row, keys);
351
+ const disabled = sortedUnion(row.disabled_keys, keys);
352
+ const remaining = row.keys.filter((key) => !disabled.includes(key) && !row.retired_keys.includes(key));
353
+ return this.update(row, actor, {
354
+ state: remaining.length === 0 ? "revoked" : "partially_revoked",
355
+ disabled_keys: disabled,
356
+ });
357
+ }
358
+ /** Revokes a live grant entirely. */
359
+ async revoke(revision, actor) {
360
+ const row = await this.requireLive(revision);
361
+ return this.update(row, actor, { state: "revoked" });
362
+ }
363
+ /**
364
+ * Retires a live grant whose revision is superseded as a whole. Retirement is not revocation,
365
+ * and nothing revives it automatically; a new review opens the next generation.
366
+ */
367
+ async retire(revision, actor) {
368
+ const row = await this.requireLive(revision);
369
+ return this.update(row, actor, { state: "retired" });
370
+ }
371
+ /**
372
+ * Retires keys of a live grant that are no longer needed; the grant stays live. Retiring every
373
+ * key leaves an approved revision with an empty surface, which is valid: a package may declare
374
+ * no permissions at all. Retire the whole grant with {@link retire} when the revision goes.
375
+ */
376
+ async retireKeys(revision, keys, actor) {
377
+ const row = await this.requireLive(revision);
378
+ this.checkKeys(row, keys);
379
+ return this.update(row, actor, { retired_keys: sortedUnion(row.retired_keys, keys) });
380
+ }
381
+ /**
382
+ * Retires one forcing key of a full-access realm (the supervisor became available, so
383
+ * `host.no-isolation` no longer applies). When no forcing key of the realm remains, its
384
+ * `execution.full-access:<realm>` key is retired too; the rest of the grant stays live.
385
+ */
386
+ async retireForcing(revision, realm, forcingKey, actor) {
387
+ const row = await this.requireLive(revision);
388
+ const forcing = row.realms[realm];
389
+ if (!forcing?.includes(forcingKey)) {
390
+ throw new RevisionGrantError("unknown_keys", `${forcingKey} does not force ${realm} here`);
391
+ }
392
+ const retiredForcing = { ...row.retired_forcing };
393
+ retiredForcing[realm] = sortedUnion(retiredForcing[realm] ?? [], [forcingKey]);
394
+ const exhausted = forcing.every((key) => retiredForcing[realm]?.includes(key));
395
+ return this.update(row, actor, {
396
+ retired_forcing: retiredForcing,
397
+ ...(exhausted && { retired_keys: sortedUnion(row.retired_keys, [fullAccessKey(realm)]) }),
398
+ });
399
+ }
400
+ /** The approved (with its grant generation) and candidate revision of an install. */
401
+ async installRevisions(plugin) {
402
+ const row = await this.db
403
+ .selectFrom("extension_installs")
404
+ .select([
405
+ "approved_version",
406
+ "approved_sha512",
407
+ "approved_generation",
408
+ "candidate_version",
409
+ "candidate_sha512",
410
+ ])
411
+ .where("name", "=", plugin)
412
+ .executeTakeFirst();
413
+ if (!row)
414
+ throw new RevisionGrantError("not_found", `No install record for ${plugin}`);
415
+ return {
416
+ approved: row.approved_version !== null &&
417
+ row.approved_sha512 !== null &&
418
+ row.approved_generation !== null
419
+ ? {
420
+ plugin,
421
+ version: row.approved_version,
422
+ sha512: row.approved_sha512,
423
+ generation: row.approved_generation,
424
+ }
425
+ : undefined,
426
+ candidate: row.candidate_version !== null && row.candidate_sha512 !== null
427
+ ? { plugin, version: row.candidate_version, sha512: row.candidate_sha512 }
428
+ : undefined,
429
+ };
430
+ }
431
+ /** Sets or clears the candidate revision of an install; a candidate needs no grant. */
432
+ async setCandidate(plugin, candidate) {
433
+ if (candidate) {
434
+ checkRevision(candidate);
435
+ if (candidate.plugin !== plugin) {
436
+ throw new RevisionGrantError("invalid", "The candidate belongs to another plugin");
437
+ }
438
+ }
439
+ const result = await this.db
440
+ .updateTable("extension_installs")
441
+ .set({
442
+ candidate_version: candidate?.version ?? null,
443
+ candidate_sha512: candidate?.sha512 ?? null,
444
+ })
445
+ .where("name", "=", plugin)
446
+ .executeTakeFirst();
447
+ if (result.numUpdatedRows === 0n) {
448
+ throw new RevisionGrantError("not_found", `No install record for ${plugin}`);
449
+ }
450
+ }
451
+ /**
452
+ * Makes a revision the approved one of its install, under its live grant's generation (rechecked
453
+ * under the grant's row lock). The candidate is cleared in the same statement only if it is
454
+ * this revision, so a candidate another request set meanwhile survives.
455
+ */
456
+ async promote(revision) {
457
+ const row = await this.requireLive(revision);
458
+ const isThis = sql `candidate_version = ${revision.version}
459
+ AND candidate_sha512 = ${revision.sha512}`;
460
+ const result = await this.db
461
+ .updateTable("extension_installs")
462
+ .set({
463
+ approved_version: revision.version,
464
+ approved_sha512: revision.sha512,
465
+ approved_generation: row.generation,
466
+ candidate_version: sql `CASE WHEN ${isThis} THEN NULL ELSE candidate_version END`,
467
+ candidate_sha512: sql `CASE WHEN ${isThis} THEN NULL ELSE candidate_sha512 END`,
468
+ })
469
+ .where("name", "=", revision.plugin)
470
+ .executeTakeFirst();
471
+ if (result.numUpdatedRows === 0n) {
472
+ throw new RevisionGrantError("not_found", `No install record for ${revision.plugin}`);
473
+ }
474
+ }
475
+ sameReview(live, reviewHash) {
476
+ if (live.review_hash === reviewHash && live.state === "approved")
477
+ return this.withOrgs(live);
478
+ const reason = live.review_hash === reviewHash ? `is ${live.state}` : "was approved under another review";
479
+ throw new RevisionGrantError("conflict", `The live grant of ${live.plugin}@${live.version} ${reason}`);
480
+ }
481
+ checkKeys(row, keys) {
482
+ const unknown = keys.filter((key) => !row.keys.includes(key));
483
+ if (keys.length === 0 || unknown.length > 0) {
484
+ throw new RevisionGrantError("unknown_keys", `Not keys of this grant: ${unknown.join(", ")}`);
485
+ }
486
+ }
487
+ async update(row, actor, set) {
488
+ await this.db
489
+ .updateTable("extension_revision_grants")
490
+ .set({
491
+ ...(set.state !== undefined && { state: set.state }),
492
+ ...(set.disabled_keys !== undefined && {
493
+ disabled_keys: JSON.stringify(set.disabled_keys),
494
+ }),
495
+ ...(set.retired_keys !== undefined && { retired_keys: JSON.stringify(set.retired_keys) }),
496
+ ...(set.retired_forcing !== undefined && {
497
+ retired_forcing: JSON.stringify(set.retired_forcing),
498
+ }),
499
+ state_changed_by: actor,
500
+ state_changed_at: sql `now()`,
501
+ })
502
+ .where(revisionIs(row))
503
+ .where("generation", "=", row.generation)
504
+ .execute();
505
+ const stored = (await this.select()
506
+ .where(revisionIs(row))
507
+ .where("generation", "=", row.generation)
508
+ .executeTakeFirst());
509
+ if (!stored)
510
+ throw new RevisionGrantError("not_found", "The grant is missing");
511
+ return this.withOrgs(stored);
512
+ }
513
+ async requireLive(revision) {
514
+ checkRevision(revision);
515
+ const row = await this.liveRow(revision, "update");
516
+ if (row)
517
+ return row;
518
+ const newest = await this.get(revision);
519
+ throw newest
520
+ ? new RevisionGrantError("terminal", `The grant of ${revision.plugin}@${revision.version} is ${newest.state}`)
521
+ : new RevisionGrantError("not_found", `${revision.plugin}@${revision.version} has no grant`);
522
+ }
523
+ /** The live generation, optionally locked for this transaction (callers run inside one). */
524
+ async liveRow(revision, lock) {
525
+ let query = this.select().where(revisionIs(revision)).where("state", "in", LIVE_STATES);
526
+ // NO KEY UPDATE: the row's key never changes, so promotions taking the installs foreign key's
527
+ // KEY SHARE lock on this row don't queue behind it.
528
+ if (lock === "update")
529
+ query = query.forNoKeyUpdate();
530
+ if (lock === "share")
531
+ query = query.forShare();
532
+ return (await query.executeTakeFirst());
533
+ }
534
+ select() {
535
+ return this.db.selectFrom("extension_revision_grants").selectAll();
536
+ }
537
+ async withOrgs(row) {
538
+ if (row.approval_scope !== "named")
539
+ return toGrant(row, []);
540
+ // org-filter: deployment-wide: a platform approval's named scope spans orgs.
541
+ const orgs = await asPlatform("read the named approval scope of a revision grant", () => this.db
542
+ .selectFrom("extension_revision_grant_orgs")
543
+ .select("org_id")
544
+ .where("plugin", "=", row.plugin)
545
+ .where("version", "=", row.version)
546
+ .where("sha512", "=", row.sha512)
547
+ .where("generation", "=", row.generation)
548
+ .execute());
549
+ return toGrant(row, orgs.map((org) => org.org_id));
550
+ }
551
+ };
552
+ __decorate([
553
+ Transactional()
554
+ ], ExtensionRevisionGrants.prototype, "record", null);
555
+ __decorate([
556
+ Transactional()
557
+ ], ExtensionRevisionGrants.prototype, "revokeKeys", null);
558
+ __decorate([
559
+ Transactional()
560
+ ], ExtensionRevisionGrants.prototype, "revoke", null);
561
+ __decorate([
562
+ Transactional()
563
+ ], ExtensionRevisionGrants.prototype, "retire", null);
564
+ __decorate([
565
+ Transactional()
566
+ ], ExtensionRevisionGrants.prototype, "retireKeys", null);
567
+ __decorate([
568
+ Transactional()
569
+ ], ExtensionRevisionGrants.prototype, "retireForcing", null);
570
+ __decorate([
571
+ Transactional()
572
+ ], ExtensionRevisionGrants.prototype, "setCandidate", null);
573
+ __decorate([
574
+ Transactional()
575
+ ], ExtensionRevisionGrants.prototype, "promote", null);
576
+ ExtensionRevisionGrants = __decorate([
577
+ Injectable(),
578
+ __param(0, Inject(KernelDb)),
579
+ __param(1, Inject(TransactionHost))
580
+ ], ExtensionRevisionGrants);
581
+ export { ExtensionRevisionGrants };
582
+ function revisionIs({ plugin, version, sha512 }) {
583
+ return (eb) => eb.and([eb("plugin", "=", plugin), eb("version", "=", version), eb("sha512", "=", sha512)]);
584
+ }
@@ -14,6 +14,8 @@ import { ExtensionBlobs } from "./blobs.js";
14
14
  import { EffectiveConfigs } from "./effective-config.js";
15
15
  import { ExtensionInstalls } from "./installs.js";
16
16
  import { ExtensionRegistryModule } from "./registry.js";
17
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
18
+ import { ExtensionRevisionGrants } from "./revision-grants.js";
17
19
  /**
18
20
  * The extension state the model domain reads below the host: the install records with their
19
21
  * packages and approvals, and each extension's effective config per org. Apart from
@@ -33,13 +35,22 @@ ExtensionStateModule = __decorate([
33
35
  // a package with client code stores its client build (`ExtensionBlobs`)
34
36
  ClientModule,
35
37
  ],
36
- providers: [ExtensionApprovals, ExtensionBlobs, ExtensionInstalls, EffectiveConfigs],
38
+ providers: [
39
+ ExtensionApprovals,
40
+ ExtensionBlobs,
41
+ ExtensionInstalls,
42
+ EffectiveConfigs,
43
+ ExtensionRevisionGrants,
44
+ ExtensionRevisionApprovals,
45
+ ],
37
46
  exports: [
38
47
  ExtensionRegistryModule,
39
48
  ExtensionApprovals,
40
49
  ExtensionBlobs,
41
50
  ExtensionInstalls,
42
51
  EffectiveConfigs,
52
+ ExtensionRevisionGrants,
53
+ ExtensionRevisionApprovals,
43
54
  ],
44
55
  })
45
56
  ], ExtensionStateModule);
@@ -4,6 +4,7 @@ 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
6
  import { OutboxService } from "../infra/outbox/outbox.service.js";
7
+ import { type Page } from "../infra/paging/paged-read.js";
7
8
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
8
9
  import { type AccountAvatar, type AccountView } from "./account-avatar.js";
9
10
  import type { Preferences } from "./me.schemas.js";
@@ -140,10 +141,15 @@ export declare class AccountsService {
140
141
  idleCompaction?: "off" | null | undefined;
141
142
  }): Promise<Preferences>;
142
143
  /** 按 id 升序分页,`after` 为上一页最后一个 id。 */
143
- list(opts: {
144
- limit: number;
145
- after?: string;
146
- }): Promise<Account[]>;
144
+ /**
145
+ * One page of every account, newest first (`created_at`, then id), by page number without a
146
+ * snapshot (table pagination spec §2.3: accounts are edited in place). Pages past the count cap
147
+ * are refused.
148
+ */
149
+ list(q: {
150
+ page: number;
151
+ size: number;
152
+ }): Promise<Page<Account>>;
147
153
  setPassword(accountId: string, password: string): Promise<void>;
148
154
  /**
149
155
  * A person changes their password (R24): one PG transaction writes the new password and revokes
@@ -18,6 +18,7 @@ import { asPlatform } from "../infra/database/org-scope.js";
18
18
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
19
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
20
  import { OutboxService } from "../infra/outbox/outbox.service.js";
21
+ import { assertReadablePage, cappedCount, PAGED_TOTAL_CAP, pageOf, pageOffset, } from "../infra/paging/paged-read.js";
21
22
  import { deletePushRegistrationsForSessions } from "../push/registration-cleanup.js";
22
23
  import { PermissionCeilingWritesModule } from "../sandbox/permission-authority.module.js";
23
24
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
@@ -314,11 +315,23 @@ let AccountsService = class AccountsService {
314
315
  return this.preferences(accountId);
315
316
  }
316
317
  /** 按 id 升序分页,`after` 为上一页最后一个 id。 */
317
- async list(opts) {
318
- let q = this.db.selectFrom("accounts").selectAll().orderBy("id").limit(opts.limit);
319
- if (opts.after !== undefined)
320
- q = q.where("id", ">", opts.after);
321
- return (await q.execute()).map(toAccount);
318
+ /**
319
+ * One page of every account, newest first (`created_at`, then id), by page number without a
320
+ * snapshot (table pagination spec §2.3: accounts are edited in place). Pages past the count cap
321
+ * are refused.
322
+ */
323
+ async list(q) {
324
+ assertReadablePage(q.page, q.size);
325
+ const all = this.db.selectFrom("accounts");
326
+ const counted = await cappedCount(this.db.db, all, PAGED_TOTAL_CAP);
327
+ const rows = await all
328
+ .selectAll()
329
+ .orderBy("created_at", "desc")
330
+ .orderBy("id", "desc")
331
+ .offset(pageOffset(q.page, q.size))
332
+ .limit(q.size)
333
+ .execute();
334
+ return pageOf(rows.map(toAccount), q, counted);
322
335
  }
323
336
  async setPassword(accountId, password) {
324
337
  validatePassword(password);