@jant/core 0.6.10 → 0.6.11

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 (42) hide show
  1. package/dist/{app-CGHkOdme.js → app-CpmficmQ.js} +531 -204
  2. package/dist/app-DqKkZenB.js +6 -0
  3. package/dist/client/.vite/manifest.json +3 -3
  4. package/dist/client/_assets/client-BhHHVvSY.css +2 -0
  5. package/dist/client/_assets/{client-DYrWuaIk.js → client-Dd9U383b.js} +1 -1
  6. package/dist/client/_assets/{client-auth-B5Re0uCd.js → client-auth-DkpSdIDz.js} +80 -80
  7. package/dist/{export-DY1v5Iqu.js → export-Ba7NJImL.js} +92 -92
  8. package/dist/{github-sync-LefaslGJ.js → github-sync-BD4w2m8-.js} +2 -2
  9. package/dist/{github-sync-2_T7nbOv.js → github-sync-Cb4_6_i7.js} +1 -1
  10. package/dist/index.js +3 -3
  11. package/dist/node.js +4 -4
  12. package/package.json +1 -1
  13. package/src/client/components/__tests__/jant-compose-editor-rehost-notice.test.ts +62 -0
  14. package/src/client/components/compose-types.ts +4 -0
  15. package/src/client/components/jant-compose-editor.ts +111 -0
  16. package/src/client/compose-bridge.ts +25 -8
  17. package/src/client/tiptap/__tests__/inline-image-upload.test.ts +143 -0
  18. package/src/client/tiptap/__tests__/paste-rehost-e2e.test.ts +65 -0
  19. package/src/client/tiptap/__tests__/rehost-images.test.ts +139 -0
  20. package/src/client/tiptap/create-editor.ts +3 -0
  21. package/src/client/tiptap/extensions.ts +4 -0
  22. package/src/client/tiptap/inline-image-upload.ts +174 -50
  23. package/src/client/tiptap/rehost-images.ts +104 -0
  24. package/src/i18n/locales/public/en.po +10 -0
  25. package/src/i18n/locales/public/en.ts +1 -1
  26. package/src/i18n/locales/public/zh-Hans.po +10 -0
  27. package/src/i18n/locales/public/zh-Hans.ts +1 -1
  28. package/src/i18n/locales/public/zh-Hant.po +10 -0
  29. package/src/i18n/locales/public/zh-Hant.ts +1 -1
  30. package/src/lib/__tests__/upload-sideload.test.ts +78 -0
  31. package/src/lib/__tests__/url-fetch.test.ts +181 -0
  32. package/src/lib/upload.ts +111 -0
  33. package/src/lib/url-fetch.ts +263 -0
  34. package/src/routes/api/__tests__/uploads.test.ts +63 -1
  35. package/src/routes/api/uploads.ts +52 -0
  36. package/src/services/__tests__/media.test.ts +168 -1
  37. package/src/services/media.ts +111 -0
  38. package/src/styles/ui.css +1 -1
  39. package/src/ui/compose/ComposeDialog.tsx +16 -0
  40. package/src/ui/layouts/BaseLayout.tsx +12 -0
  41. package/dist/app-D24n0DoH.js +0 -6
  42. package/dist/client/_assets/client-xWDl78yi.css +0 -2
package/src/lib/upload.ts CHANGED
@@ -277,6 +277,117 @@ export function isImageMimeType(mimeType: string): boolean {
277
277
  return mimeType.startsWith("image/");
278
278
  }
279
279
 
