@capybara-hq/kernel 0.1.0-rc.45 → 0.1.0-rc.46

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 (100) hide show
  1. package/dist/admin/admin.schemas.d.ts +6 -0
  2. package/dist/agents/agent-lookup.d.ts +5 -2
  3. package/dist/agents/agent-lookup.js +3 -0
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/config/schema.d.ts +7 -0
  6. package/dist/config/schema.js +27 -0
  7. package/dist/conversations/access.d.ts +14 -5
  8. package/dist/conversations/access.js +29 -20
  9. package/dist/conversations/conversations.service.d.ts +6 -1
  10. package/dist/conversations/conversations.service.js +12 -2
  11. package/dist/conversations/files.d.ts +43 -0
  12. package/dist/conversations/files.js +80 -3
  13. package/dist/ctx/create-ctx.d.ts +7 -0
  14. package/dist/ctx/create-ctx.js +9 -2
  15. package/dist/db/kernel-schema.d.ts +30 -0
  16. package/dist/errors.d.ts +22 -0
  17. package/dist/errors.js +22 -0
  18. package/dist/extensions/extensions.module.js +3 -0
  19. package/dist/extensions/host.d.ts +4 -1
  20. package/dist/extensions/host.js +15 -10
  21. package/dist/files/previewers.d.ts +44 -0
  22. package/dist/files/previewers.js +84 -30
  23. package/dist/html/csp.d.ts +13 -0
  24. package/dist/html/csp.js +33 -0
  25. package/dist/html/html-document.controller.d.ts +31 -0
  26. package/dist/html/html-document.controller.js +75 -0
  27. package/dist/html/html-document.service.d.ts +49 -0
  28. package/dist/html/html-document.service.js +143 -0
  29. package/dist/html/html-token.d.ts +58 -0
  30. package/dist/html/html-token.js +154 -0
  31. package/dist/html/html-type.d.ts +13 -0
  32. package/dist/html/html-type.js +40 -0
  33. package/dist/html/html.module.d.ts +6 -0
  34. package/dist/html/html.module.js +26 -0
  35. package/dist/http/api.module.js +14 -0
  36. package/dist/http/error.filter.d.ts +2 -0
  37. package/dist/http/error.filter.js +9 -2
  38. package/dist/http/plugin-route-access.d.ts +2 -1
  39. package/dist/http/plugin-route-access.js +16 -1
  40. package/dist/identity/settings.d.ts +26 -1
  41. package/dist/identity/settings.js +88 -2
  42. package/dist/infra/config/kernel-config.service.js +3 -0
  43. package/dist/infra/outbox/registry.d.ts +13 -0
  44. package/dist/infra/outbox/registry.js +8 -0
  45. package/dist/infra/throttler/credential-throttler.d.ts +4 -1
  46. package/dist/infra/throttler/credential-throttler.js +5 -2
  47. package/dist/infra/throttler/named-throttlers.d.ts +1 -0
  48. package/dist/infra/throttler/named-throttlers.js +14 -0
  49. package/dist/orgs/offboarding.d.ts +3 -1
  50. package/dist/orgs/offboarding.js +7 -1
  51. package/dist/orgs/settings.service.d.ts +21 -4
  52. package/dist/orgs/settings.service.js +47 -7
  53. package/dist/overrides.d.ts +3 -0
  54. package/dist/overrides.js +2 -0
  55. package/dist/platform/exclusions.js +63 -0
  56. package/dist/platform/operation.js +1 -1
  57. package/dist/platform/ops/admin.ops.js +18 -3
  58. package/dist/platform/ops/org-settings.ops.js +6 -2
  59. package/dist/platform/ops/orgs.ops.js +3 -0
  60. package/dist/platform/ops/shares.ops.d.ts +16 -0
  61. package/dist/platform/ops/shares.ops.js +107 -0
  62. package/dist/platform/platform-ops.module.d.ts +2 -1
  63. package/dist/platform/platform-ops.module.js +5 -0
  64. package/dist/platform/route-schemas.js +3 -0
  65. package/dist/roles/worker.module.js +6 -0
  66. package/dist/runtime/maintenance.d.ts +4 -2
  67. package/dist/runtime/maintenance.js +14 -4
  68. package/dist/shares/liveness.d.ts +59 -0
  69. package/dist/shares/liveness.js +163 -0
  70. package/dist/shares/revoke.d.ts +26 -0
  71. package/dist/shares/revoke.js +43 -0
  72. package/dist/shares/settings.d.ts +76 -0
  73. package/dist/shares/settings.js +117 -0
  74. package/dist/shares/share-code.d.ts +4 -0
  75. package/dist/shares/share-code.js +28 -0
  76. package/dist/shares/share-objects.d.ts +52 -0
  77. package/dist/shares/share-objects.js +123 -0
  78. package/dist/shares/share-open.controller.d.ts +35 -0
  79. package/dist/shares/share-open.controller.js +107 -0
  80. package/dist/shares/share-open.service.d.ts +107 -0
  81. package/dist/shares/share-open.service.js +287 -0
  82. package/dist/shares/share-previews.controller.d.ts +50 -0
  83. package/dist/shares/share-previews.controller.js +115 -0
  84. package/dist/shares/shares.controller.d.ts +34 -0
  85. package/dist/shares/shares.controller.js +114 -0
  86. package/dist/shares/shares.module.d.ts +8 -0
  87. package/dist/shares/shares.module.js +41 -0
  88. package/dist/shares/shares.schemas.d.ts +31 -0
  89. package/dist/shares/shares.schemas.js +25 -0
  90. package/dist/shares/shares.service.d.ts +182 -0
  91. package/dist/shares/shares.service.js +553 -0
  92. package/dist/shares/sweep.job.d.ts +72 -0
  93. package/dist/shares/sweep.job.js +330 -0
  94. package/dist/tools/builtins/sandbox/deliver.js +3 -1
  95. package/dist/ui/embed-token.d.ts +2 -2
  96. package/dist/ui/embed-token.js +38 -2
  97. package/dist/ui/views.d.ts +6 -0
  98. package/dist/ui/views.js +17 -0
  99. package/package.json +4 -4
  100. package/src/migrations/0161_file_shares.sql +35 -0
@@ -0,0 +1,330 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { TransactionHost } from "../infra/database/transaction-host.js";
14
+ import { Transactional } from "../infra/database/transactional.decorator.js";
15
+ import { LockService } from "../infra/lock/lock.service.js";
16
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
17
+ import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
18
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
19
+ import { StorageService } from "../storage/storage.service.js";
20
+ import { creatorStillHasAccess } from "./liveness.js";
21
+ import { revokeSharesIn } from "./revoke.js";
22
+ import { ShareObjects, shareObjectKey, shareRefreshLockKey, } from "./share-objects.js";
23
+ /** The daily share sweep's name (scheduler key and lock; no `:`). */
24
+ export const SHARE_SWEEP_JOB = "share-sweep";
25
+ /** Rows per batch (one transaction per batch of revokes; one query per batch of reads). */
26
+ const BATCH = 200;
27
+ /** Snapshots of shares expired or revoked longer ago than this are deleted (rows kept). */
28
+ const RETAIN_DAYS = 7;
29
+ /** An object under `shares/` no row names is deleted only once it is older than this. */
30
+ const ORPHAN_AGE_MS = 60 * 60 * 1000;
31
+ /** The objects listed per page when looking for orphans. */
32
+ const LIST_PAGE = 1000;
33
+ /** The sweep's hold on a share's refresh lock (tried once; a refresh holding it skips the key). */
34
+ const REFRESH_LOCK_TTL_MS = 30_000;
35
+ /**
36
+ * `shares/<shareId>/<generation>`, the only key shape the shares module writes. Only the shares
37
+ * module writes under `shares/`, so a key of any other shape is no snapshot and is deleted directly.
38
+ */
39
+ const SHARE_KEY_RE = /^shares\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(\d+)$/;
40
+ /**
41
+ * The daily share sweep (file sharing spec §9), a `@LockedCron` (once per tick across replicas,
42
+ * provided only under `WorkerModule`). In order, with every storage call outside a transaction:
43
+ *
44
+ * 1. revokes with `creator_lost_access` the unrevoked, unexpired shares whose creator fails the
45
+ * live check's creator predicates (account disabled, no longer a member, agent deleted or hidden,
46
+ * the conversation or its root deleted), one transaction per batch, owing each snapshot's
47
+ * deletion through the outbox (the open routes already refuse them; this frees the snapshot and
48
+ * shows a reason in the lists);
49
+ * 2. deletes the snapshots of shares expired or revoked more than {@link RETAIN_DAYS} days ago that
50
+ * still name one (a revoke owes its deletion at once; this is the expired shares' path and the
51
+ * backstop) and clears `object_key`; the rows stay for the audit trail;
52
+ * 3. per organization not deleted, lists `shares/` and deletes every object older than one hour
53
+ * that is not the `object_key` of its row (no row: an insert that failed after its copy; another
54
+ * generation: a refresh that died between its copy and its commit). An object whose age the
55
+ * store does not report is kept. Its age is read again (`head`) just before the delete, and a
56
+ * non-current generation of an existing share is deleted only under that share's refresh lock
57
+ * (tried once), so a retried refresh writing the same key again is never undone.
58
+ *
59
+ * Steps 2 and 3 go through {@link ShareObjects.deleteObject}, which re-reads the row and never
60
+ * deletes the snapshot a share that is neither revoked nor expired currently names. Deleted
61
+ * organizations are skipped: their objects go with `storage-org-purge`. Nothing is kept in process
62
+ * memory between runs; a run that stops midway (abort, error) is finished by the next one.
63
+ */
64
+ let ShareSweepJob = class ShareSweepJob {
65
+ db;
66
+ txHost;
67
+ outbox;
68
+ objects;
69
+ storage;
70
+ lockService;
71
+ log;
72
+ constructor(db, txHost, outbox, objects, storage, lockService, log) {
73
+ this.db = db;
74
+ this.txHost = txHost;
75
+ this.outbox = outbox;
76
+ this.objects = objects;
77
+ this.storage = storage;
78
+ this.lockService = lockService;
79
+ this.log = log;
80
+ }
81
+ async sweep(signal) {
82
+ const r = await this.runOnce(signal);
83
+ if (r.revoked + r.freed + r.orphans > 0)
84
+ this.log.info("share sweep done", { ...r });
85
+ }
86
+ /** One sweep without the tick lock (the cron body; tests call it directly). */
87
+ async runOnce(signal) {
88
+ const revoked = await this.revokeLostAccess(signal);
89
+ if (!this.storage.available)
90
+ return { revoked, freed: 0, orphans: 0 };
91
+ const freed = await this.freeOld(signal);
92
+ const orphans = await this.deleteOrphans(signal);
93
+ return { revoked, freed, orphans };
94
+ }
95
+ /** Step 1: revokes, batch by batch, the shares whose creator lost access. */
96
+ async revokeLostAccess(signal) {
97
+ let revoked = 0;
98
+ let after = null;
99
+ while (!signal?.aborted) {
100
+ const rows = await this.db
101
+ .selectFrom("file_shares")
102
+ .innerJoin("orgs", "orgs.id", "file_shares.org_id")
103
+ .select("file_shares.id")
104
+ .where("orgs.deleted_at", "is", null)
105
+ .where("file_shares.revoked_at", "is", null)
106
+ .where("file_shares.object_key", "is not", null)
107
+ .where((eb) => eb.or([
108
+ eb("file_shares.expires_at", "is", null),
109
+ eb("file_shares.expires_at", ">", sql `now()`),
110
+ ]))
111
+ .where((eb) => eb.not(creatorStillHasAccess(eb)))
112
+ .$if(after !== null, (q) => q.where("file_shares.id", ">", after))
113
+ .orderBy("file_shares.id")
114
+ .limit(BATCH)
115
+ .execute();
116
+ if (rows.length === 0)
117
+ break;
118
+ revoked += await this.revokeBatch(rows.map((r) => r.id));
119
+ after = rows.at(-1).id;
120
+ if (rows.length < BATCH)
121
+ break;
122
+ }
123
+ return revoked;
124
+ }
125
+ /** One batch of step 1 (the creator's access is checked again in the `UPDATE`). */
126
+ async revokeBatch(shareIds) {
127
+ return revokeSharesIn(this.db.db, this.outbox, { shareIds }, "creator_lost_access");
128
+ }
129
+ /** Step 2: frees the snapshots of shares expired or revoked more than a week ago. */
130
+ async freeOld(signal) {
131
+ let freed = 0;
132
+ let after = null;
133
+ while (!signal?.aborted) {
134
+ const old = sql `now() - make_interval(days => ${RETAIN_DAYS})`;
135
+ const rows = await this.db
136
+ .selectFrom("file_shares")
137
+ .innerJoin("orgs", "orgs.id", "file_shares.org_id")
138
+ .select([
139
+ "file_shares.id",
140
+ "file_shares.org_id",
141
+ "file_shares.generation",
142
+ "file_shares.object_key",
143
+ ])
144
+ .where("orgs.deleted_at", "is", null)
145
+ .where("file_shares.object_key", "is not", null)
146
+ .where((eb) => eb.or([
147
+ eb("file_shares.revoked_at", "<", old),
148
+ eb.and([
149
+ eb("file_shares.revoked_at", "is", null),
150
+ eb("file_shares.expires_at", "<", old),
151
+ ]),
152
+ ]))
153
+ .$if(after !== null, (q) => q.where("file_shares.id", ">", after))
154
+ .orderBy("file_shares.id")
155
+ .limit(BATCH)
156
+ .execute();
157
+ if (rows.length === 0)
158
+ break;
159
+ for (const r of rows) {
160
+ if (signal?.aborted)
161
+ break;
162
+ const data = {
163
+ orgId: r.org_id,
164
+ shareId: r.id,
165
+ generation: r.generation,
166
+ objectKey: r.object_key,
167
+ };
168
+ if (await this.deleteGuarded(data))
169
+ freed++;
170
+ }
171
+ after = rows.at(-1).id;
172
+ if (rows.length < BATCH)
173
+ break;
174
+ }
175
+ return freed;
176
+ }
177
+ /** Step 3: deletes the orphan objects under `shares/` of every organization not deleted. */
178
+ async deleteOrphans(signal) {
179
+ let deleted = 0;
180
+ let after = null;
181
+ while (!signal?.aborted) {
182
+ const orgs = await this.db
183
+ .selectFrom("orgs")
184
+ .select("id")
185
+ .where("deleted_at", "is", null)
186
+ .$if(after !== null, (q) => q.where("id", ">", after))
187
+ .orderBy("id")
188
+ .limit(BATCH)
189
+ .execute();
190
+ for (const o of orgs) {
191
+ if (signal?.aborted)
192
+ break;
193
+ try {
194
+ deleted += await this.orphansOf(o.id, signal);
195
+ }
196
+ catch (err) {
197
+ this.log.warn("share sweep: cannot clean orphan snapshots; the next run retries", {
198
+ orgId: o.id,
199
+ err,
200
+ });
201
+ }
202
+ }
203
+ if (orgs.length < BATCH)
204
+ break;
205
+ after = orgs.at(-1).id;
206
+ }
207
+ return deleted;
208
+ }
209
+ /** The orphan objects of one organization, page by page. */
210
+ async orphansOf(orgId, signal) {
211
+ const store = this.storage.kernel(orgId);
212
+ let deleted = 0;
213
+ let cursor;
214
+ do {
215
+ const page = await store.list("shares/", {
216
+ limit: LIST_PAGE,
217
+ ...(cursor !== undefined && { cursor }),
218
+ });
219
+ cursor = page.cursor;
220
+ // the rows are read once per page; `deleteObject` reads its row again before deleting
221
+ const cutoff = Date.now() - ORPHAN_AGE_MS;
222
+ const old = page.items.filter((i) => {
223
+ const at = i.lastModified === undefined ? Number.NaN : Date.parse(i.lastModified);
224
+ return Number.isFinite(at) && at < cutoff;
225
+ });
226
+ const parsed = old.map((i) => ({ key: i.key, m: SHARE_KEY_RE.exec(i.key) }));
227
+ const ids = [...new Set(parsed.flatMap((p) => (p.m ? [p.m[1]] : [])))];
228
+ const named = new Map();
229
+ if (ids.length > 0) {
230
+ const rows = await this.db
231
+ .selectFrom("file_shares")
232
+ .select(["id", "object_key"])
233
+ .where("org_id", "=", orgId)
234
+ .where("id", "in", ids)
235
+ .execute();
236
+ for (const r of rows)
237
+ named.set(r.id, r.object_key);
238
+ }
239
+ for (const p of parsed) {
240
+ if (signal?.aborted)
241
+ return deleted;
242
+ const shareId = p.m?.[1];
243
+ const generation = Number(p.m?.[2]);
244
+ const snapshot = shareId !== undefined &&
245
+ Number.isSafeInteger(generation) &&
246
+ shareObjectKey(shareId, generation) === p.key;
247
+ if (!snapshot || shareId === undefined) {
248
+ if (await this.stillOld(store, p.key, cutoff)) {
249
+ await store.delete(p.key);
250
+ deleted++;
251
+ }
252
+ continue;
253
+ }
254
+ if (named.get(shareId) === p.key)
255
+ continue; // its row's snapshot: step 2's, not an orphan
256
+ const data = { orgId, shareId, generation, objectKey: p.key };
257
+ if (!named.has(shareId)) {
258
+ // no row (an insert that failed after its copy): a new create uses a new id
259
+ if ((await this.stillOld(store, p.key, cutoff)) && (await this.deleteGuarded(data))) {
260
+ deleted++;
261
+ }
262
+ continue;
263
+ }
264
+ // another generation of an existing share: a retried refresh may be writing this very key
265
+ // again, its commit about to name it. Held, the refresh lock means no refresh is between its
266
+ // copy and its commit, so the row `deleteObject` reads is the last word; a refresh holding
267
+ // it now skips the key (the next run sees it again)
268
+ const lock = await this.lockService.acquire(shareRefreshLockKey(shareId), {
269
+ ttlMs: REFRESH_LOCK_TTL_MS,
270
+ waitMs: 0,
271
+ });
272
+ if (!lock)
273
+ continue;
274
+ try {
275
+ if ((await this.stillOld(store, p.key, cutoff)) && (await this.deleteGuarded(data))) {
276
+ deleted++;
277
+ }
278
+ }
279
+ finally {
280
+ await lock.release();
281
+ }
282
+ }
283
+ } while (cursor !== undefined && !signal?.aborted);
284
+ return deleted;
285
+ }
286
+ /**
287
+ * Whether `key` is still older than `cutoff` now: the listing may be stale (an upload that started
288
+ * long ago, or a key written again since), so its age is read again just before deleting it.
289
+ */
290
+ async stillOld(store, key, cutoff) {
291
+ const head = await store.head(key);
292
+ if (!head?.lastModified)
293
+ return false;
294
+ const at = Date.parse(head.lastModified);
295
+ return Number.isFinite(at) && at < cutoff;
296
+ }
297
+ /** {@link ShareObjects.deleteObject}, logging instead of throwing (one bad object stops nothing). */
298
+ async deleteGuarded(data) {
299
+ try {
300
+ await this.objects.deleteObject(data);
301
+ return true;
302
+ }
303
+ catch (err) {
304
+ this.log.warn("share sweep: cannot delete a share snapshot; the next run retries", {
305
+ orgId: data.orgId,
306
+ shareId: data.shareId,
307
+ generation: data.generation,
308
+ err,
309
+ });
310
+ return false;
311
+ }
312
+ }
313
+ };
314
+ __decorate([
315
+ LockedCron("40 3 * * *", { name: SHARE_SWEEP_JOB })
316
+ ], ShareSweepJob.prototype, "sweep", null);
317
+ __decorate([
318
+ Transactional()
319
+ ], ShareSweepJob.prototype, "revokeBatch", null);
320
+ ShareSweepJob = __decorate([
321
+ Injectable(),
322
+ __param(0, Inject(KernelDb)),
323
+ __param(1, Inject(TransactionHost)),
324
+ __param(2, Inject(OutboxService)),
325
+ __param(3, Inject(ShareObjects)),
326
+ __param(4, Inject(StorageService)),
327
+ __param(5, Inject(LockService)),
328
+ __param(6, Inject(KERNEL_LOGGER))
329
+ ], ShareSweepJob);
330
+ export { ShareSweepJob };
@@ -10,7 +10,9 @@ const SPEC = {
10
10
  "it when the user should receive a file you produced (a report, chart, spreadsheet, archive " +
11
11
  "and so on); files that stay in the sandbox are not visible to the user. Delivers one file " +
12
12
  "per call; archive a directory first (e.g. tar -czf with Bash). The file size is " +
13
- "limited (100 MB by default). Do not use it for intermediate files the user does not need.",
13
+ "limited (100 MB by default). Do not use it for intermediate files the user does not need. " +
14
+ "An HTML report should be one self-contained file: inline its own CSS and JS, load " +
15
+ "libraries from a public CDN, embed images as data URLs.",
14
16
  inputSchema: {
15
17
  type: "object",
16
18
  properties: {
@@ -1,4 +1,4 @@
1
- import type { EmbedClaims, OrgEmbedClaims, PlatformEmbedClaims } from "@capybara-hq/plugin-sdk";
1
+ import type { EmbedClaims, OrgEmbedClaims, PlatformEmbedClaims, ShareEmbedClaims } from "@capybara-hq/plugin-sdk";
2
2
  import type { Keyring } from "../ctx/secrets.js";
3
3
  /** 嵌入令牌的有效期(秒)。网页在过期前 60 秒续期。 */
4
4
  export declare const EMBED_TOKEN_TTL_SECONDS = 300;
@@ -22,7 +22,7 @@ export declare class EmbedTokens {
22
22
  private readonly keys;
23
23
  constructor(keyring: Keyring, now?: () => number);
24
24
  /** 签发:`exp` = 现在 + {@link EMBED_TOKEN_TTL_SECONDS}。 */
25
- issue(c: Omit<OrgEmbedClaims, "exp"> | Omit<PlatformEmbedClaims, "exp">): {
25
+ issue(c: Omit<OrgEmbedClaims, "exp"> | Omit<PlatformEmbedClaims, "exp"> | Omit<ShareEmbedClaims, "exp">): {
26
26
  token: string;
27
27
  claims: EmbedClaims;
28
28
  expiresAt: Date;
@@ -31,6 +31,8 @@ const CLAIM_KEYS = new Set([
31
31
  "conversationId",
32
32
  "agentId",
33
33
  "fileId",
34
+ "shareId",
35
+ "generation",
34
36
  "contribution",
35
37
  "exp",
36
38
  ]);
@@ -49,7 +51,9 @@ function decodeStrict(s) {
49
51
  /**
50
52
  * 逐字段核对声明:只认已知字段、类型正确,返回只含已知字段的新对象。The scope decides the shape:
51
53
  * `"platform"` exactly when `orgId` is absent and `role` is `"superAdmin"`, with no
52
- * `conversationId` / `agentId` / `fileId`; `"org"` needs an `orgId` and one of the org roles.
54
+ * `conversationId` / `agentId` / `fileId`; `"org"` needs an `orgId` and one of the org roles;
55
+ * `"share"` (file sharing spec §7) see {@link parseShareClaims}. `shareId` / `generation` only in
56
+ * the share scope.
53
57
  */
54
58
  function parseClaims(v) {
55
59
  if (typeof v !== "object" || v === null || Array.isArray(v))
@@ -59,10 +63,17 @@ function parseClaims(v) {
59
63
  return null;
60
64
  if (typeof c.plugin !== "string" || !PLUGIN_RE.test(c.plugin))
61
65
  return null;
62
- if (!isId(c.accountId) || !isId(c.contribution))
66
+ if (!isId(c.contribution))
63
67
  return null;
64
68
  if (typeof c.exp !== "number" || !Number.isSafeInteger(c.exp))
65
69
  return null;
70
+ if (c.scope === "share")
71
+ return parseShareClaims(c, c.plugin, c.contribution, c.exp);
72
+ // the share fields belong to the share scope only
73
+ if (c.shareId !== undefined || c.generation !== undefined)
74
+ return null;
75
+ if (!isId(c.accountId))
76
+ return null;
66
77
  if (c.scope === "platform") {
67
78
  if (c.orgId !== undefined || c.role !== "superAdmin")
68
79
  return null;
@@ -99,6 +110,31 @@ function parseClaims(v) {
99
110
  exp: c.exp,
100
111
  };
101
112
  }
113
+ /**
114
+ * A share token's claims: `orgId`, `shareId` and a positive safe integer `generation`, and none of
115
+ * an account, role, conversation, agent or file (the share's snapshot is the only file it names).
116
+ */
117
+ function parseShareClaims(c, plugin, contribution, exp) {
118
+ if (!isId(c.orgId) || !isId(c.shareId))
119
+ return null;
120
+ if (typeof c.generation !== "number" || !Number.isSafeInteger(c.generation))
121
+ return null;
122
+ if (c.generation < 1)
123
+ return null;
124
+ for (const k of ["accountId", "role", "conversationId", "agentId", "fileId"]) {
125
+ if (c[k] !== undefined)
126
+ return null;
127
+ }
128
+ return {
129
+ plugin,
130
+ scope: "share",
131
+ orgId: c.orgId,
132
+ shareId: c.shareId,
133
+ generation: c.generation,
134
+ contribution,
135
+ exp,
136
+ };
137
+ }
102
138
  /** Optional provider: the clock {@link EmbedTokens} issues and checks with (default `Date.now`; tests). */
103
139
  export const EMBED_TOKEN_CLOCK = Symbol("EMBED_TOKEN_CLOCK");
104
140
  /**
@@ -166,6 +166,12 @@ export declare class UiViews {
166
166
  * 组织页面不收 `conversationId`。返回签发令牌所需的目标(令牌由调用方签)。
167
167
  */
168
168
  embed(t: UiEmbedRequest): Promise<UiEmbedTarget>;
169
+ /**
170
+ * The path of a loaded `file.preview` embed contribution (a share page's embed previewer, file
171
+ * sharing spec §7), else 404 `ui.not_found`. Whether the previewer takes the share's snapshot
172
+ * and its extension is on in the org is the caller's check (`PreviewerRegistry.shareEmbed`).
173
+ */
174
+ shareEmbedPath(plugin: string, contribution: string): string;
169
175
  /** 取视图:调用插件 `render`,校验返回的视图。 */
170
176
  render(t: UiTarget): Promise<UiView>;
171
177
  /** 执行动作:调用插件 `action`(视图里的按钮 / 表单提交),校验返回的提示或新视图。 */
package/dist/ui/views.js CHANGED
@@ -310,6 +310,23 @@ let UiViews = class UiViews {
310
310
  ...(fileId !== undefined && { fileId }),
311
311
  };
312
312
  }
313
+ /**
314
+ * The path of a loaded `file.preview` embed contribution (a share page's embed previewer, file
315
+ * sharing spec §7), else 404 `ui.not_found`. Whether the previewer takes the share's snapshot
316
+ * and its extension is on in the org is the caller's check (`PreviewerRegistry.shareEmbed`).
317
+ */
318
+ shareEmbedPath(plugin, contribution) {
319
+ const entry = this.d.host
320
+ .uiContributions()
321
+ .find((c) => c.plugin === plugin &&
322
+ c.contribution.id === contribution &&
323
+ c.contribution.kind === "embed" &&
324
+ c.slot.id === "file.preview");
325
+ const path = entry?.contribution.path;
326
+ if (path === undefined)
327
+ throw notFound();
328
+ return path;
329
+ }
313
330
  /** 取视图:调用插件 `render`,校验返回的视图。 */
314
331
  async render(t) {
315
332
  const { entry, args } = await this.resolve(t, "render");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.45",
3
+ "version": "0.1.0-rc.46",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.32"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.33"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -74,8 +74,8 @@
74
74
  "@types/ws": "^8.18.2",
75
75
  "@types/yauzl": "3.4.0",
76
76
  "ws": "^8.22.0",
77
- "@capybara-hq/device": "0.1.0-rc.14",
78
- "@capybara-hq/testing": "0.1.0-rc.26"
77
+ "@capybara-hq/testing": "0.1.0-rc.26",
78
+ "@capybara-hq/device": "0.1.0-rc.14"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -b"
@@ -0,0 +1,35 @@
1
+ -- File shares (file sharing spec §1): a link to a frozen snapshot of one conversation file. A row
2
+ -- is kept after it is revoked or expired (the audit trail and the lists' recent section);
3
+ -- `object_key` is cleared once the sweep frees the snapshot. Whether a share is live (creator
4
+ -- still has access, external sharing still allowed) is checked at open time, not stored.
5
+ -- `last_opened_at` backs the Shares pages' "last opened" column.
6
+ CREATE TABLE IF NOT EXISTS file_shares (
7
+ id uuid PRIMARY KEY,
8
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
9
+ code text NOT NULL,
10
+ conversation_id text NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
11
+ -- the artifact version or attachment the current generation was copied from (no foreign key:
12
+ -- the source may be removed while the snapshot lives on)
13
+ file_id text NOT NULL,
14
+ -- delivered files: the version group (`sourcePath`); null for uploads
15
+ source_path text,
16
+ created_by text NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
17
+ audience text NOT NULL CHECK (audience IN ('internal', 'external')),
18
+ name text NOT NULL,
19
+ content_type text NOT NULL,
20
+ size bigint NOT NULL,
21
+ object_key text,
22
+ generation integer NOT NULL DEFAULT 1,
23
+ expires_at timestamptz,
24
+ revoked_at timestamptz,
25
+ revoked_by text REFERENCES accounts(id) ON DELETE SET NULL,
26
+ revoke_reason text CHECK (revoke_reason IN
27
+ ('creator', 'admin', 'conversation_deleted', 'member_offboarded', 'creator_lost_access')),
28
+ last_opened_at timestamptz,
29
+ created_at timestamptz NOT NULL DEFAULT now(),
30
+ updated_at timestamptz NOT NULL DEFAULT now()
31
+ );
32
+ CREATE UNIQUE INDEX IF NOT EXISTS file_shares_code_key ON file_shares (code);
33
+ CREATE INDEX IF NOT EXISTS file_shares_org_creator_idx ON file_shares (org_id, created_by);
34
+ CREATE INDEX IF NOT EXISTS file_shares_conversation_idx ON file_shares (conversation_id);
35
+ CREATE INDEX IF NOT EXISTS file_shares_org_live_idx ON file_shares (org_id) WHERE revoked_at IS NULL;