@capybara-hq/kernel 0.1.0-rc.44 → 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 (101) hide show
  1. package/bootstrap.json +11 -11
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/agents/agent-lookup.d.ts +5 -2
  4. package/dist/agents/agent-lookup.js +3 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +7 -0
  7. package/dist/config/schema.js +27 -0
  8. package/dist/conversations/access.d.ts +14 -5
  9. package/dist/conversations/access.js +29 -20
  10. package/dist/conversations/conversations.service.d.ts +6 -1
  11. package/dist/conversations/conversations.service.js +12 -2
  12. package/dist/conversations/files.d.ts +43 -0
  13. package/dist/conversations/files.js +80 -3
  14. package/dist/ctx/create-ctx.d.ts +7 -0
  15. package/dist/ctx/create-ctx.js +9 -2
  16. package/dist/db/kernel-schema.d.ts +30 -0
  17. package/dist/errors.d.ts +22 -0
  18. package/dist/errors.js +22 -0
  19. package/dist/extensions/extensions.module.js +3 -0
  20. package/dist/extensions/host.d.ts +4 -1
  21. package/dist/extensions/host.js +15 -10
  22. package/dist/files/previewers.d.ts +44 -0
  23. package/dist/files/previewers.js +84 -30
  24. package/dist/html/csp.d.ts +13 -0
  25. package/dist/html/csp.js +33 -0
  26. package/dist/html/html-document.controller.d.ts +31 -0
  27. package/dist/html/html-document.controller.js +75 -0
  28. package/dist/html/html-document.service.d.ts +49 -0
  29. package/dist/html/html-document.service.js +143 -0
  30. package/dist/html/html-token.d.ts +58 -0
  31. package/dist/html/html-token.js +154 -0
  32. package/dist/html/html-type.d.ts +13 -0
  33. package/dist/html/html-type.js +40 -0
  34. package/dist/html/html.module.d.ts +6 -0
  35. package/dist/html/html.module.js +26 -0
  36. package/dist/http/api.module.js +14 -0
  37. package/dist/http/error.filter.d.ts +2 -0
  38. package/dist/http/error.filter.js +9 -2
  39. package/dist/http/plugin-route-access.d.ts +2 -1
  40. package/dist/http/plugin-route-access.js +16 -1
  41. package/dist/identity/settings.d.ts +26 -1
  42. package/dist/identity/settings.js +88 -2
  43. package/dist/infra/config/kernel-config.service.js +3 -0
  44. package/dist/infra/outbox/registry.d.ts +13 -0
  45. package/dist/infra/outbox/registry.js +8 -0
  46. package/dist/infra/throttler/credential-throttler.d.ts +4 -1
  47. package/dist/infra/throttler/credential-throttler.js +5 -2
  48. package/dist/infra/throttler/named-throttlers.d.ts +1 -0
  49. package/dist/infra/throttler/named-throttlers.js +14 -0
  50. package/dist/orgs/offboarding.d.ts +3 -1
  51. package/dist/orgs/offboarding.js +7 -1
  52. package/dist/orgs/settings.service.d.ts +21 -4
  53. package/dist/orgs/settings.service.js +47 -7
  54. package/dist/overrides.d.ts +3 -0
  55. package/dist/overrides.js +2 -0
  56. package/dist/platform/exclusions.js +63 -0
  57. package/dist/platform/operation.js +1 -1
  58. package/dist/platform/ops/admin.ops.js +18 -3
  59. package/dist/platform/ops/org-settings.ops.js +6 -2
  60. package/dist/platform/ops/orgs.ops.js +3 -0
  61. package/dist/platform/ops/shares.ops.d.ts +16 -0
  62. package/dist/platform/ops/shares.ops.js +107 -0
  63. package/dist/platform/platform-ops.module.d.ts +2 -1
  64. package/dist/platform/platform-ops.module.js +5 -0
  65. package/dist/platform/route-schemas.js +3 -0
  66. package/dist/roles/worker.module.js +6 -0
  67. package/dist/runtime/maintenance.d.ts +4 -2
  68. package/dist/runtime/maintenance.js +14 -4
  69. package/dist/shares/liveness.d.ts +59 -0
  70. package/dist/shares/liveness.js +163 -0
  71. package/dist/shares/revoke.d.ts +26 -0
  72. package/dist/shares/revoke.js +43 -0
  73. package/dist/shares/settings.d.ts +76 -0
  74. package/dist/shares/settings.js +117 -0
  75. package/dist/shares/share-code.d.ts +4 -0
  76. package/dist/shares/share-code.js +28 -0
  77. package/dist/shares/share-objects.d.ts +52 -0
  78. package/dist/shares/share-objects.js +123 -0
  79. package/dist/shares/share-open.controller.d.ts +35 -0
  80. package/dist/shares/share-open.controller.js +107 -0
  81. package/dist/shares/share-open.service.d.ts +107 -0
  82. package/dist/shares/share-open.service.js +287 -0
  83. package/dist/shares/share-previews.controller.d.ts +50 -0
  84. package/dist/shares/share-previews.controller.js +115 -0
  85. package/dist/shares/shares.controller.d.ts +34 -0
  86. package/dist/shares/shares.controller.js +114 -0
  87. package/dist/shares/shares.module.d.ts +8 -0
  88. package/dist/shares/shares.module.js +41 -0
  89. package/dist/shares/shares.schemas.d.ts +31 -0
  90. package/dist/shares/shares.schemas.js +25 -0
  91. package/dist/shares/shares.service.d.ts +182 -0
  92. package/dist/shares/shares.service.js +553 -0
  93. package/dist/shares/sweep.job.d.ts +72 -0
  94. package/dist/shares/sweep.job.js +330 -0
  95. package/dist/tools/builtins/sandbox/deliver.js +3 -1
  96. package/dist/ui/embed-token.d.ts +2 -2
  97. package/dist/ui/embed-token.js +38 -2
  98. package/dist/ui/views.d.ts +6 -0
  99. package/dist/ui/views.js +17 -0
  100. package/package.json +4 -4
  101. package/src/migrations/0161_file_shares.sql +35 -0
@@ -19,6 +19,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
19
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
20
20
  import { localMachineRoots, needsWiderDeviceCeiling, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
21
21
  import { applyDevicesFullAccessPatch, DEVICES_AUTO_MODE_PATCH, DEVICES_FULL_ACCESS_DEFAULT, DEVICES_FULL_ACCESS_PATCH, DEVICES_FULL_ACCESS_SETTING, fullAccessPatchOfLegacy, LEGACY_DEVICES_AUTO_MODE_SETTING, legacyAutoModeView, legacyDevicesAutoModeStored, readDevicesFullAccess, readStoredDevicesFullAccess, } from "../sandbox/platform-full-access.js";
22
+ import { EXTERNAL_SHARING_SETTING, ExternalSharingValue, HTML_CDN_ALLOWLIST_DEFAULT, HtmlCdnAllowlistSchema, readExternalSharing, readHtmlCdnAllowlist, readShareMaxExpiry, SHARE_MAX_EXPIRY_DEFAULT, SHARE_MAX_EXPIRY_SETTING, ShareMaxExpiryDays, } from "../shares/settings.js";
22
23
  import { assertPlatformDefaultEligible, lockThemeShared } from "../themes/theme-state.js";
23
24
  import { mergeArrangement, UiArrangementPatchSchema, UiArrangementSchema, } from "../ui/arrangement.js";
24
25
  import { audit } from "./audit.js";
@@ -210,9 +211,16 @@ export const DEPLOYMENT_SETTINGS = z.object({
210
211
  * values; an organization may override any field in its own settings.
211
212
  */
212
213
  compaction: COMPACTION_SETTINGS.prefault({}),
214
+ /**
215
+ * The CDN origins a rendered HTML file may load scripts, styles, fonts and images from (file
216
+ * sharing spec §4): `https://` origins only; applies to the next document load. No org level.
217
+ */
218
+ htmlRenderCdnAllowlist: HtmlCdnAllowlistSchema.default(() => [...HTML_CDN_ALLOWLIST_DEFAULT]),
213
219
  });
214
220
  const DEFAULTS = DEPLOYMENT_SETTINGS.parse({});
215
221
  const autoModeWidenRefused = () => new ApiError("deployment.auto_mode_not_allowed", "Allowing Full permission at the platform level (devicesFullAccess) needs a super admin in the admin console; an API token or the Platform tool may only turn it off.");
222
+ const externalSharingWidenRefused = () => new ApiError("deployment.external_sharing_not_allowed", "Allowing external sharing at the platform level (externalSharing) needs a super admin in the admin console; an API token or the Platform tool may only turn it off.");
223
+ const sharingWidenRefused = (field, message) => new ApiError("deployment.sharing_widen_not_allowed", message, [{ path: field }]);
216
224
  /**
217
225
  * 设置的修改(PUT /api/v1/admin/settings 的 body):只改给出的键。
218
226
  * `runConcurrencyOverrides` 按组织合并:值为正整数 → 设置该组织的上限;值为 null → 删除该组织的覆盖
@@ -282,6 +290,20 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
282
290
  * one, fields left out keep their value.
283
291
  */
284
292
  compaction: COMPACTION_SETTINGS_PATCH.optional(),
293
+ /**
294
+ * The platform's external sharing switch (file sharing spec §8): allow or deny; null clears it
295
+ * (back to the default, deny). A value set in the startup config is read-only (409
296
+ * `deployment.setting_readonly`); an API token or the Platform tool may only turn it off (400
297
+ * `deployment.external_sharing_not_allowed`).
298
+ */
299
+ externalSharing: ExternalSharingValue.nullable().optional(),
300
+ /**
301
+ * The longest expiry a share may take, in days (1 to 365); null clears it (back to 30). A
302
+ * value set in the startup config is read-only (409 `deployment.setting_readonly`).
303
+ */
304
+ shareMaxExpiryDays: ShareMaxExpiryDays.nullable().optional(),
305
+ /** The CDN allowlist of rendered HTML files, replaced whole (stored without duplicates). */
306
+ htmlRenderCdnAllowlist: HtmlCdnAllowlistSchema.optional(),
285
307
  })
286
308
  .strict();
287
309
  /**
@@ -479,16 +501,20 @@ let SettingsService = class SettingsService {
479
501
  }
480
502
  /** The settings with the platform's Full switch and attribution defaults in effect. */