280
+ /** Image MIME types accepted by the remote-image sideload path. */
281
+ const SIDELOAD_IMAGE_MIME_TYPES = new Set<string>(IMAGE_MIME_TYPES);
282
+
283
+ /** Map of sideload-accepted image MIME types to their file extensions. */
284
+ const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
285
+ "image/jpeg": "jpg",
286
+ "image/png": "png",
287
+ "image/gif": "gif",
288
+ "image/webp": "webp",
289
+ "image/svg+xml": "svg",
290
+ "image/avif": "avif",
291
+ "image/bmp": "bmp",
292
+ "image/x-icon": "ico",
293
+ };
294
+
295
+ /**
296
+ * Whether a MIME type may be rehosted via remote-image sideload.
297
+ *
298
+ * Unlike {@link getStoredUploadPolicy} (which only allows webp/png/jpeg because
299
+ * the normal upload path re-encodes everything to WebP client-side), the
300
+ * sideload path stores the original remote bytes, so it accepts the full set of
301
+ * image formats Jant can display.
302
+ *
303
+ * @param contentType - The MIME type to check
304
+ * @returns Whether the type is an accepted sideload image
305
+ * @example
306
+ * ```ts
307
+ * isAllowedSideloadImageType("image/gif"); // true
308
+ * isAllowedSideloadImageType("text/html"); // false
309
+ * ```
310
+ */
311
+ export function isAllowedSideloadImageType(contentType: string): boolean {
312
+ return SIDELOAD_IMAGE_MIME_TYPES.has(contentType);
313
+ }
314
+
315
+ /**
316
+ * Returns the file extension for a sideload-accepted image MIME type.
317
+ *
318
+ * @param contentType - The image MIME type
319
+ * @returns Extension without a dot, or null if the type isn't sideloadable
320
+ * @example
321
+ * ```ts
322
+ * imageExtensionForMimeType("image/jpeg"); // "jpg"
323
+ * ```
324
+ */
325
+ export function imageExtensionForMimeType(contentType: string): string | null {
326
+ return IMAGE_MIME_EXTENSIONS[contentType] ?? null;
327
+ }
328
+
329
+ /**
330
+ * Identify an image format from its leading bytes (magic numbers), so a remote
331
+ * sideload can trust the actual content rather than the server's content-type
332
+ * header. Recognizes every {@link isAllowedSideloadImageType} format.
333
+ *
334
+ * @param bytes - The leading bytes of the file (≥ ~256 bytes recommended)
335
+ * @returns The detected image MIME type, or null if unrecognized
336
+ * @example
337
+ * ```ts
338
+ * sniffImageMimeType(pngBytes); // "image/png"
339
+ * ```
340
+ */
341
+ export function sniffImageMimeType(bytes: Uint8Array): string | null {
342
+ if (
343
+ bytes.length >= 3 &&
344
+ bytes[0] === 0xff &&
345
+ bytes[1] === 0xd8 &&
346
+ bytes[2] === 0xff
347
+ ) {
348
+ return "image/jpeg";
349
+ }
350
+ if (
351
+ bytes.length >= 8 &&
352
+ bytes[0] === 0x89 &&
353
+ readAscii(bytes, 1, 3) === "PNG"
354
+ ) {
355
+ return "image/png";
356
+ }
357
+ if (bytes.length >= 6 && /^GIF8[79]a$/.test(readAscii(bytes, 0, 6))) {
358
+ return "image/gif";
359
+ }
360
+ if (
361
+ bytes.length >= 12 &&
362
+ readAscii(bytes, 0, 4) === "RIFF" &&
363
+ readAscii(bytes, 8, 4) === "WEBP"
364
+ ) {
365
+ return "image/webp";
366
+ }
367
+ if (bytes.length >= 12 && readAscii(bytes, 4, 4) === "ftyp") {
368
+ const brand = readAscii(bytes, 8, 4);
369
+ if (brand === "avif" || brand === "avis") return "image/avif";
370
+ }
371
+ if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4d) {
372
+ return "image/bmp";
373
+ }
374
+ if (
375
+ bytes.length >= 4 &&
376
+ bytes[0] === 0x00 &&
377
+ bytes[1] === 0x00 &&
378
+ bytes[2] === 0x01 &&
379
+ bytes[3] === 0x00
380
+ ) {
381
+ return "image/x-icon";
382
+ }
383
+ // SVG is text — look for an <svg> root in the leading bytes.
384
+ const head = new TextDecoder().decode(bytes.subarray(0, 1024)).toLowerCase();
385
+ if (head.includes("<svg")) {
386
+ return "image/svg+xml";
387
+ }
388
+ return null;
389
+ }
390
+
280
391
  export interface ValidateUploadOptions {
281
392
  /** When true, only image MIME types are accepted (e.g. for avatar uploads). */
282
393
  imagesOnly?: boolean;
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Safe remote URL fetching for server-side image sideloading.
3
+ *
4
+ * When an author pastes an article from another site, its `<img>` tags point at
5
+ * remote URLs. To rehost those images into the site's own storage the server
6
+ * must fetch the bytes itself (a browser `fetch` of a third-party image is
7
+ * blocked by CORS for most hosts). Because the URL comes from pasted HTML it is
8
+ * attacker-influenced, so every fetch passes through an SSRF guard and a bounded
9
+ * reader that caps size and time.
10
+ *
11
+ * Note: DNS is not resolvable from a Cloudflare Worker, so the IP-literal checks
12
+ * here are defense-in-depth for self-hosted (Node) deployments and for URLs that
13
+ * embed a literal address. They are not a substitute for network-level egress
14
+ * controls.
15
+ */
16
+
17
+ import { ValidationError } from "./errors.js";
18
+
19
+ /** A browser-like UA — many CDNs serving article images block unknown bots. */
20
+ const FETCH_USER_AGENT =
21
+ "Mozilla/5.0 (compatible; Jant image sideloader) AppleWebKit/537.36";
22
+
23
+ export interface FetchedImage {
24
+ bytes: Uint8Array;
25
+ /** Lowercased content-type with parameters stripped, or null if absent. */
26
+ contentType: string | null;
27
+ }
28
+
29
+ export interface FetchImageBytesOptions {
30
+ /** Reject (and abort) once the body exceeds this many bytes. */
31
+ maxBytes: number;
32
+ /** Abort the whole request after this many milliseconds. */
33
+ timeoutMs: number;
34
+ /** Maximum redirect hops to follow (each re-validated). Default 3. */
35
+ maxRedirects?: number;
36
+ }
37
+
38
+ /**
39
+ * Validate that a string is a public http(s) URL safe to fetch server-side.
40
+ *
41
+ * Throws {@link ValidationError} for non-http(s) protocols, embedded
42
+ * credentials, localhost names, and private/loopback/link-local/ULA/CGNAT IP
43
+ * literals (including the `169.254.169.254` cloud-metadata address).
44
+ *
45
+ * @param raw - The candidate URL string
46
+ * @returns The parsed {@link URL}
47
+ * @example
48
+ * ```ts
49
+ * const url = assertPublicHttpUrl("https://example.com/photo.jpg");
50
+ * ```
51
+ */
52
+ export function assertPublicHttpUrl(raw: string): URL {
53
+ let url: URL;
54
+ try {
55
+ url = new URL(raw);
56
+ } catch {
57
+ throw new ValidationError("That doesn't look like a valid image URL.");
58
+ }
59
+
60
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
61
+ throw new ValidationError("Only http and https image URLs can be fetched.");
62
+ }
63
+ if (url.username || url.password) {
64
+ throw new ValidationError("Image URLs can't include credentials.");
65
+ }
66
+
67
+ const host = url.hostname.toLowerCase();
68
+ if (
69
+ host === "localhost" ||
70
+ host.endsWith(".localhost") ||
71
+ host === "0.0.0.0" ||
72
+ isPrivateIpv4(host) ||
73
+ isPrivateIpv6(host)
74
+ ) {
75
+ throw new ValidationError("That image URL points to a private address.");
76
+ }
77
+
78
+ return url;
79
+ }
80
+
81
+ /**
82
+ * Fetch a remote image with an SSRF-checked redirect chain, a size cap, and a
83
+ * timeout. Reads the body in chunks and aborts the moment it exceeds `maxBytes`
84
+ * so an untrusted host can't exhaust memory.
85
+ *
86
+ * @param startUrl - A URL already validated by {@link assertPublicHttpUrl}
87
+ * @param options - Size cap, timeout, and redirect budget
88
+ * @returns The raw bytes and the response content-type
89
+ * @example
90
+ * ```ts
91
+ * const { bytes, contentType } = await fetchImageBytes(url, {
92
+ * maxBytes: 25 * 1024 * 1024,
93
+ * timeoutMs: 15000,
94
+ * });
95
+ * ```
96
+ */
97
+ export async function fetchImageBytes(
98
+ startUrl: URL,
99
+ options: FetchImageBytesOptions,
100
+ ): Promise<FetchedImage> {
101
+ const maxRedirects = options.maxRedirects ?? 3;
102
+ const controller = new AbortController();
103
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
104
+
105
+ try {
106
+ let url = startUrl;
107
+ let response: Response | null = null;
108
+
109
+ for (let hop = 0; hop <= maxRedirects; hop++) {
110
+ response = await fetch(url.toString(), {
111
+ method: "GET",
112
+ redirect: "manual",
113
+ signal: controller.signal,
114
+ headers: {
115
+ Accept: "image/*,*/*;q=0.8",
116
+ "User-Agent": FETCH_USER_AGENT,
117
+ // Many CDNs (Douban, WeChat, etc.) reject hotlinked image requests
118
+ // that lack a Referer. Sending the image's own origin satisfies the
119
+ // common "referer must be same-site" hotlink check.
120
+ Referer: `${url.origin}/`,
121
+ },
122
+ }).catch((error) => {
123
+ if (controller.signal.aborted) {
124
+ throw new ValidationError("Timed out fetching the image.");
125
+ }
126
+ throw new ValidationError(
127
+ error instanceof Error
128
+ ? `Couldn't fetch the image: ${error.message}`
129
+ : "Couldn't fetch the image.",
130
+ );
131
+ });
132
+
133
+ if (response.status >= 300 && response.status < 400) {
134
+ const location = response.headers.get("location");
135
+ if (!location) break; // No target — fall through to the (failing) checks.
136
+ if (hop === maxRedirects) {
137
+ throw new ValidationError("Too many redirects fetching the image.");
138
+ }
139
+ // Re-validate every hop so a redirect can't escape the SSRF guard.
140
+ url = assertPublicHttpUrl(new URL(location, url).toString());
141
+ continue;
142
+ }
143
+ break;
144
+ }
145
+
146
+ if (!response) {
147
+ throw new ValidationError("Couldn't fetch the image.");
148
+ }
149
+ if (!response.ok) {
150
+ throw new ValidationError(
151
+ `Couldn't fetch the image (HTTP ${response.status}).`,
152
+ );
153
+ }
154
+
155
+ const declared = Number(response.headers.get("content-length"));
156
+ if (Number.isFinite(declared) && declared > options.maxBytes) {
157
+ throw new ValidationError("That image is too large.");
158
+ }
159
+
160
+ const contentType = normalizeContentType(
161
+ response.headers.get("content-type"),
162
+ );
163
+ const bytes = await readBounded(response, options.maxBytes);
164
+ return { bytes, contentType };
165
+ } finally {
166
+ clearTimeout(timer);
167
+ }
168
+ }
169
+
170
+ async function readBounded(
171
+ response: Response,
172
+ maxBytes: number,
173
+ ): Promise<Uint8Array> {
174
+ const body = response.body;
175
+ if (!body) {
176
+ const buffer = new Uint8Array(await response.arrayBuffer());
177
+ if (buffer.byteLength > maxBytes) {
178
+ throw new ValidationError("That image is too large.");
179
+ }
180
+ return buffer;
181
+ }
182
+
183
+ const reader = body.getReader();
184
+ const chunks: Uint8Array[] = [];
185
+ let total = 0;
186
+ for (;;) {
187
+ const { done, value } = await reader.read();
188
+ if (done) break;
189
+ if (!value) continue;
190
+ total += value.byteLength;
191
+ if (total > maxBytes) {
192
+ await reader.cancel().catch(() => {});
193
+ throw new ValidationError("That image is too large.");
194
+ }
195
+ chunks.push(value);
196
+ }
197
+
198
+ const out = new Uint8Array(total);
199
+ let offset = 0;
200
+ for (const chunk of chunks) {
201
+ out.set(chunk, offset);
202
+ offset += chunk.byteLength;
203
+ }
204
+ return out;
205
+ }
206
+
207
+ function normalizeContentType(raw: string | null): string | null {
208
+ if (!raw) return null;
209
+ const type = raw.split(";")[0]?.trim().toLowerCase();
210
+ return type || null;
211
+ }
212
+
213
+ /**
214
+ * True when a canonicalized IPv4 dotted-quad host is in a private, loopback,
215
+ * link-local, CGNAT, or otherwise non-public range. The WHATWG URL parser
216
+ * already normalizes decimal/octal/hex IPv4 forms to dotted-quad, so checking
217
+ * `url.hostname` is sufficient.
218
+ */
219
+ function isPrivateIpv4(host: string): boolean {
220
+ const match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
221
+ if (!match) return false;
222
+ const octets = match.slice(1, 5).map(Number);
223
+ if (octets.some((part) => part > 255)) return true; // Malformed → unsafe.
224
+ const a = octets[0] ?? 0;
225
+ const b = octets[1] ?? 0;
226
+ if (a === 0) return true; // 0.0.0.0/8 "this" network
227
+ if (a === 10) return true; // 10/8 private
228
+ if (a === 127) return true; // 127/8 loopback
229
+ if (a === 169 && b === 254) return true; // 169.254/16 link-local (metadata)
230
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16/12 private
231
+ if (a === 192 && b === 168) return true; // 192.168/16 private
232
+ if (a === 100 && b >= 64 && b <= 127) return true; // 100.64/10 CGNAT
233
+ if (a === 255 && b === 255) return true; // broadcast
234
+ return false;
235
+ }
236
+
237
+ /** True when an IPv6 host (bracketed or bare) is loopback/link-local/ULA/mapped-private. */
238
+ function isPrivateIpv6(host: string): boolean {
239
+ let inner = host;
240
+ if (inner.startsWith("[") && inner.endsWith("]")) {
241
+ inner = inner.slice(1, -1);
242
+ }
243
+ if (!inner.includes(":")) return false;
244
+ const lower = inner.toLowerCase();
245
+ if (lower === "::" || lower === "::1") return true; // unspecified / loopback
246
+
247
+ // IPv4-mapped, dotted form (::ffff:1.2.3.4).
248
+ const dotted = lower.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
249
+ if (dotted?.[1]) return isPrivateIpv4(dotted[1]);
250
+
251
+ // IPv4-mapped, hex form (::ffff:a00:1) — what the URL parser normalizes to.
252
+ const hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
253
+ if (hex) {
254
+ const hi = parseInt(hex[1] ?? "0", 16);
255
+ const lo = parseInt(hex[2] ?? "0", 16);
256
+ const v4 = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
257
+ return isPrivateIpv4(v4);
258
+ }
259
+
260
+ if (/^fe[89ab]/.test(lower)) return true; // fe80::/10 link-local
261
+ if (/^f[cd]/.test(lower)) return true; // fc00::/7 unique local
262
+ return false;
263
+ }
@@ -1,4 +1,4 @@
1
- import { describe, expect, it } from "vitest";
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
2
  import { createTestApp } from "../../../__tests__/helpers/app.js";
