@haneinfo/attachments 0.0.0-stage → 0.2.0

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 (53) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +92 -2
  3. package/agent-guide.md +93 -0
  4. package/dist/cleanup.worker.d.ts +13 -0
  5. package/dist/cleanup.worker.d.ts.map +1 -0
  6. package/dist/cleanup.worker.js +57 -0
  7. package/dist/cleanup.worker.js.map +1 -0
  8. package/dist/config.d.ts +38 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +74 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/controller.d.ts +53 -0
  13. package/dist/controller.d.ts.map +1 -0
  14. package/dist/controller.js +214 -0
  15. package/dist/controller.js.map +1 -0
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +24 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/mcp-tools.d.ts +10 -0
  21. package/dist/mcp-tools.d.ts.map +1 -0
  22. package/dist/mcp-tools.js +76 -0
  23. package/dist/mcp-tools.js.map +1 -0
  24. package/dist/module.d.ts +6 -0
  25. package/dist/module.d.ts.map +1 -0
  26. package/dist/module.js +54 -0
  27. package/dist/module.js.map +1 -0
  28. package/dist/plugin.d.ts +44 -0
  29. package/dist/plugin.d.ts.map +1 -0
  30. package/dist/plugin.js +90 -0
  31. package/dist/plugin.js.map +1 -0
  32. package/dist/service.d.ts +132 -0
  33. package/dist/service.d.ts.map +1 -0
  34. package/dist/service.js +399 -0
  35. package/dist/service.js.map +1 -0
  36. package/dist/storage.d.ts +54 -0
  37. package/dist/storage.d.ts.map +1 -0
  38. package/dist/storage.js +239 -0
  39. package/dist/storage.js.map +1 -0
  40. package/dist/store.d.ts +61 -0
  41. package/dist/store.d.ts.map +1 -0
  42. package/dist/store.js +25 -0
  43. package/dist/store.js.map +1 -0
  44. package/dist/validation.d.ts +29 -0
  45. package/dist/validation.d.ts.map +1 -0
  46. package/dist/validation.js +297 -0
  47. package/dist/validation.js.map +1 -0
  48. package/haneinfo.plugin.json +72 -0
  49. package/package.json +80 -3
  50. package/plugin.d.ts +2 -0
  51. package/plugin.js +4 -0
  52. package/prisma/attachments.prisma +32 -0
  53. package/prisma/attachments.sql +13 -0
