@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
@@ -0,0 +1,115 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Controller, Get, HttpCode, Inject, Param, Post, Req, Res } from "@nestjs/common";
11
+ import { z } from "zod";
12
+ import { ApiError } from "../errors.js";
13
+ import { PreviewerRegistry } from "../files/previewers.js";
14
+ import { isHtmlType } from "../html/html-type.js";
15
+ import { Public } from "../identity/principal.js";
16
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
17
+ import { ZQuery } from "../infra/validation/zod-params.js";
18
+ import { EMBED_TOKEN_TTL_SECONDS, EmbedTokens } from "../ui/embed-token.js";
19
+ import { embedSrc } from "../ui/views.controller.js";
20
+ import { UiViews } from "../ui/views.js";
21
+ import { ShareOpenService } from "./share-open.service.js";
22
+ /** `GET /api/v1/s/:code/previews/:plugin/:previewerId`: the locale the view is rendered in. */
23
+ export const SharePreviewQuery = z.object({ locale: z.enum(["zh", "en"]).default("en") });
24
+ class SharePreviewQueryDto extends createZodDto(SharePreviewQuery, "SharePreviewQuery") {
25
+ }
26
+ const previewerNotFound = () => new ApiError("ui.not_found", "Previewer not found");
27
+ /**
28
+ * Extension previewers on a share page (file sharing spec §3, §7), `@Public()` under
29
+ * `/api/v1/s/:code`: every route opens the share first ({@link ShareOpenService.open}: the
30
+ * `share-open` throttler, 404 `share.not_found` for every refusal, 401 `share.sign_in_required`
31
+ * for an internal share without a member's session), so the link stays the only authority.
32
+ * - `POST .../embed-token/:plugin/:previewerId` → `{ token, src, expiresIn }`: a share-scoped
33
+ * embed token (`scope: "share"`, the share's org, id and generation, no account or role) for an
34
+ * embed previewer that takes the snapshot in the org's order; a view previewer, one that does not
35
+ * take the snapshot or is off → 404 `ui.not_found`. The token is checked live on every use
36
+ * (`ctx.ui.verifyEmbedToken`) and never valid for `/api`. Unsafe: the CSRF header is required.
37
+ * - `GET .../previews/:plugin/:previewerId?locale=` → `{ view }`: a view previewer rendered for
38
+ * the snapshot (`source: "share"`); errors as the panel's preview route (404 `ui.not_found`,
39
+ * 502 `ui.render_failed`, 502 `ui.invalid_view`, 504 `ui.timeout`).
40
+ * The plugin and previewer ids are matched, not validated, so a malformed one is a 404 after the
41
+ * open like an unknown one. An HTML snapshot never reaches an extension previewer (the built-in
42
+ * wins, spec §5): both routes answer 404 `ui.not_found` for it, as its metadata lists none.
43
+ */
44
+ let SharePreviewsController = class SharePreviewsController {
45
+ shares;
46
+ previewers;
47
+ views;
48
+ embeds;
49
+ constructor(shares, previewers, views, embeds) {
50
+ this.shares = shares;
51
+ this.previewers = previewers;
52
+ this.views = views;
53
+ this.embeds = embeds;
54
+ }
55
+ async embedToken(code, plugin, previewerId, req, reply) {
56
+ const { share } = await this.shares.open(code, req, reply);
57
+ if (isHtmlType(share.name, share.contentType))
58
+ throw previewerNotFound();
59
+ const target = await this.previewers.shareEmbed(share.orgId, share, plugin, previewerId);
60
+ if (target === null)
61
+ throw previewerNotFound();
62
+ const path = this.views.shareEmbedPath(plugin, target.contribution);
63
+ const { token } = this.embeds.issue({
64
+ plugin,
65
+ scope: "share",
66
+ orgId: share.orgId,
67
+ shareId: share.id,
68
+ generation: share.generation,
69
+ contribution: target.contribution,
70
+ });
71
+ return { token, src: embedSrc(plugin, path), expiresIn: EMBED_TOKEN_TTL_SECONDS };
72
+ }
73
+ async preview(code, plugin, previewerId, q, req, reply) {
74
+ const { share } = await this.shares.open(code, req, reply);
75
+ if (isHtmlType(share.name, share.contentType))
76
+ throw previewerNotFound();
77
+ const view = await this.previewers.renderShare({
78
+ orgId: share.orgId,
79
+ shareId: share.id,
80
+ file: share,
81
+ plugin,
82
+ id: previewerId,
83
+ locale: q.locale,
84
+ });
85
+ return { view };
86
+ }
87
+ };
88
+ __decorate([
89
+ Public(),
90
+ Post("embed-token/:plugin/:previewerId"),
91
+ HttpCode(200),
92
+ __param(0, Param("code")),
93
+ __param(1, Param("plugin")),
94
+ __param(2, Param("previewerId")),
95
+ __param(3, Req()),
96
+ __param(4, Res({ passthrough: true }))
97
+ ], SharePreviewsController.prototype, "embedToken", null);
98
+ __decorate([
99
+ Public(),
100
+ Get("previews/:plugin/:previewerId"),
101
+ __param(0, Param("code")),
102
+ __param(1, Param("plugin")),
103
+ __param(2, Param("previewerId")),
104
+ __param(3, ZQuery(SharePreviewQueryDto)),
105
+ __param(4, Req()),
106
+ __param(5, Res({ passthrough: true }))
107
+ ], SharePreviewsController.prototype, "preview", null);
108
+ SharePreviewsController = __decorate([
109
+ Controller("api/v1/s/:code"),
110
+ __param(0, Inject(ShareOpenService)),
111
+ __param(1, Inject(PreviewerRegistry)),
112
+ __param(2, Inject(UiViews)),
113
+ __param(3, Inject(EmbedTokens))
114
+ ], SharePreviewsController);
115
+ export { SharePreviewsController };
@@ -0,0 +1,34 @@
1
+ import type { z } from "zod";
2
+ import { type Principal } from "../identity/principal.js";
3
+ import { type OrgContext } from "../orgs/org.guard.js";
4
+ import { CreateShareBody, ListSharesQuery, ShareFileParams, ShareIdParams } from "./shares.schemas.js";
5
+ import { type SharePolicy, SharesService, type ShareView } from "./shares.service.js";
6
+ /**
7
+ * Shares of conversation files (file sharing spec §2): `agents.use`, a person only (a service
8
+ * token is refused by `requireUser`). Creating and listing a file's shares need the conversation's
9
+ * owner (`ConversationAccess.isAccessible`, else `conversation.not_found`); refreshing needs the
10
+ * creator, revoking the creator or an org admin (else `share.not_found`).
11
+ */
12
+ export declare class SharesController {
13
+ private readonly shares;
14
+ constructor(shares: SharesService);
15
+ /** Shares one file of the caller's conversation as a snapshot: 201 `{ share }`. */
16
+ create(principal: Principal, org: OrgContext, params: z.infer<typeof ShareFileParams>, body: z.infer<typeof CreateShareBody>): Promise<{
17
+ share: ShareView;
18
+ }>;
19
+ /** The live and recent shares of one file, with what the share dialog may offer. */
20
+ forFile(principal: Principal, org: OrgContext, params: z.infer<typeof ShareFileParams>): Promise<{
21
+ shares: ShareView[];
22
+ policy: SharePolicy;
23
+ }>;
24
+ /** "Update to latest": the newest available version as the next generation (creator only). */
25
+ refresh(principal: Principal, org: OrgContext, params: z.infer<typeof ShareIdParams>): Promise<{
26
+ share: ShareView;
27
+ }>;
28
+ /** Revokes a share (creator or org admin): 204, also when it was already revoked. */
29
+ revoke(principal: Principal, org: OrgContext, params: z.infer<typeof ShareIdParams>): Promise<void>;
30
+ /** The caller's shares (`scope=mine`, default) or the org's (`scope=all`, org admins). */
31
+ list(principal: Principal, org: OrgContext, q: z.infer<typeof ListSharesQuery>): Promise<{
32
+ shares: ShareView[];
33
+ }>;
34
+ }
@@ -0,0 +1,114 @@
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, Delete, Get, Header, HttpCode, Inject, Post } from "@nestjs/common";
11
+ import { CurrentPrincipal, patTokenId, requireUser, } from "../identity/principal.js";
12
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
13
+ import { ZBody, ZParam, ZQuery } from "../infra/validation/zod-params.js";
14
+ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
15
+ import { CreateShareBody, ListSharesQuery, ShareFileParams, ShareIdParams, } from "./shares.schemas.js";
16
+ import { SharesService } from "./shares.service.js";
17
+ class ShareFileParamsDto extends createZodDto(ShareFileParams, "ShareFileParams") {
18
+ }
19
+ class CreateShareBodyDto extends createZodDto(CreateShareBody, "CreateShareBody") {
20
+ }
21
+ class ShareIdParamsDto extends createZodDto(ShareIdParams, "ShareIdParams") {
22
+ }
23
+ class ListSharesQueryDto extends createZodDto(ListSharesQuery, "ListSharesQuery") {
24
+ }
25
+ /**
26
+ * Shares of conversation files (file sharing spec §2): `agents.use`, a person only (a service
27
+ * token is refused by `requireUser`). Creating and listing a file's shares need the conversation's
28
+ * owner (`ConversationAccess.isAccessible`, else `conversation.not_found`); refreshing needs the
29
+ * creator, revoking the creator or an org admin (else `share.not_found`).
30
+ */
31
+ let SharesController = class SharesController {
32
+ shares;
33
+ constructor(shares) {
34
+ this.shares = shares;
35
+ }
36
+ /** Shares one file of the caller's conversation as a snapshot: 201 `{ share }`. */
37
+ async create(principal, org, params, body) {
38
+ const p = requireUser(principal);
39
+ return {
40
+ share: await this.shares.create(org.orgId, p.account.id, params.id, params.fileId, body, {
41
+ tokenId: patTokenId(p),
42
+ }),
43
+ };
44
+ }
45
+ /** The live and recent shares of one file, with what the share dialog may offer. */
46
+ async forFile(principal, org, params) {
47
+ const p = requireUser(principal);
48
+ return this.shares.forFile(org.orgId, p.account.id, params.id, params.fileId);
49
+ }
50
+ /** "Update to latest": the newest available version as the next generation (creator only). */
51
+ async refresh(principal, org, params) {
52
+ const p = requireUser(principal);
53
+ return {
54
+ share: await this.shares.refresh(org.orgId, p.account.id, params.shareId, {
55
+ tokenId: patTokenId(p),
56
+ }),
57
+ };
58
+ }
59
+ /** Revokes a share (creator or org admin): 204, also when it was already revoked. */
60
+ async revoke(principal, org, params) {
61
+ const p = requireUser(principal);
62
+ await this.shares.revoke(org.orgId, p.account.id, params.shareId, { tokenId: patTokenId(p) });
63
+ }
64
+ /** The caller's shares (`scope=mine`, default) or the org's (`scope=all`, org admins). */
65
+ async list(principal, org, q) {
66
+ const p = requireUser(principal);
67
+ return this.shares.list(org.orgId, p.account.id, q.scope);
68
+ }
69
+ };
70
+ __decorate([
71
+ Post("conversations/:id/files/:fileId/shares"),
72
+ OrgAction("agents.use"),
73
+ __param(0, CurrentPrincipal()),
74
+ __param(1, CurrentOrg()),
75
+ __param(2, ZParam(ShareFileParamsDto)),
76
+ __param(3, ZBody(CreateShareBodyDto))
77
+ ], SharesController.prototype, "create", null);
78
+ __decorate([
79
+ Get("conversations/:id/files/:fileId/shares"),
80
+ Header("cache-control", "private, no-store"),
81
+ OrgAction("agents.use"),
82
+ __param(0, CurrentPrincipal()),
83
+ __param(1, CurrentOrg()),
84
+ __param(2, ZParam(ShareFileParamsDto))
85
+ ], SharesController.prototype, "forFile", null);
86
+ __decorate([
87
+ Post("shares/:shareId/refresh"),
88
+ HttpCode(200),
89
+ OrgAction("agents.use"),
90
+ __param(0, CurrentPrincipal()),
91
+ __param(1, CurrentOrg()),
92
+ __param(2, ZParam(ShareIdParamsDto))
93
+ ], SharesController.prototype, "refresh", null);
94
+ __decorate([
95
+ Delete("shares/:shareId"),
96
+ HttpCode(204),
97
+ OrgAction("agents.use"),
98
+ __param(0, CurrentPrincipal()),
99
+ __param(1, CurrentOrg()),
100
+ __param(2, ZParam(ShareIdParamsDto))
101
+ ], SharesController.prototype, "revoke", null);
102
+ __decorate([
103
+ Get("shares"),
104
+ Header("cache-control", "private, no-store"),
105
+ OrgAction("agents.use"),
106
+ __param(0, CurrentPrincipal()),
107
+ __param(1, CurrentOrg()),
108
+ __param(2, ZQuery(ListSharesQueryDto))
109
+ ], SharesController.prototype, "list", null);
110
+ SharesController = __decorate([
111
+ Controller("api/v1/orgs/:orgId"),
112
+ __param(0, Inject(SharesService))
113
+ ], SharesController);
114
+ export { SharesController };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * File sharing (file sharing spec): creating, refreshing, revoking and listing shares
3
+ * ({@link SharesService}), the live check the open routes use (`ShareLiveness`), the public open
4
+ * routes' service (`ShareOpenService`) and the snapshot deletion the maintenance worker runs
5
+ * (`ShareObjects`).
6
+ */
7
+ export declare class SharesModule {
8
+ }
@@ -0,0 +1,41 @@
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 { FilesModule } from "../files/files.module.js";
10
+ import { HtmlTokensModule } from "../html/html-token.js";
11
+ import { OrgLockModule } from "../orgs/org-lock.js";
12
+ import { StorageModule } from "../storage/storage.module.js";
13
+ import { ShareLivenessModule } from "./liveness.js";
14
+ import { ShareObjectsModule } from "./share-objects.js";
15
+ import { ShareOpenService } from "./share-open.service.js";
16
+ import { SharesService } from "./shares.service.js";
17
+ /**
18
+ * File sharing (file sharing spec): creating, refreshing, revoking and listing shares
19
+ * ({@link SharesService}), the live check the open routes use (`ShareLiveness`), the public open
20
+ * routes' service (`ShareOpenService`) and the snapshot deletion the maintenance worker runs
21
+ * (`ShareObjects`).
22
+ */
23
+ let SharesModule = class SharesModule {
24
+ };
25
+ SharesModule = __decorate([
26
+ Module({
27
+ imports: [
28
+ ConversationsModule,
29
+ StorageModule,
30
+ OrgLockModule,
31
+ ShareLivenessModule,
32
+ ShareObjectsModule,
33
+ HtmlTokensModule,
34
+ // the share page's extension previewers (file sharing spec §7)
35
+ FilesModule,
36
+ ],
37
+ providers: [SharesService, ShareOpenService],
38
+ exports: [SharesService, ShareOpenService, ShareLivenessModule, ShareObjectsModule],
39
+ })
40
+ ], SharesModule);
41
+ export { SharesModule };
@@ -0,0 +1,31 @@
1
+ import { z } from "zod";
2
+ import type { RouteSchemas } from "../platform/route-schemas.js";
3
+ /** `POST …/conversations/:id/files/:fileId/shares` and its per-file list. */
4
+ export declare const ShareFileParams: z.ZodObject<{
5
+ id: z.ZodString;
6
+ fileId: z.ZodString;
7
+ }, z.core.$strip>;
8
+ /**
9
+ * A new share: who may open it and when it expires (days; null = never, internal only). An
10
+ * external share needs a non-null expiry within the platform maximum (`share.expiry_too_long`).
11
+ */
12
+ export declare const CreateShareBody: z.ZodObject<{
13
+ audience: z.ZodEnum<{
14
+ external: "external";
15
+ internal: "internal";
16
+ }>;
17
+ expiresInDays: z.ZodNullable<z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<7>, z.ZodLiteral<30>]>>;
18
+ }, z.core.$strict>;
19
+ /** `…/shares/:shareId` routes. */
20
+ export declare const ShareIdParams: z.ZodObject<{
21
+ shareId: z.ZodUUID;
22
+ }, z.core.$strip>;
23
+ /** `GET …/shares`: the actor's own shares (`mine`, default) or every share of the org (`all`, org admins). */
24
+ export declare const ListSharesQuery: z.ZodObject<{
25
+ scope: z.ZodDefault<z.ZodEnum<{
26
+ all: "all";
27
+ mine: "mine";
28
+ }>>;
29
+ }, z.core.$strip>;
30
+ /** The share routes a Platform operation mirrors (spec §10). */
31
+ export declare const SHARE_ROUTES: readonly RouteSchemas[];
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ /** `POST …/conversations/:id/files/:fileId/shares` and its per-file list. */
3
+ export const ShareFileParams = z.object({
4
+ id: z.string().min(1).max(100),
5
+ fileId: z.string().min(1).max(100),
6
+ });
7
+ /**
8
+ * A new share: who may open it and when it expires (days; null = never, internal only). An
9
+ * external share needs a non-null expiry within the platform maximum (`share.expiry_too_long`).
10
+ */
11
+ export const CreateShareBody = z
12
+ .object({
13
+ audience: z.enum(["internal", "external"]),
14
+ expiresInDays: z.union([z.literal(1), z.literal(7), z.literal(30)]).nullable(),
15
+ })
16
+ .strict();
17
+ /** `…/shares/:shareId` routes. */
18
+ export const ShareIdParams = z.object({ shareId: z.uuid() });
19
+ /** `GET …/shares`: the actor's own shares (`mine`, default) or every share of the org (`all`, org admins). */
20
+ export const ListSharesQuery = z.object({ scope: z.enum(["mine", "all"]).default("mine") });
21
+ /** The share routes a Platform operation mirrors (spec §10). */
22
+ export const SHARE_ROUTES = [
23
+ { route: "GET /api/v1/orgs/:orgId/shares", query: ListSharesQuery },
24
+ { route: "DELETE /api/v1/orgs/:orgId/shares/:shareId", params: ShareIdParams },
25
+ ];
@@ -0,0 +1,182 @@
1
+ import { ConversationAccess } from "../conversations/access.js";
2
+ import { ConversationFiles } from "../conversations/files.js";
3
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import { TransactionHost } from "../infra/database/transaction-host.js";
6
+ import { LockService } from "../infra/lock/lock.service.js";
7
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
8
+ import type { KernelLogger } from "../log.js";
9
+ import { OrgLock } from "../orgs/org-lock.js";
10
+ import { StorageService } from "../storage/storage.service.js";
11
+ import { type ExternalSharingState } from "./settings.js";
12
+ /**
13
+ * Shares of conversation files (file sharing spec §1, §2): a share is a frozen snapshot of one
14
+ * file, copied under `shares/<id>/<generation>` of the org's kernel prefix **before** the row that
15
+ * names it is written (intent first: a crash leaves an orphan object the daily sweep frees, never a
16
+ * row without its object). Freeing a snapshot is owed through the outbox by the transaction that
17
+ * stops using it (a refresh, a revoke). Nothing is held in process memory; every read is live.
18
+ */
19
+ /**
20
+ * `live`: opens now. `suspended`: not revoked or expired, but it does not open now: an external
21
+ * share while external sharing is off for the org, or its creator lost access to the file.
22
+ */
23
+ export type ShareState = "live" | "expired" | "revoked" | "suspended";
24
+ export interface ShareView {
25
+ id: string;
26
+ code: string;
27
+ /**
28
+ * The absolute link people open, `<http.publicUrl>/s/<code>`; null when `http.publicUrl` is not
29
+ * set (the web builds it from its own origin then).
30
+ */
31
+ url: string | null;
32
+ audience: "internal" | "external";
33
+ conversationId: string;
34
+ fileId: string;
35
+ sourcePath: string | null;
36
+ name: string;
37
+ contentType: string;
38
+ size: number;
39
+ generation: number;
40
+ createdBy: {
41
+ id: string;
42
+ displayName: string;
43
+ };
44
+ createdAt: string;
45
+ expiresAt: string | null;
46
+ lastOpenedAt: string | null;
47
+ state: ShareState;
48
+ revokedAt: string | null;
49
+ revokeReason: string | null;
50
+ /**
51
+ * A newer version of `sourcePath` was delivered after the snapshot's (refresh offered). In the
52
+ * per-file list ({@link SharesService.forFile}) only a version whose object is still stored
53
+ * counts; in the org and personal lists the event log alone decides (no storage reads).
54
+ */
55
+ newerVersion: boolean;
56
+ }
57
+ /** What the share dialog may offer: the effective external switch and the expiry maximum. */
58
+ export interface SharePolicy {
59
+ external: ExternalSharingState;
60
+ maxExpiryDays: number;
61
+ }
62
+ /** Who acts: a personal token's id for the audit, and the Platform tool's audit detail. */
63
+ export interface ShareActor {
64
+ tokenId?: string | undefined;
65
+ auditDetail?: Record<string, unknown> | undefined;
66
+ }
67
+ /** Revoked or expired shares stay in the lists this long (the "recent" section). */
68
+ export declare const SHARE_RECENT_DAYS = 7;
69
+ /** The most shares one list returns (newest first). */
70
+ export declare const SHARES_LIST_MAX = 500;
71
+ export declare class SharesService {
72
+ private readonly db;
73
+ readonly txHost: TransactionHost;
74
+ private readonly files;
75
+ private readonly access;
76
+ private readonly storage;
77
+ private readonly outbox;
78
+ private readonly orgLock;
79
+ private readonly locks;
80
+ private readonly config;
81
+ private readonly log?;
82
+ constructor(db: KernelDb, txHost: TransactionHost, files: Pick<ConversationFiles, "file" | "identify" | "latestAvailable">, access: Pick<ConversationAccess, "isAccessible">, storage: Pick<StorageService, "kernel">, outbox: Pick<OutboxService, "add">, orgLock: Pick<OrgLock, "lockAndAuthorize">, locks: Pick<LockService, "run">, config: Pick<KernelConfigService, "get" | "fieldSource">, log?: KernelLogger | undefined);
83
+ /** The effective external switch for the org and the platform's expiry maximum, read live. */
84
+ policy(orgId: string): Promise<SharePolicy>;
85
+ /**
86
+ * Shares one file of the viewer's conversation (any version shown in the panel, or an
87
+ * attachment sent in it). The snapshot is streamed into its object first, outside any
88
+ * transaction; then {@link insertShare} writes the row and the `share.created` audit. A code
89
+ * collision retries the insert with a new code (the object is keyed by the id, not the code).
90
+ */
91
+ create(orgId: string, accountId: string, conversationId: string, fileId: string, body: {
92
+ audience: "internal" | "external";
93
+ expiresInDays: 1 | 7 | 30 | null;
94
+ }, actor?: ShareActor): Promise<ShareView>;
95
+ /**
96
+ * The row and audit of a new share. The row's org is read from the conversation here (locked
97
+ * `FOR SHARE`, so a concurrent delete waits and then revokes this share too), never taken from
98
+ * the caller; the viewer's access is checked again inside the transaction, since the copy ran
99
+ * without one. Internal: called by {@link create} only.
100
+ */
101
+ insertShare(s: {
102
+ id: string;
103
+ orgId: string;
104
+ code: string;
105
+ conversationId: string;
106
+ fileId: string;
107
+ sourcePath: string | null;
108
+ accountId: string;
109
+ audience: "internal" | "external";
110
+ name: string;
111
+ contentType: string;
112
+ size: number;
113
+ objectKey: string;
114
+ expiresInDays: number | null;
115
+ }, actor: ShareActor): Promise<void>;
116
+ /**
117
+ * "Update to latest" (creator only): copies the newest available version of the share's source
118
+ * path delivered after its current snapshot as the next generation under the same code, then
119
+ * {@link commitRefresh} moves the row and owes the previous snapshot's deletion. Refreshes of one
120
+ * share are serialized by a lock (taken outside any transaction), so two never write the same
121
+ * generation's object.
122
+ */
123
+ refresh(orgId: string, accountId: string, shareId: string, actor?: ShareActor): Promise<ShareView>;
124
+ /**
125
+ * The row move of a refresh: generation `from` → `from + 1` with the new snapshot, the previous
126
+ * snapshot's deletion owed, `share.refreshed` audited. If the share was revoked or expired (or
127
+ * moved) since the copy began, nothing moves and the new snapshot's deletion is owed instead;
128
+ * returns whether it moved. Internal: called by {@link refresh} only.
129
+ */
130
+ commitRefresh(at: {
131
+ orgId: string;
132
+ accountId: string;
133
+ shareId: string;
134
+ from: number;
135
+ }, snap: {
136
+ fileId: string;
137
+ name: string;
138
+ contentType: string;
139
+ size: number;
140
+ objectKey: string;
141
+ }, actor: ShareActor): Promise<boolean>;
142
+ /**
143
+ * Revokes a share (its creator, or an org admin with `org.update`; anyone else: `share.not_found`)
144
+ * and owes its snapshot's deletion. Idempotent: an already revoked share is left as it is, with
145
+ * no second audit. An admin's role is re-read under the org row lock (taken before the share row).
146
+ */
147
+ revoke(orgId: string, accountId: string, shareId: string, actor?: ShareActor): Promise<void>;
148
+ /**
149
+ * The live and recent shares of one file of the viewer's conversation (every share of the same
150
+ * source path, any version, or of the attachment), newest first, with the share policy.
151
+ */
152
+ forFile(orgId: string, accountId: string, conversationId: string, fileId: string): Promise<{
153
+ shares: ShareView[];
154
+ policy: SharePolicy;
155
+ }>;
156
+ /**
157
+ * The org's live and recent shares: the actor's own (`mine`), or every member's (`all`, org
158
+ * admins with `org.update`, re-read live; anyone else `forbidden`). Newest first, at most
159
+ * {@link SHARES_LIST_MAX}.
160
+ */
161
+ list(orgId: string, accountId: string, scope: "mine" | "all"): Promise<{
162
+ shares: ShareView[];
163
+ }>;
164
+ /** One share as the lists show it (just written by this service). */
165
+ private viewOf;
166
+ /** The list query: shares of the org, live and recent (unless `all`), newest first. */
167
+ private views;
168
+ private toView;
169
+ /**
170
+ * The file to share, after the viewer's access check: a delivered version, or an attachment whose
171
+ * stored object is still the one finalize checked (else `share.file_unavailable`).
172
+ */
173
+ private fileToShare;
174
+ /**
175
+ * Streams the file's object into `objectKey` (never buffered whole); returns the snapshot's size.
176
+ * The object is gone, or an upload's object is no longer the one finalize checked →
177
+ * `share.file_unavailable`. Runs with no transaction open.
178
+ */
179
+ private copy;
180
+ /** Owes the deletion of one share generation's snapshot (in the caller's transaction). */
181
+ private oweDelete;
182
+ }