@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.
- package/bootstrap.json +11 -11
- package/dist/admin/admin.schemas.d.ts +6 -0
- package/dist/agents/agent-lookup.d.ts +5 -2
- package/dist/agents/agent-lookup.js +3 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +7 -0
- package/dist/config/schema.js +27 -0
- package/dist/conversations/access.d.ts +14 -5
- package/dist/conversations/access.js +29 -20
- package/dist/conversations/conversations.service.d.ts +6 -1
- package/dist/conversations/conversations.service.js +12 -2
- package/dist/conversations/files.d.ts +43 -0
- package/dist/conversations/files.js +80 -3
- package/dist/ctx/create-ctx.d.ts +7 -0
- package/dist/ctx/create-ctx.js +9 -2
- package/dist/db/kernel-schema.d.ts +30 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +22 -0
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +15 -10
- package/dist/files/previewers.d.ts +44 -0
- package/dist/files/previewers.js +84 -30
- package/dist/html/csp.d.ts +13 -0
- package/dist/html/csp.js +33 -0
- package/dist/html/html-document.controller.d.ts +31 -0
- package/dist/html/html-document.controller.js +75 -0
- package/dist/html/html-document.service.d.ts +49 -0
- package/dist/html/html-document.service.js +143 -0
- package/dist/html/html-token.d.ts +58 -0
- package/dist/html/html-token.js +154 -0
- package/dist/html/html-type.d.ts +13 -0
- package/dist/html/html-type.js +40 -0
- package/dist/html/html.module.d.ts +6 -0
- package/dist/html/html.module.js +26 -0
- package/dist/http/api.module.js +14 -0
- package/dist/http/error.filter.d.ts +2 -0
- package/dist/http/error.filter.js +9 -2
- package/dist/http/plugin-route-access.d.ts +2 -1
- package/dist/http/plugin-route-access.js +16 -1
- package/dist/identity/settings.d.ts +26 -1
- package/dist/identity/settings.js +88 -2
- package/dist/infra/config/kernel-config.service.js +3 -0
- package/dist/infra/outbox/registry.d.ts +13 -0
- package/dist/infra/outbox/registry.js +8 -0
- package/dist/infra/throttler/credential-throttler.d.ts +4 -1
- package/dist/infra/throttler/credential-throttler.js +5 -2
- package/dist/infra/throttler/named-throttlers.d.ts +1 -0
- package/dist/infra/throttler/named-throttlers.js +14 -0
- package/dist/orgs/offboarding.d.ts +3 -1
- package/dist/orgs/offboarding.js +7 -1
- package/dist/orgs/settings.service.d.ts +21 -4
- package/dist/orgs/settings.service.js +47 -7
- package/dist/overrides.d.ts +3 -0
- package/dist/overrides.js +2 -0
- package/dist/platform/exclusions.js +63 -0
- package/dist/platform/operation.js +1 -1
- package/dist/platform/ops/admin.ops.js +18 -3
- package/dist/platform/ops/org-settings.ops.js +6 -2
- package/dist/platform/ops/orgs.ops.js +3 -0
- package/dist/platform/ops/shares.ops.d.ts +16 -0
- package/dist/platform/ops/shares.ops.js +107 -0
- package/dist/platform/platform-ops.module.d.ts +2 -1
- package/dist/platform/platform-ops.module.js +5 -0
- package/dist/platform/route-schemas.js +3 -0
- package/dist/roles/worker.module.js +6 -0
- package/dist/runtime/maintenance.d.ts +4 -2
- package/dist/runtime/maintenance.js +14 -4
- package/dist/shares/liveness.d.ts +59 -0
- package/dist/shares/liveness.js +163 -0
- package/dist/shares/revoke.d.ts +26 -0
- package/dist/shares/revoke.js +43 -0
- package/dist/shares/settings.d.ts +76 -0
- package/dist/shares/settings.js +117 -0
- package/dist/shares/share-code.d.ts +4 -0
- package/dist/shares/share-code.js +28 -0
- package/dist/shares/share-objects.d.ts +52 -0
- package/dist/shares/share-objects.js +123 -0
- package/dist/shares/share-open.controller.d.ts +35 -0
- package/dist/shares/share-open.controller.js +107 -0
- package/dist/shares/share-open.service.d.ts +107 -0
- package/dist/shares/share-open.service.js +287 -0
- package/dist/shares/share-previews.controller.d.ts +50 -0
- package/dist/shares/share-previews.controller.js +115 -0
- package/dist/shares/shares.controller.d.ts +34 -0
- package/dist/shares/shares.controller.js +114 -0
- package/dist/shares/shares.module.d.ts +8 -0
- package/dist/shares/shares.module.js +41 -0
- package/dist/shares/shares.schemas.d.ts +31 -0
- package/dist/shares/shares.schemas.js +25 -0
- package/dist/shares/shares.service.d.ts +182 -0
- package/dist/shares/shares.service.js +553 -0
- package/dist/shares/sweep.job.d.ts +72 -0
- package/dist/shares/sweep.job.js +330 -0
- package/dist/tools/builtins/sandbox/deliver.js +3 -1
- package/dist/ui/embed-token.d.ts +2 -2
- package/dist/ui/embed-token.js +38 -2
- package/dist/ui/views.d.ts +6 -0
- package/dist/ui/views.js +17 -0
- package/package.json +4 -4
- package/src/migrations/0161_file_shares.sql +35 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { type ShareMeta, ShareOpenService } from "./share-open.service.js";
|
|
4
|
+
/** `GET /api/v1/s/:code/content`: `download=1` adds `content-disposition: attachment`. */
|
|
5
|
+
export declare const ShareContentQuery: z.ZodObject<{
|
|
6
|
+
download: z.ZodOptional<z.ZodEnum<{
|
|
7
|
+
0: "0";
|
|
8
|
+
1: "1";
|
|
9
|
+
}>>;
|
|
10
|
+
}, z.core.$strip>;
|
|
11
|
+
/** `GET /api/v1/s/:code/text`: at most this many bytes (≤ 1 MiB, the panel's text route). */
|
|
12
|
+
export declare const ShareTextQuery: z.ZodObject<{
|
|
13
|
+
limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
/**
|
|
16
|
+
* The public share link routes (file sharing spec §3), all `@Public()` under `/api/v1/s/:code`:
|
|
17
|
+
* metadata, the snapshot's bytes, its text, a bitmap inline, and the redirect to its HTML
|
|
18
|
+
* document. The code is not validated by a pipe: a malformed code is a miss like an unknown one
|
|
19
|
+
* (counted by the `share-open` throttler, 404 `share.not_found`). Every check is
|
|
20
|
+
* {@link ShareOpenService.open}'s.
|
|
21
|
+
*/
|
|
22
|
+
export declare class ShareOpenController {
|
|
23
|
+
private readonly shares;
|
|
24
|
+
constructor(shares: ShareOpenService);
|
|
25
|
+
/** The share's metadata; the open is audited (`share.opened`). */
|
|
26
|
+
meta(code: string, req: FastifyRequest, reply: FastifyReply): Promise<ShareMeta>;
|
|
27
|
+
/** The snapshot's bytes, always `application/octet-stream` under the sandbox CSP. */
|
|
28
|
+
content(code: string, q: z.infer<typeof ShareContentQuery>, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
29
|
+
/** The first bytes of a text snapshot as `text/plain; charset=utf-8`. */
|
|
30
|
+
text(code: string, q: z.infer<typeof ShareTextQuery>, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
31
|
+
/** A bitmap snapshot with its own type (png, jpeg, gif, webp); any other type → 404. */
|
|
32
|
+
inline(code: string, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
33
|
+
/** 302 to the HTML document with a fresh share token (`cache-control: no-store`). */
|
|
34
|
+
html(code: string, req: FastifyRequest, reply: FastifyReply): Promise<void>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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, Inject, Param, Req, Res } from "@nestjs/common";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { FILE_CONTENT_MAX_BYTES } from "../conversations/files.js";
|
|
13
|
+
import { Public } from "../identity/principal.js";
|
|
14
|
+
import { createZodDto } from "../infra/validation/create-zod-dto.js";
|
|
15
|
+
import { ZQuery } from "../infra/validation/zod-params.js";
|
|
16
|
+
import { ShareOpenService } from "./share-open.service.js";
|
|
17
|
+
/** `GET /api/v1/s/:code/content`: `download=1` adds `content-disposition: attachment`. */
|
|
18
|
+
export const ShareContentQuery = z.object({ download: z.enum(["0", "1"]).optional() });
|
|
19
|
+
/** `GET /api/v1/s/:code/text`: at most this many bytes (≤ 1 MiB, the panel's text route). */
|
|
20
|
+
export const ShareTextQuery = z.object({
|
|
21
|
+
limit: z.coerce.number().int().min(1).max(FILE_CONTENT_MAX_BYTES).default(FILE_CONTENT_MAX_BYTES),
|
|
22
|
+
});
|
|
23
|
+
class ShareContentQueryDto extends createZodDto(ShareContentQuery, "ShareContentQuery") {
|
|
24
|
+
}
|
|
25
|
+
class ShareTextQueryDto extends createZodDto(ShareTextQuery, "ShareTextQuery") {
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The public share link routes (file sharing spec §3), all `@Public()` under `/api/v1/s/:code`:
|
|
29
|
+
* metadata, the snapshot's bytes, its text, a bitmap inline, and the redirect to its HTML
|
|
30
|
+
* document. The code is not validated by a pipe: a malformed code is a miss like an unknown one
|
|
31
|
+
* (counted by the `share-open` throttler, 404 `share.not_found`). Every check is
|
|
32
|
+
* {@link ShareOpenService.open}'s.
|
|
33
|
+
*/
|
|
34
|
+
let ShareOpenController = class ShareOpenController {
|
|
35
|
+
shares;
|
|
36
|
+
constructor(shares) {
|
|
37
|
+
this.shares = shares;
|
|
38
|
+
}
|
|
39
|
+
/** The share's metadata; the open is audited (`share.opened`). */
|
|
40
|
+
async meta(code, req, reply) {
|
|
41
|
+
const opened = await this.shares.open(code, req, reply);
|
|
42
|
+
return this.shares.meta(opened, req.ip);
|
|
43
|
+
}
|
|
44
|
+
/** The snapshot's bytes, always `application/octet-stream` under the sandbox CSP. */
|
|
45
|
+
async content(code, q, req, reply) {
|
|
46
|
+
const { share } = await this.shares.open(code, req, reply);
|
|
47
|
+
await this.shares.content(share, q.download === "1", reply);
|
|
48
|
+
}
|
|
49
|
+
/** The first bytes of a text snapshot as `text/plain; charset=utf-8`. */
|
|
50
|
+
async text(code, q, req, reply) {
|
|
51
|
+
const { share } = await this.shares.open(code, req, reply);
|
|
52
|
+
await this.shares.text(share, q.limit, reply);
|
|
53
|
+
}
|
|
54
|
+
/** A bitmap snapshot with its own type (png, jpeg, gif, webp); any other type → 404. */
|
|
55
|
+
async inline(code, req, reply) {
|
|
56
|
+
const { share } = await this.shares.open(code, req, reply);
|
|
57
|
+
await this.shares.inline(share, reply);
|
|
58
|
+
}
|
|
59
|
+
/** 302 to the HTML document with a fresh share token (`cache-control: no-store`). */
|
|
60
|
+
async html(code, req, reply) {
|
|
61
|
+
const { share } = await this.shares.open(code, req, reply);
|
|
62
|
+
const { path } = this.shares.htmlPath(share);
|
|
63
|
+
await reply.header("cache-control", "no-store").redirect(path, 302);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
__decorate([
|
|
67
|
+
Public(),
|
|
68
|
+
Get(),
|
|
69
|
+
__param(0, Param("code")),
|
|
70
|
+
__param(1, Req()),
|
|
71
|
+
__param(2, Res({ passthrough: true }))
|
|
72
|
+
], ShareOpenController.prototype, "meta", null);
|
|
73
|
+
__decorate([
|
|
74
|
+
Public(),
|
|
75
|
+
Get("content"),
|
|
76
|
+
__param(0, Param("code")),
|
|
77
|
+
__param(1, ZQuery(ShareContentQueryDto)),
|
|
78
|
+
__param(2, Req()),
|
|
79
|
+
__param(3, Res())
|
|
80
|
+
], ShareOpenController.prototype, "content", null);
|
|
81
|
+
__decorate([
|
|
82
|
+
Public(),
|
|
83
|
+
Get("text"),
|
|
84
|
+
__param(0, Param("code")),
|
|
85
|
+
__param(1, ZQuery(ShareTextQueryDto)),
|
|
86
|
+
__param(2, Req()),
|
|
87
|
+
__param(3, Res())
|
|
88
|
+
], ShareOpenController.prototype, "text", null);
|
|
89
|
+
__decorate([
|
|
90
|
+
Public(),
|
|
91
|
+
Get("inline"),
|
|
92
|
+
__param(0, Param("code")),
|
|
93
|
+
__param(1, Req()),
|
|
94
|
+
__param(2, Res())
|
|
95
|
+
], ShareOpenController.prototype, "inline", null);
|
|
96
|
+
__decorate([
|
|
97
|
+
Public(),
|
|
98
|
+
Get("html"),
|
|
99
|
+
__param(0, Param("code")),
|
|
100
|
+
__param(1, Req()),
|
|
101
|
+
__param(2, Res())
|
|
102
|
+
], ShareOpenController.prototype, "html", null);
|
|
103
|
+
ShareOpenController = __decorate([
|
|
104
|
+
Controller("api/v1/s/:code"),
|
|
105
|
+
__param(0, Inject(ShareOpenService))
|
|
106
|
+
], ShareOpenController);
|
|
107
|
+
export { ShareOpenController };
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import { type FileOutput } from "../conversations/files.js";
|
|
3
|
+
import { ApiError } from "../errors.js";
|
|
4
|
+
import { type PreviewerItem, PreviewerRegistry } from "../files/previewers.js";
|
|
5
|
+
import { HtmlTokens } from "../html/html-token.js";
|
|
6
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
7
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
8
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
9
|
+
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
10
|
+
import { StorageService } from "../storage/storage.service.js";
|
|
11
|
+
import { type LiveShare, ShareLiveness } from "./liveness.js";
|
|
12
|
+
/** What `GET /api/v1/s/:code` answers (the web's `ShareMeta`). */
|
|
13
|
+
export interface ShareMeta {
|
|
14
|
+
name: string;
|
|
15
|
+
contentType: string;
|
|
16
|
+
size: number;
|
|
17
|
+
/** The creator's display name. */
|
|
18
|
+
sharedBy: string;
|
|
19
|
+
expiresAt: Date | null;
|
|
20
|
+
audience: "internal" | "external";
|
|
21
|
+
/** The built-in kind the share's text / inline routes serve (the conversation files list's rule). */
|
|
22
|
+
previewable: FileOutput["previewable"];
|
|
23
|
+
/** `html`: the HTML document; `previewers`: an extension previewer or a web built-in; `download`. */
|
|
24
|
+
render: "html" | "previewers" | "download";
|
|
25
|
+
/** The extension previewers that take the snapshot, in the org's order. */
|
|
26
|
+
previewers: PreviewerItem[];
|
|
27
|
+
}
|
|
28
|
+
/** An opened share and who opened it (the account of a member's web session, else none). */
|
|
29
|
+
export interface OpenedShare {
|
|
30
|
+
share: LiveShare;
|
|
31
|
+
viewerAccountId: string | null;
|
|
32
|
+
}
|
|
33
|
+
/** How long one viewer's open of one share is audited once (ms). */
|
|
34
|
+
export declare const SHARE_OPENED_DEDUPE_MS = 600000;
|
|
35
|
+
/** Every refusal of a share route: unknown, revoked, expired, not live, not a member. */
|
|
36
|
+
export declare const shareNotFound: () => ApiError;
|
|
37
|
+
/** The headers every public share response carries (errors too: set before the lookup). */
|
|
38
|
+
export declare function publicShareHeaders(reply: FastifyReply): void;
|
|
39
|
+
/**
|
|
40
|
+
* `content-disposition: attachment` with an ASCII fallback (`"` `\` and anything outside printable
|
|
41
|
+
* ASCII become `_`) and the exact name as RFC 5987 `filename*` (UTF-8, percent-encoded).
|
|
42
|
+
*/
|
|
43
|
+
export declare function attachmentDisposition(name: string): string;
|
|
44
|
+
/**
|
|
45
|
+
* The public share routes (file sharing spec §3). Each route reserves one `share-open` attempt for
|
|
46
|
+
* the client address before the lookup ({@link open}) and gives it back only after a live hit the
|
|
47
|
+
* viewer may open, so unknown, malformed, revoked, expired and refused codes are counted and codes
|
|
48
|
+
* cannot be enumerated. Every refusal of a code is one answer, 404 `share.not_found`; an internal
|
|
49
|
+
* share needs a web session of an active member of the share's own org (not the session's current
|
|
50
|
+
* org): without one 401 `share.sign_in_required`, a signed-in non-member 404. `ShareLiveness`
|
|
51
|
+
* checks the share and its creator; this service checks the viewer. The bytes are always streamed
|
|
52
|
+
* by the kernel from the snapshot, never a presigned URL; nothing lives in process memory (the
|
|
53
|
+
* throttler and the open dedupe are Redis keys with a TTL).
|
|
54
|
+
*/
|
|
55
|
+
export declare class ShareOpenService {
|
|
56
|
+
private readonly db;
|
|
57
|
+
readonly txHost: TransactionHost;
|
|
58
|
+
private readonly liveness;
|
|
59
|
+
private readonly storage;
|
|
60
|
+
private readonly tokens;
|
|
61
|
+
private readonly locks;
|
|
62
|
+
private readonly previewers;
|
|
63
|
+
private readonly throttler;
|
|
64
|
+
constructor(db: KernelDb, txHost: TransactionHost, liveness: Pick<ShareLiveness, "byCode">, storage: Pick<StorageService, "kernel">, tokens: Pick<HtmlTokens, "issue">, locks: Pick<LockService, "lease" | "releaseIf">, previewers: Pick<PreviewerRegistry, "forShare">, throttler: Pick<CredentialThrottler, "reserve" | "succeeded">);
|
|
65
|
+
/**
|
|
66
|
+
* The live share with this code that the request may open, after reserving a `share-open`
|
|
67
|
+
* attempt; the attempt is refunded only when it is returned. See the class comment.
|
|
68
|
+
*/
|
|
69
|
+
open(code: string, req: FastifyRequest, reply: FastifyReply): Promise<OpenedShare>;
|
|
70
|
+
/** The metadata of an opened share; audits the open at most once per viewer per 10 minutes. */
|
|
71
|
+
meta(opened: OpenedShare, ip: string): Promise<ShareMeta>;
|
|
72
|
+
/**
|
|
73
|
+
* The extension previewers that take a share's snapshot, in the org's order: the same rule as
|
|
74
|
+
* the right panel (enabled in the org, not disabled, a valid effective config; spec §7).
|
|
75
|
+
*/
|
|
76
|
+
previewersFor(share: LiveShare): Promise<PreviewerItem[]>;
|
|
77
|
+
/** Streams the snapshot as `application/octet-stream` (spec §3); `download` adds the attachment name. */
|
|
78
|
+
content(share: LiveShare, download: boolean, reply: FastifyReply): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* The first `limit` bytes (≤ 1 MiB) of a text snapshot as `text/plain; charset=utf-8`, as the
|
|
81
|
+
* panel's text route: not text, or NUL bytes in what was read → 400
|
|
82
|
+
* `conversation.artifact_not_previewable`; a cut never splits a UTF-8 character.
|
|
83
|
+
*/
|
|
84
|
+
text(share: LiveShare, limit: number, reply: FastifyReply): Promise<void>;
|
|
85
|
+
/** Streams a bitmap snapshot (png, jpeg, gif, webp) with its type; any other type → 404. */
|
|
86
|
+
inline(share: LiveShare, reply: FastifyReply): Promise<void>;
|
|
87
|
+
/**
|
|
88
|
+
* The HTML document path of an opened share (`/api/v1/html/<token>`, a fresh share token naming
|
|
89
|
+
* its generation). Not HTML, or larger than `FILE_PREVIEW_MAX_BYTES` → 400
|
|
90
|
+
* `conversation.artifact_not_previewable`.
|
|
91
|
+
*/
|
|
92
|
+
htmlPath(share: LiveShare): {
|
|
93
|
+
path: string;
|
|
94
|
+
expiresIn: number;
|
|
95
|
+
};
|
|
96
|
+
/** An active account with a membership in a live org. */
|
|
97
|
+
private isMember;
|
|
98
|
+
/**
|
|
99
|
+
* `share.opened` at most once per share and viewer (the session's account, else the client
|
|
100
|
+
* address hashed) per {@link SHARE_OPENED_DEDUPE_MS}: the first open sets a Redis marker with
|
|
101
|
+
* that TTL (outside any transaction), then writes the audit and `last_opened_at`; when that write
|
|
102
|
+
* fails the marker is deleted, so the next open audits again.
|
|
103
|
+
*/
|
|
104
|
+
private recordOpenOnce;
|
|
105
|
+
/** The audit of one open (the account for an internal share, none for an external one). */
|
|
106
|
+
recordOpen(opened: OpenedShare): Promise<void>;
|
|
107
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { Readable } from "node:stream";
|
|
12
|
+
import { FILE_PREVIEW_MAX_BYTES } from "@capybara-hq/plugin-sdk";
|
|
13
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
14
|
+
import { sql } from "kysely";
|
|
15
|
+
import { isInlineArtifactType, isTextArtifactType } from "../conversations/artifacts.js";
|
|
16
|
+
import { FILE_CONTENT_MAX_BYTES, previewKind, readPrefix, trimUtf8, } from "../conversations/files.js";
|
|
17
|
+
import { ApiError } from "../errors.js";
|
|
18
|
+
import { PreviewerRegistry } from "../files/previewers.js";
|
|
19
|
+
import { HTML_TOKEN_TTL_SECONDS, HtmlTokens } from "../html/html-token.js";
|
|
20
|
+
import { isHtmlType } from "../html/html-type.js";
|
|
21
|
+
import { audit } from "../identity/audit.js";
|
|
22
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
23
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
24
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
25
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
26
|
+
import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
|
|
27
|
+
import { StorageService } from "../storage/storage.service.js";
|
|
28
|
+
import { ShareLiveness } from "./liveness.js";
|
|
29
|
+
/** The share-open throttler (`NAMED_THROTTLERS`): per client address, misses count. */
|
|
30
|
+
const THROTTLER = ["share-open"];
|
|
31
|
+
/** How long one viewer's open of one share is audited once (ms). */
|
|
32
|
+
export const SHARE_OPENED_DEDUPE_MS = 600_000;
|
|
33
|
+
/** Every refusal of a share route: unknown, revoked, expired, not live, not a member. */
|
|
34
|
+
export const shareNotFound = () => new ApiError("share.not_found", "This link is invalid or has expired");
|
|
35
|
+
const signInRequired = () => new ApiError("share.sign_in_required", "Sign in as a member of this organization to open this link");
|
|
36
|
+
const notPreviewable = (message) => new ApiError("conversation.artifact_not_previewable", message);
|
|
37
|
+
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
|
|
38
|
+
/** The headers every public share response carries (errors too: set before the lookup). */
|
|
39
|
+
export function publicShareHeaders(reply) {
|
|
40
|
+
reply
|
|
41
|
+
.header("x-robots-tag", "noindex")
|
|
42
|
+
.header("referrer-policy", "no-referrer")
|
|
43
|
+
.header("cache-control", "private, no-store");
|
|
44
|
+
}
|
|
45
|
+
/** Headers of agent bytes served on the app origin: never sniffed, never a page. */
|
|
46
|
+
function sandboxedBytes(reply) {
|
|
47
|
+
return reply
|
|
48
|
+
.header("x-content-type-options", "nosniff")
|
|
49
|
+
.header("content-security-policy", "sandbox; default-src 'none'")
|
|
50
|
+
.header("cache-control", "private, no-store");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* `content-disposition: attachment` with an ASCII fallback (`"` `\` and anything outside printable
|
|
54
|
+
* ASCII become `_`) and the exact name as RFC 5987 `filename*` (UTF-8, percent-encoded).
|
|
55
|
+
*/
|
|
56
|
+
export function attachmentDisposition(name) {
|
|
57
|
+
const fallback = name.replace(/[^\x20-\x7e]|["\\]/g, "_");
|
|
58
|
+
const encoded = encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
59
|
+
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The public share routes (file sharing spec §3). Each route reserves one `share-open` attempt for
|
|
63
|
+
* the client address before the lookup ({@link open}) and gives it back only after a live hit the
|
|
64
|
+
* viewer may open, so unknown, malformed, revoked, expired and refused codes are counted and codes
|
|
65
|
+
* cannot be enumerated. Every refusal of a code is one answer, 404 `share.not_found`; an internal
|
|
66
|
+
* share needs a web session of an active member of the share's own org (not the session's current
|
|
67
|
+
* org): without one 401 `share.sign_in_required`, a signed-in non-member 404. `ShareLiveness`
|
|
68
|
+
* checks the share and its creator; this service checks the viewer. The bytes are always streamed
|
|
69
|
+
* by the kernel from the snapshot, never a presigned URL; nothing lives in process memory (the
|
|
70
|
+
* throttler and the open dedupe are Redis keys with a TTL).
|
|
71
|
+
*/
|
|
72
|
+
let ShareOpenService = class ShareOpenService {
|
|
73
|
+
db;
|
|
74
|
+
txHost;
|
|
75
|
+
liveness;
|
|
76
|
+
storage;
|
|
77
|
+
tokens;
|
|
78
|
+
locks;
|
|
79
|
+
previewers;
|
|
80
|
+
throttler;
|
|
81
|
+
constructor(db, txHost, liveness, storage, tokens, locks, previewers, throttler) {
|
|
82
|
+
this.db = db;
|
|
83
|
+
this.txHost = txHost;
|
|
84
|
+
this.liveness = liveness;
|
|
85
|
+
this.storage = storage;
|
|
86
|
+
this.tokens = tokens;
|
|
87
|
+
this.locks = locks;
|
|
88
|
+
this.previewers = previewers;
|
|
89
|
+
this.throttler = throttler;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The live share with this code that the request may open, after reserving a `share-open`
|
|
93
|
+
* attempt; the attempt is refunded only when it is returned. See the class comment.
|
|
94
|
+
*/
|
|
95
|
+
async open(code, req, reply) {
|
|
96
|
+
publicShareHeaders(reply);
|
|
97
|
+
await this.throttler.reserve(THROTTLER, req, reply);
|
|
98
|
+
const share = await this.liveness.byCode(code);
|
|
99
|
+
if (share === null)
|
|
100
|
+
throw shareNotFound();
|
|
101
|
+
const p = req.principal;
|
|
102
|
+
const sessionAccount = p?.kind === "user" && p.via === "session" && !p.account.mustChangePassword
|
|
103
|
+
? p.account.id
|
|
104
|
+
: null;
|
|
105
|
+
if (share.audience === "internal") {
|
|
106
|
+
if (sessionAccount === null)
|
|
107
|
+
throw signInRequired();
|
|
108
|
+
if (!(await this.isMember(share.orgId, sessionAccount)))
|
|
109
|
+
throw shareNotFound();
|
|
110
|
+
}
|
|
111
|
+
await this.throttler.succeeded(THROTTLER, req);
|
|
112
|
+
return { share, viewerAccountId: sessionAccount };
|
|
113
|
+
}
|
|
114
|
+
/** The metadata of an opened share; audits the open at most once per viewer per 10 minutes. */
|
|
115
|
+
async meta(opened, ip) {
|
|
116
|
+
const { share } = opened;
|
|
117
|
+
await this.recordOpenOnce(opened, ip);
|
|
118
|
+
const previewable = previewKind(share.contentType);
|
|
119
|
+
// HTML is the web built-in's (it wins over extension previewers, spec §5); over
|
|
120
|
+
// FILE_PREVIEW_MAX_BYTES it is not rendered at all and the page offers the download (spec §4)
|
|
121
|
+
const html = isHtmlType(share.name, share.contentType);
|
|
122
|
+
const previewers = html ? [] : await this.previewersFor(share);
|
|
123
|
+
let render;
|
|
124
|
+
if (html)
|
|
125
|
+
render = share.size <= FILE_PREVIEW_MAX_BYTES ? "html" : "download";
|
|
126
|
+
else
|
|
127
|
+
render = previewers.length > 0 || previewable !== null ? "previewers" : "download";
|
|
128
|
+
return {
|
|
129
|
+
name: share.name,
|
|
130
|
+
contentType: share.contentType,
|
|
131
|
+
size: share.size,
|
|
132
|
+
sharedBy: share.createdByName,
|
|
133
|
+
expiresAt: share.expiresAt,
|
|
134
|
+
audience: share.audience,
|
|
135
|
+
previewable,
|
|
136
|
+
render,
|
|
137
|
+
previewers,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The extension previewers that take a share's snapshot, in the org's order: the same rule as
|
|
142
|
+
* the right panel (enabled in the org, not disabled, a valid effective config; spec §7).
|
|
143
|
+
*/
|
|
144
|
+
async previewersFor(share) {
|
|
145
|
+
return this.previewers.forShare(share.orgId, share);
|
|
146
|
+
}
|
|
147
|
+
/** Streams the snapshot as `application/octet-stream` (spec §3); `download` adds the attachment name. */
|
|
148
|
+
async content(share, download, reply) {
|
|
149
|
+
const got = await this.storage.kernel(share.orgId).get(share.objectKey);
|
|
150
|
+
if (!got)
|
|
151
|
+
throw shareNotFound();
|
|
152
|
+
sandboxedBytes(reply)
|
|
153
|
+
.header("content-type", "application/octet-stream")
|
|
154
|
+
.header("content-length", String(got.head.size));
|
|
155
|
+
if (download)
|
|
156
|
+
reply.header("content-disposition", attachmentDisposition(share.name));
|
|
157
|
+
await reply.send(Readable.fromWeb(got.body));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The first `limit` bytes (≤ 1 MiB) of a text snapshot as `text/plain; charset=utf-8`, as the
|
|
161
|
+
* panel's text route: not text, or NUL bytes in what was read → 400
|
|
162
|
+
* `conversation.artifact_not_previewable`; a cut never splits a UTF-8 character.
|
|
163
|
+
*/
|
|
164
|
+
async text(share, limit, reply) {
|
|
165
|
+
if (!isTextArtifactType(share.contentType)) {
|
|
166
|
+
throw notPreviewable("Only text files have content");
|
|
167
|
+
}
|
|
168
|
+
const max = Math.min(limit, FILE_CONTENT_MAX_BYTES);
|
|
169
|
+
const got = await this.storage
|
|
170
|
+
.kernel(share.orgId)
|
|
171
|
+
.get(share.objectKey, { range: { start: 0, end: max - 1 } });
|
|
172
|
+
if (!got)
|
|
173
|
+
throw shareNotFound();
|
|
174
|
+
let body = await readPrefix(got.body, max);
|
|
175
|
+
if (body.includes(0)) {
|
|
176
|
+
throw notPreviewable("This file contains binary data and has no text content");
|
|
177
|
+
}
|
|
178
|
+
const truncated = got.head.size > body.byteLength;
|
|
179
|
+
if (truncated)
|
|
180
|
+
body = trimUtf8(body);
|
|
181
|
+
const base = (share.contentType.split(";")[0] ?? "").trim().toLowerCase();
|
|
182
|
+
sandboxedBytes(reply)
|
|
183
|
+
.header("content-type", "text/plain; charset=utf-8")
|
|
184
|
+
.header("x-content-original-type", base);
|
|
185
|
+
if (truncated)
|
|
186
|
+
reply.header("x-content-truncated", "true");
|
|
187
|
+
await reply.send(body);
|
|
188
|
+
}
|
|
189
|
+
/** Streams a bitmap snapshot (png, jpeg, gif, webp) with its type; any other type → 404. */
|
|
190
|
+
async inline(share, reply) {
|
|
191
|
+
if (!isInlineArtifactType(share.contentType))
|
|
192
|
+
throw shareNotFound();
|
|
193
|
+
const got = await this.storage.kernel(share.orgId).get(share.objectKey);
|
|
194
|
+
if (!got)
|
|
195
|
+
throw shareNotFound();
|
|
196
|
+
const type = (share.contentType.split(";")[0] ?? "").trim().toLowerCase();
|
|
197
|
+
sandboxedBytes(reply)
|
|
198
|
+
.header("content-type", type)
|
|
199
|
+
.header("content-length", String(got.head.size));
|
|
200
|
+
await reply.send(Readable.fromWeb(got.body));
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The HTML document path of an opened share (`/api/v1/html/<token>`, a fresh share token naming
|
|
204
|
+
* its generation). Not HTML, or larger than `FILE_PREVIEW_MAX_BYTES` → 400
|
|
205
|
+
* `conversation.artifact_not_previewable`.
|
|
206
|
+
*/
|
|
207
|
+
htmlPath(share) {
|
|
208
|
+
if (!isHtmlType(share.name, share.contentType)) {
|
|
209
|
+
throw notPreviewable("Only HTML files render as documents; download this file instead");
|
|
210
|
+
}
|
|
211
|
+
if (share.size > FILE_PREVIEW_MAX_BYTES) {
|
|
212
|
+
throw notPreviewable("This HTML file is too large to render; download it instead");
|
|
213
|
+
}
|
|
214
|
+
const { token } = this.tokens.issue({
|
|
215
|
+
kind: "share",
|
|
216
|
+
shareId: share.id,
|
|
217
|
+
generation: share.generation,
|
|
218
|
+
});
|
|
219
|
+
return { path: `/api/v1/html/${token}`, expiresIn: HTML_TOKEN_TTL_SECONDS };
|
|
220
|
+
}
|
|
221
|
+
/** An active account with a membership in a live org. */
|
|
222
|
+
async isMember(orgId, accountId) {
|
|
223
|
+
const row = await this.db
|
|
224
|
+
.selectFrom("memberships")
|
|
225
|
+
.innerJoin("orgs", "orgs.id", "memberships.org_id")
|
|
226
|
+
.innerJoin("accounts", "accounts.id", "memberships.account_id")
|
|
227
|
+
.select("memberships.role")
|
|
228
|
+
.where("memberships.org_id", "=", orgId)
|
|
229
|
+
.where("memberships.account_id", "=", accountId)
|
|
230
|
+
.where("orgs.deleted_at", "is", null)
|
|
231
|
+
.where("accounts.status", "=", "active")
|
|
232
|
+
.executeTakeFirst();
|
|
233
|
+
return row !== undefined;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* `share.opened` at most once per share and viewer (the session's account, else the client
|
|
237
|
+
* address hashed) per {@link SHARE_OPENED_DEDUPE_MS}: the first open sets a Redis marker with
|
|
238
|
+
* that TTL (outside any transaction), then writes the audit and `last_opened_at`; when that write
|
|
239
|
+
* fails the marker is deleted, so the next open audits again.
|
|
240
|
+
*/
|
|
241
|
+
async recordOpenOnce(opened, ip) {
|
|
242
|
+
const viewer = opened.viewerAccountId ?? `ip-${sha256(ip)}`;
|
|
243
|
+
const key = `capk:share-opened:${opened.share.id}:${viewer}`;
|
|
244
|
+
const first = await this.locks.lease(key, "1", SHARE_OPENED_DEDUPE_MS);
|
|
245
|
+
if (!first)
|
|
246
|
+
return;
|
|
247
|
+
try {
|
|
248
|
+
await this.recordOpen(opened);
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
// a failed audit must not suppress the next one: give the marker back (best effort)
|
|
252
|
+
await this.locks.releaseIf(key, "1").catch(() => { });
|
|
253
|
+
throw err;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** The audit of one open (the account for an internal share, none for an external one). */
|
|
257
|
+
async recordOpen(opened) {
|
|
258
|
+
const { share } = opened;
|
|
259
|
+
await this.db
|
|
260
|
+
.updateTable("file_shares")
|
|
261
|
+
.set({ last_opened_at: sql `now()` })
|
|
262
|
+
.where("id", "=", share.id)
|
|
263
|
+
.execute();
|
|
264
|
+
await audit(this.db.db, {
|
|
265
|
+
actorAccountId: share.audience === "internal" ? opened.viewerAccountId : null,
|
|
266
|
+
orgId: share.orgId,
|
|
267
|
+
action: "share.opened",
|
|
268
|
+
target: share.id,
|
|
269
|
+
detail: { shareId: share.id, audience: share.audience },
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
__decorate([
|
|
274
|
+
Transactional()
|
|
275
|
+
], ShareOpenService.prototype, "recordOpen", null);
|
|
276
|
+
ShareOpenService = __decorate([
|
|
277
|
+
Injectable(),
|
|
278
|
+
__param(0, Inject(KernelDb)),
|
|
279
|
+
__param(1, Inject(TransactionHost)),
|
|
280
|
+
__param(2, Inject(ShareLiveness)),
|
|
281
|
+
__param(3, Inject(StorageService)),
|
|
282
|
+
__param(4, Inject(HtmlTokens)),
|
|
283
|
+
__param(5, Inject(LockService)),
|
|
284
|
+
__param(6, Inject(PreviewerRegistry)),
|
|
285
|
+
__param(7, Inject(CredentialThrottler))
|
|
286
|
+
], ShareOpenService);
|
|
287
|
+
export { ShareOpenService };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { UiView } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { PreviewerRegistry } from "../files/previewers.js";
|
|
5
|
+
import { EmbedTokens } from "../ui/embed-token.js";
|
|
6
|
+
import { UiViews } from "../ui/views.js";
|
|
7
|
+
import { ShareOpenService } from "./share-open.service.js";
|
|
8
|
+
/** `GET /api/v1/s/:code/previews/:plugin/:previewerId`: the locale the view is rendered in. */
|
|
9
|
+
export declare const SharePreviewQuery: z.ZodObject<{
|
|
10
|
+
locale: z.ZodDefault<z.ZodEnum<{
|
|
11
|
+
en: "en";
|
|
12
|
+
zh: "zh";
|
|
13
|
+
}>>;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
/** What the share embed-token route answers (the web's `ShareEmbedToken`). */
|
|
16
|
+
export interface ShareEmbedTokenResponse {
|
|
17
|
+
token: string;
|
|
18
|
+
/** `/plugin-ui/<plugin>/<path without the leading /ui/>`. */
|
|
19
|
+
src: string;
|
|
20
|
+
/** Seconds; the page renews from the moment it received it. */
|
|
21
|
+
expiresIn: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Extension previewers on a share page (file sharing spec §3, §7), `@Public()` under
|
|
25
|
+
* `/api/v1/s/:code`: every route opens the share first ({@link ShareOpenService.open}: the
|
|
26
|
+
* `share-open` throttler, 404 `share.not_found` for every refusal, 401 `share.sign_in_required`
|
|
27
|
+
* for an internal share without a member's session), so the link stays the only authority.
|
|
28
|
+
* - `POST .../embed-token/:plugin/:previewerId` → `{ token, src, expiresIn }`: a share-scoped
|
|
29
|
+
* embed token (`scope: "share"`, the share's org, id and generation, no account or role) for an
|
|
30
|
+
* embed previewer that takes the snapshot in the org's order; a view previewer, one that does not
|
|
31
|
+
* take the snapshot or is off → 404 `ui.not_found`. The token is checked live on every use
|
|
32
|
+
* (`ctx.ui.verifyEmbedToken`) and never valid for `/api`. Unsafe: the CSRF header is required.
|
|
33
|
+
* - `GET .../previews/:plugin/:previewerId?locale=` → `{ view }`: a view previewer rendered for
|
|
34
|
+
* the snapshot (`source: "share"`); errors as the panel's preview route (404 `ui.not_found`,
|
|
35
|
+
* 502 `ui.render_failed`, 502 `ui.invalid_view`, 504 `ui.timeout`).
|
|
36
|
+
* The plugin and previewer ids are matched, not validated, so a malformed one is a 404 after the
|
|
37
|
+
* open like an unknown one. An HTML snapshot never reaches an extension previewer (the built-in
|
|
38
|
+
* wins, spec §5): both routes answer 404 `ui.not_found` for it, as its metadata lists none.
|
|
39
|
+
*/
|
|
40
|
+
export declare class SharePreviewsController {
|
|
41
|
+
private readonly shares;
|
|
42
|
+
private readonly previewers;
|
|
43
|
+
private readonly views;
|
|
44
|
+
private readonly embeds;
|
|
45
|
+
constructor(shares: ShareOpenService, previewers: PreviewerRegistry, views: UiViews, embeds: EmbedTokens);
|
|
46
|
+
embedToken(code: string, plugin: string, previewerId: string, req: FastifyRequest, reply: FastifyReply): Promise<ShareEmbedTokenResponse>;
|
|
47
|
+
preview(code: string, plugin: string, previewerId: string, q: z.infer<typeof SharePreviewQuery>, req: FastifyRequest, reply: FastifyReply): Promise<{
|
|
48
|
+
view: UiView;
|
|
49
|
+
}>;
|
|
50
|
+
}
|