@@ -0,0 +1,132 @@
1
+ import type { Readable } from 'node:stream';
2
+ import { type AttachmentScannerPort, type BackgroundJobContext, type BackgroundJobsPort, type FileStoragePort, type IdentityStorePort, type RbacPolicyPort } from '@haneinfo/plugin-api';
3
+ import { StateMachineRuntime } from '@haneinfo/state-machine';
4
+ import { type OnModuleInit } from '@nestjs/common';
5
+ import { type AttachmentsConfig } from './config';
6
+ import { AttachmentsStore } from './store';
7
+ export declare class AttachmentsService implements OnModuleInit {
8
+ readonly store: AttachmentsStore;
9
+ readonly storage: FileStoragePort;
10
+ private readonly jobs;
11
+ private readonly runtime;
12
+ private readonly rbac?;
13
+ private readonly identity?;
14
+ private readonly scanner?;
15
+ private readonly now;
16
+ readonly config: {
17
+ driver: "local" | "s3";
18
+ maxFileBytes: number;
19
+ maxAttachmentsPerInstance: number;
20
+ allowedTypes: ("pdf" | "png" | "jpeg" | "webp" | "gif" | "docx" | "xlsx" | "pptx" | "csv" | "txt")[];
21
+ deletedRetentionDays: number;
22
+ pendingScanTimeoutMs: number;
23
+ maxUploadMs: number;
24
+ cleanupBatchSize: number;
25
+ cleanupPollIntervalMs: number;
26
+ cleanupWorkerEnabled: boolean;
27
+ localRoot?: string | undefined;
28
+ s3?: {
29
+ bucket: string;
30
+ region: string;
31
+ forcePathStyle: boolean;
32
+ endpoint?: string | undefined;
33
+ } | undefined;
34
+ };
35
+ private readonly logger;
36
+ constructor(store: AttachmentsStore, storage: FileStoragePort, jobs: BackgroundJobsPort, runtime: StateMachineRuntime, config: AttachmentsConfig, rbac?: RbacPolicyPort | undefined, identity?: IdentityStorePort | undefined, scanner?: AttachmentScannerPort | undefined, now?: () => Date);
37
+ onModuleInit(): void;
38
+ private authorize;
39
+ private checkCount;
40
+ private quotaCount;
41
+ /** Must run before attaching a multipart parser or consuming the incoming file stream. */
42
+ preflight(userId: string, instanceId: string): Promise<void>;
43
+ private metadata;
44
+ listFor(userId: string, instanceId: string): Promise<{
45
+ items: {
46
+ id: string;
47
+ instanceId: string;
48
+ fileName: string;
49
+ declaredContentType: string;
50
+ detectedContentType: string;
51
+ size: number;
52
+ sha256: string;
53
+ status: "READY" | "PENDING_SCAN" | "REJECTED";
54
+ uploadedBy: string;
55
+ uploadedByName: string | null;
56
+ createdAt: Date;
57
+ canDelete: boolean;
58
+ }[];
59
+ canUpload: boolean;
60
+ limits: {
61
+ maxFileBytes: number;
62
+ maxAttachmentsPerInstance: number;
63
+ allowedTypes: ("pdf" | "png" | "jpeg" | "webp" | "gif" | "docx" | "xlsx" | "pptx" | "csv" | "txt")[];
64
+ count: number;
65
+ remaining: number;
66
+ };
67
+ }>;
68
+ private visible;
69
+ private notFound;
70
+ getFor(userId: string, instanceId: string, id: string): Promise<{
71
+ id: string;
72
+ instanceId: string;
73
+ fileName: string;
74
+ declaredContentType: string;
75
+ detectedContentType: string;
76
+ size: number;
77
+ sha256: string;
78
+ status: "READY" | "PENDING_SCAN" | "REJECTED";
79
+ uploadedBy: string;
80
+ uploadedByName: string | null;
81
+ createdAt: Date;
82
+ canDelete: boolean;
83
+ }>;
84
+ downloadFor(userId: string, instanceId: string, id: string): Promise<{
85
+ stream: Readable;
86
+ headers: {
87
+ 'Content-Disposition': string;
88
+ 'X-Content-Type-Options': string;
89
+ 'Cache-Control': string;
90
+ 'Content-Type': string;
91
+ 'Content-Length': string;
92
+ };
93
+ }>;
94
+ private history;
95
+ uploadFor(userId: string, instanceId: string, input: {
96
+ fileName: string;
97
+ declaredContentType: string;
98
+ stream: Readable;
99
+ complete?: Promise<void>;
100
+ }, signal?: AbortSignal): Promise<{
101
+ id: string;
102
+ instanceId: string;
103
+ fileName: string;
104
+ declaredContentType: string;
105
+ detectedContentType: string;
106
+ size: number;
107
+ sha256: string;
108
+ status: "READY" | "PENDING_SCAN" | "REJECTED";
109
+ uploadedBy: string;
110
+ uploadedByName: string | null;
111
+ createdAt: Date;
112
+ canDelete: boolean;
113
+ }>;
114
+ deleteFor(userId: string, instanceId: string, id: string): Promise<{
115
+ deleted: boolean;
116
+ }>;
117
+ private enqueueScan;
118
+ enqueueCleanup(): Promise<import("@haneinfo/plugin-api").BackgroundJobRecord>;
119
+ scan(id: string, ctx: BackgroundJobContext): Promise<{
120
+ skipped: boolean;
121
+ status?: undefined;
122
+ } | {
123
+ status: string;
124
+ skipped?: undefined;
125
+ }>;
126
+ cleanup(ctx: BackgroundJobContext): Promise<{
127
+ removed: number;
128
+ garbage: number;
129
+ staged: number;
130
+ }>;
131
+ }
132
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAEL,KAAK,qBAAqB,EAG1B,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EAEvB,KAAK,eAAe,EAGpB,KAAK,iBAAiB,EAGtB,KAAK,cAAc,EACpB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAyB,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACrF,OAAO,EAA8B,KAAK,YAAY,EAAY,MAAM,gBAAgB,CAAC;AACzF,OAAO,EAAE,KAAK,iBAAiB,EAA2B,MAAM,UAAU,CAAC;AAC3E,OAAO,EAML,gBAAgB,EAGjB,MAAM,SAAS,CAAC;AASjB,qBACa,kBAAmB,YAAW,YAAY;IAIxB,QAAQ,CAAC,KAAK,EAAE,gBAAgB;IACrC,QAAQ,CAAC,OAAO,EAAE,eAAe;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACjB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAEpB,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O,CAAC,IAAI,CAAC,CAAC;KAC1B,EACD,MAAM,CAAC,EAAE,WAAW;;;;;;;;;;;;;;IA+EhB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;;;YAsBhD,WAAW;IAiBnB,cAAc;IAGd,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,oBAAoB;;;;;;;IA0C1C,OAAO,CAAC,GAAG,EAAE,oBAAoB;;;;;CAoDxC"}
@@ -0,0 +1,399 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AttachmentsService = void 0;
16
+ const node_crypto_1 = require("node:crypto");
17
+ const promises_1 = require("node:fs/promises");
18
+ const plugin_api_1 = require("@haneinfo/plugin-api");
19
+ const state_machine_1 = require("@haneinfo/state-machine");
20
+ const common_1 = require("@nestjs/common");
21
+ const config_1 = require("./config");
22
+ const store_1 = require("./store");
23
+ const validation_1 = require("./validation");
24
+ let AttachmentsService = class AttachmentsService {
25
+ constructor(store, storage, jobs, runtime, config, rbac, identity, scanner, now = () => new Date()) {
26
+ this.store = store;
27
+ this.storage = storage;
28
+ this.jobs = jobs;
29
+ this.runtime = runtime;
30
+ this.rbac = rbac;
31
+ this.identity = identity;
32
+ this.scanner = scanner;
33
+ this.now = now;
34
+ this.logger = new common_1.Logger('AttachmentsService');
35
+ this.config = config_1.attachmentsConfigSchema.parse(config);
36
+ }
37
+ onModuleInit() {
38
+ this.jobs.register(store_1.SCAN_JOB, (params, ctx) => this.scan(params.attachmentId, ctx));
39
+ this.jobs.register(store_1.CLEANUP_JOB, (_params, ctx) => this.cleanup(ctx));
40
+ }
41
+ async authorize(tx, userId, instanceId, write = false) {
42
+ return this.store.instances.run(tx, async (instances) => {
43
+ const record = await instances.find(instanceId);
44
+ const auth = await (0, plugin_api_1.authorizationOfUser)(this.rbac, userId);
45
+ if (!record || !(await (0, state_machine_1.instanceAccessAllowed)(userId, record, auth, instances)))
46
+ throw new plugin_api_1.MechanismError('INSTANCE_NOT_FOUND', 'Instance not found', 404);
47
+ const canUpload = await (0, state_machine_1.instanceAccessAllowed)(userId, record, auth, instances, 'WRITE');
48
+ if (write && !canUpload)
49
+ throw new plugin_api_1.MechanismError('FORBIDDEN', 'Instance write access is required', 403);
50
+ return { record, canUpload, admin: (0, plugin_api_1.hasPermission)(auth, 'state-machine:instance:admin') };
51
+ });
52
+ }
53
+ async checkCount(client, instanceId) {
54
+ if ((await this.quotaCount(client, instanceId)) >= this.config.maxAttachmentsPerInstance)
55
+ throw new plugin_api_1.MechanismError('ATTACHMENT_LIMIT_EXCEEDED', 'The instance attachment limit has been reached', 409);
56
+ }
57
+ quotaCount(client, instanceId) {
58
+ return client.attachment.count({
59
+ where: { instanceId, deletedAt: null, status: { in: ['READY', 'PENDING_SCAN'] } },
60
+ });
61
+ }
62
+ /** Must run before attaching a multipart parser or consuming the incoming file stream. */
63
+ async preflight(userId, instanceId) {
64
+ return this.store.run(undefined, async (client, tx) => {
65
+ await this.authorize(tx, userId, instanceId, true);
66
+ await this.checkCount(client, instanceId);
67
+ });
68
+ }
69
+ async metadata(records, userId, admin, tx) {
70
+ const ids = [...new Set(records.map((record) => record.uploadedBy))];
71
+ const names = new Map(ids.length && this.identity?.findActiveNamesByIds
72
+ ? (await this.identity.findActiveNamesByIds(ids, tx)).map((user) => [user.id, user.name])
73
+ : []);
74
+ return records.map((record) => ({
75
+ id: record.id,
76
+ instanceId: record.instanceId,
77
+ fileName: record.fileName,
78
+ declaredContentType: record.declaredContentType,
79
+ detectedContentType: record.detectedContentType,
80
+ size: Number(record.size),
81
+ sha256: record.sha256,
82
+ status: record.status,
83
+ uploadedBy: record.uploadedBy,
84
+ uploadedByName: names.get(record.uploadedBy) ?? null,
85
+ createdAt: record.createdAt,
86
+ canDelete: admin || record.uploadedBy === userId,
87
+ }));
88
+ }
89
+ async listFor(userId, instanceId) {
90
+ return this.store.run(undefined, async (client, tx) => {
91
+ const { admin, canUpload } = await this.authorize(tx, userId, instanceId);
92
+ const records = await client.attachment.findMany({
93
+ where: { instanceId, deletedAt: null },
94
+ orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
95
+ });
96
+ const count = await this.quotaCount(client, instanceId);
97
+ return {
98
+ items: await this.metadata(records, userId, admin, tx),
99
+ canUpload,
100
+ limits: {
101
+ maxFileBytes: this.config.maxFileBytes,
102
+ maxAttachmentsPerInstance: this.config.maxAttachmentsPerInstance,
103
+ allowedTypes: [...this.config.allowedTypes],
104
+ count,
105
+ remaining: Math.max(0, this.config.maxAttachmentsPerInstance - count),
106
+ },
107
+ };
108
+ });
109
+ }
110
+ async visible(client, instanceId, id) {
111
+ const record = await client.attachment.findUnique({ where: { id } });
112
+ if (!record || record.instanceId !== instanceId || record.deletedAt)
113
+ throw this.notFound();
114
+ return record;
115
+ }
116
+ notFound() {
117
+ return new plugin_api_1.MechanismError('ATTACHMENT_NOT_FOUND', 'Attachment not found', 404);
118
+ }
119
+ async getFor(userId, instanceId, id) {
120
+ return this.store.run(undefined, async (client, tx) => {
121
+ const { admin } = await this.authorize(tx, userId, instanceId);
122
+ return (await this.metadata([await this.visible(client, instanceId, id)], userId, admin, tx))[0];
123
+ });
124
+ }
125
+ async downloadFor(userId, instanceId, id) {
126
+ const record = await this.store.run(undefined, async (client, tx) => {
127
+ await this.authorize(tx, userId, instanceId);
128
+ const record = await this.visible(client, instanceId, id);
129
+ if (record.status !== 'READY')
130
+ throw this.notFound();
131
+ return record;
132
+ });
133
+ try {
134
+ return {
135
+ stream: await this.storage.get(record.storageKey),
136
+ headers: (0, validation_1.downloadHeaders)(record),
137
+ };
138
+ }
139
+ catch (error) {
140
+ if (error.code === 'ENOENT' ||
141
+ error.name === 'NoSuchKey')
142
+ throw this.notFound();
143
+ throw error;
144
+ }
145
+ }
146
+ async history(tx, record, action, userId) {
147
+ await this.store.instances.run(tx, async (instances) => {
148
+ const instance = await instances.find(record.instanceId);
149
+ if (!instance)
150
+ throw new plugin_api_1.MechanismError('INSTANCE_NOT_FOUND', 'Instance not found', 404);
151
+ await instances.appendHistory({
152
+ instanceId: record.instanceId,
153
+ transition: null,
154
+ fromState: instance.state,
155
+ toState: instance.state,
156
+ triggerType: 'ATTACHMENT',
157
+ triggerUserId: userId,
158
+ triggerRef: null,
159
+ at: this.now(),
160
+ decision: { attachment: { action, id: record.id, fileName: record.fileName } },
161
+ });
162
+ });
163
+ }
164
+ async uploadFor(userId, instanceId, input, signal) {
165
+ await this.preflight(userId, instanceId);
166
+ const { fileName, extension } = (0, validation_1.cleanFileName)(input.fileName);
167
+ if (!this.config.allowedTypes.includes(extension))
168
+ throw new plugin_api_1.MechanismError('ATTACHMENT_TYPE_NOT_ALLOWED', 'The file type is not allowed');
169
+ const id = (0, node_crypto_1.randomUUID)(), at = this.now();
170
+ const storageKey = `attachments/${at.getUTCFullYear()}/${String(at.getUTCMonth() + 1).padStart(2, '0')}/${id}`;
171
+ const abort = new AbortController();
172
+ const onAbort = () => abort.abort(signal?.reason);
173
+ signal?.addEventListener('abort', onAbort, { once: true });
174
+ if (signal?.aborted)
175
+ onAbort();
176
+ const timer = setTimeout(() => abort.abort(), this.config.maxUploadMs);
177
+ timer.unref?.();
178
+ let staged, marked = false;
179
+ try {
180
+ staged = await (0, validation_1.stageUpload)(input.stream, id, extension, this.config, abort.signal);
181
+ // Wait for the entire multipart envelope: extra fields/files must prevent any commit.
182
+ await input.complete;
183
+ abort.signal.throwIfAborted();
184
+ await this.store.db.attachmentGarbage.create({
185
+ data: { storageKey, notBefore: new Date(at.getTime() + 60 * 60 * 1000) },
186
+ });
187
+ marked = true;
188
+ const written = await this.storage.put(storageKey, (0, validation_1.createReadStream)(staged.file), {
189
+ contentType: staged.detectedContentType,
190
+ signal: abort.signal,
191
+ });
192
+ if (written.size !== staged.size)
193
+ throw new Error('Storage byte count mismatch');
194
+ const record = await this.store.run(undefined, async (client, tx) => {
195
+ await this.runtime.get(instanceId, tx, { lock: true });
196
+ await this.authorize(tx, userId, instanceId, true);
197
+ await this.checkCount(client, instanceId);
198
+ abort.signal.throwIfAborted();
199
+ const record = await client.attachment.create({
200
+ data: {
201
+ id,
202
+ instanceId,
203
+ fileName,
204
+ declaredContentType: input.declaredContentType.slice(0, 200),
205
+ detectedContentType: staged?.detectedContentType,
206
+ size: BigInt(staged?.size ?? 0),
207
+ sha256: staged?.sha256,
208
+ storageKey,
209
+ status: this.scanner ? 'PENDING_SCAN' : 'READY',
210
+ uploadedBy: userId,
211
+ createdAt: at,
212
+ },
213
+ });
214
+ await this.history(tx, record, 'UPLOADED', userId);
215
+ await client.attachmentGarbage.deleteMany({ where: { storageKey } });
216
+ return record;
217
+ });
218
+ marked = false;
219
+ if (this.scanner)
220
+ await this.enqueueScan(record).catch(() => this.logger.error('Attachment scan enqueue failed; cleanup will recover it'));
221
+ return await this.getFor(userId, instanceId, record.id);
222
+ }
223
+ catch (error) {
224
+ input.stream.destroy();
225
+ if (marked) {
226
+ try {
227
+ const committed = await this.store.db.attachment.findUnique({ where: { storageKey } });
228
+ if (!committed)
229
+ await this.storage.delete(storageKey);
230
+ await this.store.db.attachmentGarbage.deleteMany({ where: { storageKey } });
231
+ }
232
+ catch {
233
+ this.logger.error('Attachment rollback left a durable garbage marker');
234
+ }
235
+ }
236
+ throw error;
237
+ }
238
+ finally {
239
+ clearTimeout(timer);
240
+ signal?.removeEventListener('abort', onAbort);
241
+ if (staged)
242
+ await (0, promises_1.rm)(staged.file, { force: true });
243
+ }
244
+ }
245
+ async deleteFor(userId, instanceId, id) {
246
+ return this.store.run(undefined, async (client, tx) => {
247
+ await this.runtime.get(instanceId, tx, { lock: true });
248
+ const { admin } = await this.authorize(tx, userId, instanceId);
249
+ const record = await client.attachment.findUnique({ where: { id } });
250
+ if (!record || record.instanceId !== instanceId)
251
+ return { deleted: true };
252
+ if (!admin && record.uploadedBy !== userId)
253
+ throw new plugin_api_1.MechanismError('FORBIDDEN', 'Only the uploader or an instance administrator may delete this attachment', 403);
254
+ if (!record.deletedAt) {
255
+ await client.attachment.update({
256
+ where: { id },
257
+ data: { deletedAt: this.now(), deletedBy: userId },
258
+ });
259
+ await this.history(tx, record, 'DELETED', userId);
260
+ }
261
+ return { deleted: true };
262
+ });
263
+ }
264
+ async enqueueScan(record) {
265
+ if (await this.store.db.backgroundJob.findFirst({
266
+ where: {
267
+ type: store_1.SCAN_JOB,
268
+ status: { in: ['PENDING', 'RUNNING'] },
269
+ params: { path: ['attachmentId'], equals: record.id },
270
+ },
271
+ }))
272
+ return;
273
+ await this.jobs.enqueue({
274
+ type: store_1.SCAN_JOB,
275
+ params: { attachmentId: record.id },
276
+ createdBy: record.uploadedBy,
277
+ });
278
+ }
279
+ async enqueueCleanup() {
280
+ return this.jobs.enqueue({ type: store_1.CLEANUP_JOB, params: {}, createdBy: 'system:attachments' });
281
+ }
282
+ async scan(id, ctx) {
283
+ return this.store.run(ctx.tx, async (client) => {
284
+ const record = await this.store.lock(client, id);
285
+ if (!record || record.deletedAt || record.status !== 'PENDING_SCAN')
286
+ return { skipped: true };
287
+ if (!this.scanner)
288
+ throw new Error('Pending attachment requires its scanner to be restored');
289
+ let stream;
290
+ try {
291
+ stream = await this.storage.get(record.storageKey);
292
+ }
293
+ catch (error) {
294
+ if (error.code !== 'ENOENT' &&
295
+ error.name !== 'NoSuchKey')
296
+ throw error;
297
+ // A previous rejection may have deleted content before its DB transaction rolled back.
298
+ await client.attachment.update({ where: { id }, data: { status: 'REJECTED' } });
299
+ return { status: 'REJECTED' };
300
+ }
301
+ const onAbort = () => stream.destroy(new Error('Scan cancelled'));
302
+ ctx.signal.addEventListener('abort', onAbort, { once: true });
303
+ try {
304
+ const result = await this.scanner.scan(stream, {
305
+ id,
306
+ fileName: record.fileName,
307
+ contentType: record.detectedContentType,
308
+ size: Number(record.size),
309
+ sha256: record.sha256,
310
+ });
311
+ await ctx.checkpoint();
312
+ if (result.status === 'CLEAN')
313
+ await client.attachment.update({ where: { id }, data: { status: 'READY' } });
314
+ else {
315
+ await this.storage.delete(record.storageKey);
316
+ await client.attachment.update({ where: { id }, data: { status: 'REJECTED' } });
317
+ }
318
+ return { status: result.status };
319
+ }
320
+ finally {
321
+ ctx.signal.removeEventListener('abort', onAbort);
322
+ stream.destroy();
323
+ }
324
+ });
325
+ }
326
+ async cleanup(ctx) {
327
+ const now = this.now(), before = new Date(now.getTime() - this.config.deletedRetentionDays * 86400000);
328
+ const stale = new Date(now.getTime() - this.config.pendingScanTimeoutMs);
329
+ const limit = this.config.cleanupBatchSize;
330
+ const client = ctx.tx;
331
+ const records = await client.attachment.findMany({
332
+ where: {
333
+ OR: [
334
+ { deletedAt: { lte: before } },
335
+ { status: 'REJECTED', deletedAt: null, createdAt: { lte: before } },
336
+ { status: 'PENDING_SCAN', deletedAt: null },
337
+ ],
338
+ },
339
+ orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
340
+ take: limit,
341
+ });
342
+ let removed = 0;
343
+ for (const candidate of records) {
344
+ await ctx.checkpoint();
345
+ const record = await this.store.lock(client, candidate.id);
346
+ if (!record)
347
+ continue;
348
+ const expiredDeletion = record.deletedAt && record.deletedAt <= before;
349
+ if (record.deletedAt && !expiredDeletion)
350
+ continue;
351
+ if (record.status === 'PENDING_SCAN' && !record.deletedAt && record.createdAt > stale) {
352
+ if (this.scanner)
353
+ await this.enqueueScan(record);
354
+ continue;
355
+ }
356
+ if (record.status === 'PENDING_SCAN' && record.createdAt <= stale)
357
+ await client.attachment.update({ where: { id: record.id }, data: { status: 'REJECTED' } });
358
+ if (record.status !== 'READY' || expiredDeletion)
359
+ await this.storage.delete(record.storageKey);
360
+ if (expiredDeletion || (record.status !== 'READY' && record.createdAt <= before)) {
361
+ await client.attachment.deleteMany({ where: { id: record.id } });
362
+ removed++;
363
+ }
364
+ }
365
+ const garbage = await client.attachmentGarbage.findMany({
366
+ where: { notBefore: { lte: now } },
367
+ orderBy: { notBefore: 'asc' },
368
+ take: limit,
369
+ });
370
+ for (const item of garbage) {
371
+ await ctx.checkpoint();
372
+ // A commit with an ambiguous response must never delete a referenced object.
373
+ if (!(await client.attachment.findUnique({ where: { storageKey: item.storageKey } })))
374
+ await this.storage.delete(item.storageKey);
375
+ await client.attachmentGarbage.deleteMany({ where: { storageKey: item.storageKey } });
376
+ }
377
+ const staged = await (0, validation_1.cleanupStaging)(new Date(now.getTime() - 60 * 60 * 1000), limit);
378
+ return { removed, garbage: garbage.length, staged };
379
+ }
380
+ };
381
+ exports.AttachmentsService = AttachmentsService;
382
+ exports.AttachmentsService = AttachmentsService = __decorate([
383
+ (0, common_1.Injectable)(),
384
+ __param(0, (0, common_1.Inject)(store_1.ATTACHMENTS_STORE)),
385
+ __param(1, (0, common_1.Inject)(plugin_api_1.FILE_STORAGE)),
386
+ __param(2, (0, common_1.Inject)(plugin_api_1.BACKGROUND_JOBS)),
387
+ __param(3, (0, common_1.Inject)(state_machine_1.StateMachineRuntime)),
388
+ __param(4, (0, common_1.Inject)(store_1.ATTACHMENTS_CONFIG)),
389
+ __param(5, (0, common_1.Optional)()),
390
+ __param(5, (0, common_1.Inject)(plugin_api_1.RBAC_POLICY)),
391
+ __param(6, (0, common_1.Optional)()),
392
+ __param(6, (0, common_1.Inject)(plugin_api_1.IDENTITY_STORE)),
393
+ __param(7, (0, common_1.Optional)()),
394
+ __param(7, (0, common_1.Inject)(plugin_api_1.ATTACHMENT_SCANNER)),
395
+ __param(8, (0, common_1.Optional)()),
396
+ __param(8, (0, common_1.Inject)(store_1.ATTACHMENTS_CLOCK)),
397
+ __metadata("design:paramtypes", [store_1.AttachmentsStore, Object, Object, state_machine_1.StateMachineRuntime, Object, Object, Object, Object, Function])
398
+ ], AttachmentsService);
399
+ //# sourceMappingURL=service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,6CAAyC;AACzC,+CAAsC;AAEtC,qDAe8B;AAC9B,2DAAqF;AACrF,2CAAyF;AACzF,qCAA2E;AAC3E,mCASiB;AACjB,6CAMsB;AAGf,IAAM,kBAAkB,GAAxB,MAAM,kBAAkB;IAG7B,YAC6B,KAAgC,EACrC,OAAiC,EAC9B,IAAyC,EACrC,OAA6C,EAC9C,MAAyB,EACpB,IAAsC,EACnC,QAA6C,EACzC,OAAgD,EACjD,MAAmC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE;QARtD,UAAK,GAAL,KAAK,CAAkB;QAC5B,YAAO,GAAP,OAAO,CAAiB;QACb,SAAI,GAAJ,IAAI,CAAoB;QACpB,YAAO,GAAP,OAAO,CAAqB;QAExB,SAAI,GAAJ,IAAI,CAAiB;QAClB,aAAQ,GAAR,QAAQ,CAAoB;QACxB,YAAO,GAAP,OAAO,CAAwB;QAChC,QAAG,GAAH,GAAG,CAA+B;QAV3E,WAAM,GAAG,IAAI,eAAM,CAAC,oBAAoB,CAAC,CAAC;QAYzD,IAAI,CAAC,MAAM,GAAG,gCAAuB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtD,CAAC;IAED,YAAY;QACV,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,gBAAQ,EAAE,CAAC,MAAM,EAA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ResolvedAttachmentsConfig } from './config';
4
+ export declare function validateStorageKey(key: string): void;
5
+ export declare class LocalFileStorage implements FileStoragePort {
6
+ private readonly root;
7
+ constructor(root: string);
8
+ private target;
9
+ put(key: string, stream: Readable, options?: {
10
+ signal?: AbortSignal;
11
+ }): Promise<{
12
+ size: number;
13
+ }>;
14
+ get(key: string): Promise<import("fs").ReadStream>;
15
+ delete(key: string): Promise<void>;
16
+ exists(key: string): Promise<boolean>;
17
+ }
18
+ type S3Options = NonNullable<ResolvedAttachmentsConfig['s3']>;
19
+ interface S3ClientLike {
20
+ send(command: unknown): Promise<{
21
+ Body?: unknown;
22
+ }>;
23
+ destroy?(): void;
24
+ }
25
+ interface S3Dependencies {
26
+ client: S3ClientLike;
27
+ command(kind: 'get' | 'head' | 'delete', input: Record<string, unknown>): unknown;
28
+ upload(input: Record<string, unknown>): {
29
+ done(): Promise<unknown>;
30
+ abort(): Promise<void>;
31
+ };
32
+ }
33
+ export type S3ClientFactory = (config: S3Options) => Promise<S3Dependencies>;
34
+ /** Variable imports keep the SDK optional, including in local-driver builds. */
35
+ export declare const defaultS3ClientFactory: S3ClientFactory;
36
+ export declare class S3FileStorage implements FileStoragePort {
37
+ private readonly config;
38
+ private readonly deps;
39
+ private constructor();
40
+ static create(config: S3Options, factory?: S3ClientFactory): Promise<S3FileStorage>;
41
+ private input;
42
+ put(key: string, stream: Readable, options?: {
43
+ contentType?: string;
44
+ signal?: AbortSignal;
45
+ }): Promise<{
46
+ size: number;
47
+ }>;
48
+ get(key: string): Promise<Readable>;
49
+ delete(key: string): Promise<void>;
50
+ exists(key: string): Promise<boolean>;
51
+ onModuleDestroy(): void;
52
+ }
53
+ export {};
54
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAa,MAAM,aAAa,CAAC;AAElD,OAAO,KAAK,EAAE,eA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