481
503
  async view() {
482
- const [settings, devicesFullAccess, attribution] = await Promise.all([
504
+ const [settings, devicesFullAccess, attribution, externalSharing, shareMaxExpiryDays] = await Promise.all([
483
505
  this.get(),
484
506
  readDevicesFullAccess(this.db.db, this.config, this.log),
485
507
  readStoredPlatformAttribution(this.db.db, this.log),
508
+ readExternalSharing(this.db.db, this.config, this.log),
509
+ readShareMaxExpiry(this.db.db, this.config, this.log),
486
510
  ]);
487
511
  return {
488
512
  ...settings,
489
513
  devicesFullAccess,
490
514
  devicesAutoMode: legacyAutoModeView(devicesFullAccess),
491
515
  attribution: this.attributionView(attribution),
516
+ externalSharing,
517
+ shareMaxExpiryDays,
492
518
  };
493
519
  }
494
520
  attributionView(stored) {
@@ -518,6 +544,42 @@ let SettingsService = class SettingsService {
518
544
  }
519
545
  return { next, before };
520
546
  }
547
+ /**
548
+ * The refusals of an `externalSharing` / `shareMaxExpiryDays` / `htmlRenderCdnAllowlist` change:
549
+ * a field set in the startup config (`deployment.setting_readonly`) and, with `onlyNarrows` (an
550
+ * API token, the Platform tool), any widening: allowing external sharing where it is denied
551
+ * (`deployment.external_sharing_not_allowed`; clearing it goes back to deny, a narrowing), an
552
+ * expiry maximum above the effective one (null counts as the default, 30) or an allowlist origin
553
+ * the effective list does not hold (`deployment.sharing_widen_not_allowed`). Only a person widens.
554
+ */
555
+ async checkSharing(patch, opts = {}) {
556
+ const fields = [
557
+ ["externalSharing", "sharing.external"],
558
+ ["shareMaxExpiryDays", "sharing.maxExpiryDays"],
559
+ ];
560
+ const readonly = fields.filter(([key, path]) => patch[key] !== undefined && this.config.fieldSource(path) !== undefined);
561
+ if (readonly.length > 0) {
562
+ throw new ApiError("deployment.setting_readonly", `These sharing settings are set in the startup config (file, Nacos or environment) and are read-only here: ${readonly.map(([key]) => key).join(", ")}`, readonly.map(([key, path]) => ({ path: key, source: this.config.fieldSource(path) })));
563
+ }
564
+ if (opts.onlyNarrows && patch.externalSharing === "allow") {
565
+ const before = await readExternalSharing(this.db.db, this.config, this.log);
566
+ if (before.value !== "allow")
567
+ throw externalSharingWidenRefused();
568
+ }
569
+ if (opts.onlyNarrows && patch.shareMaxExpiryDays !== undefined) {
570
+ const before = await readShareMaxExpiry(this.db.db, this.config, this.log);
571
+ const after = patch.shareMaxExpiryDays ?? SHARE_MAX_EXPIRY_DEFAULT;
572
+ if (after > before.value)
573
+ throw sharingWidenRefused("shareMaxExpiryDays", `Raising the share expiry maximum (now ${before.value} days) needs a super admin in the admin console; an API token or the Platform tool may only lower it.`);
574
+ }
575
+ if (opts.onlyNarrows && patch.htmlRenderCdnAllowlist !== undefined) {
576
+ // both sides are lower-cased by the schema; a Set compares them without duplicates
577
+ const current = new Set(await readHtmlCdnAllowlist(this.db.db, this.log));
578
+ const added = [...new Set(patch.htmlRenderCdnAllowlist)].filter((o) => !current.has(o));
579
+ if (added.length > 0)
580
+ throw sharingWidenRefused("htmlRenderCdnAllowlist", `Adding origins to the HTML CDN allowlist (${added.join(", ")}) needs a super admin in the admin console; an API token or the Platform tool may only remove origins.`);
581
+ }
582
+ }
521
583
  /**
522
584
  * The refusals of an `attribution` change against the stored choice: a field set in the startup
523
585
  * config (`deployment.setting_readonly`). Returns the next stored choice.
@@ -561,7 +623,9 @@ let SettingsService = class SettingsService {
561
623
  }
562
624
  /**
563
625
  * Updates settings under the super admin lock, re-checking the actor (else `forbidden`).
564
- * `onlyNarrows` (an API token, the Platform tool): `devicesFullAccess` may only turn Full off.
626
+ * `onlyNarrows` (an API token, the Platform tool): `devicesFullAccess` may only turn Full off,
627
+ * `externalSharing` may only turn external sharing off, `shareMaxExpiryDays` may only decrease and
628
+ * `htmlRenderCdnAllowlist` may only shrink.
565
629
  */
566
630
  async update(patch, actorAccountId, actorTokenId,
567
631
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
@@ -599,6 +663,9 @@ let SettingsService = class SettingsService {
599
663
  if (patch.orgMarketplaceBrowse !== undefined) {
600
664
  next.orgMarketplaceBrowse = patch.orgMarketplaceBrowse;
601
665
  }
666
+ if (patch.htmlRenderCdnAllowlist !== undefined) {
667
+ next.htmlRenderCdnAllowlist = [...new Set(patch.htmlRenderCdnAllowlist)];
668
+ }
602
669
  if (patch.uiTheme !== undefined) {
603
670
  // The one theme lock order (themes spec §7), inside the super admin lock above: the chosen
604
671
  // theme's catalog item, then its `platform_themes` row FOR SHARE, then the `uiTheme` row FOR
@@ -681,6 +748,25 @@ let SettingsService = class SettingsService {
681
748
  if (patch.attribution !== undefined) {
682
749
  writes.push([PLATFORM_ATTRIBUTION_SETTING, await this.checkAttribution(patch.attribution)]);
683
750
  }
751
+ // the sharing switches: checked under the lock; null deletes the stored choice (the default)
752
+ const deletes = [];
753
+ if (patch.externalSharing !== undefined ||
754
+ patch.shareMaxExpiryDays !== undefined ||
755
+ patch.htmlRenderCdnAllowlist !== undefined) {
756
+ await this.checkSharing(patch, opts);
757
+ for (const [key, value] of [
758
+ [EXTERNAL_SHARING_SETTING, patch.externalSharing],
759
+ [SHARE_MAX_EXPIRY_SETTING, patch.shareMaxExpiryDays],
760
+ ]) {
761
+ if (value === null)
762
+ deletes.push(key);
763
+ else if (value !== undefined)
764
+ writes.push([key, value]);
765
+ }
766
+ }
767
+ if (deletes.length > 0) {
768
+ await this.db.deleteFrom("deployment_settings").where("key", "in", deletes).execute();
769
+ }
684
770
  for (const [key, value] of writes) {
685
771
  if (value === undefined)
686
772
  continue;
@@ -72,6 +72,9 @@ const HOT_APPLIERS = {
72
72
  "attribution.commit": () => { },
73
73
  "attribution.pr": () => { },
74
74
  "attribution.sessionUrl": () => { },
75
+ // The sharing switches are read live at every share create, open and settings read.
76
+ "sharing.external": () => { },
77
+ "sharing.maxExpiryDays": () => { },
75
78
  };
76
79
  const HOT_PATHS = configFields(KernelConfigSchema)
77
80
  .filter((f) => f.meta?.hot)
@@ -19,6 +19,19 @@ export interface OutboxJobSpec {
19
19
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
20
20
  */
21
21
  export declare const OUTBOX_JOBS: {
22
+ readonly "share-object-delete": {
23
+ readonly queue: "cap-kernel-maintenance";
24
+ readonly idempotent: "Deletes one object key; deleting a missing object is a no-op";
25
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
26
+ readonly opts: {
27
+ readonly attempts: 10;
28
+ readonly backoff: {
29
+ readonly type: "exponential";
30
+ readonly delay: 5000;
31
+ };
32
+ readonly removeOnComplete: true;
33
+ };
34
+ };
22
35
  readonly "permission-approval-recheck": {
23
36
  readonly queue: "cap-kernel-maintenance";
24
37
  readonly idempotent: "Reads the current revision and resumes only waiting runs without another pending wait; queued runs are unchanged.";
@@ -21,6 +21,14 @@ const SCOPE_JOB_OPTS = {
21
21
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
22
22
  */
23
23
  export const OUTBOX_JOBS = {
24
+ // `shares/share-objects.ts` SHARE_OBJECT_DELETE_JOB: owed by a share's refresh (the previous
25
+ // generation) and revoke (the current one), under `shareObjectDeleteJobId` (file sharing spec §2)
26
+ "share-object-delete": {
27
+ queue: "cap-kernel-maintenance",
28
+ idempotent: "Deletes one object key; deleting a missing object is a no-op",
29
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
30
+ opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
31
+ },
24
32
  "permission-approval-recheck": {
25
33
  queue: "cap-kernel-maintenance",
26
34
  idempotent: "Reads the current revision and resumes only waiting runs without another pending wait; queued runs are unchanged.",
@@ -26,7 +26,10 @@ export declare const credentialRedisKey: (t: NamedThrottler, tracker: string) =>
26
26
  export declare class CredentialThrottler {
27
27
  private readonly storage;
28
28
  constructor(storage: ThrottlerStorage);
29
- /** Reserves one attempt on every named throttler or throws 429 `auth.rate_limited` (header set on `reply`). */
29
+ /**
30
+ * Reserves one attempt on every named throttler or throws 429 with the throttlers' `code`
31
+ * (default `auth.rate_limited`; `retry-after` set on `reply`).
32
+ */
30
33
  reserve(names: readonly string[], req: FastifyRequest, reply: FastifyReply): Promise<void>;
31
34
  /** A successful attempt: clears the `clear` counters and refunds one on the `refund` ones. */
32
35
  succeeded(names: readonly string[], req: FastifyRequest): Promise<void>;
@@ -38,14 +38,17 @@ let CredentialThrottler = class CredentialThrottler {
38
38
  constructor(storage) {
39
39
  this.storage = storage;
40
40
  }
41
- /** Reserves one attempt on every named throttler or throws 429 `auth.rate_limited` (header set on `reply`). */
41
+ /**
42
+ * Reserves one attempt on every named throttler or throws 429 with the throttlers' `code`
43
+ * (default `auth.rate_limited`; `retry-after` set on `reply`).
44
+ */
42
45
  async reserve(names, req, reply) {
43
46
  const ts = this.resolve(names);
44
47
  const r = await this.redisStorage().reserve(ts.map((t) => credentialRedisKey(t, t.getTracker(req))), ts.map((t) => t.limit), ts[0]?.ttl ?? 0);
45
48
  if (r.allowed)
46
49
  return;
47
50
  reply.header("retry-after", String(r.retryAfterSeconds));
48
- throw new ApiError("auth.rate_limited", ts[0]?.message ?? "");
51
+ throw new ApiError(ts[0]?.code ?? "auth.rate_limited", ts[0]?.message ?? "");
49
52
  }
50
53
  /** A successful attempt: clears the `clear` counters and refunds one on the `refund` ones. */
51
54
  async succeeded(names, req) {
@@ -28,6 +28,7 @@ export interface NamedThrottler {
28
28
  * | `POST /api/v1/setup` | `setup-token`, `setup-ip` |
29
29
  * | `POST /api/v1/invitations/:token/accept` | `invitation`, `invitation-ip` |
30
30
  * | `GET /api/v1/device/pending/:userCode`, `POST /api/v1/device/confirm`, `POST /api/v1/device/deny` | `device-code-account` |
31
+ * | `GET /api/v1/s/:code`, `…/content`, `…/text`, `…/inline`, `…/html`, `POST …/embed-token/:plugin/:previewerId`, `GET …/previews/:plugin/:previewerId` | `share-open` |
31
32
  *
32
33
  * `POST /api/v1/orgs/:orgId/ui/client/reports` and `POST /api/v1/admin/ui/client/reports` opt in to
33
34
  * `client-reports` with `@Throttled` (20 per minute per account: a crash loop in a browser must
@@ -29,6 +29,7 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
29
29
  * | `POST /api/v1/setup` | `setup-token`, `setup-ip` |
30
30
  * | `POST /api/v1/invitations/:token/accept` | `invitation`, `invitation-ip` |
31
31
  * | `GET /api/v1/device/pending/:userCode`, `POST /api/v1/device/confirm`, `POST /api/v1/device/deny` | `device-code-account` |
32
+ * | `GET /api/v1/s/:code`, `…/content`, `…/text`, `…/inline`, `…/html`, `POST …/embed-token/:plugin/:previewerId`, `GET …/previews/:plugin/:previewerId` | `share-open` |
32
33
  *
33
34
  * `POST /api/v1/orgs/:orgId/ui/client/reports` and `POST /api/v1/admin/ui/client/reports` opt in to
34
35
  * `client-reports` with `@Throttled` (20 per minute per account: a crash loop in a browser must
@@ -197,6 +198,19 @@ export const NAMED_THROTTLERS = [
197
198
  code: "rate_limited",
198
199
  getTracker: (req) => `${req.url.split("/")[2] ?? ""}:${ip(req)}`,
199
200
  },
201
+ // public share link lookups per client address (file sharing spec §3): 30 misses in 10 minutes.
202
+ // Reserved via CredentialThrottler before the lookup; a live share refunds the attempt, so only
203
+ // unknown, revoked, expired or refused codes count (codes cannot be enumerated)
204
+ {
205
+ name: "share-open",
206
+ group: "share-open",
207
+ onSuccess: "refund",
208
+ limit: 30,
209
+ ttl: 600_000,
210
+ code: "rate_limited",
211
+ message: "Too many share link requests; try again later",
212
+ getTracker: ip,
213
+ },
200
214
  ];
201
215
  /** The storage key of a named throttler's counter for a tracker (shared by the guard and success paths). */
202
216
  export const throttlerKey = (name, tracker) => sha256(`${name}:${tracker}`);
@@ -114,7 +114,9 @@ export declare class Offboarding {
114
114
  * 9. Soft-deletes the person's devices in the org and clears their default row, and owes the
115
115
  * destruction of each (instance and files, `device-destroy-<deviceId>`);
116
116
  * 10. Owes the `org.member_removed` lifecycle hook deliveries (outbox jobs, one per subscribing
117
- * plugin).
117
+ * plugin);
118
+ * 11. Revokes the person's file shares in the org (`member_offboarded`) and owes the deletion of
119
+ * each snapshot (`share-object-delete-<shareId>-<generation>`, file sharing spec §9).
118
120
  */
119
121
  offboard(orgId: string, accountId: string, reason: OffboardReason, actor?: {
120
122
  actorAccountId?: string;
@@ -28,6 +28,7 @@ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
28
28
  import { RunControl } from "../runtime/run-control.js";
29
29
  import { oweDeviceDestroy } from "../sandbox/jobs.js";
30
30
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
31
+ import { revokeSharesIn } from "../shares/revoke.js";
31
32
  import { ApprovalsService } from "../tools/approvals.service.js";
32
33
  import { Credentials } from "../tools/credentials.js";
33
34
  import { QuestionsService } from "../tools/questions.service.js";
@@ -111,7 +112,9 @@ let Offboarding = class Offboarding {
111
112
  * 9. Soft-deletes the person's devices in the org and clears their default row, and owes the
112
113
  * destruction of each (instance and files, `device-destroy-<deviceId>`);
113
114
  * 10. Owes the `org.member_removed` lifecycle hook deliveries (outbox jobs, one per subscribing
114
- * plugin).
115
+ * plugin);
116
+ * 11. Revokes the person's file shares in the org (`member_offboarded`) and owes the deletion of
117
+ * each snapshot (`share-object-delete-<shareId>-<generation>`, file sharing spec §9).
115
118
  */
116
119
  async offboard(orgId, accountId, reason, actor = {}) {
117
120
  // the org admission lock exclusively (the callers take it first, before the org row; a no-op
@@ -313,6 +316,8 @@ let Offboarding = class Offboarding {
313
316
  .where("org_id", "=", orgId)
314
317
  .where("account_id", "=", accountId)
315
318
  .execute();
319
+ // after the conversations above (the share rows come last, as in every other share write)
320
+ const sharesRevoked = await revokeSharesIn(this.db.db, this.outbox, { orgId, createdBy: accountId }, "member_offboarded");
316
321
  await audit(this.db.db, {
317
322
  ...(actor.actorAccountId !== undefined && { actorAccountId: actor.actorAccountId }),
318
323
  ...(actor.actorTokenId !== undefined && { actorTokenId: actor.actorTokenId }),
@@ -335,6 +340,7 @@ let Offboarding = class Offboarding {
335
340
  ...(excluded.length > 0 && { directoryExcluded: excluded }),
336
341
  ...(devices.length > 0 && { devicesDeleted: devices.length }),
337
342
  ...(queued.length > 0 && { queuedMessagesDeleted: queued.length }),
343
+ ...(sharesRevoked > 0 && { sharesRevoked }),
338
344
  },
339
345
  });
340
346
  await this.lifecycle.recordIn("org.member_removed", {
@@ -9,6 +9,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
9
9
  import type { KernelLogger } from "../log.js";
10
10
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
11
11
  import { type DevicesAutoModeView, type DevicesFullAccessView, type FullAccessPermission } from "../sandbox/platform-full-access.js";
12
+ import { type ExternalSharingView } from "../shares/settings.js";
12
13
  import { type CloudNetworkSetting } from "./cloud-network-setting.js";
13
14
  import { OrgLock } from "./org-lock.js";
14
15
  /**
@@ -192,6 +193,10 @@ export declare const OrgSettingsSchema: z.ZodObject<{
192
193
  reserveTokens: z.ZodOptional<z.ZodNumber>;
193
194
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
194
195
  }, z.core.$strip>>>;
196
+ externalSharing: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
197
+ off: "off";
198
+ on: "on";
199
+ }>>>;
195
200
  }, z.core.$strip>;
196
201
  export type OrgSettings = z.infer<typeof OrgSettingsSchema>;
197
202
  /**
@@ -278,6 +283,10 @@ export declare const OrgSettingsPatchSchema: z.ZodObject<{
278
283
  reserveTokens: z.ZodOptional<z.ZodNumber>;
279
284
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
280
285
  }, z.core.$strict>>>;
286
+ externalSharing: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
287
+ off: "off";
288
+ on: "on";
289
+ }>>>;
281
290
  }, z.core.$strict>;
282
291
  export type OrgSettingsPatch = z.infer<typeof OrgSettingsPatchSchema>;
283
292
  /** A patch with the old `autoMode` moved to `fullAccess` (the schema refuses both together). */
@@ -334,6 +343,10 @@ export interface OrgSettingsDeployment {
334
343
  publicUrl: boolean;
335
344
  /** The platform's conversation compaction settings (what "follow the platform" means). */
336
345
  compaction: CompactionSettings;
346
+ /** The platform's external sharing switch and its source (deny: the org cannot turn it on). */
347
+ externalSharing: ExternalSharingView;
348
+ /** The longest expiry a share may take, in days. */
349
+ shareMaxExpiryDays: number;
337
350
  }
338
351
  /**
339
352
  * Parses the stored jsonb into settings (leniently, see {@link OrgSettingsSchema}). Until 8.6 `fullAccess` is read
@@ -368,6 +381,8 @@ export declare const FORBIDDEN_TOOLS_UNREADABLE_GRANT_ERROR = "The organization'
368
381
  * than written, with the org id.
369
382
  */
370
383
  export declare function logUnreadableSecuritySettings(log: (msg: string, fields: Record<string, unknown>) => void, orgId: string, raw: unknown): void;
384
+ /** Whether a stored settings object holds an `externalSharing` this version reads as `off`. */
385
+ export declare function invalidStoredExternalSharing(raw: unknown): boolean;
371
386
  /** Whether a stored settings object holds a `fullAccess` this version reads as `off`. */
372
387
  export declare function invalidStoredFullAccess(raw: unknown): boolean;
373
388
  /** Whether a stored settings object holds a `cloudNetwork` this version reads as an empty allowlist. */
@@ -414,7 +429,7 @@ export declare class OrgSettingsService {
414
429
  get(orgId: string): Promise<OrgSettingsView>;
415
430
  /**
416
431
  * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
417
- * auto mode where the platform turned it off.
432
+ * auto mode where the platform turned it off, external sharing where the platform denies it.
418
433
  */
419
434
  check(input: OrgSettingsPatch): Promise<void>;
420
435
  /**
@@ -429,8 +444,9 @@ export declare class OrgSettingsService {
429
444
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
430
445
  auditDetail?: Record<string, unknown>,
431
446
  /**
432
- * `onlyNarrows` (the Platform tool, API tokens): refuse a `fullAccess` or `cloudNetwork`
433
- * change that widens (see {@link assertOnlyNarrows}); only a person in a session widens.
447
+ * `onlyNarrows` (the Platform tool, API tokens): refuse a `fullAccess`, `cloudNetwork` or
448
+ * `externalSharing` change that widens (see {@link assertOnlyNarrows}); only a person in a
449
+ * session widens.
434
450
  */
435
451
  opts?: {
436
452
  onlyNarrows?: boolean;
@@ -443,7 +459,8 @@ export declare class OrgSettingsService {
443
459
  * platform); clearing it follows the platform too, never wider than the platform allows;
444
460
  * - `cloudNetwork`: compared as stored deltas ({@link cloudNetworkWidens}), never as effective
445
461
  * values: under the kill switch or the platform ceiling the effective values hide a widening
446
- * that takes effect when the platform relaxes (org egress ceiling spec §D3).
462
+ * that takes effect when the platform relaxes (org egress ceiling spec §D3);
463
+ * - `externalSharing`: `on` where the org is off (absent = off).
447
464
  */
448
465
  assertOnlyNarrows(before: OrgSettings, input: OrgSettingsPatch): Promise<void>;
449
466
  private updateIn;
@@ -23,6 +23,7 @@ import { isExecutionMethod } from "../sandbox/operation-authority-types.js";
23
23
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
24
24
  import { localMachineRoots, needsFullCeiling, needsWiderDeviceCeiling, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
25
25
  import { legacyAutoModeView, narrowedOrgFullAccess, readDevicesFullAccess, } from "../sandbox/platform-full-access.js";
26
+ import { readExternalSharing, readShareMaxExpiry, } from "../shares/settings.js";
26
27
  import { assertThemeOnIn } from "../themes/theme-state.js";
27
28
  import { IanaTimeZone } from "../time-zone.js";
28
29
  import { mergeArrangement, OrgUiArrangementPatchSchema, UiArrangementSchema, } from "../ui/arrangement.js";
@@ -137,6 +138,7 @@ export const GitGatewaySettingSchema = z.object({
137
138
  });
138
139
  /** What an invalid stored `gitGateway` reads as: the gateway off for the org. */
139
140
  export const GIT_GATEWAY_INVALID = { enabled: false };
141
+ const ExternalSharingSetting = z.enum(["on", "off"]);
140
142
  export const OrgSettingsSchema = z.object({
141
143
  toolSearch: z.enum(["on", "off"]).default("on").catch("on"),
142
144
  locale: z.enum(["zh", "en"]).default("en").catch("en"),
@@ -164,6 +166,11 @@ export const OrgSettingsSchema = z.object({
164
166
  * rest follow the platform; absent (or an invalid stored value) follows the platform entirely.
165
167
  */
166
168
  compaction: COMPACTION_SETTINGS_PARTIAL.optional().catch(undefined),
169
+ /**
170
+ * The org's external sharing switch (file sharing spec §8); absent = off. An invalid stored
171
+ * value reads as `off` (never wider). The platform's switch must allow it too.
172
+ */
173
+ externalSharing: ExternalSharingSetting.optional().catch("off"),
167
174
  });
168
175
  /** {@link OrgSettingsView} of `settings`, flagged from the stored value `raw`. */
169
176
  const viewOf = (settings, raw) => invalidStoredForbiddenTools(raw)
@@ -213,6 +220,12 @@ export const OrgSettingsPatchSchema = z
213
220
  * (follow the platform again). Strict: a misspelled field is a 400, not a silent no-op.
214
221
  */
215
222
  compaction: COMPACTION_SETTINGS_PATCH.nullable().optional(),
223
+ /**
224
+ * The org's external sharing switch; null clears it (off). `on` while the platform denies it
225
+ * -> 400 `org.external_sharing_not_allowed`; through the Platform tool or an API token it may
226
+ * only be turned off (the same code).
227
+ */
228
+ externalSharing: ExternalSharingSetting.nullable().optional(),
216
229
  })
217
230
  .strict()
218
231
  .refine((p) => p.autoMode === undefined || p.fullAccess === undefined, {
@@ -329,6 +342,12 @@ export function logUnreadableSecuritySettings(log, orgId, raw) {
329
342
  }
330
343
  }
331
344
  const autoModeNotAllowed = (message) => new ApiError("org.auto_mode_not_allowed", message);
345
+ const externalSharingNotAllowed = (message) => new ApiError("org.external_sharing_not_allowed", message);
346
+ /** Whether a stored settings object holds an `externalSharing` this version reads as `off`. */
347
+ export function invalidStoredExternalSharing(raw) {
348
+ const v = asObject(raw).externalSharing;
349
+ return v !== undefined && !ExternalSharingSetting.safeParse(v).success;
350
+ }
332
351
  /** Whether a stored settings object holds a `fullAccess` this version reads as `off`. */
333
352
  export function invalidStoredFullAccess(raw) {
334
353
  const v = asObject(raw).fullAccess;
@@ -389,6 +408,9 @@ let OrgSettingsService = class OrgSettingsService {
389
408
  if (invalidStoredFullAccess(raw)) {
390
409
  this.log?.warn("org settings: stored fullAccess is invalid; it reads as off", { orgId });
391
410
  }
411
+ if (invalidStoredExternalSharing(raw)) {
412
+ this.log?.warn("org settings: stored externalSharing is invalid; it reads as off", { orgId });
413
+ }
392
414
  if (invalidStoredCloudNetwork(raw)) {
393
415
  this.log?.warn("org settings: stored cloudNetwork is invalid; it reads as an empty allowlist", {
394
416
  orgId,
@@ -402,10 +424,12 @@ let OrgSettingsService = class OrgSettingsService {
402
424
  /** 部署默认值(设置页展示「跟随部署」时的实际取值)。 */
403
425
  async deployment() {
404
426
  const lim = this.config.get().sandbox.limits;
405
- const [fullAccess, attribution, compaction] = await Promise.all([
427
+ const [fullAccess, attribution, compaction, externalSharing, shareMaxExpiry] = await Promise.all([
406
428
  readDevicesFullAccess(this.db.db, this.config, this.log),
407
429
  readPlatformAttribution(this.db.db, this.config, this.log),
408
430
  readPlatformCompactionSettings(this.db.db),
431
+ readExternalSharing(this.db.db, this.config, this.log),
432
+ readShareMaxExpiry(this.db.db, this.config, this.log),
409
433
  ]);
410
434
  return {
411
435
  fullAccess,
@@ -418,6 +442,8 @@ let OrgSettingsService = class OrgSettingsService {
418
442
  attribution,
419
443
  publicUrl: this.config.get().http.publicUrl !== undefined,
420
444
  compaction,
445
+ externalSharing,
446
+ shareMaxExpiryDays: shareMaxExpiry.value,
421
447
  };
422
448
  }
423
449
  /**
@@ -454,7 +480,7 @@ let OrgSettingsService = class OrgSettingsService {
454
480
  }
455
481
  /**
456
482
  * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
457
- * auto mode where the platform turned it off.
483
+ * auto mode where the platform turned it off, external sharing where the platform denies it.
458
484
  */
459
485
  async check(input) {
460
486
  const patch = normalizeOrgSettingsPatch(input);
@@ -465,6 +491,12 @@ let OrgSettingsService = class OrgSettingsService {
465
491
  throw autoModeNotAllowed("The platform does not allow Full permission");
466
492
  }
467
493
  }
494
+ if (patch.externalSharing === "on") {
495
+ const platform = await readExternalSharing(this.db.db, this.config, this.log);
496
+ if (platform.value !== "allow") {
497
+ throw externalSharingNotAllowed("The platform does not allow external sharing; a super admin must allow it in the admin console settings first");
498
+ }
499
+ }
468
500
  }
469
501
  /**
470
502
  * Under `sandbox.limits.orgHosts: within` (spec §D2), refuses what would widen past the platform
@@ -493,8 +525,9 @@ let OrgSettingsService = class OrgSettingsService {
493
525
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
494
526
  auditDetail,
495
527
  /**
496
- * `onlyNarrows` (the Platform tool, API tokens): refuse a `fullAccess` or `cloudNetwork`
497
- * change that widens (see {@link assertOnlyNarrows}); only a person in a session widens.
528
+ * `onlyNarrows` (the Platform tool, API tokens): refuse a `fullAccess`, `cloudNetwork` or
529
+ * `externalSharing` change that widens (see {@link assertOnlyNarrows}); only a person in a
530
+ * session widens.
498
531
  */
499
532
  opts) {
500
533
  const patch = normalizeOrgSettingsPatch(input);
@@ -516,7 +549,8 @@ let OrgSettingsService = class OrgSettingsService {
516
549
  * platform); clearing it follows the platform too, never wider than the platform allows;
517
550
  * - `cloudNetwork`: compared as stored deltas ({@link cloudNetworkWidens}), never as effective
518
551
  * values: under the kill switch or the platform ceiling the effective values hide a widening
519
- * that takes effect when the platform relaxes (org egress ceiling spec §D3).
552
+ * that takes effect when the platform relaxes (org egress ceiling spec §D3);
553
+ * - `externalSharing`: `on` where the org is off (absent = off).
520
554
  */
521
555
  async assertOnlyNarrows(before, input) {
522
556
  const patch = normalizeOrgSettingsPatch(input);
@@ -531,6 +565,9 @@ let OrgSettingsService = class OrgSettingsService {
531
565
  cloudNetworkWidens(before.cloudNetwork, patch.cloudNetwork ?? undefined)) {
532
566
  throw new ApiError("org.sandbox_egress_not_allowed", "Widening the cloud network needs a person in the organization settings.");
533
567
  }
568
+ if (patch.externalSharing === "on" && before.externalSharing !== "on") {
569
+ throw externalSharingNotAllowed("Turning external sharing on needs a person in the organization settings on the web; an API token or the Platform tool may only turn it off.");
570
+ }
534
571
  }
535
572
  async updateIn(orgId, patch, actorAccountId, actorTokenId, auditDetail, opts) {
536
573
  // held since the prelude (`lockFor`); naming them again re-checks the actor's role
@@ -550,7 +587,8 @@ let OrgSettingsService = class OrgSettingsService {
550
587
  await this.assertOnlyNarrows(before, patch);
551
588
  const changes = Object.fromEntries(Object.entries(patch)
552
589
  .filter(([, v]) => v !== undefined)
553
- // null clears fullAccess / cloudNetwork / wakeOnBackgroundTask: follow the deployment again
590
+ // null clears fullAccess / cloudNetwork / wakeOnBackgroundTask (follow the deployment
591
+ // again) and externalSharing (off)
554
592
  .map(([k, v]) => [k, v === null ? undefined : v]));
555
593
  const arrangementPatch = patch.uiArrangement;
556
594
  const compactionPatch = patch.compaction;
@@ -603,6 +641,8 @@ let OrgSettingsService = class OrgSettingsService {
603
641
  }
604
642
  if (after.compaction === undefined)
605
643
  delete after.compaction;
644
+ if (after.externalSharing === undefined)
645
+ delete after.externalSharing;
606
646
  // saving an unreadable security setting writes it even when it equals what it read as
607
647
  const repairs = (invalidStoredForbiddenTools(stored) && patch.scheduledTasks?.forbiddenTools !== undefined) ||
608
648
  (invalidStoredSandboxToolPolicy(stored) && patch.sandboxToolPolicy !== undefined);
@@ -615,7 +655,7 @@ let OrgSettingsService = class OrgSettingsService {
615
655
  }
616
656
  // Merge with the stored value: keep the keys this version does not know (a cleared fullAccess /
617
657
  // cloudNetwork is not kept, nor the old name autoMode)
618
- const { autoMode: _legacyAutoMode, fullAccess: _oldFullAccess, cloudNetwork: _oldNetwork, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, scheduledTasks: _oldScheduled, compaction: _oldCompaction, ...rest } = stored;
658
+ const { autoMode: _legacyAutoMode, fullAccess: _oldFullAccess, cloudNetwork: _oldNetwork, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, scheduledTasks: _oldScheduled, compaction: _oldCompaction, externalSharing: _oldExternalSharing, ...rest } = stored;
619
659
  const written = {
620
660
  ...rest,
621
661
  ...after,
@@ -11,6 +11,7 @@ import { USAGE_SUBSCRIBERS_CLOCK } from "./extensions/usage-subscribers.js";
11
11
  import { FILE_PREVIEW_TIMEOUT } from "./files/previewers.js";
12
12
  import { GIT_UPSTREAM_ORIGIN, type GitUpstreamOrigin } from "./git/gateway.js";
13
13
  import { GIT_IDENTITY_API_BASE, type GitIdentityApiBase } from "./git/identity.js";
14
+ import { HTML_TOKEN_CLOCK } from "./html/html-token.js";
14
15
  import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
15
16
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
16
17
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
@@ -43,6 +44,7 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
43
44
  * `PRESENCE_INTERVAL_MS`: shorter timings;
44
45
  * - `ADMIN_USAGE_TIMINGS`: the usage aggregate's statement timeout and clock;
45
46
  * - `EMBED_TOKEN_CLOCK`: the clock embed tokens are issued and checked with;
47
+ * - `HTML_TOKEN_CLOCK`: the clock HTML document tokens are issued and checked with;
46
48
  * - `RUN_CONTEXT_CLOCK`: the clock run start reads the run context's date from, and the
47
49
  * `CurrentTime` builtin the time;
48
50
  * - `GIT_IDENTITY_API_BASE`: the API base of a git host for the commit identity (a loopback fake);
@@ -81,6 +83,7 @@ interface KernelSeams {
81
83
  [PRESENCE_INTERVAL_MS]: number;
82
84
  [ADMIN_USAGE_TIMINGS]: Partial<AdminUsageTimings>;
83
85
  [EMBED_TOKEN_CLOCK]: () => number;
86
+ [HTML_TOKEN_CLOCK]: () => number;
84
87
  [RUN_CONTEXT_CLOCK]: () => number;
85
88
  [GIT_IDENTITY_API_BASE]: GitIdentityApiBase;
86
89
  [GIT_UPSTREAM_ORIGIN]: GitUpstreamOrigin;
package/dist/overrides.js CHANGED
@@ -9,6 +9,7 @@ import { USAGE_SUBSCRIBERS_CLOCK } from "./extensions/usage-subscribers.js";
9
9
  import { FILE_PREVIEW_TIMEOUT } from "./files/previewers.js";
10
10
  import { GIT_UPSTREAM_ORIGIN } from "./git/gateway.js";
11
11
  import { GIT_IDENTITY_API_BASE } from "./git/identity.js";
12
+ import { HTML_TOKEN_CLOCK } from "./html/html-token.js";
12
13
  import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
13
14
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
14
15
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
@@ -42,6 +43,7 @@ const SEAM_TOKENS = [
42
43
  PRESENCE_INTERVAL_MS,
43
44
  ADMIN_USAGE_TIMINGS,
44
45
  EMBED_TOKEN_CLOCK,
46
+ HTML_TOKEN_CLOCK,
45
47
  RUN_CONTEXT_CLOCK,
46
48
  GIT_IDENTITY_API_BASE,
47
49
  GIT_UPSTREAM_ORIGIN,