@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,553 @@
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 { randomUUID } from "node:crypto";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { ConversationAccess } from "../conversations/access.js";
14
+ import { attachmentContentMatches } from "../conversations/attachments.service.js";
15
+ import { ConversationFiles } from "../conversations/files.js";
16
+ import { ApiError } from "../errors.js";
17
+ import { audit } from "../identity/audit.js";
18
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
+ import { KernelDb } from "../infra/database/kernel-db.js";
20
+ import { TransactionHost } from "../infra/database/transaction-host.js";
21
+ import { Transactional } from "../infra/database/transactional.decorator.js";
22
+ import { LockService } from "../infra/lock/lock.service.js";
23
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
24
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
25
+ import { OrgLock } from "../orgs/org-lock.js";
26
+ import { can } from "../orgs/roles.js";
27
+ import { parseOrgSettings, readStoredOrgSettings } from "../orgs/settings.service.js";
28
+ import { StorageService } from "../storage/storage.service.js";
29
+ import { UUID_RE } from "../ui/registry.js";
30
+ import { creatorStillHasAccess } from "./liveness.js";
31
+ import { effectiveExternalSharing, readExternalSharing, readShareMaxExpiry, } from "./settings.js";
32
+ import { newShareCode } from "./share-code.js";
33
+ import { oweShareObjectDelete, shareObjectKey, shareRefreshLockKey } from "./share-objects.js";
34
+ /** Revoked or expired shares stay in the lists this long (the "recent" section). */
35
+ export const SHARE_RECENT_DAYS = 7;
36
+ /** The most shares one list returns (newest first). */
37
+ export const SHARES_LIST_MAX = 500;
38
+ /** Attempts at a unique code before giving up (a collision is ~2^-59 per pair). */
39
+ const CODE_ATTEMPTS = 3;
40
+ /** The refresh lock's lifetime without renewal (renewed while the copy runs). */
41
+ const REFRESH_LOCK_TTL_MS = 30_000;
42
+ /** How long a refresh waits for another refresh of the same share. */
43
+ const REFRESH_LOCK_WAIT_MS = 10_000;
44
+ const notFound = () => new ApiError("share.not_found", "Share not found");
45
+ const fileUnavailable = (message = "The file is no longer available, so it cannot be shared") => new ApiError("share.file_unavailable", message);
46
+ const conversationNotFound = () => new ApiError("conversation.not_found", "Conversation not found");
47
+ const externalNotAllowed = (state) => new ApiError("share.external_not_allowed", state === "platform_denied"
48
+ ? "External sharing is not allowed on this platform; a super admin must allow it first, then an org admin must turn it on in the organization settings."
49
+ : "External sharing is off in this organization; an org admin can turn it on in the organization settings.");
50
+ const expiryTooLong = (max) => new ApiError("share.expiry_too_long", `An external share must expire within ${max} day${max === 1 ? "" : "s"}; pick a shorter expiry.`);
51
+ /** Whether `e` is the unique violation of `file_shares.code`. */
52
+ const isCodeConflict = (e) => typeof e === "object" &&
53
+ e !== null &&
54
+ e.code === "23505" &&
55
+ e.constraint === "file_shares_code_key";
56
+ /** Not expired now (never-expiring included). */
57
+ const notExpired = (eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]);
58
+ const iso = (d) => (d === null ? null : d.toISOString());
59
+ let SharesService = class SharesService {
60
+ db;
61
+ txHost;
62
+ files;
63
+ access;
64
+ storage;
65
+ outbox;
66
+ orgLock;
67
+ locks;
68
+ config;
69
+ log;
70
+ constructor(db, txHost, files, access, storage, outbox, orgLock, locks, config, log) {
71
+ this.db = db;
72
+ this.txHost = txHost;
73
+ this.files = files;
74
+ this.access = access;
75
+ this.storage = storage;
76
+ this.outbox = outbox;
77
+ this.orgLock = orgLock;
78
+ this.locks = locks;
79
+ this.config = config;
80
+ this.log = log;
81
+ }
82
+ /** The effective external switch for the org and the platform's expiry maximum, read live. */
83
+ async policy(orgId) {
84
+ const [platform, max, stored] = await Promise.all([
85
+ readExternalSharing(this.db.db, this.config, this.log),
86
+ readShareMaxExpiry(this.db.db, this.config, this.log),
87
+ readStoredOrgSettings(this.db.db, orgId),
88
+ ]);
89
+ return {
90
+ external: effectiveExternalSharing(platform.value, parseOrgSettings(stored).externalSharing),
91
+ maxExpiryDays: max.value,
92
+ };
93
+ }
94
+ /**
95
+ * Shares one file of the viewer's conversation (any version shown in the panel, or an
96
+ * attachment sent in it). The snapshot is streamed into its object first, outside any
97
+ * transaction; then {@link insertShare} writes the row and the `share.created` audit. A code
98
+ * collision retries the insert with a new code (the object is keyed by the id, not the code).
99
+ */
100
+ async create(orgId, accountId, conversationId, fileId, body, actor = {}) {
101
+ const file = await this.fileToShare(orgId, conversationId, accountId, fileId);
102
+ if (body.audience === "external") {
103
+ const policy = await this.policy(orgId);
104
+ if (policy.external !== "allowed")
105
+ throw externalNotAllowed(policy.external);
106
+ if (body.expiresInDays === null || body.expiresInDays > policy.maxExpiryDays) {
107
+ throw expiryTooLong(policy.maxExpiryDays);
108
+ }
109
+ }
110
+ const id = randomUUID();
111
+ const objectKey = shareObjectKey(id, 1);
112
+ const size = await this.copy(orgId, file, objectKey);
113
+ for (let attempt = 1;; attempt++) {
114
+ try {
115
+ await this.insertShare({
116
+ id,
117
+ orgId,
118
+ code: newShareCode(),
119
+ conversationId,
120
+ fileId: file.id,
121
+ sourcePath: file.sourcePath,
122
+ accountId,
123
+ audience: body.audience,
124
+ name: file.name,
125
+ contentType: file.contentType,
126
+ size,
127
+ objectKey,
128
+ expiresInDays: body.expiresInDays,
129
+ }, actor);
130
+ break;
131
+ }
132
+ catch (e) {
133
+ if (attempt < CODE_ATTEMPTS && isCodeConflict(e))
134
+ continue;
135
+ throw e;
136
+ }
137
+ }
138
+ return this.viewOf(orgId, id);
139
+ }
140
+ /**
141
+ * The row and audit of a new share. The row's org is read from the conversation here (locked
142
+ * `FOR SHARE`, so a concurrent delete waits and then revokes this share too), never taken from
143
+ * the caller; the viewer's access is checked again inside the transaction, since the copy ran
144
+ * without one. Internal: called by {@link create} only.
145
+ */
146
+ async insertShare(s, actor) {
147
+ const conv = await this.db
148
+ .selectFrom("conversations")
149
+ .select("org_id")
150
+ .where("id", "=", s.conversationId)
151
+ .where("org_id", "=", s.orgId)
152
+ .where("deleted_at", "is", null)
153
+ .forShare()
154
+ .executeTakeFirst();
155
+ if (!conv || !(await this.access.isAccessible(conv.org_id, s.conversationId, s.accountId))) {
156
+ throw conversationNotFound();
157
+ }
158
+ await this.db
159
+ .insertInto("file_shares")
160
+ .values({
161
+ id: s.id,
162
+ org_id: conv.org_id,
163
+ code: s.code,
164
+ conversation_id: s.conversationId,
165
+ file_id: s.fileId,
166
+ source_path: s.sourcePath,
167
+ created_by: s.accountId,
168
+ audience: s.audience,
169
+ name: s.name,
170
+ content_type: s.contentType,
171
+ size: s.size,
172
+ object_key: s.objectKey,
173
+ generation: 1,
174
+ expires_at: s.expiresInDays === null
175
+ ? null
176
+ : sql `now() + make_interval(days => ${s.expiresInDays})`,
177
+ })
178
+ .execute();
179
+ await audit(this.db.db, {
180
+ actorAccountId: s.accountId,
181
+ ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
182
+ orgId: conv.org_id,
183
+ action: "share.created",
184
+ target: s.id,
185
+ detail: { shareId: s.id, audience: s.audience, ...actor.auditDetail },
186
+ });
187
+ }
188
+ /**
189
+ * "Update to latest" (creator only): copies the newest available version of the share's source
190
+ * path delivered after its current snapshot as the next generation under the same code, then
191
+ * {@link commitRefresh} moves the row and owes the previous snapshot's deletion. Refreshes of one
192
+ * share are serialized by a lock (taken outside any transaction), so two never write the same
193
+ * generation's object.
194
+ */
195
+ async refresh(orgId, accountId, shareId, actor = {}) {
196
+ if (!UUID_RE.test(shareId))
197
+ throw notFound();
198
+ await this.locks.run(shareRefreshLockKey(shareId), { ttlMs: REFRESH_LOCK_TTL_MS, waitMs: REFRESH_LOCK_WAIT_MS }, async () => {
199
+ const s = await this.db
200
+ .selectFrom("file_shares")
201
+ .select(["conversation_id", "file_id", "source_path", "generation"])
202
+ .where("id", "=", shareId)
203
+ .where("org_id", "=", orgId)
204
+ .where("created_by", "=", accountId)
205
+ .where("revoked_at", "is", null)
206
+ .where(notExpired)
207
+ .executeTakeFirst();
208
+ if (!s)
209
+ throw notFound();
210
+ if (s.source_path === null) {
211
+ throw new ApiError("validation_failed", "A share of an uploaded file cannot be updated: it has no newer versions. Share the new file instead.");
212
+ }
213
+ const next = await this.files.latestAvailable(orgId, s.conversation_id, accountId, s.source_path, { after: s.file_id });
214
+ if (next === null) {
215
+ throw fileUnavailable("There is no newer available version of this file to share");
216
+ }
217
+ const generation = s.generation + 1;
218
+ const objectKey = shareObjectKey(shareId, generation);
219
+ const size = await this.copy(orgId, next, objectKey);
220
+ const moved = await this.commitRefresh({ orgId, accountId, shareId, from: s.generation }, { fileId: next.id, name: next.name, contentType: next.contentType, size, objectKey }, actor);
221
+ // revoked or expired while copying: the new snapshot was owed for deletion instead
222
+ if (!moved)
223
+ throw notFound();
224
+ });
225
+ return this.viewOf(orgId, shareId);
226
+ }
227
+ /**
228
+ * The row move of a refresh: generation `from` → `from + 1` with the new snapshot, the previous
229
+ * snapshot's deletion owed, `share.refreshed` audited. If the share was revoked or expired (or
230
+ * moved) since the copy began, nothing moves and the new snapshot's deletion is owed instead;
231
+ * returns whether it moved. Internal: called by {@link refresh} only.
232
+ */
233
+ async commitRefresh(at, snap, actor) {
234
+ const generation = at.from + 1;
235
+ const row = await this.db
236
+ .selectFrom("file_shares")
237
+ .select(["object_key"])
238
+ .where("id", "=", at.shareId)
239
+ .where("org_id", "=", at.orgId)
240
+ .where("created_by", "=", at.accountId)
241
+ .where("generation", "=", at.from)
242
+ .where("revoked_at", "is", null)
243
+ .where(notExpired)
244
+ .forUpdate()
245
+ .executeTakeFirst();
246
+ if (!row) {
247
+ await this.oweDelete(at.orgId, at.shareId, generation);
248
+ return false;
249
+ }
250
+ await this.db
251
+ .updateTable("file_shares")
252
+ .set({
253
+ generation,
254
+ file_id: snap.fileId,
255
+ name: snap.name,
256
+ content_type: snap.contentType,
257
+ size: snap.size,
258
+ object_key: snap.objectKey,
259
+ updated_at: sql `now()`,
260
+ })
261
+ .where("id", "=", at.shareId)
262
+ .execute();
263
+ if (row.object_key !== null)
264
+ await this.oweDelete(at.orgId, at.shareId, at.from);
265
+ await audit(this.db.db, {
266
+ actorAccountId: at.accountId,
267
+ ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
268
+ orgId: at.orgId,
269
+ action: "share.refreshed",
270
+ target: at.shareId,
271
+ detail: { shareId: at.shareId, generation, ...actor.auditDetail },
272
+ });
273
+ return true;
274
+ }
275
+ /**
276
+ * Revokes a share (its creator, or an org admin with `org.update`; anyone else: `share.not_found`)
277
+ * and owes its snapshot's deletion. Idempotent: an already revoked share is left as it is, with
278
+ * no second audit. An admin's role is re-read under the org row lock (taken before the share row).
279
+ */
280
+ async revoke(orgId, accountId, shareId, actor = {}) {
281
+ if (!UUID_RE.test(shareId))
282
+ throw notFound();
283
+ const found = await this.db
284
+ .selectFrom("file_shares")
285
+ .select("created_by")
286
+ .where("id", "=", shareId)
287
+ .where("org_id", "=", orgId)
288
+ .executeTakeFirst();
289
+ if (!found)
290
+ throw notFound();
291
+ let reason = "creator";
292
+ if (found.created_by !== accountId) {
293
+ try {
294
+ await this.orgLock.lockAndAuthorize(orgId, accountId, "org.update");
295
+ }
296
+ catch (e) {
297
+ if (e instanceof ApiError && e.code === "forbidden")
298
+ throw notFound();
299
+ throw e;
300
+ }
301
+ reason = "admin";
302
+ }
303
+ const s = await this.db
304
+ .selectFrom("file_shares")
305
+ .select(["revoked_at", "object_key", "generation"])
306
+ .where("id", "=", shareId)
307
+ .where("org_id", "=", orgId)
308
+ .forUpdate()
309
+ .executeTakeFirst();
310
+ if (!s)
311
+ throw notFound();
312
+ if (s.revoked_at !== null)
313
+ return;
314
+ await this.db
315
+ .updateTable("file_shares")
316
+ .set({
317
+ revoked_at: sql `now()`,
318
+ revoked_by: accountId,
319
+ revoke_reason: reason,
320
+ updated_at: sql `now()`,
321
+ })
322
+ .where("id", "=", shareId)
323
+ .execute();
324
+ if (s.object_key !== null)
325
+ await this.oweDelete(orgId, shareId, s.generation);
326
+ await audit(this.db.db, {
327
+ actorAccountId: accountId,
328
+ ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
329
+ orgId,
330
+ action: "share.revoked",
331
+ target: shareId,
332
+ detail: { shareId, reason, ...actor.auditDetail },
333
+ });
334
+ }
335
+ /**
336
+ * The live and recent shares of one file of the viewer's conversation (every share of the same
337
+ * source path, any version, or of the attachment), newest first, with the share policy.
338
+ */
339
+ async forFile(orgId, accountId, conversationId, fileId) {
340
+ const f = await this.files.identify(orgId, conversationId, accountId, fileId);
341
+ const policy = await this.policy(orgId);
342
+ const rows = await this.views(orgId)
343
+ .where("file_shares.conversation_id", "=", conversationId)
344
+ .where((eb) => f.sourcePath === null
345
+ ? eb.and([
346
+ eb("file_shares.source_path", "is", null),
347
+ eb("file_shares.file_id", "=", f.id),
348
+ ])
349
+ : eb("file_shares.source_path", "=", f.sourcePath))
350
+ .execute();
351
+ const shares = rows.map((r) => this.toView(r, policy.external));
352
+ // only a newer version that is still stored can be shared: confirm the log's answer
353
+ for (const s of shares) {
354
+ if (!s.newerVersion || s.state === "revoked" || s.sourcePath === null)
355
+ continue;
356
+ s.newerVersion =
357
+ (await this.files.latestAvailable(orgId, conversationId, accountId, s.sourcePath, {
358
+ after: s.fileId,
359
+ })) !== null;
360
+ }
361
+ return { shares, policy };
362
+ }
363
+ /**
364
+ * The org's live and recent shares: the actor's own (`mine`), or every member's (`all`, org
365
+ * admins with `org.update`, re-read live; anyone else `forbidden`). Newest first, at most
366
+ * {@link SHARES_LIST_MAX}.
367
+ */
368
+ async list(orgId, accountId, scope) {
369
+ if (scope === "all") {
370
+ const m = await this.db
371
+ .selectFrom("memberships")
372
+ .select("role")
373
+ .where("org_id", "=", orgId)
374
+ .where("account_id", "=", accountId)
375
+ .executeTakeFirst();
376
+ if (!m || !can(m.role, "org.update")) {
377
+ throw new ApiError("forbidden", "Only org admins can list every member's shares");
378
+ }
379
+ }
380
+ const { external } = await this.policy(orgId);
381
+ let q = this.views(orgId);
382
+ if (scope === "mine")
383
+ q = q.where("file_shares.created_by", "=", accountId);
384
+ const rows = await q.limit(SHARES_LIST_MAX).execute();
385
+ return { shares: rows.map((r) => this.toView(r, external)) };
386
+ }
387
+ /** One share as the lists show it (just written by this service). */
388
+ async viewOf(orgId, shareId) {
389
+ const { external } = await this.policy(orgId);
390
+ const row = await this.views(orgId, { all: true })
391
+ .where("file_shares.id", "=", shareId)
392
+ .executeTakeFirstOrThrow();
393
+ return this.toView(row, external);
394
+ }
395
+ /** The list query: shares of the org, live and recent (unless `all`), newest first. */
396
+ views(orgId, opts = {}) {
397
+ let q = this.db
398
+ .selectFrom("file_shares")
399
+ .innerJoin("accounts as creator", "creator.id", "file_shares.created_by")
400
+ .select([
401
+ "file_shares.id",
402
+ "file_shares.code",
403
+ "file_shares.audience",
404
+ "file_shares.conversation_id",
405
+ "file_shares.file_id",
406
+ "file_shares.source_path",
407
+ "file_shares.name",
408
+ "file_shares.content_type",
409
+ "file_shares.size",
410
+ "file_shares.generation",
411
+ "file_shares.created_by",
412
+ "creator.display_name",
413
+ "file_shares.created_at",
414
+ "file_shares.expires_at",
415
+ "file_shares.last_opened_at",
416
+ "file_shares.revoked_at",
417
+ "file_shares.revoke_reason",
418
+ sql `file_shares.expires_at IS NOT NULL AND file_shares.expires_at <= now()`.as("expired"),
419
+ (eb) => creatorStillHasAccess(eb).as("creator_ok"),
420
+ // a later delivery of the same source path in the conversation (refresh offered)
421
+ sql `file_shares.source_path IS NOT NULL AND EXISTS (
422
+ SELECT 1 FROM capybara.conversation_events later
423
+ WHERE later.conversation_id = file_shares.conversation_id
424
+ AND later.type = 'artifact_created'
425
+ AND later.payload->>'sourcePath' = file_shares.source_path
426
+ AND later.seq > (
427
+ SELECT e.seq FROM capybara.conversation_events e
428
+ WHERE e.conversation_id = file_shares.conversation_id
429
+ AND e.type = 'artifact_created'
430
+ AND e.payload->>'artifactId' = file_shares.file_id
431
+ LIMIT 1
432
+ )
433
+ )`.as("newer_delivery"),
434
+ ])
435
+ .where("file_shares.org_id", "=", orgId)
436
+ .orderBy("file_shares.created_at", "desc")
437
+ .orderBy("file_shares.id", "desc");
438
+ if (!opts.all) {
439
+ const since = sql `now() - make_interval(days => ${SHARE_RECENT_DAYS})`;
440
+ q = q.where((eb) => eb.or([
441
+ eb.and([
442
+ eb("file_shares.revoked_at", "is", null),
443
+ eb.or([
444
+ eb("file_shares.expires_at", "is", null),
445
+ eb("file_shares.expires_at", ">", since),
446
+ ]),
447
+ ]),
448
+ eb("file_shares.revoked_at", ">", since),
449
+ ]));
450
+ }
451
+ return q;
452
+ }
453
+ toView(r, external) {
454
+ const state = r.revoked_at !== null
455
+ ? "revoked"
456
+ : r.expired
457
+ ? "expired"
458
+ : !r.creator_ok || (r.audience === "external" && external !== "allowed")
459
+ ? "suspended"
460
+ : "live";
461
+ const publicUrl = this.config.get().http.publicUrl;
462
+ return {
463
+ id: r.id,
464
+ code: r.code,
465
+ url: publicUrl ? `${publicUrl.replace(/\/+$/, "")}/s/${r.code}` : null,
466
+ audience: r.audience,
467
+ conversationId: r.conversation_id,
468
+ fileId: r.file_id,
469
+ sourcePath: r.source_path,
470
+ name: r.name,
471
+ contentType: r.content_type,
472
+ size: Number(r.size),
473
+ generation: r.generation,
474
+ createdBy: { id: r.created_by, displayName: r.display_name },
475
+ createdAt: r.created_at.toISOString(),
476
+ expiresAt: iso(r.expires_at),
477
+ lastOpenedAt: iso(r.last_opened_at),
478
+ state,
479
+ revokedAt: iso(r.revoked_at),
480
+ revokeReason: r.revoke_reason,
481
+ newerVersion: Boolean(r.newer_delivery) && state !== "revoked",
482
+ };
483
+ }
484
+ /**
485
+ * The file to share, after the viewer's access check: a delivered version, or an attachment whose
486
+ * stored object is still the one finalize checked (else `share.file_unavailable`).
487
+ */
488
+ async fileToShare(orgId, conversationId, accountId, fileId) {
489
+ try {
490
+ return await this.files.file(orgId, conversationId, accountId, fileId);
491
+ }
492
+ catch (e) {
493
+ if (e instanceof ApiError && e.code === "conversation.artifact_removed") {
494
+ throw fileUnavailable();
495
+ }
496
+ throw e;
497
+ }
498
+ }
499
+ /**
500
+ * Streams the file's object into `objectKey` (never buffered whole); returns the snapshot's size.
501
+ * The object is gone, or an upload's object is no longer the one finalize checked →
502
+ * `share.file_unavailable`. Runs with no transaction open.
503
+ */
504
+ async copy(orgId, file, objectKey) {
505
+ const store = this.storage.kernel(orgId);
506
+ const got = await store.get(file.objectKey);
507
+ if (!got)
508
+ throw fileUnavailable();
509
+ if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
510
+ await got.body.cancel().catch(() => { });
511
+ throw fileUnavailable();
512
+ }
513
+ try {
514
+ await store.put(objectKey, got.body, {
515
+ contentType: file.contentType,
516
+ size: got.head.size,
517
+ });
518
+ }
519
+ catch (e) {
520
+ await got.body.cancel().catch(() => { });
521
+ throw e;
522
+ }
523
+ return got.head.size;
524
+ }
525
+ /** Owes the deletion of one share generation's snapshot (in the caller's transaction). */
526
+ async oweDelete(orgId, shareId, generation) {
527
+ await oweShareObjectDelete(this.outbox, orgId, shareId, generation);
528
+ }
529
+ };
530
+ __decorate([
531
+ Transactional()
532
+ ], SharesService.prototype, "insertShare", null);
533
+ __decorate([
534
+ Transactional()
535
+ ], SharesService.prototype, "commitRefresh", null);
536
+ __decorate([
537
+ Transactional()
538
+ ], SharesService.prototype, "revoke", null);
539
+ SharesService = __decorate([
540
+ Injectable(),
541
+ __param(0, Inject(KernelDb)),
542
+ __param(1, Inject(TransactionHost)),
543
+ __param(2, Inject(ConversationFiles)),
544
+ __param(3, Inject(ConversationAccess)),
545
+ __param(4, Inject(StorageService)),
546
+ __param(5, Inject(OutboxService)),
547
+ __param(6, Inject(OrgLock)),
548
+ __param(7, Inject(LockService)),
549
+ __param(8, Inject(KernelConfigService)),
550
+ __param(9, Optional()),
551
+ __param(9, Inject(KERNEL_LOGGER))
552
+ ], SharesService);
553
+ export { SharesService };
@@ -0,0 +1,72 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { LockService } from "../infra/lock/lock.service.js";
4
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
5
+ import type { KernelLogger } from "../log.js";
6
+ import { StorageService } from "../storage/storage.service.js";
7
+ import { ShareObjects } from "./share-objects.js";
8
+ /** The daily share sweep's name (scheduler key and lock; no `:`). */
9
+ export declare const SHARE_SWEEP_JOB = "share-sweep";
10
+ /** What one sweep did (logged; returned for tests). */
11
+ export interface ShareSweepResult {
12
+ /** Shares revoked with `creator_lost_access` (their snapshots owed for deletion). */
13
+ revoked: number;
14
+ /** Snapshots of shares expired or revoked more than {@link RETAIN_DAYS} days ago deleted. */
15
+ freed: number;
16
+ /** Orphan objects under `shares/` deleted. */
17
+ orphans: number;
18
+ }
19
+ /**
20
+ * The daily share sweep (file sharing spec §9), a `@LockedCron` (once per tick across replicas,
21
+ * provided only under `WorkerModule`). In order, with every storage call outside a transaction:
22
+ *
23
+ * 1. revokes with `creator_lost_access` the unrevoked, unexpired shares whose creator fails the
24
+ * live check's creator predicates (account disabled, no longer a member, agent deleted or hidden,
25
+ * the conversation or its root deleted), one transaction per batch, owing each snapshot's
26
+ * deletion through the outbox (the open routes already refuse them; this frees the snapshot and
27
+ * shows a reason in the lists);
28
+ * 2. deletes the snapshots of shares expired or revoked more than {@link RETAIN_DAYS} days ago that
29
+ * still name one (a revoke owes its deletion at once; this is the expired shares' path and the
30
+ * backstop) and clears `object_key`; the rows stay for the audit trail;
31
+ * 3. per organization not deleted, lists `shares/` and deletes every object older than one hour
32
+ * that is not the `object_key` of its row (no row: an insert that failed after its copy; another
33
+ * generation: a refresh that died between its copy and its commit). An object whose age the
34
+ * store does not report is kept. Its age is read again (`head`) just before the delete, and a
35
+ * non-current generation of an existing share is deleted only under that share's refresh lock
36
+ * (tried once), so a retried refresh writing the same key again is never undone.
37
+ *
38
+ * Steps 2 and 3 go through {@link ShareObjects.deleteObject}, which re-reads the row and never
39
+ * deletes the snapshot a share that is neither revoked nor expired currently names. Deleted
40
+ * organizations are skipped: their objects go with `storage-org-purge`. Nothing is kept in process
41
+ * memory between runs; a run that stops midway (abort, error) is finished by the next one.
42
+ */
43
+ export declare class ShareSweepJob {
44
+ private readonly db;
45
+ readonly txHost: TransactionHost;
46
+ private readonly outbox;
47
+ private readonly objects;
48
+ private readonly storage;
49
+ readonly lockService: LockService;
50
+ readonly log: KernelLogger;
51
+ constructor(db: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">, objects: Pick<ShareObjects, "deleteObject">, storage: Pick<StorageService, "available" | "kernel">, lockService: LockService, log: KernelLogger);
52
+ sweep(signal?: AbortSignal): Promise<void>;
53
+ /** One sweep without the tick lock (the cron body; tests call it directly). */
54
+ runOnce(signal?: AbortSignal): Promise<ShareSweepResult>;
55
+ /** Step 1: revokes, batch by batch, the shares whose creator lost access. */
56
+ private revokeLostAccess;
57
+ /** One batch of step 1 (the creator's access is checked again in the `UPDATE`). */
58
+ revokeBatch(shareIds: readonly string[]): Promise<number>;
59
+ /** Step 2: frees the snapshots of shares expired or revoked more than a week ago. */
60
+ private freeOld;
61
+ /** Step 3: deletes the orphan objects under `shares/` of every organization not deleted. */
62
+ private deleteOrphans;
63
+ /** The orphan objects of one organization, page by page. */
64
+ private orphansOf;
65
+ /**
66
+ * Whether `key` is still older than `cutoff` now: the listing may be stale (an upload that started
67
+ * long ago, or a key written again since), so its age is read again just before deleting it.
68
+ */
69
+ private stillOld;
70
+ /** {@link ShareObjects.deleteObject}, logging instead of throwing (one bad object stops nothing). */
71
+ private deleteGuarded;
72
+ }