@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,143 @@
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 { Readable } from "node:stream";
11
+ import { FILE_PREVIEW_MAX_BYTES } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable, Optional } from "@nestjs/common";
13
+ import { attachmentContentMatches } from "../conversations/attachments.service.js";
14
+ import { ConversationFiles } from "../conversations/files.js";
15
+ import { ApiError } from "../errors.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { ShareLiveness } from "../shares/liveness.js";
19
+ import { readHtmlCdnAllowlist } from "../shares/settings.js";
20
+ import { StorageService } from "../storage/storage.service.js";
21
+ import { htmlDocumentCsp } from "./csp.js";
22
+ import { HTML_TOKEN_TTL_SECONDS, HtmlTokens } from "./html-token.js";
23
+ import { htmlContentType, isHtmlType } from "./html-type.js";
24
+ /** Every refusal of the document route: one answer, no reason (a token is not an oracle). */
25
+ export const htmlNotFound = () => new ApiError("not_found", "Not found");
26
+ const notPreviewable = (message) => new ApiError("conversation.artifact_not_previewable", message);
27
+ /**
28
+ * HTML files served as stand-alone documents (file sharing spec §4). The owner of a conversation
29
+ * mints a short-lived document token for one version of an HTML file ({@link mint}); the public
30
+ * route serves it ({@link serve}) under the sandbox CSP after re-checking, live, what the token
31
+ * names: the owner can still read the file (`ConversationFiles.file`: membership, active account,
32
+ * conversation and agent not deleted; an upload's object still the one finalize checked), or the
33
+ * share is still live at that generation (`ShareLiveness.byId`). The bytes are streamed by the
34
+ * kernel as stored; never a presigned URL on the app origin. HTML larger than
35
+ * `FILE_PREVIEW_MAX_BYTES` is never rendered.
36
+ */
37
+ let HtmlDocumentService = class HtmlDocumentService {
38
+ db;
39
+ files;
40
+ liveness;
41
+ storage;
42
+ tokens;
43
+ log;
44
+ constructor(db, files, liveness, storage, tokens, log) {
45
+ this.db = db;
46
+ this.files = files;
47
+ this.liveness = liveness;
48
+ this.storage = storage;
49
+ this.tokens = tokens;
50
+ this.log = log;
51
+ }
52
+ /**
53
+ * A document token for one version of the caller's conversation file (a delivered version or an
54
+ * upload). Not the owner → `conversation.not_found`; unknown file →
55
+ * `conversation.artifact_not_found`; an upload changed since finalize →
56
+ * `conversation.artifact_removed`; not HTML, or larger than `FILE_PREVIEW_MAX_BYTES` →
57
+ * `conversation.artifact_not_previewable`.
58
+ */
59
+ async mint(orgId, conversationId, accountId, fileId) {
60
+ const f = await this.files.file(orgId, conversationId, accountId, fileId);
61
+ if (!isHtmlType(f.name, f.contentType)) {
62
+ throw notPreviewable("Only HTML files render as documents; download this file instead");
63
+ }
64
+ if (f.size > FILE_PREVIEW_MAX_BYTES) {
65
+ throw notPreviewable("This HTML file is too large to render; download it instead");
66
+ }
67
+ const { token } = this.tokens.issue({
68
+ kind: "file",
69
+ orgId,
70
+ conversationId,
71
+ fileId: f.id,
72
+ accountId,
73
+ });
74
+ return { path: `/api/v1/html/${token}`, expiresIn: HTML_TOKEN_TTL_SECONDS };
75
+ }
76
+ /**
77
+ * Serves the document verified claims name with the spec §4 headers, the CSP built from the CDN
78
+ * allowlist read now. Any live check failing → 404 `not_found`.
79
+ */
80
+ async serve(claims, reply) {
81
+ const source = await this.resolve(claims);
82
+ if (source === null)
83
+ throw htmlNotFound();
84
+ // read before the object is opened, so no stream is held across this query
85
+ const allowlist = await readHtmlCdnAllowlist(this.db.db, this.log);
86
+ const got = await this.storage.kernel(source.orgId).get(source.objectKey);
87
+ if (!got)
88
+ throw htmlNotFound();
89
+ if (got.head.size > FILE_PREVIEW_MAX_BYTES ||
90
+ (source.recorded && !attachmentContentMatches(source.recorded, got.head))) {
91
+ await got.body.cancel().catch(() => { });
92
+ throw htmlNotFound();
93
+ }
94
+ await reply
95
+ .header("content-type", htmlContentType(source.contentType))
96
+ .header("content-length", String(got.head.size))
97
+ .header("content-security-policy", htmlDocumentCsp(allowlist))
98
+ .header("x-content-type-options", "nosniff")
99
+ .header("referrer-policy", "no-referrer")
100
+ .header("cache-control", "private, no-store")
101
+ .header("x-robots-tag", "noindex")
102
+ .send(Readable.fromWeb(got.body));
103
+ }
104
+ /** The object the claims name if their live checks pass now; null otherwise. */
105
+ async resolve(claims) {
106
+ if (claims.kind === "share") {
107
+ const s = await this.liveness.byId(claims.shareId, claims.generation);
108
+ if (s === null || !isHtmlType(s.name, s.contentType) || s.size > FILE_PREVIEW_MAX_BYTES) {
109
+ return null;
110
+ }
111
+ return { orgId: s.orgId, objectKey: s.objectKey, contentType: s.contentType };
112
+ }
113
+ let f;
114
+ try {
115
+ f = await this.files.file(claims.orgId, claims.conversationId, claims.accountId, claims.fileId);
116
+ }
117
+ catch (e) {
118
+ // the owner lost access, the file is unknown or the upload changed: all the same 404
119
+ if (e instanceof ApiError)
120
+ return null;
121
+ throw e;
122
+ }
123
+ if (!isHtmlType(f.name, f.contentType) || f.size > FILE_PREVIEW_MAX_BYTES)
124
+ return null;
125
+ return {
126
+ orgId: claims.orgId,
127
+ objectKey: f.objectKey,
128
+ contentType: f.contentType,
129
+ recorded: f.recorded,
130
+ };
131
+ }
132
+ };
133
+ HtmlDocumentService = __decorate([
134
+ Injectable(),
135
+ __param(0, Inject(KernelDb)),
136
+ __param(1, Inject(ConversationFiles)),
137
+ __param(2, Inject(ShareLiveness)),
138
+ __param(3, Inject(StorageService)),
139
+ __param(4, Inject(HtmlTokens)),
140
+ __param(5, Optional()),
141
+ __param(5, Inject(KERNEL_LOGGER))
142
+ ], HtmlDocumentService);
143
+ export { HtmlDocumentService };
@@ -0,0 +1,58 @@
1
+ import type { Keyring } from "../ctx/secrets.js";
2
+ /** HKDF purpose of the document key, also the domain prefix of the signed input. */
3
+ export declare const HTML_KEY_INFO = "capybara-html/1";
4
+ /** How long a document token loads its document (seconds). */
5
+ export declare const HTML_TOKEN_TTL_SECONDS = 300;
6
+ /** Clock skew between replicas tolerated when checking `exp` (seconds). */
7
+ export declare const HTML_TOKEN_SKEW_SECONDS = 30;
8
+ /**
9
+ * What a document token names (file sharing spec §4): one version of a conversation file for its
10
+ * owner (the right panel), or one generation of a share (the share page). Re-checked live on use.
11
+ */
12
+ export type HtmlClaims = {
13
+ kind: "file";
14
+ orgId: string;
15
+ conversationId: string;
16
+ fileId: string;
17
+ accountId: string;
18
+ exp: number;
19
+ } | {
20
+ kind: "share";
21
+ shareId: string;
22
+ generation: number;
23
+ exp: number;
24
+ };
25
+ /** Claims before issuing (the token's expiry is set by {@link HtmlTokens.issue}). */
26
+ export type HtmlClaimsInput = Omit<Extract<HtmlClaims, {
27
+ kind: "file";
28
+ }>, "exp"> | Omit<Extract<HtmlClaims, {
29
+ kind: "share";
30
+ }>, "exp">;
31
+ /** Optional provider: the clock {@link HtmlTokens} issues and checks with (default `Date.now`; tests). */
32
+ export declare const HTML_TOKEN_CLOCK: unique symbol;
33
+ /**
34
+ * HTML document tokens: `base64url(JSON claims).base64url(HMAC-SHA256(key, "capybara-html/1." +
35
+ * first part))`, the format and checks of `EmbedTokens` with its own key (HKDF info
36
+ * {@link HTML_KEY_INFO}: an embed token never verifies here, nor the reverse). No header (no alg to
37
+ * confuse); keys from the master keyring, so a token signed before a rotation verifies until it
38
+ * expires. Verifying: strict base64url, constant-time comparison over every candidate key, strict
39
+ * claim keys, `exp` with {@link HTML_TOKEN_SKEW_SECONDS} of skew and never further ahead than the
40
+ * TTL plus the skew; any failure is null, with no reason. Stateless: every replica verifies with
41
+ * the same master key.
42
+ */
43
+ export declare class HtmlTokens {
44
+ private readonly now;
45
+ private readonly current;
46
+ private readonly keys;
47
+ constructor(keyring: Keyring, now?: () => number);
48
+ /** Issues a token whose `exp` is now + {@link HTML_TOKEN_TTL_SECONDS}. */
49
+ issue(c: HtmlClaimsInput): {
50
+ token: string;
51
+ expiresAt: Date;
52
+ };
53
+ /** The claims of a valid, unexpired token this kernel issued; null otherwise. */
54
+ verify(token: unknown): HtmlClaims | null;
55
+ }
56
+ /** {@link HtmlTokens} on its own: the HTML document routes and the share routes import it. */
57
+ export declare class HtmlTokensModule {
58
+ }
@@ -0,0 +1,154 @@
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 { createHmac, timingSafeEqual } from "node:crypto";
11
+ import { Inject, Injectable, Module, Optional } from "@nestjs/common";
12
+ import { KEYRING } from "../infra/tokens.js";
13
+ /** HKDF purpose of the document key, also the domain prefix of the signed input. */
14
+ export const HTML_KEY_INFO = "capybara-html/1";
15
+ /** How long a document token loads its document (seconds). */
16
+ export const HTML_TOKEN_TTL_SECONDS = 300;
17
+ /** Clock skew between replicas tolerated when checking `exp` (seconds). */
18
+ export const HTML_TOKEN_SKEW_SECONDS = 30;
19
+ const TOKEN_MAX = 2048;
20
+ const MAC_LEN = 32;
21
+ const B64URL = /^[A-Za-z0-9_-]+$/;
22
+ const FILE_KEYS = ["kind", "orgId", "conversationId", "fileId", "accountId", "exp"];
23
+ const SHARE_KEYS = ["kind", "shareId", "generation", "exp"];
24
+ const isId = (v) => typeof v === "string" && v !== "" && v.length <= 100;
25
+ /** Strict base64url: the alphabet only, no padding, the canonical encoding of its bytes. */
26
+ function decodeStrict(s) {
27
+ if (!B64URL.test(s))
28
+ return null;
29
+ const buf = Buffer.from(s, "base64url");
30
+ return buf.toString("base64url") === s ? buf : null;
31
+ }
32
+ const sameKeys = (c, keys) => {
33
+ const own = Object.keys(c);
34
+ return own.length === keys.length && own.every((k) => keys.includes(k));
35
+ };
36
+ /** Exactly the keys of one kind, each of the right type; a new object with those keys only. */
37
+ function parseClaims(v) {
38
+ if (typeof v !== "object" || v === null || Array.isArray(v))
39
+ return null;
40
+ const c = v;
41
+ if (typeof c.exp !== "number" || !Number.isSafeInteger(c.exp))
42
+ return null;
43
+ if (c.kind === "file") {
44
+ if (!sameKeys(c, FILE_KEYS))
45
+ return null;
46
+ if (!isId(c.orgId) || !isId(c.conversationId) || !isId(c.fileId) || !isId(c.accountId)) {
47
+ return null;
48
+ }
49
+ return {
50
+ kind: "file",
51
+ orgId: c.orgId,
52
+ conversationId: c.conversationId,
53
+ fileId: c.fileId,
54
+ accountId: c.accountId,
55
+ exp: c.exp,
56
+ };
57
+ }
58
+ if (c.kind === "share") {
59
+ if (!sameKeys(c, SHARE_KEYS) || !isId(c.shareId))
60
+ return null;
61
+ if (typeof c.generation !== "number" || !Number.isSafeInteger(c.generation))
62
+ return null;
63
+ if (c.generation < 1)
64
+ return null;
65
+ return { kind: "share", shareId: c.shareId, generation: c.generation, exp: c.exp };
66
+ }
67
+ return null;
68
+ }
69
+ /** Optional provider: the clock {@link HtmlTokens} issues and checks with (default `Date.now`; tests). */
70
+ export const HTML_TOKEN_CLOCK = Symbol("HTML_TOKEN_CLOCK");
71
+ /**
72
+ * HTML document tokens: `base64url(JSON claims).base64url(HMAC-SHA256(key, "capybara-html/1." +
73
+ * first part))`, the format and checks of `EmbedTokens` with its own key (HKDF info
74
+ * {@link HTML_KEY_INFO}: an embed token never verifies here, nor the reverse). No header (no alg to
75
+ * confuse); keys from the master keyring, so a token signed before a rotation verifies until it
76
+ * expires. Verifying: strict base64url, constant-time comparison over every candidate key, strict
77
+ * claim keys, `exp` with {@link HTML_TOKEN_SKEW_SECONDS} of skew and never further ahead than the
78
+ * TTL plus the skew; any failure is null, with no reason. Stateless: every replica verifies with
79
+ * the same master key.
80
+ */
81
+ let HtmlTokens = class HtmlTokens {
82
+ now;
83
+ current;
84
+ keys;
85
+ constructor(keyring, now = Date.now) {
86
+ this.now = now;
87
+ const derived = keyring.deriveKey(HTML_KEY_INFO);
88
+ const ids = [derived.currentId, ...keyring.toJSON().previousIds];
89
+ this.current = derived.current;
90
+ this.keys = ids.map((id) => derived.byId(id)).filter((k) => k !== undefined);
91
+ }
92
+ /** Issues a token whose `exp` is now + {@link HTML_TOKEN_TTL_SECONDS}. */
93
+ issue(c) {
94
+ const exp = Math.floor(this.now() / 1000) + HTML_TOKEN_TTL_SECONDS;
95
+ const claims = parseClaims({ ...c, exp });
96
+ if (claims === null)
97
+ throw new Error("HTML token claims are invalid");
98
+ const payload = Buffer.from(JSON.stringify(claims), "utf8").toString("base64url");
99
+ const token = `${payload}.${mac(this.current, payload).toString("base64url")}`;
100
+ return { token, expiresAt: new Date(exp * 1000) };
101
+ }
102
+ /** The claims of a valid, unexpired token this kernel issued; null otherwise. */
103
+ verify(token) {
104
+ if (typeof token !== "string" || token.length > TOKEN_MAX)
105
+ return null;
106
+ const dot = token.indexOf(".");
107
+ if (dot <= 0 || dot !== token.lastIndexOf("."))
108
+ return null;
109
+ const payload = token.slice(0, dot);
110
+ const sig = decodeStrict(token.slice(dot + 1));
111
+ const body = decodeStrict(payload);
112
+ if (sig === null || body === null || sig.length !== MAC_LEN)
113
+ return null;
114
+ // every candidate key, compared in constant time (no early return on the first match)
115
+ let ok = false;
116
+ for (const key of this.keys)
117
+ ok = timingSafeEqual(mac(key, payload), sig) || ok;
118
+ if (!ok)
119
+ return null;
120
+ let parsed;
121
+ try {
122
+ parsed = JSON.parse(body.toString("utf8"));
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ const claims = parseClaims(parsed);
128
+ if (claims === null)
129
+ return null;
130
+ const nowSec = this.now() / 1000;
131
+ if (claims.exp + HTML_TOKEN_SKEW_SECONDS <= nowSec)
132
+ return null;
133
+ if (claims.exp > nowSec + HTML_TOKEN_TTL_SECONDS + HTML_TOKEN_SKEW_SECONDS)
134
+ return null;
135
+ return claims;
136
+ }
137
+ };
138
+ HtmlTokens = __decorate([
139
+ Injectable(),
140
+ __param(0, Inject(KEYRING)),
141
+ __param(1, Optional()),
142
+ __param(1, Inject(HTML_TOKEN_CLOCK))
143
+ ], HtmlTokens);
144
+ export { HtmlTokens };
145
+ function mac(key, payload) {
146
+ return createHmac("sha256", key).update(`${HTML_KEY_INFO}.${payload}`).digest();
147
+ }
148
+ /** {@link HtmlTokens} on its own: the HTML document routes and the share routes import it. */
149
+ let HtmlTokensModule = class HtmlTokensModule {
150
+ };
151
+ HtmlTokensModule = __decorate([
152
+ Module({ providers: [HtmlTokens], exports: [HtmlTokens] })
153
+ ], HtmlTokensModule);
154
+ export { HtmlTokensModule };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Which files are HTML documents, and the content type they are served with (file sharing spec
3
+ * §4, §5). The rule is the web's `isHtmlFile` (`apps/web/src/lib/files.ts`), so the panel and the
4
+ * kernel agree on what renders.
5
+ */
6
+ /** An HTML file: base type `text/html`, or a name ending in `.html` / `.htm` (any case). */
7
+ export declare function isHtmlType(name: string, contentType: string): boolean;
8
+ /**
9
+ * `text/html; charset=<charset>`: the stored type's `charset` parameter (lower case, quotes
10
+ * removed) when it is a valid token, else `utf-8`. The bytes are served as stored, so a file
11
+ * delivered as GBK keeps rendering as GBK.
12
+ */
13
+ export declare function htmlContentType(stored: string): string;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Which files are HTML documents, and the content type they are served with (file sharing spec
3
+ * §4, §5). The rule is the web's `isHtmlFile` (`apps/web/src/lib/files.ts`), so the panel and the
4
+ * kernel agree on what renders.
5
+ */
6
+ /** The content type without its parameters, lower case. */
7
+ const baseType = (contentType) => (contentType.split(";")[0] ?? "").trim().toLowerCase();
8
+ const ext = (name) => {
9
+ const i = name.lastIndexOf(".");
10
+ return i < 0 ? "" : name.slice(i + 1).toLowerCase();
11
+ };
12
+ /** An HTML file: base type `text/html`, or a name ending in `.html` / `.htm` (any case). */
13
+ export function isHtmlType(name, contentType) {
14
+ const e = ext(name);
15
+ return baseType(contentType) === "text/html" || e === "html" || e === "htm";
16
+ }
17
+ /** A charset name as a MIME token (IANA names: letters, digits and `-_.:+`), at most 40 chars. */
18
+ const CHARSET_RE = /^[a-z0-9][a-z0-9._:+-]{0,39}$/;
19
+ /**
20
+ * `text/html; charset=<charset>`: the stored type's `charset` parameter (lower case, quotes
21
+ * removed) when it is a valid token, else `utf-8`. The bytes are served as stored, so a file
22
+ * delivered as GBK keeps rendering as GBK.
23
+ */
24
+ export function htmlContentType(stored) {
25
+ let charset = "utf-8";
26
+ for (const param of stored.split(";").slice(1)) {
27
+ const eq = param.indexOf("=");
28
+ if (eq < 0 || param.slice(0, eq).trim().toLowerCase() !== "charset")
29
+ continue;
30
+ const value = param
31
+ .slice(eq + 1)
32
+ .trim()
33
+ .replace(/^"(.*)"$/, "$1")
34
+ .toLowerCase();
35
+ if (CHARSET_RE.test(value))
36
+ charset = value;
37
+ break;
38
+ }
39
+ return `text/html; charset=${charset}`;
40
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * HTML files rendered as sandboxed documents (file sharing spec §4): the document tokens
3
+ * (`HtmlTokens`) and the service that mints them and serves the document.
4
+ */
5
+ export declare class HtmlModule {
6
+ }
@@ -0,0 +1,26 @@
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
+ import { Module } from "@nestjs/common";
8
+ import { ConversationsModule } from "../conversations/conversations.module.js";
9
+ import { ShareLivenessModule } from "../shares/liveness.js";
10
+ import { StorageModule } from "../storage/storage.module.js";
11
+ import { HtmlDocumentService } from "./html-document.service.js";
12
+ import { HtmlTokensModule } from "./html-token.js";
13
+ /**
14
+ * HTML files rendered as sandboxed documents (file sharing spec §4): the document tokens
15
+ * (`HtmlTokens`) and the service that mints them and serves the document.
16
+ */
17
+ let HtmlModule = class HtmlModule {
18
+ };
19
+ HtmlModule = __decorate([
20
+ Module({
21
+ imports: [ConversationsModule, ShareLivenessModule, StorageModule, HtmlTokensModule],
22
+ providers: [HtmlDocumentService],
23
+ exports: [HtmlDocumentService, HtmlTokensModule],
24
+ })
25
+ ], HtmlModule);
26
+ export { HtmlModule };
@@ -52,6 +52,8 @@ import { ExtensionPointDefaultsController } from "../extensions/point-defaults.c
52
52
  import { FilesModule } from "../files/files.module.js";
53
53
  import { FilePreviewersController } from "../files/previewers.controller.js";
54
54
  import { GitModule } from "../git/git.module.js";
55
+ import { HtmlModule } from "../html/html.module.js";
56
+ import { HtmlDocumentController } from "../html/html-document.controller.js";
55
57
  import { AuthController } from "../identity/auth.controller.js";
56
58
  import { AuthGuard } from "../identity/auth.guard.js";
57
59
  import { IdentityModule } from "../identity/identity.module.js";
@@ -77,6 +79,10 @@ import { SchedulesModule } from "../schedules/schedules.module.js";
77
79
  import { SetupModule } from "../setup/setup.module.js";
78
80
  import { SetupChecksController } from "../setup/setup-checks.controller.js";
79
81
  import { SetupGuidesController } from "../setup/setup-guides.controller.js";
82
+ import { ShareOpenController } from "../shares/share-open.controller.js";
83
+ import { SharePreviewsController } from "../shares/share-previews.controller.js";
84
+ import { SharesController } from "../shares/shares.controller.js";
85
+ import { SharesModule } from "../shares/shares.module.js";
80
86
  import { AgentSkillsController } from "../skills/agent-skills.controller.js";
81
87
  import { InboxController, SkillChangesController } from "../skills/changes.controller.js";
82
88
  import { InvocableSkillsController } from "../skills/invocable.controller.js";
@@ -159,6 +165,10 @@ const CONTROLLERS = [
159
165
  AdminUiController,
160
166
  SlotsController,
161
167
  FilePreviewersController,
168
+ SharesController,
169
+ ShareOpenController,
170
+ SharePreviewsController,
171
+ HtmlDocumentController,
162
172
  ExtensionPointDefaultsController,
163
173
  TrajectoryController,
164
174
  EvalSetsController,
@@ -219,6 +229,10 @@ ApiModule = __decorate([
219
229
  SchedulesModule,
220
230
  // the git gateway (run tickets; the gateway route comes with it)
221
231
  GitModule,
232
+ // file sharing (shares of conversation files)
233
+ SharesModule,
234
+ // HTML files rendered as sandboxed documents (the document token and route)
235
+ HtmlModule,
222
236
  ],
223
237
  controllers: CONTROLLERS,
224
238
  providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
@@ -6,6 +6,8 @@ export declare function codeForStatus(status: number): ErrorCode;
6
6
  /**
7
7
  * 记日志用的请求路径:去掉查询串,公开邀请路由 `/api/v1/invitations/<token>` 的令牌段换成 `:token`,
8
8
  * 其他任何以 `cap_` 开头的路径段(内核各类令牌的前缀)换成 `:redacted`,令牌不落日志。
9
+ * The HTML document route `/api/v1/html/<token>` becomes `/api/v1/html/:token` too, and a share
10
+ * link's code (a bearer secret: `/api/v1/s/<code>…`, the web's `/s/<code>`) becomes `:code`.
9
11
  */
10
12
  export declare function redactPath(url: string): string;
11
13
  /**
@@ -32,12 +32,19 @@ export function codeForStatus(status) {
32
32
  /**
33
33
  * 记日志用的请求路径:去掉查询串,公开邀请路由 `/api/v1/invitations/<token>` 的令牌段换成 `:token`,
34
34
  * 其他任何以 `cap_` 开头的路径段(内核各类令牌的前缀)换成 `:redacted`,令牌不落日志。
35
+ * The HTML document route `/api/v1/html/<token>` becomes `/api/v1/html/:token` too, and a share
36
+ * link's code (a bearer secret: `/api/v1/s/<code>…`, the web's `/s/<code>`) becomes `:code`.
35
37
  */
36
38
  export function redactPath(url) {
37
39
  const path = url.split("?")[0] ?? "";
38
- return path
40
+ return (path
39
41
  .replace(/^\/api\/v1\/invitations\/[^/]+/, "/api/v1/invitations/:token")
40
- .replace(/\/cap_[^/]*/g, "/:redacted");
42
+ // the HTML document token (file sharing spec §4) loads a document while it lives
43
+ .replace(/^\/api\/v1\/html\/.+/, "/api/v1/html/:token")
44
+ // a share link's code (file sharing spec §3) opens the share while it is live
45
+ .replace(/^\/api\/v1\/s\/[^/]+/, "/api/v1/s/:code")
46
+ .replace(/^\/s\/[^/]+/, "/s/:code")
47
+ .replace(/\/cap_[^/]*/g, "/:redacted"));
41
48
  }
42
49
  /**
43
50
  * 全局错误过滤器:一切异常都转成错误信封 `{ error: { code, message, details? } }`。
@@ -24,7 +24,8 @@ export declare function orgRouteMember(db: KernelSchemaDb, plugin: string, orgId
24
24
  * with `retry-after`.
25
25
  * - `embed`: an embed token of this extension as `Authorization: Bearer` (not a `cap_` kernel
26
26
  * token) or `?token=`, verified by the route's own `verifyEmbed` (signature, TTL, scope, live
27
- * membership, slot role, extension enabled); missing or invalid -> 401 `auth.required`. An org
27
+ * membership, slot role, extension enabled; a share token: a `file.preview` contribution of a
28
+ * live share at its generation); missing or invalid -> 401 `auth.required`. An org or share
28
29
  * token also needs a valid effective config (409 `extension.needs_config`; 503
29
30
  * `extension.unavailable` when the extension is not running on this replica).
30
31
  * - `member` / `admin`: a personal API token only (`authenticatePersonalToken`; a cookie is no
@@ -47,7 +47,8 @@ const authRequired = () => new ApiError("auth.required", "Authentication require
47
47
  * with `retry-after`.
48
48
  * - `embed`: an embed token of this extension as `Authorization: Bearer` (not a `cap_` kernel
49
49
  * token) or `?token=`, verified by the route's own `verifyEmbed` (signature, TTL, scope, live
50
- * membership, slot role, extension enabled); missing or invalid -> 401 `auth.required`. An org
50
+ * membership, slot role, extension enabled; a share token: a `file.preview` contribution of a
51
+ * live share at its generation); missing or invalid -> 401 `auth.required`. An org or share
51
52
  * token also needs a valid effective config (409 `extension.needs_config`; 503
52
53
  * `extension.unavailable` when the extension is not running on this replica).
53
54
  * - `member` / `admin`: a personal API token only (`authenticatePersonalToken`; a cookie is no
@@ -110,6 +111,20 @@ let PluginRouteAccess = class PluginRouteAccess {
110
111
  exp: claims.exp,
111
112
  };
112
113
  }
114
+ if (claims.scope === "share") {
115
+ // verifyEmbed held: a `file.preview` contribution of a live share whose org has the extension
116
+ // on; the handler sees an org call for the share's org with no account or role
117
+ const config = await this.config(claims.orgId, route.plugin);
118
+ return {
119
+ access: "embed",
120
+ scope: "share",
121
+ orgId: claims.orgId,
122
+ shareId: claims.shareId,
123
+ contribution: claims.contribution,
124
+ exp: claims.exp,
125
+ config,
126
+ };
127
+ }
113
128
  const config = await this.config(claims.orgId, route.plugin);
114
129
  return {
115
130
  access: "embed",
@@ -7,6 +7,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
7
7
  import type { KernelLogger } from "../log.js";
8
8
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
9
9
  import { type DevicesAutoModeView, type DevicesFullAccessPatch, type DevicesFullAccessStored, type DevicesFullAccessView } from "../sandbox/platform-full-access.js";
10
+ import { type ExternalSharingView, type ShareMaxExpiryView } from "../shares/settings.js";
10
11
  import { type UiArrangement } from "../ui/arrangement.js";
11
12
  import { SuperAdminLock } from "./super-admin.js";
12
13
  /** 沙箱 cpu(核)与内存(MB)覆盖的范围(C19)。 */
@@ -158,6 +159,7 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
158
159
  reserveTokens: z.ZodDefault<z.ZodNumber>;
159
160
  maxOutputTokens: z.ZodDefault<z.ZodNumber>;
160
161
  }, z.core.$strip>>;
162
+ htmlRenderCdnAllowlist: z.ZodDefault<z.ZodArray<z.ZodType<string, unknown, z.core.$ZodTypeInternals<string, unknown>>>>;
161
163
  }, z.core.$strip>;
162
164
  export type DeploymentSettings = z.infer<typeof DEPLOYMENT_SETTINGS>;
163
165
  /**
@@ -171,6 +173,10 @@ export type DeploymentSettingsView = DeploymentSettings & {
171
173
  /** The same switch under its old public name, until the old public readers are removed. */
172
174
  devicesAutoMode: DevicesAutoModeView;
173
175
  attribution: PlatformAttributionView;
176
+ /** The platform's external sharing switch in effect and where it comes from. */
177
+ externalSharing: ExternalSharingView;
178
+ /** The longest expiry a share may take, in days, and where it comes from. */
179
+ shareMaxExpiryDays: ShareMaxExpiryView;
174
180
  };
175
181
  /**
176
182
  * 设置的修改(PUT /api/v1/admin/settings 的 body):只改给出的键。
@@ -238,6 +244,12 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
238
244
  reserveTokens: z.ZodOptional<z.ZodNumber>;
239
245
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
240
246
  }, z.core.$strict>>;
247
+ externalSharing: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
248
+ allow: "allow";
249
+ deny: "deny";
250
+ }>>>;
251
+ shareMaxExpiryDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
252
+ htmlRenderCdnAllowlist: z.ZodOptional<z.ZodArray<z.ZodType<string, unknown, z.core.$ZodTypeInternals<string, unknown>>>>;
241
253
  }, z.core.$strict>;
242
254
  export type DeploymentSettingsPatch = z.infer<typeof DEPLOYMENT_SETTINGS_PATCH>;
243
255
  /**
@@ -321,6 +333,17 @@ export declare class SettingsService {
321
333
  next: DevicesFullAccessStored;
322
334
  before: DevicesFullAccessView;
323
335
  }>;
336
+ /**
337
+ * The refusals of an `externalSharing` / `shareMaxExpiryDays` / `htmlRenderCdnAllowlist` change:
338
+ * a field set in the startup config (`deployment.setting_readonly`) and, with `onlyNarrows` (an
339
+ * API token, the Platform tool), any widening: allowing external sharing where it is denied
340
+ * (`deployment.external_sharing_not_allowed`; clearing it goes back to deny, a narrowing), an
341
+ * expiry maximum above the effective one (null counts as the default, 30) or an allowlist origin
342
+ * the effective list does not hold (`deployment.sharing_widen_not_allowed`). Only a person widens.
343
+ */
344
+ checkSharing(patch: Pick<DeploymentSettingsPatch, "externalSharing" | "shareMaxExpiryDays" | "htmlRenderCdnAllowlist">, opts?: {
345
+ onlyNarrows?: boolean;
346
+ }): Promise<void>;
324
347
  /**
325
348
  * The refusals of an `attribution` change against the stored choice: a field set in the startup
326
349
  * config (`deployment.setting_readonly`). Returns the next stored choice.
@@ -335,7 +358,9 @@ export declare class SettingsService {
335
358
  get(): Promise<DeploymentSettings>;
336
359
  /**
337
360
  * Updates settings under the super admin lock, re-checking the actor (else `forbidden`).
338
- * `onlyNarrows` (an API token, the Platform tool): `devicesFullAccess` may only turn Full off.
361
+ * `onlyNarrows` (an API token, the Platform tool): `devicesFullAccess` may only turn Full off,
362
+ * `externalSharing` may only turn external sharing off, `shareMaxExpiryDays` may only decrease and
363
+ * `htmlRenderCdnAllowlist` may only shrink.
339
364
  */
340
365
  update(patch: DeploymentSettingsPatch, actorAccountId: string, actorTokenId?: string,
341
366
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */