@meith/attachments 0.16.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.
package/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@meith/attachments",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/attachments"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "exports": {
14
+ ".": "./src/index.ts",
15
+ "./limits": "./src/limits.ts",
16
+ "./types": "./src/types.ts"
17
+ },
18
+ "files": [
19
+ "src",
20
+ "!src/**/*.test.*",
21
+ "!src/**/*.type-test.*"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "dependencies": {
27
+ "@meith/core": "0.16.0",
28
+ "@meith/i18n": "0.16.0"
29
+ }
30
+ }
@@ -0,0 +1,85 @@
1
+ import type { AttachmentType } from './types'
2
+
3
+ export interface Dimensions {
4
+ readonly width: number
5
+ readonly height: number
6
+ }
7
+
8
+ function readUint32BE(bytes: Uint8Array, at: number): number | undefined {
9
+ if (at + 4 > bytes.length) return undefined
10
+ return (
11
+ (((bytes[at] as number) << 24) |
12
+ ((bytes[at + 1] as number) << 16) |
13
+ ((bytes[at + 2] as number) << 8) |
14
+ (bytes[at + 3] as number)) >>>
15
+ 0
16
+ )
17
+ }
18
+
19
+ function readUint16BE(bytes: Uint8Array, at: number): number | undefined {
20
+ if (at + 2 > bytes.length) return undefined
21
+ return ((bytes[at] as number) << 8) | (bytes[at + 1] as number)
22
+ }
23
+
24
+ function pngDimensions(bytes: Uint8Array): Dimensions | undefined {
25
+ const isIhdr =
26
+ bytes[12] === 0x49 && bytes[13] === 0x48 && bytes[14] === 0x44 && bytes[15] === 0x52
27
+ if (!isIhdr) return undefined
28
+
29
+ const width = readUint32BE(bytes, 16)
30
+ const height = readUint32BE(bytes, 20)
31
+ if (width === undefined || height === undefined) return undefined
32
+ if (width === 0 || height === 0) return undefined
33
+ return { width, height }
34
+ }
35
+
36
+ const JPEG_START_OF_FRAME = new Set([
37
+ 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
38
+ ])
39
+
40
+ function jpegDimensions(bytes: Uint8Array): Dimensions | undefined {
41
+ let at = 2
42
+
43
+ while (at + 4 <= bytes.length) {
44
+ if (bytes[at] !== 0xff) return undefined
45
+
46
+ const marker = bytes[at + 1] as number
47
+ if (marker === 0xff) {
48
+ at += 1
49
+ continue
50
+ }
51
+ if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd9)) {
52
+ at += 2
53
+ continue
54
+ }
55
+
56
+ const length = readUint16BE(bytes, at + 2)
57
+ if (length === undefined || length < 2) return undefined
58
+
59
+ if (JPEG_START_OF_FRAME.has(marker)) {
60
+ const height = readUint16BE(bytes, at + 5)
61
+ const width = readUint16BE(bytes, at + 7)
62
+ if (width === undefined || height === undefined) return undefined
63
+ if (width === 0 || height === 0) return undefined
64
+ return { width, height }
65
+ }
66
+
67
+ at += 2 + length
68
+ }
69
+
70
+ return undefined
71
+ }
72
+
73
+ export function declaredDimensions(
74
+ bytes: Uint8Array,
75
+ type: AttachmentType,
76
+ ): Dimensions | undefined {
77
+ switch (type.codec) {
78
+ case 'png':
79
+ return pngDimensions(bytes)
80
+ case 'jpeg':
81
+ return jpegDimensions(bytes)
82
+ default:
83
+ return undefined
84
+ }
85
+ }
@@ -0,0 +1,27 @@
1
+ import type { AttachmentType } from './types'
2
+
3
+ export const MAX_FILENAME_LENGTH = 100
4
+
5
+ const UNSAFE = /[^A-Za-z0-9._ -]+/g
6
+
7
+ const EDGES = /^[.\s]+|[.\s]+$/g
8
+
9
+ export function sanitiseFilename(raw: string, type: AttachmentType): string {
10
+ const extension = type.extensions[0] as string
11
+
12
+ const base = raw.split(/[\\/]/).pop() ?? ''
13
+
14
+ const stem = base
15
+ .replace(/\.[^.]*$/, '')
16
+ .replace(UNSAFE, '-')
17
+ .replace(/-{2,}/g, '-')
18
+ .replace(EDGES, '')
19
+ .slice(0, MAX_FILENAME_LENGTH - extension.length - 1)
20
+ .replace(EDGES, '')
21
+
22
+ return `${stem === '' ? 'file' : stem}.${extension}`
23
+ }
24
+
25
+ export function storageKeyFor(purpose: 'source' | 'file' | 'thumb', random: () => string): string {
26
+ return `attachments/${random()}/${purpose}`
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,47 @@
1
+ export { type Dimensions, declaredDimensions } from './dimensions'
2
+ export {
3
+ MAX_FILENAME_LENGTH,
4
+ sanitiseFilename,
5
+ storageKeyFor,
6
+ } from './filename'
7
+ export {
8
+ HARD_MAX_BYTES,
9
+ HARD_MAX_PER_POST,
10
+ maxBytesFor,
11
+ maxPerPostFor,
12
+ type UploadLimits,
13
+ } from './limits'
14
+ export {
15
+ type AttachmentForDownload,
16
+ type AttachmentRepository,
17
+ AttachmentService,
18
+ type AttachmentServiceDeps,
19
+ acceptFile,
20
+ acceptFiles,
21
+ type CreateAttachmentInput,
22
+ type ImageProcessor,
23
+ isViewable,
24
+ MAX_IMAGE,
25
+ MAX_MEGAPIXELS,
26
+ ORPHAN_GRACE_MINUTES,
27
+ PROCESSING_GRACE_MINUTES,
28
+ type ProcessedImage,
29
+ type ReadyInput,
30
+ type StagedUpload,
31
+ THUMBNAIL,
32
+ THUMBNAIL_THRESHOLD,
33
+ } from './service'
34
+ export {
35
+ ACCEPTED_EXTENSIONS,
36
+ type AcceptedUpload,
37
+ ATTACHMENT_FIELD,
38
+ ATTACHMENT_TYPES,
39
+ type AttachmentHandling,
40
+ type AttachmentRecord,
41
+ type AttachmentStatus,
42
+ type AttachmentType,
43
+ attachmentType,
44
+ type IncomingFile,
45
+ MAGIC_BYTES_NEEDED,
46
+ sniff,
47
+ } from './types'
package/src/limits.ts ADDED
@@ -0,0 +1,17 @@
1
+ export const HARD_MAX_BYTES = 16 * 1024 * 1024
2
+ export const HARD_MAX_PER_POST = 10
3
+
4
+ export interface UploadLimits {
5
+ readonly maxPerPost: number
6
+ readonly maxSizeKb: number
7
+ }
8
+
9
+ export function maxBytesFor(limits: UploadLimits): number {
10
+ const configured = limits.maxSizeKb <= 0 ? HARD_MAX_BYTES : limits.maxSizeKb * 1024
11
+ return Math.min(configured, HARD_MAX_BYTES)
12
+ }
13
+
14
+ export function maxPerPostFor(limits: UploadLimits): number {
15
+ const configured = limits.maxPerPost <= 0 ? HARD_MAX_PER_POST : limits.maxPerPost
16
+ return Math.min(configured, HARD_MAX_PER_POST)
17
+ }
package/src/service.ts ADDED
@@ -0,0 +1,377 @@
1
+ import type { FileStore } from '@meith/core'
2
+ import { ValidationError } from '@meith/core'
3
+ import { msg } from '@meith/i18n'
4
+
5
+ import { declaredDimensions } from './dimensions'
6
+ import { sanitiseFilename, storageKeyFor } from './filename'
7
+ import { maxBytesFor, maxPerPostFor, type UploadLimits } from './limits'
8
+ import {
9
+ type AcceptedUpload,
10
+ type AttachmentRecord,
11
+ type AttachmentType,
12
+ type IncomingFile,
13
+ MAGIC_BYTES_NEEDED,
14
+ sniff,
15
+ } from './types'
16
+
17
+ export const MAX_MEGAPIXELS = 50
18
+
19
+ export const MAX_IMAGE = { width: 2000, height: 2000 } as const
20
+ export const THUMBNAIL = { width: 320, height: 320 } as const
21
+
22
+ export const THUMBNAIL_THRESHOLD = THUMBNAIL.width
23
+
24
+ export function acceptFile(file: IncomingFile, limits: UploadLimits): AcceptedUpload {
25
+ const shown = file.filename.slice(0, 60)
26
+
27
+ if (file.bytes.length === 0) {
28
+ throw new ValidationError(msg('error.attachments.empty', { name: shown }))
29
+ }
30
+
31
+ const maxBytes = maxBytesFor(limits)
32
+ if (file.bytes.length > maxBytes) {
33
+ throw new ValidationError(
34
+ msg('error.attachments.too-large', {
35
+ name: shown,
36
+ size: describeSize(file.bytes.length),
37
+ limit: describeSize(maxBytes),
38
+ }),
39
+ )
40
+ }
41
+
42
+ if (file.bytes.length < MAGIC_BYTES_NEEDED) {
43
+ throw new ValidationError(msg('error.attachments.too-short', { name: shown }))
44
+ }
45
+
46
+ const type = sniff(file.bytes)
47
+ if (type === undefined) {
48
+ throw new ValidationError(msg('error.attachments.bad-type', { name: shown }))
49
+ }
50
+
51
+ if (type.codec !== null) {
52
+ const size = declaredDimensions(file.bytes, type)
53
+ if (size === undefined) {
54
+ throw new ValidationError(msg('error.attachments.damaged', { name: shown }))
55
+ }
56
+ if ((size.width * size.height) / 1_000_000 > MAX_MEGAPIXELS) {
57
+ throw new ValidationError(
58
+ msg('error.attachments.too-many-pixels', {
59
+ name: shown,
60
+ width: size.width,
61
+ height: size.height,
62
+ max: MAX_MEGAPIXELS,
63
+ }),
64
+ )
65
+ }
66
+ }
67
+
68
+ return { filename: sanitiseFilename(file.filename, type), type, bytes: file.bytes }
69
+ }
70
+
71
+ export function acceptFiles(
72
+ files: readonly IncomingFile[],
73
+ limits: UploadLimits,
74
+ existing = 0,
75
+ ): readonly AcceptedUpload[] {
76
+ const cap = maxPerPostFor(limits)
77
+ if (existing + files.length > cap) {
78
+ throw new ValidationError(msg('error.attachments.per-post', { max: cap }))
79
+ }
80
+ return files.map((file) => acceptFile(file, limits))
81
+ }
82
+
83
+ function describeSize(bytes: number): string {
84
+ if (bytes >= 1024 * 1024) return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`
85
+ return `${Math.max(1, Math.round(bytes / 1024))} KB`
86
+ }
87
+
88
+ export interface ProcessedImage {
89
+ readonly bytes: Uint8Array
90
+ readonly contentType: string
91
+ readonly width: number
92
+ readonly height: number
93
+ readonly thumbnail?: {
94
+ readonly bytes: Uint8Array
95
+ readonly contentType: string
96
+ }
97
+ }
98
+
99
+ export interface ImageProcessor {
100
+ process(input: {
101
+ readonly bytes: Uint8Array
102
+ readonly codec: 'png' | 'jpeg'
103
+ readonly fit?: { readonly width: number; readonly height: number }
104
+ readonly thumbnail?: boolean
105
+ }): Promise<ProcessedImage>
106
+ }
107
+
108
+ export interface CreateAttachmentInput {
109
+ readonly postId: number | null
110
+ readonly forumId: number
111
+ readonly uploaderUserId: number
112
+ readonly filename: string
113
+ readonly contentType: string
114
+ readonly sizeBytes: number
115
+ readonly sourceKey: string | null
116
+ readonly storageKey: string | null
117
+ readonly status: 'pending' | 'ready'
118
+ }
119
+
120
+ export interface ReadyInput {
121
+ readonly storageKey: string
122
+ readonly thumbnailKey: string | null
123
+ readonly width: number | null
124
+ readonly height: number | null
125
+ readonly sizeBytes: number
126
+ }
127
+
128
+ export interface AttachmentForDownload {
129
+ readonly record: AttachmentRecord
130
+ readonly postVisibility: string
131
+ readonly threadVisibility: string
132
+ readonly threadAuthorUserId: number | null
133
+ }
134
+
135
+ export interface AttachmentRepository {
136
+ create(input: CreateAttachmentInput): Promise<AttachmentRecord>
137
+ findById(id: number): Promise<AttachmentRecord | null>
138
+ findForDownload(id: number): Promise<AttachmentForDownload | null>
139
+ listForPosts(postIds: readonly number[]): Promise<readonly AttachmentRecord[]>
140
+ countForPost(postId: number): Promise<number>
141
+ markReady(id: number, input: ReadyInput): Promise<void>
142
+ markFailed(id: number, reason: string): Promise<void>
143
+ recordDownload(id: number): Promise<void>
144
+ stalled(before: Date, limit: number): Promise<readonly AttachmentRecord[]>
145
+
146
+ attachTo(id: number, postId: number): Promise<AttachmentRecord | null>
147
+ deleteOrphans(before: Date, limit: number): Promise<readonly AttachmentRecord[]>
148
+
149
+ rememberKey(key: string): Promise<void>
150
+ forgetKeys(keys: readonly string[]): Promise<void>
151
+ staleKeys(before: Date, limit: number): Promise<readonly string[]>
152
+ }
153
+
154
+ export interface AttachmentServiceDeps {
155
+ readonly attachments: AttachmentRepository
156
+ readonly files: FileStore
157
+ readonly images: ImageProcessor
158
+ readonly random?: () => string
159
+ readonly now?: () => Date
160
+ }
161
+
162
+ export const ORPHAN_GRACE_MINUTES = 60
163
+
164
+ export const PROCESSING_GRACE_MINUTES = 30
165
+
166
+ export class AttachmentService {
167
+ private readonly deps: AttachmentServiceDeps
168
+ private readonly random: () => string
169
+ private readonly now: () => Date
170
+
171
+ constructor(deps: AttachmentServiceDeps) {
172
+ this.deps = deps
173
+ this.random = deps.random ?? defaultRandom
174
+ this.now = deps.now ?? (() => new Date())
175
+ }
176
+
177
+ async stage(uploads: readonly AcceptedUpload[]): Promise<readonly StagedUpload[]> {
178
+ const staged: StagedUpload[] = []
179
+ for (const upload of uploads) {
180
+ const opaque = upload.type.handling === 'opaque'
181
+ const key = storageKeyFor(opaque ? 'file' : 'source', this.random)
182
+
183
+ await this.deps.attachments.rememberKey(key)
184
+ await this.deps.files.put(key, upload.bytes, {
185
+ contentType: upload.type.contentType,
186
+ visibility: 'private',
187
+ })
188
+
189
+ staged.push({ upload, key, opaque })
190
+ }
191
+ return staged
192
+ }
193
+
194
+ async attach(
195
+ staged: readonly StagedUpload[],
196
+ post: { readonly postId: number; readonly forumId: number; readonly userId: number },
197
+ ): Promise<readonly AttachmentRecord[]> {
198
+ const created: AttachmentRecord[] = []
199
+
200
+ for (const item of staged) {
201
+ const record = await this.deps.attachments.create({
202
+ postId: post.postId,
203
+ forumId: post.forumId,
204
+ uploaderUserId: post.userId,
205
+ filename: item.upload.filename,
206
+ contentType: item.upload.type.contentType,
207
+ sizeBytes: item.upload.bytes.length,
208
+ sourceKey: item.opaque ? null : item.key,
209
+ storageKey: item.opaque ? item.key : null,
210
+ status: item.opaque ? 'ready' : 'pending',
211
+ })
212
+ await this.deps.attachments.forgetKeys([item.key])
213
+ created.push(record)
214
+ }
215
+
216
+ return created
217
+ }
218
+
219
+ async uploadOrphan(
220
+ upload: AcceptedUpload,
221
+ owner: { readonly forumId: number; readonly uploaderUserId: number },
222
+ ): Promise<AttachmentRecord> {
223
+ const opaque = upload.type.handling === 'opaque'
224
+ const key = storageKeyFor(opaque ? 'file' : 'source', this.random)
225
+
226
+ await this.deps.attachments.rememberKey(key)
227
+ await this.deps.files.put(key, upload.bytes, {
228
+ contentType: upload.type.contentType,
229
+ visibility: 'private',
230
+ })
231
+
232
+ const record = await this.deps.attachments.create({
233
+ postId: null,
234
+ forumId: owner.forumId,
235
+ uploaderUserId: owner.uploaderUserId,
236
+ filename: upload.filename,
237
+ contentType: upload.type.contentType,
238
+ sizeBytes: upload.bytes.length,
239
+ sourceKey: opaque ? null : key,
240
+ storageKey: opaque ? key : null,
241
+ status: opaque ? 'ready' : 'pending',
242
+ })
243
+ await this.deps.attachments.forgetKeys([key])
244
+
245
+ return record
246
+ }
247
+
248
+ async claim(
249
+ ids: readonly number[],
250
+ post: { readonly postId: number; readonly forumId: number; readonly uploaderUserId: number },
251
+ ): Promise<readonly AttachmentRecord[]> {
252
+ const claimed: AttachmentRecord[] = []
253
+
254
+ for (const id of ids) {
255
+ const record = await this.deps.attachments.findById(id)
256
+ if (record === null || record.postId !== null) continue
257
+ if (record.forumId !== post.forumId || record.uploaderUserId !== post.uploaderUserId) continue
258
+
259
+ const attached = await this.deps.attachments.attachTo(id, post.postId)
260
+ if (attached !== null) claimed.push(attached)
261
+ }
262
+
263
+ return claimed
264
+ }
265
+
266
+ async process(attachmentId: number): Promise<'done' | 'skipped' | 'failed'> {
267
+ const record = await this.deps.attachments.findById(attachmentId)
268
+ if (record === null || record.status !== 'pending' || record.sourceKey === null) {
269
+ return 'skipped'
270
+ }
271
+
272
+ const type = attachmentCodec(record.contentType)
273
+ if (type === null) {
274
+ await this.deps.attachments.markFailed(record.id, 'Unsupported image type.')
275
+ return 'failed'
276
+ }
277
+
278
+ const source = await this.deps.files.get(record.sourceKey)
279
+ if (source === undefined) {
280
+ await this.deps.attachments.markFailed(record.id, 'The uploaded file is no longer available.')
281
+ return 'failed'
282
+ }
283
+
284
+ let processed: ProcessedImage
285
+ try {
286
+ processed = await this.deps.images.process({ bytes: source, codec: type })
287
+ } catch {
288
+ await this.deps.attachments.markFailed(record.id, 'That image could not be read.')
289
+ await this.discard(record.sourceKey)
290
+ return 'failed'
291
+ }
292
+
293
+ const fileKey = storageKeyFor('file', this.random)
294
+ await this.deps.attachments.rememberKey(fileKey)
295
+ await this.deps.files.put(fileKey, processed.bytes, {
296
+ contentType: processed.contentType,
297
+ visibility: 'private',
298
+ })
299
+
300
+ let thumbKey: string | null = null
301
+ if (processed.thumbnail !== undefined) {
302
+ thumbKey = storageKeyFor('thumb', this.random)
303
+ await this.deps.attachments.rememberKey(thumbKey)
304
+ await this.deps.files.put(thumbKey, processed.thumbnail.bytes, {
305
+ contentType: processed.thumbnail.contentType,
306
+ visibility: 'private',
307
+ })
308
+ }
309
+
310
+ await this.deps.attachments.markReady(record.id, {
311
+ storageKey: fileKey,
312
+ thumbnailKey: thumbKey,
313
+ width: processed.width,
314
+ height: processed.height,
315
+ sizeBytes: processed.bytes.length,
316
+ })
317
+ await this.deps.attachments.forgetKeys(thumbKey === null ? [fileKey] : [fileKey, thumbKey])
318
+
319
+ await this.discard(record.sourceKey)
320
+ return 'done'
321
+ }
322
+
323
+ async sweep(limit = 200): Promise<{ deleted: number; failed: number }> {
324
+ const now = this.now()
325
+
326
+ const stalled = await this.deps.attachments.stalled(
327
+ new Date(now.getTime() - PROCESSING_GRACE_MINUTES * 60_000),
328
+ limit,
329
+ )
330
+ for (const record of stalled) {
331
+ await this.deps.attachments.markFailed(
332
+ record.id,
333
+ 'Processing did not finish. Please upload it again.',
334
+ )
335
+ if (record.sourceKey !== null) await this.discard(record.sourceKey)
336
+ }
337
+
338
+ const orphanCutoff = new Date(now.getTime() - ORPHAN_GRACE_MINUTES * 60_000)
339
+
340
+ const staleOrphans = await this.deps.attachments.deleteOrphans(orphanCutoff, limit)
341
+ for (const record of staleOrphans) {
342
+ for (const key of [record.sourceKey, record.storageKey, record.thumbnailKey]) {
343
+ if (key !== null) await this.discard(key)
344
+ }
345
+ }
346
+
347
+ const keys = await this.deps.attachments.staleKeys(orphanCutoff, limit)
348
+ for (const key of keys) await this.discard(key)
349
+
350
+ return { deleted: keys.length + staleOrphans.length, failed: stalled.length }
351
+ }
352
+
353
+ private async discard(key: string): Promise<void> {
354
+ await this.deps.files.delete(key)
355
+ await this.deps.attachments.forgetKeys([key])
356
+ }
357
+ }
358
+
359
+ export interface StagedUpload {
360
+ readonly upload: AcceptedUpload
361
+ readonly key: string
362
+ readonly opaque: boolean
363
+ }
364
+
365
+ function attachmentCodec(contentType: string): 'png' | 'jpeg' | null {
366
+ if (contentType === 'image/png') return 'png'
367
+ if (contentType === 'image/jpeg') return 'jpeg'
368
+ return null
369
+ }
370
+
371
+ function defaultRandom(): string {
372
+ return crypto.randomUUID()
373
+ }
374
+
375
+ export function isViewable(record: AttachmentRecord, type: AttachmentType | undefined): boolean {
376
+ return record.status === 'ready' && record.storageKey !== null && type?.inline === true
377
+ }
package/src/types.ts ADDED
@@ -0,0 +1,105 @@
1
+ export type AttachmentHandling = 'reencode' | 'opaque'
2
+
3
+ export interface AttachmentType {
4
+ readonly contentType: string
5
+ readonly extensions: readonly string[]
6
+ readonly magic: readonly (readonly number[])[]
7
+ readonly handling: AttachmentHandling
8
+ readonly codec: 'png' | 'jpeg' | null
9
+ readonly inline: boolean
10
+ }
11
+
12
+ export const ATTACHMENT_TYPES: readonly AttachmentType[] = [
13
+ {
14
+ contentType: 'image/png',
15
+ extensions: ['png'],
16
+ magic: [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]],
17
+ handling: 'reencode',
18
+ codec: 'png',
19
+ inline: true,
20
+ },
21
+ {
22
+ contentType: 'image/jpeg',
23
+ extensions: ['jpg', 'jpeg', 'jpe'],
24
+ magic: [[0xff, 0xd8, 0xff]],
25
+ handling: 'reencode',
26
+ codec: 'jpeg',
27
+ inline: true,
28
+ },
29
+ {
30
+ contentType: 'application/pdf',
31
+ extensions: ['pdf'],
32
+ magic: [[0x25, 0x50, 0x44, 0x46, 0x2d]],
33
+ handling: 'opaque',
34
+ codec: null,
35
+ inline: false,
36
+ },
37
+ {
38
+ contentType: 'application/zip',
39
+ extensions: ['zip'],
40
+ magic: [
41
+ [0x50, 0x4b, 0x03, 0x04],
42
+ [0x50, 0x4b, 0x05, 0x06],
43
+ [0x50, 0x4b, 0x07, 0x08],
44
+ ],
45
+ handling: 'opaque',
46
+ codec: null,
47
+ inline: false,
48
+ },
49
+ ] as const
50
+
51
+ export const MAGIC_BYTES_NEEDED = ATTACHMENT_TYPES.reduce(
52
+ (most, type) => Math.max(most, ...type.magic.map((m) => m.length)),
53
+ 0,
54
+ )
55
+
56
+ export function sniff(bytes: Uint8Array): AttachmentType | undefined {
57
+ return ATTACHMENT_TYPES.find((type) =>
58
+ type.magic.some(
59
+ (signature) =>
60
+ bytes.length >= signature.length && signature.every((byte, at) => bytes[at] === byte),
61
+ ),
62
+ )
63
+ }
64
+
65
+ export function attachmentType(contentType: string): AttachmentType | undefined {
66
+ return ATTACHMENT_TYPES.find((type) => type.contentType === contentType)
67
+ }
68
+
69
+ export const ACCEPTED_EXTENSIONS: readonly string[] = ATTACHMENT_TYPES.flatMap(
70
+ (type) => type.extensions,
71
+ )
72
+
73
+ export const ATTACHMENT_FIELD = 'attachments'
74
+
75
+ export type AttachmentStatus = 'pending' | 'ready' | 'failed'
76
+
77
+ export interface AttachmentRecord {
78
+ readonly id: number
79
+ readonly postId: number | null
80
+ readonly forumId: number
81
+ readonly uploaderUserId: number | null
82
+ readonly filename: string
83
+ readonly contentType: string
84
+ readonly sizeBytes: number
85
+ readonly storageKey: string | null
86
+ readonly sourceKey: string | null
87
+ readonly thumbnailKey: string | null
88
+ readonly width: number | null
89
+ readonly height: number | null
90
+ readonly status: AttachmentStatus
91
+ readonly failureReason: string | null
92
+ readonly downloadCount: number
93
+ readonly createdAt: Date
94
+ }
95
+
96
+ export interface IncomingFile {
97
+ readonly filename: string
98
+ readonly bytes: Uint8Array
99
+ }
100
+
101
+ export interface AcceptedUpload {
102
+ readonly filename: string
103
+ readonly type: AttachmentType
104
+ readonly bytes: Uint8Array
105
+ }