@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
package/dist/errors.js CHANGED
@@ -42,10 +42,32 @@ export const ERROR_CODES = {
42
42
  "org.network_allowance_not_found": 404,
43
43
  /** Adding an org network allowance through an API token or the Platform tool (a person widens). */
44
44
  "org.network_allowance_widen_not_allowed": 400,
45
+ /**
46
+ * The org turned external sharing on where the platform denies it, or through an API token or
47
+ * the Platform tool (only a person turns it on).
48
+ */
49
+ "org.external_sharing_not_allowed": 400,
45
50
  /** A deployment setting set in the startup config (file, Nacos or env): read-only in the admin console. */
46
51
  "deployment.setting_readonly": 409,
47
52
  /** Turning the platform's auto mode on through an API token or the Platform tool (only off). */
48
53
  "deployment.auto_mode_not_allowed": 400,
54
+ /** Allowing external sharing at the platform level through an API token or the Platform tool. */
55
+ "deployment.external_sharing_not_allowed": 400,
56
+ /**
57
+ * Raising the share expiry maximum or adding a CDN allowlist origin through an API token or the
58
+ * Platform tool (only lowering and removing).
59
+ */
60
+ "deployment.sharing_widen_not_allowed": 400,
61
+ /** No live share with this code (unknown, revoked, expired, or its creator lost access). */
62
+ "share.not_found": 404,
63
+ /** An internal share opened without a session: sign in as a member of its org. */
64
+ "share.sign_in_required": 401,
65
+ /** An external share where external sharing is not allowed for the org now. */
66
+ "share.external_not_allowed": 403,
67
+ /** A share expiry beyond the platform's maximum (or no expiry on an external share). */
68
+ "share.expiry_too_long": 400,
69
+ /** The file to share is gone (removed) or its snapshot cannot be made (upload mismatch). */
70
+ "share.file_unavailable": 410,
49
71
  "member.not_found": 404,
50
72
  "member.already_exists": 409,
51
73
  "member.anonymous_guest": 409,
@@ -9,6 +9,7 @@ import { SuperAdminLockModule } from "../identity/super-admin.js";
9
9
  import { ModelsModule } from "../models/models.module.js";
10
10
  import { OrgNetworkAllowancesModule } from "../orgs/network-allowances.service.js";
11
11
  import { OrgLockModule } from "../orgs/org-lock.js";
12
+ import { ShareLivenessModule } from "../shares/liveness.js";
12
13
  import { StorageModule } from "../storage/storage.module.js";
13
14
  import { EmbedTokensModule } from "../ui/embed-token.js";
14
15
  import { ExtensionAdminOps } from "./admin-ops.js";
@@ -47,6 +48,8 @@ ExtensionsModule = __decorate([
47
48
  StorageModule,
48
49
  // ctx.ui verifies embed tokens with the one provider the UI routes issue them with
49
50
  EmbedTokensModule,
51
+ // ctx.ui checks a share-scoped embed token live (database and config only: no cycle)
52
+ ShareLivenessModule,
50
53
  ExtensionStateModule,
51
54
  // ctx.models: the embeddings broker (models domain, below the host through ExtensionStateModule)
52
55
  ModelsModule,
@@ -14,6 +14,7 @@ import type { KernelLogger } from "../log.js";
14
14
  import { ModelEmbeddings } from "../models/embeddings.js";
15
15
  import { ModelImages } from "../models/images.js";
16
16
  import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
17
+ import { ShareLiveness } from "../shares/liveness.js";
17
18
  import { EmbedTokens } from "../ui/embed-token.js";
18
19
  import type { UiActionHandler, UiRender } from "../ui/registry.js";
19
20
  import { ExtensionApprovals, type PendingExtension } from "./approvals.js";
@@ -260,7 +261,9 @@ export declare class ExtensionHost {
260
261
  */
261
262
  installs: ExtensionInstalls, approvals: ExtensionApprovals,
262
263
  /** This replica's load status table (`extension_replica_status`): every load result writes a row. */
263
- status: ReplicaStatusStore, config: KernelConfigService, kdb: KernelDb, redis: Redis, busSubscriber: BusSubscriber, keyring: Keyring, embedTokens: EmbedTokens, locks: LockService, log: KernelLogger, options: Pick<KernelAppOptions, "resolveFrom">,
264
+ status: ReplicaStatusStore, config: KernelConfigService, kdb: KernelDb, redis: Redis, busSubscriber: BusSubscriber, keyring: Keyring, embedTokens: EmbedTokens,
265
+ /** `ctx.ui.verifyEmbedToken`: the live check of a share-scoped token (file sharing spec §7). */
266
+ shares: ShareLiveness, locks: LockService, log: KernelLogger, options: Pick<KernelAppOptions, "resolveFrom">,
264
267
  /**
265
268
  * Each hook call's effective config for its organization, and the providers excluded from an
266
269
  * org's point resolution (layering spec A §6).
@@ -29,6 +29,7 @@ import { ModelEmbeddings } from "../models/embeddings.js";
29
29
  import { ModelImages } from "../models/images.js";
30
30
  import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
31
31
  import { packagePath } from "../packages/tgz.js";
32
+ import { ShareLiveness } from "../shares/liveness.js";
32
33
  import { EmbedTokens } from "../ui/embed-token.js";
33
34
  import { ExtensionApprovals, planApprovals, readSnapshots, withPreApproved, } from "./approvals.js";
34
35
  import { ExtensionBlobIntegrityError } from "./blobs.js";
@@ -407,7 +408,9 @@ let ExtensionHost = class ExtensionHost {
407
408
  */
408
409
  installs, approvals,
409
410
  /** This replica's load status table (`extension_replica_status`): every load result writes a row. */
410
- status, config, kdb, redis, busSubscriber, keyring, embedTokens, locks, log, options,
411
+ status, config, kdb, redis, busSubscriber, keyring, embedTokens,
412
+ /** `ctx.ui.verifyEmbedToken`: the live check of a share-scoped token (file sharing spec §7). */
413
+ shares, locks, log, options,
411
414
  /**
412
415
  * Each hook call's effective config for its organization, and the providers excluded from an
413
416
  * org's point resolution (layering spec A §6).
@@ -451,6 +454,7 @@ let ExtensionHost = class ExtensionHost {
451
454
  models: { embeddings, images },
452
455
  // ctx.models.embed and generateImage fire model.request through the same registry
453
456
  hooks: this.hooks,
457
+ shares,
454
458
  net: { config, allowances, ...(netSeams !== undefined && { seams: netSeams }) },
455
459
  locks,
456
460
  runWorkers: c.roles.includes("worker"),
@@ -2393,14 +2397,15 @@ ExtensionHost = __decorate([
2393
2397
  __param(7, Inject(REDIS_SUBSCRIBER)),
2394
2398
  __param(8, Inject(KEYRING)),
2395
2399
  __param(9, Inject(EmbedTokens)),
2396
- __param(10, Inject(LockService)),
2397
- __param(11, Inject(KERNEL_LOGGER)),
2398
- __param(12, Inject(KERNEL_APP_OPTIONS)),
2399
- __param(13, Inject(EffectiveConfigs)),
2400
- __param(14, Inject(ModelEmbeddings)),
2401
- __param(15, Inject(ModelImages)),
2402
- __param(16, Inject(OrgNetworkAllowances)),
2403
- __param(17, Optional()),
2404
- __param(17, Inject(EXTENSION_NET_SEAMS))
2400
+ __param(10, Inject(ShareLiveness)),
2401
+ __param(11, Inject(LockService)),
2402
+ __param(12, Inject(KERNEL_LOGGER)),
2403
+ __param(13, Inject(KERNEL_APP_OPTIONS)),
2404
+ __param(14, Inject(EffectiveConfigs)),
2405
+ __param(15, Inject(ModelEmbeddings)),
2406
+ __param(16, Inject(ModelImages)),
2407
+ __param(17, Inject(OrgNetworkAllowances)),
2408
+ __param(18, Optional()),
2409
+ __param(18, Inject(EXTENSION_NET_SEAMS))
2405
2410
  ], ExtensionHost);
2406
2411
  export { ExtensionHost };
@@ -26,6 +26,19 @@ export interface OrgPreviewerItem extends PreviewerItem {
26
26
  position: number;
27
27
  disabled: boolean;
28
28
  }
29
+ /** The file a previewer reads: the share's snapshot or a conversation file (no storage key). */
30
+ type PreviewFile = {
31
+ name: string;
32
+ contentType: string;
33
+ size: number;
34
+ };
35
+ /** A share's snapshot as the share routes pass it (`ShareLiveness`'s `LiveShare`). */
36
+ export interface ShareSnapshot extends PreviewFile {
37
+ id: string;
38
+ orgId: string;
39
+ /** Relative to the org's kernel prefix. */
40
+ objectKey: string;
41
+ }
29
42
  /** Optional provider: a view previewer's render time limit (ms) instead of {@link FILE_PREVIEW_TIMEOUT_MS} (tests). */
30
43
  export declare const FILE_PREVIEW_TIMEOUT: unique symbol;
31
44
  /**
@@ -86,6 +99,36 @@ export declare class PreviewerRegistry {
86
99
  id: string;
87
100
  locale: "zh" | "en";
88
101
  }): Promise<UiView>;
102
+ /** The previewers that take a share's snapshot, in the org's order (file sharing spec §7). */
103
+ forShare(orgId: string, file: PreviewFile): Promise<PreviewerItem[]>;
104
+ /**
105
+ * Renders a view previewer for a share's snapshot (file sharing spec §7): args `source: "share"`
106
+ * with the share's org and id (`file.id` is the share id), no account and no conversation; the
107
+ * read grant reads the snapshot. The caller has opened the share (`ShareOpenService.open`).
108
+ * Errors as {@link render}; a previewer that needs the conversation declines by throwing (502).
109
+ */
110
+ renderShare(t: {
111
+ orgId: string;
112
+ shareId: string;
113
+ file: ShareSnapshot;
114
+ plugin: string;
115
+ id: string;
116
+ locale: "zh" | "en";
117
+ }): Promise<UiView>;
118
+ /**
119
+ * The `file.preview` contribution of an embed previewer that takes a share's snapshot (enabled in
120
+ * the org, not disabled, a valid effective config), or null: what a share embed token may name.
121
+ */
122
+ shareEmbed(orgId: string, file: PreviewFile, plugin: string, previewerId: string): Promise<{
123
+ contribution: string;
124
+ } | null>;
125
+ /** The enabled view previewer that takes the file, else 404 `ui.not_found`. */
126
+ private viewPreviewer;
127
+ /**
128
+ * Calls a view previewer's render with a read grant over `open` (the file's bytes, capped at the
129
+ * previewer's `maxBytes`, valid only during the call) and validates the view.
130
+ */
131
+ private renderWith;
89
132
  /**
90
133
  * Whether an embed token for a `file.preview` contribution may be issued for this file: the
91
134
  * viewer reads the conversation, the file is in it, and an enabled previewer of that extension
@@ -100,3 +143,4 @@ export declare class PreviewerRegistry {
100
143
  contribution: string;
101
144
  }): Promise<boolean>;
102
145
  }
146
+ export {};
@@ -223,13 +223,82 @@ let PreviewerRegistry = class PreviewerRegistry {
223
223
  */
224
224
  async render(t) {
225
225
  const file = await this.d.files.file(t.orgId, t.conversationId, t.accountId, t.fileId);
226
- const l = (await this.accepting(t.orgId, file)).find((x) => x.plugin === t.plugin && x.previewer.id === t.id);
227
- const render = l?.previewer.render;
228
- if (!l || render === undefined)
226
+ const l = await this.viewPreviewer(t.orgId, file, t.plugin, t.id);
227
+ const store = this.d.storage.kernel(t.orgId);
228
+ return this.renderWith(l, t, {
229
+ source: "conversation",
230
+ orgId: t.orgId,
231
+ accountId: t.accountId,
232
+ conversationId: t.conversationId,
233
+ file: { id: file.id, name: file.name, contentType: file.contentType, size: file.size },
234
+ }, async (signal) => {
235
+ const got = await store.get(file.objectKey, { signal });
236
+ if (!got)
237
+ throw new Error("the file is no longer available");
238
+ // an attachment replaced since it was checked is not the file any more
239
+ if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
240
+ await got.body.cancel().catch(() => { });
241
+ throw new Error("the file is no longer available");
242
+ }
243
+ return got.body;
244
+ });
245
+ }
246
+ /** The previewers that take a share's snapshot, in the org's order (file sharing spec §7). */
247
+ async forShare(orgId, file) {
248
+ return (await this.accepting(orgId, file)).map(item);
249
+ }
250
+ /**
251
+ * Renders a view previewer for a share's snapshot (file sharing spec §7): args `source: "share"`
252
+ * with the share's org and id (`file.id` is the share id), no account and no conversation; the
253
+ * read grant reads the snapshot. The caller has opened the share (`ShareOpenService.open`).
254
+ * Errors as {@link render}; a previewer that needs the conversation declines by throwing (502).
255
+ */
256
+ async renderShare(t) {
257
+ const l = await this.viewPreviewer(t.orgId, t.file, t.plugin, t.id);
258
+ const store = this.d.storage.kernel(t.orgId);
259
+ return this.renderWith(l, t, {
260
+ source: "share",
261
+ orgId: t.orgId,
262
+ shareId: t.shareId,
263
+ file: {
264
+ id: t.shareId,
265
+ name: t.file.name,
266
+ contentType: t.file.contentType,
267
+ size: t.file.size,
268
+ },
269
+ }, async (signal) => {
270
+ const got = await store.get(t.file.objectKey, { signal });
271
+ if (!got)
272
+ throw new Error("the file is no longer available");
273
+ return got.body;
274
+ });
275
+ }
276
+ /**
277
+ * The `file.preview` contribution of an embed previewer that takes a share's snapshot (enabled in
278
+ * the org, not disabled, a valid effective config), or null: what a share embed token may name.
279
+ */
280
+ async shareEmbed(orgId, file, plugin, previewerId) {
281
+ const l = (await this.accepting(orgId, file)).find((x) => x.plugin === plugin && x.previewer.id === previewerId);
282
+ const contribution = l?.previewer.embed;
283
+ return contribution === undefined ? null : { contribution };
284
+ }
285
+ /** The enabled view previewer that takes the file, else 404 `ui.not_found`. */
286
+ async viewPreviewer(orgId, file, plugin, id) {
287
+ const l = (await this.accepting(orgId, file)).find((x) => x.plugin === plugin && x.previewer.id === id);
288
+ if (!l || l.previewer.render === undefined)
289
+ throw notFound();
290
+ return l;
291
+ }
292
+ /**
293
+ * Calls a view previewer's render with a read grant over `open` (the file's bytes, capped at the
294
+ * previewer's `maxBytes`, valid only during the call) and validates the view.
295
+ */
296
+ async renderWith(l, t, identity, open) {
297
+ const render = l.previewer.render;
298
+ if (render === undefined)
229
299
  throw notFound();
230
300
  const maxBytes = l.previewer.maxBytes;
231
- const store = this.d.storage.kernel(t.orgId);
232
- let open = true;
301
+ let granted = true;
233
302
  const expired = () => new Error("the file read grant has expired");
234
303
  const fields = { plugin: t.plugin, previewer: t.id, orgId: t.orgId };
235
304
  let view;
@@ -248,51 +317,36 @@ let PreviewerRegistry = class PreviewerRegistry {
248
317
  fn: (signal) => l.inflight.run(signal, async (s) => {
249
318
  try {
250
319
  return await render.call(l.previewer, {
251
- orgId: t.orgId,
252
- accountId: t.accountId,
253
- conversationId: t.conversationId,
320
+ ...identity,
254
321
  locale: t.locale,
255
322
  config: l.config,
256
323
  signal: s,
257
- file: {
258
- id: file.id,
259
- name: file.name,
260
- contentType: file.contentType,
261
- size: file.size,
262
- },
263
324
  read: async () => {
264
- if (!open || s.aborted)
325
+ if (!granted || s.aborted)
265
326
  throw expired();
266
- if (file.size > maxBytes) {
327
+ if (identity.file.size > maxBytes) {
267
328
  throw new Error(`the file is larger than this previewer's maxBytes (${maxBytes})`);
268
329
  }
269
- const got = await store.get(file.objectKey, { signal: s });
270
- if (!got)
271
- throw new Error("the file is no longer available");
272
- // an attachment replaced since it was checked is not the file any more
273
- if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
274
- await got.body.cancel().catch(() => { });
275
- throw new Error("the file is no longer available");
276
- }
277
- if (!open || s.aborted) {
278
- await got.body.cancel().catch(() => { });
330
+ const body = await open(s);
331
+ if (!granted || s.aborted) {
332
+ await body.cancel().catch(() => { });
279
333
  throw expired();
280
334
  }
281
- const bytes = await readAtMost(got.body, maxBytes);
282
- if (!open || s.aborted)
335
+ const bytes = await readAtMost(body, maxBytes);
336
+ if (!granted || s.aborted)
283
337
  throw expired();
284
338
  return bytes;
285
339
  },
286
340
  });
287
341
  }
288
342
  finally {
289
- open = false;
343
+ granted = false;
290
344
  }
291
345
  }),
292
346
  });
293
347
  }
294
348
  finally {
295
- open = false;
349
+ granted = false;
296
350
  }
297
351
  const problems = validateUiView(view);
298
352
  if (problems.length > 0) {
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The Content-Security-Policy of an HTML document (file sharing spec §4, "Isolation without a
3
+ * second origin"): `sandbox` without `allow-same-origin` makes the document an opaque origin even
4
+ * at the app's own URL (no cookies, no storage, no scripting of its parent); `allow-top-navigation`
5
+ * is never granted. Scripts, styles, fonts and images load inline or from the CDN allowlist only;
6
+ * every connection (fetch, XHR, WebSocket, beacons) is blocked.
7
+ */
8
+ /**
9
+ * The exact spec §4 policy for `allowlist` (directives joined with `"; "`). An entry that is not a
10
+ * bare https origin is dropped (the setting is validated when stored; this keeps a bad row from
11
+ * ever adding a directive).
12
+ */
13
+ export declare function htmlDocumentCsp(allowlist: readonly string[]): string;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The Content-Security-Policy of an HTML document (file sharing spec §4, "Isolation without a
3
+ * second origin"): `sandbox` without `allow-same-origin` makes the document an opaque origin even
4
+ * at the app's own URL (no cookies, no storage, no scripting of its parent); `allow-top-navigation`
5
+ * is never granted. Scripts, styles, fonts and images load inline or from the CDN allowlist only;
6
+ * every connection (fetch, XHR, WebSocket, beacons) is blocked.
7
+ */
8
+ /** A bare `https://` origin: what may go into a source list (no spaces, quotes or `;`). */
9
+ const SOURCE_RE = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/;
10
+ /**
11
+ * The exact spec §4 policy for `allowlist` (directives joined with `"; "`). An entry that is not a
12
+ * bare https origin is dropped (the setting is validated when stored; this keeps a bad row from
13
+ * ever adding a directive).
14
+ */
15
+ export function htmlDocumentCsp(allowlist) {
16
+ const cdn = allowlist.filter((o) => SOURCE_RE.test(o));
17
+ const src = (...base) => [...base, ...cdn].join(" ");
18
+ return [
19
+ "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox",
20
+ "default-src 'none'",
21
+ src("script-src", "'unsafe-inline'", "'unsafe-eval'"),
22
+ src("style-src", "'unsafe-inline'"),
23
+ src("font-src", "data:"),
24
+ src("img-src", "data:", "blob:"),
25
+ "media-src data: blob:",
26
+ "connect-src 'none'",
27
+ "frame-src 'none'",
28
+ "worker-src 'none'",
29
+ "form-action 'none'",
30
+ "base-uri 'none'",
31
+ "frame-ancestors 'self'",
32
+ ].join("; ");
33
+ }
@@ -0,0 +1,31 @@
1
+ import type { FastifyReply } from "fastify";
2
+ import { z } from "zod";
3
+ import { type Principal } from "../identity/principal.js";
4
+ import { type OrgContext } from "../orgs/org.guard.js";
5
+ import { HtmlDocumentService, type HtmlTokenResponse } from "./html-document.service.js";
6
+ import { HtmlTokens } from "./html-token.js";
7
+ /** `POST …/conversations/:id/files/:fileId/html-token`. */
8
+ export declare const HtmlTokenParams: z.ZodObject<{
9
+ id: z.ZodString;
10
+ fileId: z.ZodString;
11
+ }, z.core.$strip>;
12
+ /**
13
+ * The HTML document (file sharing spec §4): the right panel mints a document token for one
14
+ * version of the caller's HTML file (`agents.use`, the conversation's owner), then frames
15
+ * `/api/v1/html/<token>`. The document route is public: the token is the authority, checked and
16
+ * then re-checked live by {@link HtmlDocumentService.serve}.
17
+ */
18
+ export declare class HtmlDocumentController {
19
+ private readonly documents;
20
+ private readonly tokens;
21
+ constructor(documents: HtmlDocumentService, tokens: HtmlTokens);
22
+ /** A document token: 200 `{ path, expiresIn }`. */
23
+ mint(principal: Principal, org: OrgContext, params: z.infer<typeof HtmlTokenParams>): Promise<HtmlTokenResponse>;
24
+ /**
25
+ * The document a token names (`/api/v1/html/<token>`), under the sandbox CSP. A bad or expired
26
+ * token, or a live check failing, is 404 `not_found` (one answer for every refusal). A wildcard
27
+ * route: a token (up to 2048 characters) is longer than Fastify's `maxParamLength` (100) allows
28
+ * a `:param`; a token never contains `/`, so anything with one fails verification.
29
+ */
30
+ document(token: string, reply: FastifyReply): Promise<void>;
31
+ }
@@ -0,0 +1,75 @@
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 { Controller, Get, HttpCode, Inject, Param, Post, Res } from "@nestjs/common";
11
+ import { z } from "zod";
12
+ import { CurrentPrincipal, Public, requireUser } from "../identity/principal.js";
13
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
+ import { ZParam } from "../infra/validation/zod-params.js";
15
+ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
16
+ import { HtmlDocumentService, htmlNotFound, } from "./html-document.service.js";
17
+ import { HtmlTokens } from "./html-token.js";
18
+ /** `POST …/conversations/:id/files/:fileId/html-token`. */
19
+ export const HtmlTokenParams = z.object({
20
+ id: z.string().min(1).max(100),
21
+ fileId: z.string().min(1).max(100),
22
+ });
23
+ class HtmlTokenParamsDto extends createZodDto(HtmlTokenParams, "HtmlTokenParams") {
24
+ }
25
+ /**
26
+ * The HTML document (file sharing spec §4): the right panel mints a document token for one
27
+ * version of the caller's HTML file (`agents.use`, the conversation's owner), then frames
28
+ * `/api/v1/html/<token>`. The document route is public: the token is the authority, checked and
29
+ * then re-checked live by {@link HtmlDocumentService.serve}.
30
+ */
31
+ let HtmlDocumentController = class HtmlDocumentController {
32
+ documents;
33
+ tokens;
34
+ constructor(documents, tokens) {
35
+ this.documents = documents;
36
+ this.tokens = tokens;
37
+ }
38
+ /** A document token: 200 `{ path, expiresIn }`. */
39
+ async mint(principal, org, params) {
40
+ const p = requireUser(principal);
41
+ return this.documents.mint(org.orgId, params.id, p.account.id, params.fileId);
42
+ }
43
+ /**
44
+ * The document a token names (`/api/v1/html/<token>`), under the sandbox CSP. A bad or expired
45
+ * token, or a live check failing, is 404 `not_found` (one answer for every refusal). A wildcard
46
+ * route: a token (up to 2048 characters) is longer than Fastify's `maxParamLength` (100) allows
47
+ * a `:param`; a token never contains `/`, so anything with one fails verification.
48
+ */
49
+ async document(token, reply) {
50
+ const claims = this.tokens.verify(token);
51
+ if (claims === null)
52
+ throw htmlNotFound();
53
+ await this.documents.serve(claims, reply);
54
+ }
55
+ };
56
+ __decorate([
57
+ Post("orgs/:orgId/conversations/:id/files/:fileId/html-token"),
58
+ HttpCode(200),
59
+ OrgAction("agents.use"),
60
+ __param(0, CurrentPrincipal()),
61
+ __param(1, CurrentOrg()),
62
+ __param(2, ZParam(HtmlTokenParamsDto))
63
+ ], HtmlDocumentController.prototype, "mint", null);
64
+ __decorate([
65
+ Public(),
66
+ Get("html/*"),
67
+ __param(0, Param("*")),
68
+ __param(1, Res())
69
+ ], HtmlDocumentController.prototype, "document", null);
70
+ HtmlDocumentController = __decorate([
71
+ Controller("api/v1"),
72
+ __param(0, Inject(HtmlDocumentService)),
73
+ __param(1, Inject(HtmlTokens))
74
+ ], HtmlDocumentController);
75
+ export { HtmlDocumentController };
@@ -0,0 +1,49 @@
1
+ import type { FastifyReply } from "fastify";
2
+ import { ConversationFiles } from "../conversations/files.js";
3
+ import { ApiError } from "../errors.js";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import type { KernelLogger } from "../log.js";
6
+ import { ShareLiveness } from "../shares/liveness.js";
7
+ import { StorageService } from "../storage/storage.service.js";
8
+ import { type HtmlClaims, HtmlTokens } from "./html-token.js";
9
+ /** What `POST …/html-token` returns: `path` loads the document once within `expiresIn` seconds. */
10
+ export interface HtmlTokenResponse {
11
+ path: string;
12
+ expiresIn: number;
13
+ }
14
+ /** Every refusal of the document route: one answer, no reason (a token is not an oracle). */
15
+ export declare const htmlNotFound: () => ApiError;
16
+ /**
17
+ * HTML files served as stand-alone documents (file sharing spec §4). The owner of a conversation
18
+ * mints a short-lived document token for one version of an HTML file ({@link mint}); the public
19
+ * route serves it ({@link serve}) under the sandbox CSP after re-checking, live, what the token
20
+ * names: the owner can still read the file (`ConversationFiles.file`: membership, active account,
21
+ * conversation and agent not deleted; an upload's object still the one finalize checked), or the
22
+ * share is still live at that generation (`ShareLiveness.byId`). The bytes are streamed by the
23
+ * kernel as stored; never a presigned URL on the app origin. HTML larger than
24
+ * `FILE_PREVIEW_MAX_BYTES` is never rendered.
25
+ */
26
+ export declare class HtmlDocumentService {
27
+ private readonly db;
28
+ private readonly files;
29
+ private readonly liveness;
30
+ private readonly storage;
31
+ private readonly tokens;
32
+ private readonly log?;
33
+ constructor(db: KernelDb, files: Pick<ConversationFiles, "file">, liveness: Pick<ShareLiveness, "byId">, storage: Pick<StorageService, "kernel">, tokens: HtmlTokens, log?: KernelLogger | undefined);
34
+ /**
35
+ * A document token for one version of the caller's conversation file (a delivered version or an
36
+ * upload). Not the owner → `conversation.not_found`; unknown file →
37
+ * `conversation.artifact_not_found`; an upload changed since finalize →
38
+ * `conversation.artifact_removed`; not HTML, or larger than `FILE_PREVIEW_MAX_BYTES` →
39
+ * `conversation.artifact_not_previewable`.
40
+ */
41
+ mint(orgId: string, conversationId: string, accountId: string, fileId: string): Promise<HtmlTokenResponse>;
42
+ /**
43
+ * Serves the document verified claims name with the spec §4 headers, the CSP built from the CDN
44
+ * allowlist read now. Any live check failing → 404 `not_found`.
45
+ */
46
+ serve(claims: HtmlClaims, reply: FastifyReply): Promise<void>;
47
+ /** The object the claims name if their live checks pass now; null otherwise. */
48
+ private resolve;
49
+ }