3
3
  import type {
4
4
  PresignedPutOptions,
@@ -136,6 +136,68 @@ function createMockStorage(options?: {
136
136
  };
137
137
  }
138
138
 
139
+ describe("POST /api/uploads/sideload", () => {
140
+ afterEach(() => {
141
+ vi.restoreAllMocks();
142
+ });
143
+
144
+ function pngBytes(): Uint8Array {
145
+ return new Uint8Array([
146
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
147
+ 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x06,
148
+ 0x08, 0x06, 0x00, 0x00, 0x00,
149
+ ]);
150
+ }
151
+
152
+ it("rehosts a remote image and returns its stored URL", async () => {
153
+ vi.stubGlobal(
154
+ "fetch",
155
+ vi.fn(
156
+ async () =>
157
+ new Response(pngBytes(), {
158
+ headers: { "content-type": "image/png" },
159
+ }),
160
+ ),
161
+ );
162
+ const storage = createMockStorage();
163
+ const { app, services } = createTestApp({ authenticated: true, storage });
164
+ app.route("/api/uploads", uploadsApiRoutes);
165
+
166
+ const res = await app.request("/api/uploads/sideload", {
167
+ method: "POST",
168
+ headers: { "Content-Type": "application/json" },
169
+ body: JSON.stringify({ url: "https://example.com/photo.png" }),
170
+ });
171
+
172
+ expect(res.status).toBe(200);
173
+ const data = (await res.json()) as {
174
+ id: string;
175
+ url: string;
176
+ mimeType: string;
177
+ width: number;
178
+ height: number;
179
+ };
180
+ expect(data.mimeType).toBe("image/png");
181
+ expect(data.width).toBe(4);
182
+ expect(data.height).toBe(6);
183
+ const media = await services.media.getById(data.id);
184
+ expect(media?.mimeType).toBe("image/png");
185
+ });
186
+
187
+ it("requires authentication", async () => {
188
+ const { app } = createTestApp({ authenticated: false });
189
+ app.route("/api/uploads", uploadsApiRoutes);
190
+
191
+ const res = await app.request("/api/uploads/sideload", {
192
+ method: "POST",
193
+ headers: { "Content-Type": "application/json" },
194
+ body: JSON.stringify({ url: "https://example.com/photo.png" }),
195
+ });
196
+
197
+ expect(res.status).toBe(401);
198
+ });
199
+ });
200
+
139
201
  describe("Upload Session API Routes", () => {
140
202
  it("completes a relay image upload and stores inline media metadata", async () => {
141
203
  const storage = createMockStorage();
@@ -35,10 +35,62 @@ const CompleteUploadSchema = z.object({
35
35
  .optional(),
36
36
  });
37
37
 
38
+ const SideloadSchema = z.object({
39
+ url: z.string().url(),
40
+ alt: z.string().max(2000).optional(),
41
+ });
42
+
38
43
  export const uploadsApiRoutes = new Hono<Env>();
39
44
 
40
45
  uploadsApiRoutes.use("*", requireAuthApi());
41
46
 
47
+ /**
48
+ * Rehost a remote image into the site's own storage. Used when an author pastes
49
+ * an article whose `<img>` tags point at external URLs — the server fetches the
50
+ * bytes (bypassing browser CORS) and stores them. Returns the new media's
51
+ * public URL so the editor can swap the node's `src`.
52
+ */
53
+ uploadsApiRoutes.post("/sideload", async (c) => {
54
+ const storage = c.var.storage;
55
+ if (!storage) {
56
+ return c.json(
57
+ { error: "File storage isn't set up. Check your server config." },
58
+ 500,
59
+ );
60
+ }
61
+
62
+ const { url, alt } = parseValidated(SideloadSchema, await c.req.json());
63
+
64
+ const media = await c.var.services.media.ingestFromUrl(
65
+ { url, alt },
66
+ {
67
+ storage,
68
+ storageDriver: c.var.appConfig.storageDriver,
69
+ maxFileSizeMB: c.var.appConfig.uploadMaxFileSize,
70
+ },
71
+ );
72
+
73
+ const mediaPublicUrl = getPublicUrlForProvider(
74
+ c.var.appConfig.storageDriver,
75
+ c.var.appConfig.r2PublicUrl,
76
+ c.var.appConfig.s3PublicUrl,
77
+ c.var.appConfig.localPublicUrl,
78
+ );
79
+
80
+ return c.json({
81
+ id: media.id,
82
+ url: getMediaUrl(
83
+ media.storageKey,
84
+ mediaPublicUrl,
85
+ c.var.appConfig.sitePathPrefix,
86
+ ),
87
+ width: media.width,
88
+ height: media.height,
89
+ mimeType: media.mimeType,
90
+ size: media.size,
91
+ });
92
+ });
93
+
42
94
  function scheduleExpiredUploadCleanup(
43
95
  c: {
44
96
  executionCtx?: { waitUntil: (promise: Promise<unknown>) => void };
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/no-non-null-assertion -- Test assertions use ! for readability */
2
- import { describe, it, expect, beforeEach, vi } from "vitest";
2
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
3
3
  import { eq } from "drizzle-orm";
4
4
  import {
5
5
  createTestDatabase,
@@ -1546,3 +1546,170 @@ describe("MediaService", () => {
1546
1546
  });
1547
1547
  });
1548
1548
  });
1549
+
1550
+ /** Minimal valid PNG header (signature + IHDR with width 4, height 6). */
1551
+ function createPngBytes(): Uint8Array {
1552
+ return new Uint8Array([
1553
+ 0x89,
1554
+ 0x50,
1555
+ 0x4e,
1556
+ 0x47,
1557
+ 0x0d,
1558
+ 0x0a,
1559
+ 0x1a,
1560
+ 0x0a, // signature
1561
+ 0x00,
1562
+ 0x00,
1563
+ 0x00,
1564
+ 0x0d, // IHDR length (13)
1565
+ 0x49,
1566
+ 0x48,
1567
+ 0x44,
1568
+ 0x52, // "IHDR"
1569
+ 0x00,
1570
+ 0x00,
1571
+ 0x00,
1572
+ 0x04, // width = 4
1573
+ 0x00,
1574
+ 0x00,
1575
+ 0x00,
1576
+ 0x06, // height = 6
1577
+ 0x08,
1578
+ 0x06,
1579
+ 0x00,
1580
+ 0x00,
1581
+ 0x00, // bit depth, color type, ...
1582
+ ]);
1583
+ }
1584
+
1585
+ describe("MediaService.ingestFromUrl", () => {
1586
+ let db: Database;
1587
+ let mediaService: ReturnType<typeof createMediaService>;
1588
+
1589
+ beforeEach(() => {
1590
+ const testDb = createTestDatabase();
1591
+ db = testDb.db as unknown as Database;
1592
+ mediaService = createMediaService(db, DEFAULT_TEST_SITE_ID);
1593
+ });
1594
+
1595
+ afterEach(() => {
1596
+ vi.restoreAllMocks();
1597
+ });
1598
+
1599
+ const deps = () => ({
1600
+ storage: createMockStorage(),
1601
+ storageDriver: "local",
1602
+ maxFileSizeMB: 25,
1603
+ });
1604
+
1605
+ it("fetches a remote image, stores it, and creates a media row", async () => {
1606
+ const bytes = createPngBytes();
1607
+ vi.stubGlobal(
1608
+ "fetch",
1609
+ vi.fn(
1610
+ async () =>
1611
+ new Response(bytes, { headers: { "content-type": "image/png" } }),
1612
+ ),
1613
+ );
1614
+
1615
+ const d = deps();
1616
+ const media = await mediaService.ingestFromUrl(
1617
+ { url: "https://example.com/photo.png", alt: "A photo" },
1618
+ d,
1619
+ );
1620
+
1621
+ expect(media.mimeType).toBe("image/png");
1622
+ expect(media.mediaKind).toBe("image");
1623
+ expect(media.width).toBe(4);
1624
+ expect(media.height).toBe(6);
1625
+ expect(media.alt).toBe("A photo");
1626
+ expect(media.postId).toBeNull();
1627
+
1628
+ const stored = d.storage.files.get(media.storageKey);
1629
+ expect(stored).toBeDefined();
1630
+ expect(stored?.contentType).toBe("image/png");
1631
+ expect(stored?.contentDisposition).toBe("inline");
1632
+ });
1633
+
1634
+ it("stores SVG with attachment disposition (XSS-safe direct navigation)", async () => {
1635
+ const svg = new TextEncoder().encode(
1636
+ '<svg xmlns="http://www.w3.org/2000/svg"></svg>',
1637
+ );
1638
+ vi.stubGlobal(
1639
+ "fetch",
1640
+ vi.fn(
1641
+ async () =>
1642
+ new Response(svg, {
1643
+ headers: { "content-type": "image/svg+xml" },
1644
+ }),
1645
+ ),
1646
+ );
1647
+
1648
+ const d = deps();
1649
+ const media = await mediaService.ingestFromUrl(
1650
+ { url: "https://example.com/icon.svg" },
1651
+ d,
1652
+ );
1653
+
1654
+ expect(media.mimeType).toBe("image/svg+xml");
1655
+ const stored = d.storage.files.get(media.storageKey);
1656
+ expect(stored?.contentDisposition).toBe("attachment");
1657
+ });
1658
+
1659
+ it("rejects content that isn't a real image (content-type spoofing)", async () => {
1660
+ const html = new TextEncoder().encode(
1661
+ "<!doctype html><script>alert(1)</script>",
1662
+ );
1663
+ vi.stubGlobal(
1664
+ "fetch",
1665
+ vi.fn(
1666
+ // Server lies: claims PNG, returns HTML.
1667
+ async () =>
1668
+ new Response(html, { headers: { "content-type": "image/png" } }),
1669
+ ),
1670
+ );
1671
+
1672
+ await expect(
1673
+ mediaService.ingestFromUrl(
1674
+ { url: "https://example.com/evil.png" },
1675
+ deps(),
1676
+ ),
1677
+ ).rejects.toThrow(/supported image/i);
1678
+ });
1679
+
1680
+ it("rejects an oversize image", async () => {
1681
+ const stream = new ReadableStream<Uint8Array>({
1682
+ start(controller) {
1683
+ controller.enqueue(new Uint8Array(2 * 1024 * 1024));
1684
+ controller.close();
1685
+ },
1686
+ });
1687
+ vi.stubGlobal(
1688
+ "fetch",
1689
+ vi.fn(
1690
+ async () =>
1691
+ new Response(stream, { headers: { "content-type": "image/png" } }),
1692
+ ),
1693
+ );
1694
+
1695
+ await expect(
1696
+ mediaService.ingestFromUrl(
1697
+ { url: "https://example.com/huge.png" },
1698
+ { ...deps(), maxFileSizeMB: 1 },
1699
+ ),
1700
+ ).rejects.toThrow(/too large/i);
1701
+ });
1702
+
1703
+ it("rejects a private/SSRF URL before fetching", async () => {
1704
+ const fetchMock = vi.fn();
1705
+ vi.stubGlobal("fetch", fetchMock);
1706
+
1707
+ await expect(
1708
+ mediaService.ingestFromUrl(
1709
+ { url: "http://169.254.169.254/latest/meta-data" },
1710
+ deps(),
1711
+ ),
1712
+ ).rejects.toThrow(/private address/i);
1713
+ expect(fetchMock).not.toHaveBeenCalled();
1714
+ });
1715
+ });