Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

remove(web): uninstall URL preview chain (#598)

Gustavo Ye47d7b54322f7
diff --git a/package.json b/package.json
index 9ec2e6786..8a1182ffb 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,7 @@
"db:migrate": "pnpm --filter @alook/web exec wrangler d1 migrations apply alook-app --local",
"db:reset": "rm -rf src/web/.wrangler/state && pnpm run db:migrate",
"test:all": "vitest run",
- "deploy:web": "pnpm --filter @alook/web preflight:link-preview-thumbnails && pnpm db:migrate:remote && cd src/web && npx opennextjs-cloudflare build && npx opennextjs-cloudflare deploy",
+ "deploy:web": "pnpm db:migrate:remote && cd src/web && npx opennextjs-cloudflare build && npx opennextjs-cloudflare deploy",
"deploy:ws-do": "cd src/ws-do && npx wrangler deploy",
"deploy:email": "cd src/email-worker && npx wrangler deploy",
"deploy:wake-worker": "cd src/wake-worker && npx wrangler deploy",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 045d2b774..d7c9fa7ca 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -445,9 +445,6 @@ importers:
katex:
specifier: ^0.18.4
version: 0.18.4
- link-preview-js:
- specifier: 5.0.0
- version: 5.0.0
lucide-react:
specifier: ^1.31.0
version: 1.31.0([email protected])
@@ -4814,9 +4811,6 @@ packages:
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
-
resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
@@ -4920,13 +4914,6 @@ packages:
resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==}
- resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
-
- resolution: {integrity: sha512-bQwNaDIBKID5ts/DsdhxrjqFXYfLw4ste+wMKqWA8DyKcS4qwsPP4Bk8ZNaTJjvpiX/qW3BT4sU7d6Bh5i+dag==}
- engines: {node: '>= 6'}
-
resolution: {integrity: sha512-PvVJm3oGqrveUVW2Vt/eZGeiAIsJszYweUcYwcskg9e+IubNYKKD+rHHem7A6XVO22eDAL+inxNIGAzZ/VIWlA==}
peerDependencies:
@@ -5161,13 +5148,6 @@ packages:
resolution: {integrity: sha512-EL/iN9etCTzw/fBnp0/uj0f5BOOGvZut2mzsiiBZ/FdT6gFQCKRO/tmcKOxn5drWZ2Ndm/xBb1SI4zwWbGtmIw==}
- resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
-
- resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
- engines: {node: '>= 6'}
-
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
@@ -5497,22 +5477,9 @@ packages:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
-
- resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
-
- resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
- engines: {node: '>= 4'}
-
resolution: {integrity: sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==}
- resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
-
resolution: {integrity: sha512-BTJ9aZYL3vCfZlZOBLy9v8TUqWGQ0pzFnygKwFZt5udj6viBoFIBviKPUoZLDCPn1FoXffv6McQFDenrm5Krfw==}
engines: {node: '>=20'}
@@ -5672,10 +5639,6 @@ packages:
resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==}
engines: {node: '>=8.6'}
- resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
- engines: {node: '>=0.12'}
-
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
@@ -6403,9 +6366,6 @@ packages:
resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
- resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}
-
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
@@ -7072,10 +7032,6 @@ packages:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
- resolution: {integrity: sha512-+/R92+k6wwhkdJa7tSXp2WqLaRjyo2eTNbgxNyuZV9fKZ6zLcM9ZSd2ZdzsvrZwAvu4sk3vSfxEmj0xwfOVe7Q==}
- engines: {node: '>=22'}
-
resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}
@@ -7647,9 +7603,6 @@ packages:
resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
-
resolution: {integrity: sha512-MCnImG4Q5vPwhSXnov56nOuyyKn6LC+Qd7II1UiKc+ACRtug5iAtn0+CwXNxM38AC5lSowEY+oYEtZX2qMnUyw==}
@@ -7846,9 +7799,6 @@ packages:
resolution: {integrity: sha512-twN+njEipszzlMJd4ONUYgSfZPDxgHhT9Ahed5uTigpQn90FggW4SA/AIPq/6a149fTbE9qBEcSwE3FAEp6wQQ==}
- resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==}
-
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -9024,10 +8974,6 @@ packages:
resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
engines: {node: '>=20.18.1'}
- resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==}
- engines: {node: '>=22.19.0'}
-
resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
@@ -13695,8 +13641,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
-
@@ -13797,26 +13741,6 @@ snapshots:
- dependencies:
- boolbase: 1.0.0
- css-select: 5.2.2
- css-what: 6.2.2
- domelementtype: 2.3.0
- domhandler: 5.0.3
- domutils: 3.2.2
-
- dependencies:
- cheerio-select: 2.1.0
- dom-serializer: 2.0.0
- domhandler: 5.0.3
- domutils: 3.2.2
- htmlparser2: 8.0.2
- parse5: 7.3.0
- parse5-htmlparser2-tree-adapter: 7.1.0
- tslib: 2.8.1
-
dependencies:
chevrotain: 12.0.0
@@ -14070,16 +13994,6 @@ snapshots:
- dependencies:
- boolbase: 1.0.0
- css-what: 6.2.2
- domhandler: 5.0.3
- domutils: 3.2.2
- nth-check: 2.1.1
-
-
@@ -14403,28 +14317,10 @@ snapshots:
dependencies:
esutils: 2.0.3
- dependencies:
- domelementtype: 2.3.0
- domhandler: 5.0.3
- entities: 4.5.0
-
-
- dependencies:
- domelementtype: 2.3.0
-
optionalDependencies:
'@types/trusted-types': 2.0.7
- dependencies:
- dom-serializer: 2.0.0
- domelementtype: 2.3.0
- domhandler: 5.0.3
-
dependencies:
type-fest: 5.8.0
@@ -14495,8 +14391,6 @@ snapshots:
ansi-colors: 4.1.3
strip-ansi: 6.0.1
-
@@ -15648,13 +15542,6 @@ snapshots:
- dependencies:
- domelementtype: 2.3.0
- domhandler: 5.0.3
- domutils: 3.2.2
- entities: 4.5.0
-
dependencies:
depd: 2.0.0
@@ -16297,11 +16184,6 @@ snapshots:
- dependencies:
- cheerio: 1.0.0-rc.11
- undici: 8.10.0
-
@@ -17188,10 +17070,6 @@ snapshots:
path-key: 4.0.0
unicorn-magic: 0.3.0
- dependencies:
- boolbase: 1.0.0
-
dependencies:
esm-env: 1.2.2
@@ -17488,11 +17366,6 @@ snapshots:
- dependencies:
- domhandler: 5.0.3
- parse5: 7.3.0
-
dependencies:
entities: 6.0.1
@@ -19159,8 +19032,6 @@ snapshots:
-
dependencies:
pathe: 2.0.3
diff --git a/src/shared/src/lib/rate-limits.ts b/src/shared/src/lib/rate-limits.ts
index 1b4f37ef7..4ea0f8d7c 100644
--- a/src/shared/src/lib/rate-limits.ts
+++ b/src/shared/src/lib/rate-limits.ts
@@ -23,17 +23,6 @@ export const RATE_LIMITS = {
* any single channel/DM without throttling normal chat bursts.
*/
"community:msgSend": { windowMs: 10_000, max: 30 },
- /**
- * Authenticated link-preview lookups. Cache hits are cheap but still count:
- * the boundary accepts a user-controlled public URL and must stay bounded
- * even when KV is cold or unavailable.
- */
- "community:linkPreview": { windowMs: 60_000, max: 60 },
- /**
- * Authenticated same-origin thumbnail cache misses. The digest-only route
- * cannot choose an origin, but decoding/transcoding is still bounded work.
- */
- "community:linkPreviewThumbnail": { windowMs: 60_000, max: 120 },
/**
* OTP send (better-auth `/email-otp/send-verification-otp`). Prevents
* cost/abuse from someone spamming another user's inbox. Window/max are
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index 3542f13e4..f070e56b9 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -1,6 +1,6 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: a27a7b391b3db90b6ddb2cd1ea69e00b)
-// Runtime types generated with [email protected] 2026-04-09 global_fetch_strictly_public,nodejs_compat
+// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: 6e7be9d51dee6db54c6b2628dea1f79e)
+// Runtime types generated with [email protected] 2026-04-09 nodejs_compat
interface __BaseEnv_CloudflareEnv {
CACHE_KV: KVNamespace;
NEXT_INC_CACHE_R2_BUCKET: R2Bucket;
@@ -10,7 +10,6 @@ interface __BaseEnv_CloudflareEnv {
NEXT_TAG_CACHE_D1: D1Database;
DB: D1Database;
WAKE_QUEUE: Queue;
- IMAGES: ImagesBinding;
ASSETS: Fetcher;
RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";
MIN_CLI_VERSION: "0.0.159";
diff --git a/src/web/package.json b/src/web/package.json
index 367d3c026..560f205f9 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -7,11 +7,10 @@
"build": "tsx scripts/validate-blog-assets.ts && next build",
"validate:blog": "tsx scripts/validate-blog-assets.ts",
"preflight:bug-reports": "tsx scripts/preflight-bug-reports.ts",
- "preflight:link-preview-thumbnails": "tsx scripts/preflight-link-preview-thumbnails.ts",
"start": "next start",
"lint": "eslint src/",
- "deploy": "pnpm preflight:link-preview-thumbnails && opennextjs-cloudflare build && opennextjs-cloudflare deploy",
- "upload": "pnpm preflight:link-preview-thumbnails && opennextjs-cloudflare build && opennextjs-cloudflare upload",
+ "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
+ "upload": "opennextjs-cloudflare build && opennextjs-cloudflare upload",
"preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
"cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts",
"test": "vitest run --config vitest.workspace.config.ts",
@@ -81,7 +80,6 @@
"idb-keyval": "^6.3.0",
"input-otp": "^1.4.2",
"katex": "^0.18.4",
- "link-preview-js": "5.0.0",
"lucide-react": "^1.31.0",
"mdast-util-find-and-replace": "^3.0.2",
"mdast-util-from-markdown": "^2.0.3",
diff --git a/src/web/scripts/preflight-link-preview-thumbnails.test.ts b/src/web/scripts/preflight-link-preview-thumbnails.test.ts
deleted file mode 100644
index ea18e3d8a..000000000
--- a/src/web/scripts/preflight-link-preview-thumbnails.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { describe, expect, it, vi } from "vitest"
-import { verifyLinkPreviewThumbnailLifecycle } from "./preflight-link-preview-thumbnails"
-
-const ACCOUNT = "0123456789abcdef0123456789abcdef"
-const BUCKET = "alook-community-media"
-const TOKEN = "CF_PRIVATE_PREFLIGHT_TOKEN"
-const URL = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/r2/buckets/${BUCKET}/lifecycle`
-
-function lifecycleRule(overrides: Record<string, unknown> = {}) {
- return {
- id: "delete-link-preview-thumbnails-after-seven-days",
- enabled: true,
- conditions: { prefix: "link-preview-thumbnails/v1/" },
- deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_800 } },
- ...overrides,
- }
-}
-
-describe("link-preview thumbnail R2 lifecycle preflight", () => {
- it("passes one exact seven-day prefix rule without mutating Cloudflare", async () => {
- const fetchImpl = vi.fn().mockResolvedValue(Response.json({
- success: true,
- result: { rules: [lifecycleRule(), { enabled: true, conditions: { prefix: "other/" } }] },
- }))
-
- await expect(verifyLinkPreviewThumbnailLifecycle({
- accountId: ACCOUNT,
- bucketName: BUCKET,
- apiToken: TOKEN,
- fetchImpl,
- })).resolves.toEqual({ ok: true, sevenDayLifecycle: true })
- expect(fetchImpl).toHaveBeenCalledWith(URL, {
- method: "GET",
- headers: { authorization: `Bearer ${TOKEN}` },
- })
- })
-
- it.each([
- ["missing", []],
- ["disabled", [lifecycleRule({ enabled: false })]],
- ["wrong prefix", [lifecycleRule({ conditions: { prefix: "link-preview-thumbnails/" } })]],
- ["wrong age", [lifecycleRule({ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_801 } } })]],
- ["duplicate", [lifecycleRule(), lifecycleRule()]],
- ])("fails closed when the required lifecycle is %s", async (_label, rules) => {
- const fetchImpl = vi.fn().mockResolvedValue(Response.json({ success: true, result: { rules } }))
- await expect(verifyLinkPreviewThumbnailLifecycle({
- accountId: ACCOUNT,
- bucketName: BUCKET,
- apiToken: TOKEN,
- fetchImpl,
- })).resolves.toEqual({ ok: false, sevenDayLifecycle: false })
- })
-
- it("rejects unsafe inputs and transport failures without leaking credentials", async () => {
- const fetchImpl = vi.fn()
- await expect(verifyLinkPreviewThumbnailLifecycle({
- accountId: "../account",
- bucketName: BUCKET,
- apiToken: TOKEN,
- fetchImpl,
- })).resolves.toMatchObject({ ok: false })
- expect(fetchImpl).not.toHaveBeenCalled()
-
- const logs: string[] = []
- await expect(verifyLinkPreviewThumbnailLifecycle({
- accountId: ACCOUNT,
- bucketName: BUCKET,
- apiToken: TOKEN,
- fetchImpl: vi.fn().mockRejectedValue(new Error(TOKEN)),
- log: (message) => logs.push(message),
- })).resolves.toMatchObject({ ok: false })
- expect(JSON.stringify(logs)).not.toContain(TOKEN)
- })
-})
diff --git a/src/web/scripts/preflight-link-preview-thumbnails.ts b/src/web/scripts/preflight-link-preview-thumbnails.ts
deleted file mode 100644
index 32df1163b..000000000
--- a/src/web/scripts/preflight-link-preview-thumbnails.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { pathToFileURL } from "node:url"
-
-const THUMBNAIL_PREFIX = "link-preview-thumbnails/v1/"
-const SEVEN_DAYS_SECONDS = 7 * 24 * 60 * 60
-
-type CloudflareEnvelope = { success?: unknown; result?: unknown }
-
-function record(value: unknown): Record<string, unknown> | null {
- return value !== null && typeof value === "object" && !Array.isArray(value)
- ? value as Record<string, unknown>
- : null
-}
-
-export async function verifyLinkPreviewThumbnailLifecycle(args: {
- accountId: string
- bucketName: string
- apiToken: string
- fetchImpl?: typeof fetch
- log?: (message: string) => void
-}): Promise<{ ok: boolean; sevenDayLifecycle: boolean }> {
- const fail = () => ({ ok: false, sevenDayLifecycle: false })
- if (!/^[0-9a-f]{32}$/.test(args.accountId)
- || !/^[a-z0-9](?:[a-z0-9.-]{1,61}[a-z0-9])?$/.test(args.bucketName)
- || args.apiToken.trim().length === 0) {
- return fail()
- }
-
- try {
- const fetchImpl = args.fetchImpl ?? fetch
- const url = `https://api.cloudflare.com/client/v4/accounts/${args.accountId}/r2/buckets/${args.bucketName}/lifecycle`
- const response = await fetchImpl(url, {
- method: "GET",
- headers: { authorization: `Bearer ${args.apiToken}` },
- })
- if (!response.ok) return fail()
- const envelope = await response.json() as CloudflareEnvelope
- const lifecycle = envelope.success === true ? record(envelope.result) : null
- const rules = Array.isArray(lifecycle?.rules) ? lifecycle.rules : []
- const matches = rules.filter((value) => {
- const rule = record(value)
- const conditions = record(rule?.conditions)
- const transition = record(rule?.deleteObjectsTransition)
- const condition = record(transition?.condition)
- return rule?.enabled === true
- && conditions?.prefix === THUMBNAIL_PREFIX
- && condition?.type === "Age"
- && condition?.maxAge === SEVEN_DAYS_SECONDS
- })
- const sevenDayLifecycle = matches.length === 1
- return { ok: sevenDayLifecycle, sevenDayLifecycle }
- } catch {
- args.log?.("link-preview thumbnail R2 preflight failed closed")
- return fail()
- }
-}
-
-async function main(): Promise<void> {
- const result = await verifyLinkPreviewThumbnailLifecycle({
- accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "",
- bucketName: process.env.COMMUNITY_MEDIA_BUCKET_NAME ?? "alook-community-media",
- apiToken: process.env.CLOUDFLARE_API_TOKEN ?? "",
- log: (message) => process.stderr.write(`${message}\n`),
- })
- process.stdout.write(`${JSON.stringify(result)}\n`)
- if (!result.ok) process.exitCode = 1
-}
-
-const invokedPath = process.argv[1]
-if (invokedPath && import.meta.url === pathToFileURL(invokedPath).href) {
- void main().catch(() => {
- process.stderr.write("link-preview thumbnail R2 preflight failed closed\n")
- process.stdout.write(`${JSON.stringify({ ok: false, sevenDayLifecycle: false })}\n`)
- process.exitCode = 1
- })
-}
diff --git a/src/web/src/app/api/community/link-preview/route.test.ts b/src/web/src/app/api/community/link-preview/route.test.ts
deleted file mode 100644
index 267b5d613..000000000
--- a/src/web/src/app/api/community/link-preview/route.test.ts
+++ /dev/null
@@ -1,370 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest"
-import { NextRequest, NextResponse } from "next/server"
-
-const mockFetchLinkPreview = vi.fn()
-const mockCheckRateLimit = vi.fn()
-const mockKvGet = vi.fn()
-const mockKvPut = vi.fn()
-const mockR2Put = vi.fn()
-const mockWaitUntil = vi.fn()
-const mockLogError = vi.fn()
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ ctx: { waitUntil: mockWaitUntil } })),
-}))
-
-vi.mock("@/lib/community/link-preview-fetch", async () => {
- const actual = await vi.importActual<typeof import("@/lib/community/link-preview-fetch")>(
- "@/lib/community/link-preview-fetch",
- )
- return {
- ...actual,
- fetchLinkPreview: (...args: unknown[]) => mockFetchLinkPreview(...args),
- }
-})
-
-vi.mock("@/lib/rate-limit", () => ({
- checkRateLimit: (...args: unknown[]) => mockCheckRateLimit(...args),
-}))
-
-vi.mock("@/lib/logger", () => ({
- log: { error: (...args: unknown[]) => mockLogError(...args) },
-}))
-
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: (...args: any[]) => unknown) => (req: NextRequest) => handler(req, {
- env: {
- CACHE_KV: { get: mockKvGet, put: mockKvPut },
- COMMUNITY_MEDIA: { put: mockR2Put },
- },
- userId: "user_1",
- email: "[email protected]",
- }),
-}))
-
-vi.mock("@/lib/middleware/helpers", () => ({
- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
- writeError: (message: string, status: number, headers?: HeadersInit) =>
- NextResponse.json({ error: message }, { status, headers }),
-}))
-
-import { POST } from "./route"
-import { LinkPreviewFetchError } from "@/lib/community/link-preview-fetch"
-
-function request(body: unknown): NextRequest {
- return new NextRequest("http://localhost/api/community/link-preview", {
- method: "POST",
- body: JSON.stringify(body),
- })
-}
-
-function rawRequest(body: BodyInit, headers?: HeadersInit): NextRequest {
- return new NextRequest("http://localhost/api/community/link-preview", {
- method: "POST",
- body,
- headers,
- })
-}
-
-describe("POST /api/community/link-preview", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockCheckRateLimit.mockResolvedValue({ allowed: true })
- mockKvGet.mockResolvedValue(null)
- mockKvPut.mockResolvedValue(undefined)
- mockR2Put.mockResolvedValue(undefined)
- mockFetchLinkPreview.mockResolvedValue({
- url: "https://example.com/",
- hostname: "example.com",
- title: "Example",
- })
- })
-
- it("rate-limits before rejecting an invalid target", async () => {
- const response = await POST(request({ url: "http://127.0.0.1/private" }))
-
- expect(response.status).toBe(400)
- expect(mockCheckRateLimit).toHaveBeenCalledWith(
- expect.anything(),
- "community:linkPreview",
- "user_1",
- )
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it("rejects an oversized declared body after applying the rate limit", async () => {
- const response = await POST(rawRequest("{}", { "content-length": "4097" }))
-
- expect(response.status).toBe(413)
- expect(mockCheckRateLimit).toHaveBeenCalledOnce()
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it("streams and rejects an oversized body when content-length is absent", async () => {
- const req = rawRequest("x".repeat(4097), { "content-type": "application/json" })
- expect(req.headers.get("content-length")).toBeNull()
-
- const response = await POST(req)
-
- expect(response.status).toBe(413)
- expect(mockCheckRateLimit).toHaveBeenCalledOnce()
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it("rejects malformed JSON only after applying the rate limit", async () => {
- const response = await POST(rawRequest("{"))
-
- expect(response.status).toBe(400)
- expect(mockCheckRateLimit).toHaveBeenCalledOnce()
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it("rejects a request with no body only after applying the rate limit", async () => {
- const req = new NextRequest("http://localhost/api/community/link-preview", { method: "POST" })
-
- const response = await POST(req)
-
- expect(response.status).toBe(400)
- expect(mockCheckRateLimit).toHaveBeenCalledOnce()
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it("returns a valid cached preview without fetching the origin", async () => {
- mockKvGet.mockResolvedValue(JSON.stringify({
- preview: { url: "https://example.com/", hostname: "example.com", title: "Cached" },
- staleTimeSeconds: 21_600,
- }))
-
- const response = await POST(request({ url: "https://example.com/#fragment" }))
- expect(await response.json()).toEqual({
- preview: { url: "https://example.com/", hostname: "example.com", title: "Cached" },
- staleTimeSeconds: 21_600,
- })
- expect(mockCheckRateLimit).toHaveBeenCalledWith(
- expect.anything(),
- "community:linkPreview",
- "user_1",
- )
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it("returns a cached negative preview without fetching the origin", async () => {
- mockKvGet.mockResolvedValue(JSON.stringify({ preview: null, staleTimeSeconds: 300 }))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect(await response.json()).toEqual({ preview: null, staleTimeSeconds: 300 })
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- expect(mockKvPut).not.toHaveBeenCalled()
- })
-
- it("returns a valid degraded cached preview with its exact digest path", async () => {
- const thumbnailUrl = "/api/community/link-preview/thumbnail/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7"
- mockKvGet.mockResolvedValue(JSON.stringify({
- preview: {
- url: "https://example.com/",
- hostname: "example.com",
- title: "Cached",
- thumbnailUrl,
- },
- staleTimeSeconds: 300,
- }))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect(await response.json()).toEqual({
- preview: {
- url: "https://example.com/",
- hostname: "example.com",
- title: "Cached",
- thumbnailUrl,
- },
- staleTimeSeconds: 300,
- })
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-
- it.each([
- ["an unsupported TTL", "/api/community/link-preview/thumbnail/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7", 123],
- ["an upstream image URL", "https://images.example.com/og.jpg", 21_600],
- ["a mismatched digest path", `/api/community/link-preview/thumbnail/${"a".repeat(64)}`, 21_600],
- ])("treats a cached preview with %s as a miss", async (_label, thumbnailUrl, staleTimeSeconds) => {
- mockKvGet.mockResolvedValue(JSON.stringify({
- preview: {
- url: "https://example.com/",
- hostname: "example.com",
- title: "Unsafe cache entry",
- thumbnailUrl,
- },
- staleTimeSeconds,
- }))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect((await response.json()).preview.title).toBe("Example")
- expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
- })
-
- it("treats a malformed cache entry as a miss", async () => {
- mockKvGet.mockResolvedValue("not-json")
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect((await response.json()).preview.title).toBe("Example")
- expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
- })
-
- it("treats a cached primitive preview as a miss", async () => {
- mockKvGet.mockResolvedValue(JSON.stringify({
- preview: "not-an-object",
- staleTimeSeconds: 21_600,
- }))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect((await response.json()).preview.title).toBe("Example")
- expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
- })
-
- it("degrades a KV read failure to a bounded origin fetch", async () => {
- mockKvGet.mockRejectedValue(new Error("KV unavailable"))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect((await response.json()).preview.title).toBe("Example")
- expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
- })
-
- it("fetches a cache miss and schedules the sanitized result for KV", async () => {
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect(await response.json()).toMatchObject({ preview: { title: "Example" } })
- expect(mockFetchLinkPreview).toHaveBeenCalledWith("https://example.com/")
- expect(mockKvPut).toHaveBeenCalledWith(
- expect.stringMatching(/^link-preview:v2:[a-f0-9]{64}$/),
- JSON.stringify({
- preview: { url: "https://example.com/", hostname: "example.com", title: "Example" },
- staleTimeSeconds: 21_600,
- }),
- { expirationTtl: 21_600 },
- )
- expect(mockWaitUntil).toHaveBeenCalledWith(expect.any(Promise))
- expect(mockLogError).not.toHaveBeenCalled()
- })
-
- it("negative-caches a bounded origin failure and degrades to no card", async () => {
- mockFetchLinkPreview.mockRejectedValue(new LinkPreviewFetchError(
- "origin unavailable",
- "document_fetch",
- "upstream_http_status",
- 503,
- ))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect(await response.json()).toEqual({ preview: null, staleTimeSeconds: 300 })
- expect(mockKvPut).toHaveBeenCalledWith(
- expect.any(String),
- JSON.stringify({ preview: null, staleTimeSeconds: 300 }),
- { expirationTtl: 300 },
- )
- expect(mockLogError).toHaveBeenCalledOnce()
- expect(mockLogError).toHaveBeenCalledWith("link_preview_failure", expect.objectContaining({
- stage: "document_fetch",
- errorCode: "upstream_http_status",
- httpStatus: 503,
- elapsedMs: expect.any(Number),
- disposition: "negative_cache",
- pageDigestPrefix: "0f115db062b7",
- }))
- const serialized = JSON.stringify(mockLogError.mock.calls[0]?.[1])
- expect(serialized).not.toContain("https://example.com")
- expect(serialized).not.toContain("origin unavailable")
- expect(serialized).not.toContain("user_1")
- })
-
- it("swallows a background KV write failure", async () => {
- mockKvPut.mockRejectedValue(new Error("KV unavailable"))
-
- const response = await POST(request({ url: "https://example.com/" }))
- const backgroundWrite = mockWaitUntil.mock.calls[0]?.[0] as Promise<void>
-
- expect((await response.json()).preview.title).toBe("Example")
- await expect(backgroundWrite).resolves.toBeUndefined()
- })
-
- it("awaits a private R2 manifest before returning only a same-origin thumbnail path", async () => {
- mockFetchLinkPreview.mockResolvedValue({
- url: "https://example.com/",
- hostname: "example.com",
- title: "Example",
- thumbnailSource: "https://images.example.com/og.png",
- })
-
- const response = await POST(request({ url: "https://example.com/" }))
- const body = await response.json()
-
- expect(body).toEqual({
- preview: {
- url: "https://example.com/",
- hostname: "example.com",
- title: "Example",
- thumbnailUrl: "/api/community/link-preview/thumbnail/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7",
- },
- staleTimeSeconds: 21_600,
- })
- expect(JSON.stringify(body)).not.toContain("images.example.com")
- expect(mockR2Put).toHaveBeenCalledWith(
- "link-preview-thumbnails/v1/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7/manifest.json",
- expect.stringContaining('"sourceUrl":"https://images.example.com/og.png"'),
- expect.objectContaining({ httpMetadata: { contentType: "application/json" } }),
- )
- expect(mockR2Put.mock.invocationCallOrder[0]).toBeLessThan(mockKvPut.mock.invocationCallOrder[0]!)
- expect(mockLogError).not.toHaveBeenCalled()
- })
-
- it("omits a thumbnail and uses the recovery TTL when the manifest write fails", async () => {
- mockFetchLinkPreview.mockResolvedValue({
- url: "https://example.com/",
- hostname: "example.com",
- title: "Example",
- thumbnailSource: "https://images.example.com/og.png",
- })
- mockR2Put.mockRejectedValue(new Error("R2 unavailable"))
-
- const response = await POST(request({ url: "https://example.com/" }))
-
- expect(await response.json()).toEqual({
- preview: { url: "https://example.com/", hostname: "example.com", title: "Example" },
- staleTimeSeconds: 300,
- })
- expect(mockKvPut).toHaveBeenCalledWith(
- expect.any(String),
- expect.stringContaining('"staleTimeSeconds":300'),
- { expirationTtl: 300 },
- )
- expect(mockLogError).toHaveBeenCalledOnce()
- expect(mockLogError).toHaveBeenCalledWith("link_preview_failure", expect.objectContaining({
- stage: "manifest_write",
- errorCode: "manifest_write_failed",
- elapsedMs: expect.any(Number),
- disposition: "text_only_recovery_ttl",
- pageDigestPrefix: "0f115db062b7",
- }))
- const serialized = JSON.stringify(mockLogError.mock.calls[0]?.[1])
- expect(serialized).not.toContain("https://example.com")
- expect(serialized).not.toContain("images.example.com")
- expect(serialized).not.toContain("R2 unavailable")
- })
-
- it("enforces the authenticated preview rate limit", async () => {
- mockCheckRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 17 })
-
- const response = await POST(rawRequest("not-json"))
-
- expect(response.status).toBe(429)
- expect(response.headers.get("retry-after")).toBe("17")
- expect(mockKvGet).not.toHaveBeenCalled()
- expect(mockFetchLinkPreview).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/app/api/community/link-preview/route.ts b/src/web/src/app/api/community/link-preview/route.ts
deleted file mode 100644
index a61ed2124..000000000
--- a/src/web/src/app/api/community/link-preview/route.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { NextRequest } from "next/server"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { withAuth } from "@/lib/middleware/auth"
-import { writeError, writeJSON } from "@/lib/middleware/helpers"
-import { checkRateLimit } from "@/lib/rate-limit"
-import { log } from "@/lib/logger"
-import {
- fetchLinkPreview,
- LinkPreviewFetchError,
- normalizePublicPreviewUrl,
-} from "@/lib/community/link-preview-fetch"
-import {
- linkPreviewPageDigest,
- linkPreviewThumbnailUrl,
- writeLinkPreviewThumbnailManifest,
-} from "@/lib/community/link-preview-thumbnail"
-import type { LinkPreview } from "@/lib/community/link-preview"
-
-const POSITIVE_TTL_SECONDS = 6 * 60 * 60
-const NEGATIVE_TTL_SECONDS = 5 * 60
-const MAX_REQUEST_BODY_BYTES = 4 * 1024
-
-type CacheEntry = {
- preview: LinkPreview | null
- staleTimeSeconds: typeof POSITIVE_TTL_SECONDS | typeof NEGATIVE_TTL_SECONDS
-}
-
-class RequestBodyTooLargeError extends Error {}
-
-async function readBoundedJson(req: NextRequest): Promise<unknown> {
- const declaredLength = req.headers.get("content-length")
- if (declaredLength && /^\d+$/.test(declaredLength) && Number(declaredLength) > MAX_REQUEST_BODY_BYTES) {
- await req.body?.cancel().catch(() => {})
- throw new RequestBodyTooLargeError("request body too large")
- }
- if (!req.body) throw new Error("invalid request body")
-
- const reader = req.body.getReader()
- const decoder = new TextDecoder()
- let body = ""
- let total = 0
- try {
- while (true) {
- const { done, value } = await reader.read()
- if (done) break
- total += value.byteLength
- if (total > MAX_REQUEST_BODY_BYTES) {
- await reader.cancel()
- throw new RequestBodyTooLargeError("request body too large")
- }
- body += decoder.decode(value, { stream: true })
- }
- } finally {
- reader.releaseLock()
- }
- return JSON.parse(body + decoder.decode())
-}
-
-function isLinkPreview(value: unknown, expectedDigest: string): value is LinkPreview {
- if (!value || typeof value !== "object") return false
- const item = value as Record<string, unknown>
- return typeof item.url === "string"
- && typeof item.hostname === "string"
- && typeof item.title === "string"
- && (item.description === undefined || typeof item.description === "string")
- && (item.siteName === undefined || typeof item.siteName === "string")
- && (item.thumbnailUrl === undefined
- || item.thumbnailUrl === linkPreviewThumbnailUrl(expectedDigest))
-}
-
-function parseCacheEntry(raw: string, expectedDigest: string): CacheEntry | null {
- try {
- const value = JSON.parse(raw) as { preview?: unknown; staleTimeSeconds?: unknown }
- if (value.preview === null && value.staleTimeSeconds === NEGATIVE_TTL_SECONDS) {
- return { preview: null, staleTimeSeconds: NEGATIVE_TTL_SECONDS }
- }
- if (isLinkPreview(value.preview, expectedDigest)
- && (value.staleTimeSeconds === POSITIVE_TTL_SECONDS
- || value.staleTimeSeconds === NEGATIVE_TTL_SECONDS)) {
- return { preview: value.preview, staleTimeSeconds: value.staleTimeSeconds }
- }
- } catch {
- // Treat a stale/malformed cache entry as a miss.
- }
- return null
-}
-
-function cacheKey(pageDigest: string): string {
- return `link-preview:v2:${pageDigest}`
-}
-
-function elapsedSince(startedAt: number): number {
- return Math.max(0, Date.now() - startedAt)
-}
-
-function logLinkPreviewFailure(fields: {
- stage: string
- errorCode: string
- elapsedMs: number
- disposition: "negative_cache" | "text_only_recovery_ttl"
- pageDigestPrefix: string
- httpStatus?: number
-}) {
- log.error("link_preview_failure", fields)
-}
-
-/**
- * Independent, authenticated URL-unfurl boundary. It is deliberately not part
- * of message list/send: text paints first, and a slow/failed origin only makes
- * this optional card disappear.
- */
-export const POST = withAuth(async (req: NextRequest, ctx) => {
- const rateLimit = await checkRateLimit(ctx.env, "community:linkPreview", ctx.userId)
- if (!rateLimit.allowed) {
- return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })
- }
-
- let raw: unknown
- try {
- raw = await readBoundedJson(req)
- } catch (error) {
- if (error instanceof RequestBodyTooLargeError) return writeError("request body too large", 413)
- return writeError("invalid request body", 400)
- }
- const requestedUrl = typeof (raw as { url?: unknown } | null)?.url === "string"
- ? (raw as { url: string }).url
- : ""
-
- let normalized: string
- try {
- normalized = normalizePublicPreviewUrl(requestedUrl).href
- } catch {
- return writeError("invalid preview URL", 400)
- }
-
- const pageDigest = await linkPreviewPageDigest(normalized)
- const key = cacheKey(pageDigest)
- const kv = ctx.env.CACHE_KV ?? null
- if (kv) {
- try {
- const cached = await kv.get(key)
- if (cached) {
- const entry = parseCacheEntry(cached, pageDigest)
- if (entry) return writeJSON(entry)
- }
- } catch {
- // KV is memoization only; a cache outage degrades to the bounded fetch.
- }
- }
-
- let entry: CacheEntry
- const metadataStartedAt = Date.now()
- try {
- const fetched = await fetchLinkPreview(normalized)
- const { thumbnailSource, ...preview } = fetched
- let staleTimeSeconds: CacheEntry["staleTimeSeconds"] = POSITIVE_TTL_SECONDS
- if (thumbnailSource) {
- const manifestStartedAt = Date.now()
- try {
- await writeLinkPreviewThumbnailManifest({
- bucket: ctx.env.COMMUNITY_MEDIA,
- pageDigest,
- sourceUrl: thumbnailSource,
- })
- preview.thumbnailUrl = linkPreviewThumbnailUrl(pageDigest)
- } catch {
- logLinkPreviewFailure({
- stage: "manifest_write",
- errorCode: "manifest_write_failed",
- elapsedMs: elapsedSince(manifestStartedAt),
- disposition: "text_only_recovery_ttl",
- pageDigestPrefix: pageDigest.slice(0, 12),
- })
- // A capability is exposed only after its strongly-consistent manifest
- // exists. Retry this degraded text-only preview after the negative TTL.
- staleTimeSeconds = NEGATIVE_TTL_SECONDS
- }
- }
- entry = { preview, staleTimeSeconds }
- } catch (error) {
- const failure = error instanceof LinkPreviewFetchError ? error : null
- logLinkPreviewFailure({
- stage: failure?.stage ?? "metadata_fetch",
- errorCode: failure?.code ?? "unexpected_error",
- elapsedMs: elapsedSince(metadataStartedAt),
- disposition: "negative_cache",
- pageDigestPrefix: pageDigest.slice(0, 12),
- ...(failure?.httpStatus === undefined ? {} : { httpStatus: failure.httpStatus }),
- })
- entry = { preview: null, staleTimeSeconds: NEGATIVE_TTL_SECONDS }
- }
-
- if (kv) {
- const write = kv.put(key, JSON.stringify(entry), {
- expirationTtl: entry.staleTimeSeconds,
- }).catch(() => {
- // A cache write failure must never turn a valid message link into an error.
- })
- getCloudflareContext().ctx.waitUntil(write)
- }
- return writeJSON(entry)
-})
diff --git a/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.test.ts b/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.test.ts
deleted file mode 100644
index 38304dc66..000000000
--- a/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.test.ts
+++ /dev/null
@@ -1,486 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { NextRequest } from "next/server"
-
-const DIGEST = "a".repeat(64)
-const SOURCE = "https://images.example.com/og.jpg"
-let sourceDigest = ""
-const mockR2Get = vi.fn()
-const mockR2Put = vi.fn()
-const mockKvGet = vi.fn()
-const mockKvPut = vi.fn()
-const mockCheckRateLimit = vi.fn()
-const mockWaitUntil = vi.fn()
-const mockImagesInfo = vi.fn()
-const mockImagesInput = vi.fn()
-const mockImagesTransform = vi.fn()
-const mockImagesOutput = vi.fn()
-const mockLogError = vi.fn()
-let includeKv = true
-let includeImages = true
-
-vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({ ctx: { waitUntil: mockWaitUntil } })),
-}))
-
-vi.mock("@/lib/rate-limit", () => ({
- checkRateLimit: (...args: unknown[]) => mockCheckRateLimit(...args),
-}))
-
-vi.mock("@/lib/logger", () => ({
- log: { error: (...args: unknown[]) => mockLogError(...args) },
-}))
-
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: (handler: (...args: any[]) => unknown) => (req: NextRequest, context?: { params?: Record<string, string> }) => {
- const env: Record<string, unknown> = {
- COMMUNITY_MEDIA: { get: mockR2Get, put: mockR2Put },
- }
- if (includeKv) env.CACHE_KV = { get: mockKvGet, put: mockKvPut }
- if (includeImages) {
- env.IMAGES = {
- info: mockImagesInfo,
- input: mockImagesInput,
- }
- }
- return handler(req, {
- env,
- userId: "user_1",
- email: "[email protected]",
- params: context?.params,
- })
- },
-}))
-
-import { GET } from "./route"
-
-afterEach(() => {
- vi.useRealTimers()
- vi.unstubAllGlobals()
-})
-
-function stream(bytes: Uint8Array, cancel?: () => void): ReadableStream<Uint8Array> {
- return new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(bytes)
- controller.close()
- },
- cancel,
- })
-}
-
-function manifestObject(overrides: Record<string, unknown> = {}) {
- const value = JSON.stringify({
- version: 1,
- pageDigest: DIGEST,
- sourceUrl: SOURCE,
- sourceDigest,
- expiresAt: Date.now() + 60_000,
- ...overrides,
- })
- return {
- size: value.length,
- body: stream(new TextEncoder().encode(value)),
- text: vi.fn().mockResolvedValue(value),
- }
-}
-
-function cachedObject(overrides: Record<string, unknown> = {}) {
- return {
- size: 3,
- body: stream(new Uint8Array([4, 5, 6])),
- httpMetadata: { contentType: "image/webp" },
- customMetadata: { sourceDigest, expiresAt: String(Date.now() + 60_000) },
- ...overrides,
- }
-}
-
-function request(digest = DIGEST, query = ""): Promise<Response> {
- return GET(
- new NextRequest(`http://localhost/api/community/link-preview/thumbnail/${digest}${query}`),
- { params: { digest } },
- )
-}
-
-describe("GET /api/community/link-preview/thumbnail/[digest]", () => {
- beforeEach(async () => {
- vi.clearAllMocks()
- includeKv = true
- includeImages = true
- mockCheckRateLimit.mockResolvedValue({ allowed: true })
- mockKvGet.mockResolvedValue(null)
- mockKvPut.mockResolvedValue(undefined)
- mockR2Put.mockResolvedValue(undefined)
- mockR2Get.mockImplementation((key: string) => {
- if (key.endsWith("manifest.json")) return Promise.resolve(manifestObject())
- return Promise.resolve(null)
- })
- mockImagesInfo.mockResolvedValue({ format: "image/jpeg", fileSize: 3, width: 1200, height: 630 })
- mockImagesTransform.mockReturnThis()
- mockImagesOutput.mockResolvedValue({
- contentType: () => "image/webp",
- image: () => stream(new Uint8Array([7, 8, 9])),
- })
- mockImagesInput.mockReturnValue({
- transform: (...args: unknown[]) => {
- mockImagesTransform(...args)
- return { output: (...values: unknown[]) => mockImagesOutput(...values) }
- },
- })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), {
- headers: { "content-type": "image/jpeg" },
- })))
-
- // The fixture source digest must exactly match the production SHA-256.
- const digestBytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(SOURCE))
- sourceDigest = Array.from(new Uint8Array(digestBytes), (byte) => byte.toString(16).padStart(2, "0")).join("")
- expect(sourceDigest).toHaveLength(64)
- mockR2Get.mockImplementation((key: string) => {
- if (key.endsWith("manifest.json")) return Promise.resolve(manifestObject({ sourceDigest }))
- return Promise.resolve(null)
- })
- })
-
- it("rejects an invalid digest before R2, rate limiting, or any outbound fetch", async () => {
- const response = await request("../source")
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockR2Get).not.toHaveBeenCalled()
- expect(mockCheckRateLimit).not.toHaveBeenCalled()
- expect(fetch).not.toHaveBeenCalled()
- expect(mockLogError).not.toHaveBeenCalled()
- })
-
- it.each([
- ["missing", null],
- ["expired", manifestObject({ expiresAt: 1 })],
- ["mismatched", manifestObject({ pageDigest: "c".repeat(64) })],
- ])("returns the same no-store 404 for a %s manifest with zero outbound work", async (_label, object) => {
- mockR2Get.mockResolvedValueOnce(object)
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockCheckRateLimit).not.toHaveBeenCalled()
- expect(fetch).not.toHaveBeenCalled()
- expect(mockImagesInfo).not.toHaveBeenCalled()
- })
-
- it("returns the same no-store 404 when the manifest read fails", async () => {
- mockR2Get.mockRejectedValueOnce(new Error("R2 unavailable"))
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockCheckRateLimit).not.toHaveBeenCalled()
- expect(fetch).not.toHaveBeenCalled()
- expect(mockLogError).toHaveBeenCalledWith("link_preview_thumbnail_failure", expect.objectContaining({
- stage: "storage",
- disposition: "transient",
- }))
- })
-
- it.each([
- [Object.assign(new Error("coded storage error"), { code: "R2_TEMP" }), "storage_r2_temp"],
- ["unknown storage error", "storage_error"],
- ])("logs a stable storage code without exposing the raw failure", async (error, errorCode) => {
- mockR2Get.mockRejectedValueOnce(error)
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(mockLogError).toHaveBeenCalledWith("link_preview_thumbnail_failure", expect.objectContaining({
- stage: "storage",
- disposition: "transient",
- errorCode,
- }))
- expect(JSON.stringify(mockLogError.mock.calls)).not.toContain("coded storage error")
- expect(JSON.stringify(mockLogError.mock.calls)).not.toContain("unknown storage error")
- })
-
- it("serves a valid R2 WebP hit without rate limiting, network, or Images work", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(cachedObject({ customMetadata: { sourceDigest, expiresAt: String(Date.now() + 60_000) } }))
-
- const response = await request()
-
- expect(response.status).toBe(200)
- expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([4, 5, 6]))
- expect(response.headers.get("content-type")).toBe("image/webp")
- expect(response.headers.get("cache-control")).toBe("private, max-age=21600, immutable")
- expect(response.headers.get("content-disposition")).toBe("inline")
- expect(response.headers.get("x-content-type-options")).toBe("nosniff")
- expect(response.headers.get("cross-origin-resource-policy")).toBe("same-origin")
- expect(response.headers.get("referrer-policy")).toBe("no-referrer")
- expect(mockCheckRateLimit).not.toHaveBeenCalled()
- expect(fetch).not.toHaveBeenCalled()
- expect(mockImagesInfo).not.toHaveBeenCalled()
- })
-
- it("uses a valid manifest source only, ignores query inputs, and stores the fixed transformed WebP", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
-
- const response = await request(DIGEST, "?url=https://127.0.0.1/&width=9999&format=svg")
-
- expect(response.status).toBe(200)
- expect(fetch).toHaveBeenCalledWith(SOURCE, expect.objectContaining({ redirect: "manual", credentials: "omit" }))
- expect(mockCheckRateLimit).toHaveBeenCalledWith(expect.anything(), "community:linkPreviewThumbnail", "user_1")
- expect(mockImagesTransform).toHaveBeenCalledWith({ width: 640, height: 360, fit: "cover" })
- expect(mockImagesOutput).toHaveBeenCalledWith({ format: "image/webp", quality: 78, anim: false })
- expect(mockR2Put).toHaveBeenCalledWith(
- `link-preview-thumbnails/v1/${DIGEST}/thumbnail.webp`,
- new Uint8Array([7, 8, 9]),
- expect.objectContaining({
- httpMetadata: expect.objectContaining({ contentType: "image/webp" }),
- customMetadata: expect.objectContaining({ sourceDigest }),
- }),
- )
- expect(JSON.stringify(await response.arrayBuffer())).not.toContain("images.example.com")
- })
-
- it("refreshes a stale or source-mismatched object after canceling its body", async () => {
- const cancel = vi.fn()
- const stale = cachedObject({
- body: stream(new Uint8Array([1]), cancel),
- customMetadata: { sourceDigest: "c".repeat(64), expiresAt: "1" },
- })
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(stale)
-
- const response = await request()
-
- expect(response.status).toBe(200)
- expect(cancel).toHaveBeenCalledOnce()
- expect(fetch).toHaveBeenCalledOnce()
- expect(mockR2Put).toHaveBeenCalledOnce()
- })
-
- it("continues after a stale object's body refuses cancellation", async () => {
- const cancel = vi.fn().mockRejectedValue(new Error("already closed"))
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(cachedObject({
- body: { cancel },
- customMetadata: { sourceDigest: "c".repeat(64), expiresAt: "1" },
- }))
-
- const response = await request()
-
- expect(response.status).toBe(200)
- expect(cancel).toHaveBeenCalledOnce()
- expect(fetch).toHaveBeenCalledOnce()
- })
-
- it("returns the same no-store 404 when the cached-object read fails", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockRejectedValueOnce(new Error("R2 unavailable"))
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockCheckRateLimit).not.toHaveBeenCalled()
- expect(fetch).not.toHaveBeenCalled()
- expect(mockLogError).toHaveBeenCalledWith("link_preview_thumbnail_failure", expect.objectContaining({
- stage: "storage",
- disposition: "transient",
- }))
- })
-
- it("honors the five-minute negative cache before rate limiting or outbound work", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- mockKvGet.mockResolvedValue("1")
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(mockCheckRateLimit).not.toHaveBeenCalled()
- expect(fetch).not.toHaveBeenCalled()
- })
-
- it("rate-limits before cache-miss network and transform work", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- mockCheckRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 10 })
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(fetch).not.toHaveBeenCalled()
- expect(mockImagesInfo).not.toHaveBeenCalled()
- })
-
- it("fails closed without optional KV or an Images binding", async () => {
- includeKv = false
- includeImages = false
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(mockCheckRateLimit).toHaveBeenCalledOnce()
- expect(fetch).not.toHaveBeenCalled()
- expect(mockKvGet).not.toHaveBeenCalled()
- expect(mockKvPut).not.toHaveBeenCalled()
- expect(mockWaitUntil).not.toHaveBeenCalled()
- })
-
- it("treats negative-cache reads and writes as best-effort", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- mockKvGet.mockRejectedValueOnce(new Error("KV read unavailable"))
- vi.mocked(fetch).mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3]), {
- headers: { "content-type": "image/gif" },
- }))
- mockKvPut.mockRejectedValueOnce(new Error("KV write unavailable"))
-
- const response = await request()
- const backgroundWrite = mockWaitUntil.mock.calls[0]?.[0] as Promise<void>
-
- expect(response.status).toBe(404)
- expect(mockCheckRateLimit).toHaveBeenCalledOnce()
- expect(mockWaitUntil).toHaveBeenCalledOnce()
- await expect(backgroundWrite).resolves.toBeUndefined()
- })
-
- it("negative-caches a deterministic rejection while preserving the indistinguishable 404", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- vi.mocked(fetch).mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3]), {
- headers: { "content-type": "image/gif" },
- }))
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockKvPut).toHaveBeenCalledOnce()
- expect(mockKvPut).toHaveBeenCalledWith(
- `link-preview-thumbnail-negative:v1:${DIGEST}:${sourceDigest}`,
- "1",
- { expirationTtl: 300 },
- )
- expect(mockWaitUntil).toHaveBeenCalledWith(expect.any(Promise))
- expect(mockLogError).toHaveBeenCalledWith("link_preview_thumbnail_failure", expect.objectContaining({
- stage: "source",
- disposition: "deterministic",
- errorCode: "source_mime",
- pageDigestPrefix: DIGEST.slice(0, 12),
- }))
- })
-
- it("does not negative-cache source, Images, or R2 transient failures", async () => {
- for (const fail of [
- () => vi.mocked(fetch).mockRejectedValueOnce(new Error("origin unavailable")),
- () => mockImagesInfo.mockRejectedValueOnce(new Error("decode failed")),
- () => mockR2Put.mockRejectedValueOnce(new Error("R2 unavailable")),
- ]) {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- fail()
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockKvPut).not.toHaveBeenCalled()
- expect(mockWaitUntil).not.toHaveBeenCalled()
- vi.mocked(fetch).mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), {
- headers: { "content-type": "image/jpeg" },
- }))
- mockImagesInfo.mockResolvedValue({ format: "image/jpeg", fileSize: 3, width: 1200, height: 630 })
- mockR2Put.mockResolvedValue(undefined)
- }
- expect(mockLogError).toHaveBeenNthCalledWith(1, "link_preview_thumbnail_failure", expect.objectContaining({
- stage: "source",
- disposition: "transient",
- }))
- expect(mockLogError).toHaveBeenNthCalledWith(2, "link_preview_thumbnail_failure", expect.objectContaining({
- stage: "inspect",
- disposition: "transient",
- }))
- expect(mockLogError).toHaveBeenNthCalledWith(3, "link_preview_thumbnail_failure", expect.objectContaining({
- stage: "storage",
- disposition: "transient",
- }))
- })
-
- it("sanitizes an unexpected synchronous storage binding failure without negative caching", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- mockR2Put.mockImplementationOnce(() => {
- throw "raw synchronous storage failure"
- })
-
- const response = await request()
-
- expect(response.status).toBe(404)
- expect(response.headers.get("cache-control")).toBe("no-store")
- expect(mockKvPut).not.toHaveBeenCalled()
- expect(mockWaitUntil).not.toHaveBeenCalled()
- expect(mockLogError).toHaveBeenCalledWith("link_preview_thumbnail_failure", expect.objectContaining({
- stage: "transform",
- disposition: "transient",
- errorCode: "transform_unknown",
- pageDigestPrefix: DIGEST.slice(0, 12),
- }))
- expect(JSON.stringify(mockLogError.mock.calls)).not.toContain("raw synchronous storage failure")
- })
-
- it("bounds R2 persistence at two seconds and safely observes late rejection", async () => {
- vi.useFakeTimers()
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- mockR2Put.mockImplementationOnce(() => new Promise((_resolve, reject) => {
- setTimeout(() => reject(new Error("late R2 failure")), 3_000)
- }))
-
- const result = request()
- await vi.waitFor(() => expect(mockR2Put).toHaveBeenCalledOnce(), { interval: 1, timeout: 100 })
- await vi.advanceTimersByTimeAsync(2_000)
- const response = await result
-
- expect(response.status).toBe(404)
- expect(mockKvPut).not.toHaveBeenCalled()
- expect(mockLogError).toHaveBeenCalledWith("link_preview_thumbnail_failure", expect.objectContaining({
- stage: "storage",
- disposition: "transient",
- errorCode: "storage_timeout",
- elapsedMs: 2_000,
- }))
- await vi.advanceTimersByTimeAsync(1_000)
- })
-
- it("logs only sanitized stage evidence", async () => {
- mockR2Get
- .mockResolvedValueOnce(manifestObject({ sourceDigest }))
- .mockResolvedValueOnce(null)
- vi.mocked(fetch).mockRejectedValueOnce(new Error(`failed ${SOURCE} ${sourceDigest}`))
-
- await request()
-
- const serialized = JSON.stringify(mockLogError.mock.calls)
- expect(serialized).toContain("link_preview_thumbnail_failure")
- expect(serialized).toContain(DIGEST.slice(0, 12))
- expect(serialized).not.toContain(SOURCE)
- expect(serialized).not.toContain(sourceDigest)
- expect(serialized).not.toContain(`link-preview-thumbnails/v1/${DIGEST}`)
- })
-})
diff --git a/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.ts b/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.ts
deleted file mode 100644
index 402bd2265..000000000
--- a/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { NextResponse, type NextRequest } from "next/server"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { withAuth } from "@/lib/middleware/auth"
-import { checkRateLimit } from "@/lib/rate-limit"
-import { log } from "@/lib/logger"
-import {
- fetchAndTransformLinkPreviewThumbnail,
- isFreshLinkPreviewThumbnailObject,
- isLinkPreviewThumbnailDigest,
- LinkPreviewThumbnailFailure,
- linkPreviewThumbnailNegativeKey,
- linkPreviewThumbnailObjectKey,
- linkPreviewThumbnailObjectMetadata,
- readLinkPreviewThumbnailManifest,
-} from "@/lib/community/link-preview-thumbnail"
-
-const NEGATIVE_TTL_SECONDS = 5 * 60
-const PRIVATE_THUMBNAIL_CACHE = "private, max-age=21600, immutable"
-const STORAGE_TIMEOUT_MS = 2_000
-
-function stableStorageCode(error: unknown): string {
- if (typeof error === "object" && error !== null) {
- const value = error as { code?: unknown; name?: unknown }
- if ((typeof value.code === "string" || typeof value.code === "number")
- && /^[a-zA-Z0-9_.-]{1,64}$/.test(String(value.code))) {
- return `storage_${String(value.code).toLowerCase()}`
- }
- if (typeof value.name === "string" && /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(value.name)) {
- return `storage_${value.name.toLowerCase()}`
- }
- }
- return "storage_error"
-}
-
-function storageFailure(error: unknown, startedAt: number): LinkPreviewThumbnailFailure {
- return new LinkPreviewThumbnailFailure({
- stage: "storage",
- disposition: "transient",
- code: stableStorageCode(error),
- elapsedMs: Math.max(0, Date.now() - startedAt),
- message: "thumbnail storage operation failed",
- })
-}
-
-async function withStorageDeadline<T>(promise: Promise<T>, startedAt: number): Promise<T> {
- let timer: ReturnType<typeof setTimeout> | undefined
- const observed = promise.catch((error) => {
- throw storageFailure(error, startedAt)
- })
- observed.catch(() => {})
- const timeout = new Promise<never>((_resolve, reject) => {
- timer = setTimeout(() => reject(new LinkPreviewThumbnailFailure({
- stage: "storage",
- disposition: "transient",
- code: "storage_timeout",
- elapsedMs: Math.max(0, Date.now() - startedAt),
- message: "thumbnail storage operation timed out",
- })), STORAGE_TIMEOUT_MS)
- })
- try {
- return await Promise.race([observed, timeout])
- } finally {
- if (timer !== undefined) clearTimeout(timer)
- }
-}
-
-function logThumbnailFailure(pageDigest: string, error: LinkPreviewThumbnailFailure): void {
- log.error("link_preview_thumbnail_failure", {
- stage: error.stage,
- disposition: error.disposition,
- errorCode: error.code,
- elapsedMs: error.elapsedMs,
- pageDigestPrefix: pageDigest.slice(0, 12),
- })
-}
-
-function notFound(): NextResponse {
- return NextResponse.json({ error: "thumbnail not found" }, {
- status: 404,
- headers: {
- "Cache-Control": "no-store",
- "X-Content-Type-Options": "nosniff",
- },
- })
-}
-
-function thumbnailResponse(body: BodyInit): Response {
- return new Response(body, {
- headers: {
- "Content-Type": "image/webp",
- "Content-Disposition": "inline",
- "Cache-Control": PRIVATE_THUMBNAIL_CACHE,
- "X-Content-Type-Options": "nosniff",
- "Cross-Origin-Resource-Policy": "same-origin",
- "Referrer-Policy": "no-referrer",
- },
- })
-}
-
-export const GET = withAuth(async (_req: NextRequest, ctx) => {
- const pageDigest = ctx.params?.digest
- if (!isLinkPreviewThumbnailDigest(pageDigest)) return notFound()
-
- let manifest
- const manifestReadStartedAt = Date.now()
- try {
- manifest = await readLinkPreviewThumbnailManifest({
- bucket: ctx.env.COMMUNITY_MEDIA,
- pageDigest,
- })
- } catch (error) {
- logThumbnailFailure(pageDigest, storageFailure(error, manifestReadStartedAt))
- return notFound()
- }
- if (!manifest) return notFound()
-
- const objectKey = linkPreviewThumbnailObjectKey(pageDigest)
- const objectReadStartedAt = Date.now()
- try {
- const cached = await ctx.env.COMMUNITY_MEDIA.get(objectKey)
- if (cached && isFreshLinkPreviewThumbnailObject(cached, manifest)) {
- return thumbnailResponse(cached.body)
- }
- await cached?.body.cancel().catch(() => {})
- } catch (error) {
- logThumbnailFailure(pageDigest, storageFailure(error, objectReadStartedAt))
- return notFound()
- }
-
- const kv = ctx.env.CACHE_KV ?? null
- const negativeKey = linkPreviewThumbnailNegativeKey(pageDigest, manifest.sourceDigest)
- if (kv) {
- try {
- if (await kv.get(negativeKey)) return notFound()
- } catch {
- // Negative caching is best-effort; all expensive work remains bounded.
- }
- }
-
- const rateLimit = await checkRateLimit(ctx.env, "community:linkPreviewThumbnail", ctx.userId)
- if (!rateLimit.allowed) return notFound()
-
- try {
- const images = ctx.env.IMAGES
- if (!images) {
- throw new LinkPreviewThumbnailFailure({
- stage: "transform",
- disposition: "transient",
- code: "transform_binding_missing",
- elapsedMs: 0,
- message: "Images binding unavailable",
- })
- }
- const bytes = await fetchAndTransformLinkPreviewThumbnail(manifest.sourceUrl, images)
- const storageStartedAt = Date.now()
- await withStorageDeadline(ctx.env.COMMUNITY_MEDIA.put(
- objectKey,
- bytes,
- linkPreviewThumbnailObjectMetadata(manifest),
- ), storageStartedAt)
- return thumbnailResponse(bytes.slice().buffer as ArrayBuffer)
- } catch (error) {
- const thumbnailFailure = error instanceof LinkPreviewThumbnailFailure
- ? error
- : new LinkPreviewThumbnailFailure({
- stage: "transform",
- disposition: "transient",
- code: "transform_unknown",
- elapsedMs: 0,
- message: "thumbnail generation failed",
- })
- logThumbnailFailure(pageDigest, thumbnailFailure)
- if (kv && thumbnailFailure.disposition === "deterministic") {
- const write = kv.put(negativeKey, "1", { expirationTtl: NEGATIVE_TTL_SECONDS }).catch(() => {
- // A negative-cache outage must not turn an image-only miss into a 500.
- })
- getCloudflareContext().ctx.waitUntil(write)
- }
- return notFound()
- }
-})
-
-export const LINK_PREVIEW_THUMBNAIL_RESPONSE_HEADERS = {
- cacheControl: PRIVATE_THUMBNAIL_CACHE,
- storageTimeoutMs: STORAGE_TIMEOUT_MS,
-} as const
diff --git a/src/web/src/components/community/messages/link-preview-card.test.ts b/src/web/src/components/community/messages/link-preview-card.test.ts
deleted file mode 100644
index 273ac916f..000000000
--- a/src/web/src/components/community/messages/link-preview-card.test.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { createElement } from "react"
-import { renderToStaticMarkup } from "react-dom/server"
-import { act, create, type ReactTestRenderer } from "react-test-renderer"
-import { afterEach, describe, expect, it, vi } from "vitest"
-import { tid } from "@/lib/community/testids"
-import { LinkPreviewCardView, linkPreviewStaleTime } from "./link-preview-card"
-
-const THUMBNAIL_URL = `/api/community/link-preview/thumbnail/${"a".repeat(64)}`
-const PREVIEW = {
- url: "https://github.com/alookai/alook/pull/511",
- hostname: "github.com",
- siteName: "GitHub",
- title: "Pull Request #511",
- description: "Rooms for people and agents.",
- thumbnailUrl: THUMBNAIL_URL,
-}
-
-afterEach(() => {
- vi.useRealTimers()
-})
-
-function renderPreview(preview = PREVIEW): ReactTestRenderer {
- let renderer!: ReactTestRenderer
- act(() => {
- renderer = create(createElement(LinkPreviewCardView, { preview }))
- })
- return renderer
-}
-
-describe("LinkPreviewCardView", () => {
- it("mounts only a layout-free preload until the thumbnail loads, then reveals the existing card", () => {
- const renderer = renderPreview()
- const preload = renderer.root.findByType("img")
-
- expect(preload.props).toMatchObject({
- "data-testid": tid.linkPreviewThumbnail,
- src: THUMBNAIL_URL,
- alt: "",
- width: 640,
- height: 360,
- loading: "eager",
- decoding: "async",
- referrerPolicy: "no-referrer",
- "aria-hidden": "true",
- })
- expect(preload.props.className).not.toContain("aspect-video")
- expect(renderer.root.findAllByType("a")).toHaveLength(0)
- expect(renderer.root.findAll((node) => node.props["data-testid"] === tid.linkPreviewCard)).toHaveLength(0)
- expect(renderer.root.findAll((node) => node.props["data-slot"] === "card")).toHaveLength(0)
-
- act(() => preload.props.onLoad())
-
- const link = renderer.root.findByType("a")
- const image = renderer.root.findByType("img")
- expect(link.props).toMatchObject({
- href: PREVIEW.url,
- target: "_blank",
- rel: "noopener noreferrer",
- "aria-label": "Open link preview: Pull Request #511",
- "data-testid": tid.linkPreviewCard,
- })
- expect(image.props).toMatchObject({
- src: THUMBNAIL_URL,
- loading: "lazy",
- referrerPolicy: "no-referrer",
- className: "aspect-video w-full bg-muted object-cover",
- })
- expect(renderer.root.findAll((node) => node.props["data-slot"] === "card")).toHaveLength(1)
- expect(renderer.root.findAll((node) => node.type === "div" && node.props.className === "pb-2")).toHaveLength(1)
- })
-
- it("keeps positive previews fresh for 6h but retries negative results after 5m", () => {
- expect(linkPreviewStaleTime({ preview: {
- url: "https://example.com/",
- hostname: "example.com",
- title: "Example",
- } })).toBe(6 * 60 * 60 * 1_000)
- expect(linkPreviewStaleTime({ preview: null })).toBe(5 * 60 * 1_000)
- expect(linkPreviewStaleTime(undefined)).toBe(5 * 60 * 1_000)
- expect(linkPreviewStaleTime({ preview: {
- url: "https://example.com/",
- hostname: "example.com",
- title: "Recoverable image",
- }, staleTimeSeconds: 300 })).toBe(5 * 60 * 1_000)
- })
-
- it("does not create a redundant text card when there is no safe thumbnail", () => {
- const html = renderToStaticMarkup(createElement(LinkPreviewCardView, {
- preview: {
- url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
- hostname: "www.youtube.com",
- siteName: "YouTube",
- title: "A YouTube video",
- },
- }))
-
- expect(html).toBe("")
- })
-
- it("retries the identical digest URL after one and three seconds, then stops", async () => {
- vi.useFakeTimers()
- const renderer = renderPreview()
- const first = renderer.root.findByType("img")
-
- act(() => first.props.onError())
- await act(() => vi.advanceTimersByTimeAsync(999))
- expect(renderer.root.findByType("img")).toBe(first)
- await act(() => vi.advanceTimersByTimeAsync(1))
- const second = renderer.root.findByType("img")
- expect(second).not.toBe(first)
- expect(second.props.src).toBe(THUMBNAIL_URL)
- expect(second.props.src).not.toContain("?")
-
- act(() => second.props.onError())
- await act(() => vi.advanceTimersByTimeAsync(2_999))
- expect(renderer.root.findByType("img")).toBe(second)
- await act(() => vi.advanceTimersByTimeAsync(1))
- const third = renderer.root.findByType("img")
- expect(third).not.toBe(second)
- expect(third.props.src).toBe(THUMBNAIL_URL)
-
- act(() => third.props.onError())
- expect(renderer.root.findAllByType("img")).toHaveLength(0)
- expect(renderer.root.findAllByType("a")).toHaveLength(0)
- })
-
- it("cancels a pending retry on success, URL change, and unmount", async () => {
- vi.useFakeTimers()
- const renderer = renderPreview()
- const first = renderer.root.findByType("img")
- act(() => first.props.onError())
- act(() => first.props.onLoad())
- await act(() => vi.advanceTimersByTimeAsync(5_000))
- expect(renderer.root.findByType("a").props.href).toBe(PREVIEW.url)
-
- const nextThumbnailUrl = `/api/community/link-preview/thumbnail/${"b".repeat(64)}`
- act(() => {
- renderer.update(createElement(LinkPreviewCardView, {
- preview: { ...PREVIEW, url: "https://example.com/next", thumbnailUrl: nextThumbnailUrl },
- }))
- })
- const nextPreload = renderer.root.findByType("img")
- expect(nextPreload.props.src).toBe(nextThumbnailUrl)
- expect(renderer.root.findAllByType("a")).toHaveLength(0)
-
- act(() => nextPreload.props.onError())
- act(() => renderer.unmount())
- await act(() => vi.advanceTimersByTimeAsync(5_000))
- })
-
- it("never places an upstream image URL in the DOM", () => {
- const renderer = renderPreview()
- expect(JSON.stringify(renderer.toJSON())).toContain(THUMBNAIL_URL)
- expect(JSON.stringify(renderer.toJSON())).not.toContain("avatars.githubusercontent.com")
- })
-})
diff --git a/src/web/src/components/community/messages/link-preview-card.tsx b/src/web/src/components/community/messages/link-preview-card.tsx
deleted file mode 100644
index 5c7da79ab..000000000
--- a/src/web/src/components/community/messages/link-preview-card.tsx
+++ /dev/null
@@ -1,165 +0,0 @@
-"use client"
-
-import { memo, useEffect, useRef, useState } from "react"
-import { ExternalLink } from "lucide-react"
-import { useQuery } from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
-import { communityKeys } from "@/lib/query-keys"
-import { tid } from "@/lib/community/testids"
-import type { LinkPreview } from "@/lib/community/link-preview"
-import { Card } from "@/components/ui/card"
-
-type LinkPreviewResponse = {
- preview: LinkPreview | null
- staleTimeSeconds?: number
-}
-
-const POSITIVE_STALE_TIME_MS = 6 * 60 * 60 * 1_000
-const NEGATIVE_STALE_TIME_MS = 5 * 60 * 1_000
-const THUMBNAIL_RETRY_DELAYS_MS = [1_000, 3_000] as const
-
-export function linkPreviewStaleTime(data: LinkPreviewResponse | undefined): number {
- if (data?.staleTimeSeconds === 6 * 60 * 60) return POSITIVE_STALE_TIME_MS
- if (data?.staleTimeSeconds === 5 * 60) return NEGATIVE_STALE_TIME_MS
- return data?.preview ? POSITIVE_STALE_TIME_MS : NEGATIVE_STALE_TIME_MS
-}
-
-function LinkPreviewCardThumbnail({ preview }: { preview: LinkPreview & { thumbnailUrl: string } }) {
- const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const [attempt, setAttempt] = useState(0)
- const [loaded, setLoaded] = useState(false)
- const [failed, setFailed] = useState(false)
-
- const clearRetry = () => {
- if (retryTimerRef.current === null) return
- clearTimeout(retryTimerRef.current)
- retryTimerRef.current = null
- }
-
- useEffect(() => () => {
- if (retryTimerRef.current !== null) clearTimeout(retryTimerRef.current)
- }, [])
-
- const handleLoad = () => {
- clearRetry()
- setLoaded(true)
- }
-
- const handleError = () => {
- clearRetry()
- setLoaded(false)
- const delay = THUMBNAIL_RETRY_DELAYS_MS[attempt]
- if (delay === undefined) {
- setFailed(true)
- return
- }
- retryTimerRef.current = setTimeout(() => {
- retryTimerRef.current = null
- setAttempt((current) => current + 1)
- }, delay)
- }
-
- if (failed) return null
- if (!loaded) {
- return (
- <img
- key={attempt}
- data-testid={tid.linkPreviewThumbnail}
- src={preview.thumbnailUrl}
- alt=""
- width={640}
- height={360}
- loading="eager"
- decoding="async"
- referrerPolicy="no-referrer"
- aria-hidden="true"
- className="pointer-events-none absolute size-px opacity-0"
- onLoad={handleLoad}
- onError={handleError}
- />
- )
- }
-
- return (
- <div className="pb-2">
- <a
- data-testid={tid.linkPreviewCard}
- href={preview.url}
- target="_blank"
- rel="noopener noreferrer"
- className="group block w-full max-w-96 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- aria-label={`Open link preview: ${preview.title}`}
- >
- <Card className="relative gap-0 py-0 transition-shadow group-hover:ring-foreground/20">
- <img
- data-testid={tid.linkPreviewThumbnail}
- src={preview.thumbnailUrl}
- alt=""
- width={640}
- height={360}
- loading="lazy"
- decoding="async"
- referrerPolicy="no-referrer"
- className="aspect-video w-full bg-muted object-cover"
- onLoad={handleLoad}
- onError={handleError}
- />
- <span className="pointer-events-none absolute top-2 right-2 flex size-7 items-center justify-center rounded-full bg-background/80 text-foreground shadow-sm backdrop-blur-sm">
- <ExternalLink aria-hidden="true" className="size-3.5" />
- </span>
- </Card>
- </a>
- </div>
- )
-}
-
-export function LinkPreviewCardView({ preview }: { preview: LinkPreview }) {
- if (!preview.thumbnailUrl) return null
- return <LinkPreviewCardThumbnail key={preview.thumbnailUrl} preview={preview as LinkPreview & { thumbnailUrl: string }} />
-}
-
-function LinkPreviewCardImpl({ url }: { url: string }) {
- const sentinelRef = useRef<HTMLSpanElement>(null)
- const [nearViewport, setNearViewport] = useState(false)
-
- useEffect(() => {
- const node = sentinelRef.current
- if (!node || typeof IntersectionObserver === "undefined") {
- setNearViewport(true)
- return
- }
- const observer = new IntersectionObserver(([entry]) => {
- if (!entry?.isIntersecting) return
- setNearViewport(true)
- observer.disconnect()
- }, { rootMargin: "240px 0px" })
- observer.observe(node)
- return () => observer.disconnect()
- }, [])
-
- const query = useQuery({
- queryKey: communityKeys.linkPreview(url),
- queryFn: () => apiFetch<LinkPreviewResponse>("/api/community/link-preview", {
- method: "POST",
- body: JSON.stringify({ url }),
- }),
- enabled: nearViewport,
- staleTime: (query) => linkPreviewStaleTime(query.state.data),
- gcTime: 24 * 60 * 60 * 1_000,
- retry: false,
- })
-
- const preview = query.data?.preview
- if (!preview) {
- return (
- <span
- ref={sentinelRef}
- className="pointer-events-none absolute size-px overflow-hidden opacity-0"
- aria-hidden="true"
- />
- )
- }
- return <LinkPreviewCardView preview={preview} />
-}
-
-export const LinkPreviewCard = memo(LinkPreviewCardImpl)
diff --git a/src/web/src/components/community/messages/message-body.test.ts b/src/web/src/components/community/messages/message-body.test.ts
index cb61f9974..f10a4ca1d 100644
--- a/src/web/src/components/community/messages/message-body.test.ts
+++ b/src/web/src/components/community/messages/message-body.test.ts
@@ -1,129 +1,20 @@
import { describe, it, expect, vi } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { MessageBody } from "./message-body"
-import { communityKeys } from "@/lib/query-keys"
-import { tid } from "@/lib/community/testids"
-import type { LinkPreview } from "@/lib/community/link-preview"
-const PREVIEW_URL = "https://example.com/story"
-
-function renderLinkPreviewMessage(preview?: LinkPreview | null) {
- class MockIntersectionObserver {
- observe = vi.fn()
- disconnect = vi.fn()
- }
- vi.stubGlobal("IntersectionObserver", MockIntersectionObserver)
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- if (preview !== undefined) {
- client.setQueryData(communityKeys.linkPreview(PREVIEW_URL), { preview })
- }
- let renderer: TestRenderer.ReactTestRenderer
- act(() => {
- renderer = TestRenderer.create(
- React.createElement(
- QueryClientProvider,
- { client },
- React.createElement(MessageBody, { text: PREVIEW_URL }),
- ),
- )
- })
- return {
- renderer: renderer!,
- cleanup() {
- act(() => renderer!.unmount())
- client.clear()
- vi.unstubAllGlobals()
- },
- }
-}
-
-function previewSpacing(renderer: TestRenderer.ReactTestRenderer) {
- return renderer.root.findAll(
- (node) => node.type === "div" && node.props.className === "pb-2",
- )
-}
-
-describe("MessageBody — link preview spacing", () => {
- it("keeps a pending preview sentinel out of message layout", () => {
- const rendered = renderLinkPreviewMessage()
- try {
- expect(previewSpacing(rendered.renderer)).toHaveLength(0)
- const sentinel = rendered.renderer.root.findByType("span")
- expect(sentinel.props.className).toContain("absolute")
- } finally {
- rendered.cleanup()
- }
- })
-
- it("does not reserve preview spacing when the result has no safe thumbnail", () => {
- const rendered = renderLinkPreviewMessage({
- url: PREVIEW_URL,
- hostname: "example.com",
- title: "No image",
- })
- try {
- expect(previewSpacing(rendered.renderer)).toHaveLength(0)
- expect(rendered.renderer.root.findAllByProps({
- "data-testid": tid.linkPreviewCard,
- })).toHaveLength(0)
- } finally {
- rendered.cleanup()
- }
- })
-
- it("gives bottom spacing only to a successfully rendered preview card", () => {
- const rendered = renderLinkPreviewMessage({
- url: PREVIEW_URL,
- hostname: "example.com",
- title: "With image",
- thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+describe("MessageBody — plain URL rendering", () => {
+ it("keeps an HTTPS URL as a normal clickable link", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "Visit https://example.com/story" }),
+ )
})
- try {
- expect(previewSpacing(rendered.renderer)).toHaveLength(0)
- expect(rendered.renderer.root.findAllByProps({
- "data-testid": tid.linkPreviewCard,
- })).toHaveLength(0)
- const preload = rendered.renderer.root.findByProps({
- "data-testid": tid.linkPreviewThumbnail,
- })
- act(() => preload.props.onLoad())
- expect(previewSpacing(rendered.renderer)).toHaveLength(1)
- expect(rendered.renderer.root.findAllByProps({
- "data-testid": tid.linkPreviewCard,
- })).toHaveLength(1)
- } finally {
- rendered.cleanup()
- }
- })
- it("removes preview spacing together with a thumbnail that fails to load", () => {
- const rendered = renderLinkPreviewMessage({
- url: PREVIEW_URL,
- hostname: "example.com",
- title: "Broken image",
- thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- })
- try {
- const preload = rendered.renderer.root.findByProps({
- "data-testid": tid.linkPreviewThumbnail,
- })
- act(() => preload.props.onLoad())
- expect(previewSpacing(rendered.renderer)).toHaveLength(1)
- const image = rendered.renderer.root.findByProps({
- "data-testid": tid.linkPreviewThumbnail,
- })
- act(() => image.props.onError())
- expect(previewSpacing(rendered.renderer)).toHaveLength(0)
- expect(rendered.renderer.root.findAllByProps({
- "data-testid": tid.linkPreviewCard,
- })).toHaveLength(0)
- } finally {
- rendered.cleanup()
- }
+ const link = renderer!.root.findByType("a")
+ expect(link.props.href).toBe("https://example.com/story")
+ expect(link.children.join("")).toBe("https://example.com/story")
})
})
diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsx
index bdf563d9b..d0cbb772e 100644
--- a/src/web/src/components/community/messages/message-body.tsx
+++ b/src/web/src/components/community/messages/message-body.tsx
@@ -14,8 +14,6 @@ import {
buildMdComponents,
} from "./message-markdown"
import { CommunityInviteCard } from "../social/community-invite-card"
-import { LinkPreviewCard } from "./link-preview-card"
-import { extractLinkPreviewUrl } from "@/lib/community/link-preview"
import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"
import type { OpenProfile } from "@/components/community/social/profile-types"
@@ -98,18 +96,12 @@ function MessageBodyImpl({
text,
onOpenProfile,
perspective = "neutral",
- enableLinkPreview = true,
}: {
text: string
onOpenProfile?: OpenProfile
perspective?: MessagePerspective
- enableLinkPreview?: boolean
}) {
const inviteTokens = useMemo(() => extractInviteTokens(text), [text])
- const previewUrl = useMemo(
- () => enableLinkPreview ? extractLinkPreviewUrl(text) : null,
- [enableLinkPreview, text],
- )
const components = useMemo(
() => buildMdComponents(onOpenProfile),
[onOpenProfile],
@@ -157,7 +149,6 @@ function MessageBodyImpl({
))}
</div>
)}
- {previewUrl && <LinkPreviewCard url={previewUrl} />}
</div>
)
}
diff --git a/src/web/src/components/community/messages/message-share-dialog.test.ts b/src/web/src/components/community/messages/message-share-dialog.test.ts
index 6a41ee34f..814deecd0 100644
--- a/src/web/src/components/community/messages/message-share-dialog.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.test.ts
@@ -13,7 +13,7 @@ vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
vi.mock("next/image", () => ({ default: "img" }))
vi.mock("../avatar", () => ({ Avatar: "mock-avatar" }))
vi.mock("./message-body", () => ({
- MessageBody: (props: { text: string; enableLinkPreview?: boolean }) => (
+ MessageBody: (props: { text: string }) => (
React.createElement("mock-message-body", props)
),
}))
@@ -137,23 +137,6 @@ describe("MessageShareDialog message context", () => {
expect(text).toEqual(expect.arrayContaining(["👍", "2", "🎉", "11"]))
})
- it("matches the live message link-preview suppression when a richer embed exists", () => {
- const withEmbed = renderMessage(message({
- content: "https://example.com/story",
- embeds: [{ title: "Story" }],
- }))
- const embeddedBody = withEmbed.root.find(
- (node) => node.type === "mock-message-body",
- )
- expect(embeddedBody.props.enableLinkPreview).toBe(false)
-
- const withoutEmbed = renderMessage(message({ content: "https://example.com/story" }))
- const plainBody = withoutEmbed.root.find(
- (node) => node.type === "mock-message-body",
- )
- expect(plainBody.props.enableLinkPreview).toBe(true)
- })
-
it("renders attached originals at their intrinsic ratio and omits files", () => {
const renderer = renderMessage(message({
attachments: [
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index 6bb07e0a3..7fcc0681e 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -304,7 +304,6 @@ export function MessageShareDialog({ m, open, onClose }: {
<MessageBody
text={visibleContent}
perspective="neutral"
- enableLinkPreview={!msg.embeds?.length}
/>
</div>
)}
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index bfd02a94c..e4c1cc38d 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -404,7 +404,6 @@ function MessageImpl({
<MessageBody
text={visibleContent}
onOpenProfile={onOpenProfile}
- enableLinkPreview={!m.embeds?.length}
perspective={
viewerUserId
? m.authorId === viewerUserId ? "sender" : "recipient"
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index e803b1154..eddb187ce 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -13,7 +13,6 @@ declare namespace Cloudflare {
DB: D1Database
EMAIL_BUCKET: R2Bucket
COMMUNITY_MEDIA: R2Bucket
- IMAGES: ImagesBinding
BUG_REPORTS: R2Bucket
WS_DO_WORKER: Fetcher
EMAIL_WORKER: Fetcher
diff --git a/src/web/src/lib/community/link-preview-fetch.test.ts b/src/web/src/lib/community/link-preview-fetch.test.ts
deleted file mode 100644
index 80caa748e..000000000
--- a/src/web/src/lib/community/link-preview-fetch.test.ts
+++ /dev/null
@@ -1,568 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest"
-import * as linkPreviewMobile from "link-preview-js/mobile"
-import {
- LINK_PREVIEW_LIMITS,
- fetchLinkPreview,
- LinkPreviewFetchError,
- normalizePublicPreviewUrl,
-} from "./link-preview-fetch"
-
-afterEach(() => {
- vi.useRealTimers()
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
-})
-
-describe("normalizePublicPreviewUrl", () => {
- it("canonicalizes public HTTP(S) URLs and removes fragments", () => {
- expect(normalizePublicPreviewUrl("HTTPS://Example.COM/path?q=1#private").href)
- .toBe("https://example.com/path?q=1")
- })
-
- it.each([
- ["https://8.8.8.8/path#private", "https://8.8.8.8/path"],
- ["https://[2606:4700:4700::1111]/dns#private", "https://[2606:4700:4700::1111]/dns"],
- ])("accepts a globally routable literal address: %s", (input, expected) => {
- expect(normalizePublicPreviewUrl(input).href).toBe(expected)
- })
-
- it.each([
- "http://localhost/",
- "http://service.internal/",
- "http://127.0.0.1/",
- "http://10.0.0.1/",
- "http://100.64.0.1/",
- "http://169.254.169.254/",
- "http://172.16.0.1/",
- "http://192.168.0.1/",
- "http://192.0.0.1/",
- "http://192.0.2.1/",
- "http://192.88.99.1/",
- "http://198.18.0.1/",
- "http://198.51.100.1/",
- "http://203.0.113.1/",
- "http://224.0.0.1/",
- "http://[::1]/",
- "http://[fc00::1]/",
- "http://[fe80::1]/",
- "http://[2001:db8::1]/",
- "http://[2001::1]/",
- "http://[2001:2::1]/",
- "http://[2001:d::1]/",
- "http://[2001:10::1]/",
- "http://[2002::1]/",
- "http://[::ffff:127.0.0.1]/",
- "http://127.1/",
- "http://2130706433/",
- "http://0x7f000001/",
- "http://0177.0.0.1/",
- ])("rejects non-public targets: %s", (url) => {
- expect(() => normalizePublicPreviewUrl(url)).toThrow("non-public preview host")
- })
-
- it.each([
- "file:///etc/passwd",
- "https://user:[email protected]/",
- "https://example.com:8443/",
- ])("rejects unsupported URL authority/protocol shapes: %s", (url) => {
- expect(() => normalizePublicPreviewUrl(url)).toThrow()
- })
-
- it.each([
- "",
- "not a URL",
- `https://example.com/${"x".repeat(2_048)}`,
- ])("rejects an empty, malformed, or oversized URL: %s", (url) => {
- expect(() => normalizePublicPreviewUrl(url)).toThrow("invalid preview URL")
- })
-})
-
-describe("fetchLinkPreview", () => {
- it("uses bounded YouTube oEmbed metadata instead of scanning oversized HTML", async () => {
- const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
- title: "A YouTube video",
- provider_name: "YouTube",
- author_name: "Example creator",
- }), { headers: { "content-type": "application/json; charset=utf-8" } }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://www.youtube.com/watch?v=dQw4w9WgXcQ#chapter")).resolves.toEqual({
- url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
- hostname: "www.youtube.com",
- title: "A YouTube video",
- siteName: "YouTube",
- description: "Example creator",
- })
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(fetchMock.mock.calls[0]?.[0]).toBe(
- "https://www.youtube.com/oembed?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ&format=json",
- )
- expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
- method: "GET",
- redirect: "error",
- referrerPolicy: "no-referrer",
- })
- })
-
- it("keeps a validated YouTube thumbnail URL internal to the server result", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({
- title: "A YouTube video",
- provider_name: "YouTube",
- thumbnail_url: "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
- }), { headers: { "content-type": "application/json" } })))
-
- await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ")).resolves.toMatchObject({
- title: "A YouTube video",
- thumbnailSource: "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
- })
- })
-
- it.each([
- "https://youtu.be/dQw4w9WgXcQ?t=5",
- "https://m.youtube.com/shorts/dQw4w9WgXcQ",
- "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",
- ])("extracts a legal video id from an explicit supported shape: %s", async (url) => {
- const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
- title: "Supported video shape",
- provider_name: "YouTube",
- }), { headers: { "content-type": "application/json" } }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview(url)).resolves.toMatchObject({ title: "Supported video shape" })
- expect(fetchMock.mock.calls[0]?.[0]).toBe(
- "https://www.youtube.com/oembed?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ&format=json",
- )
- })
-
- it("caps YouTube oEmbed bodies and cancels the oversized stream", async () => {
- const cancel = vi.fn()
- const oversized = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(new Uint8Array(LINK_PREVIEW_LIMITS.maxOEmbedBytes + 1))
- },
- cancel,
- })
- const fetchMock = vi.fn().mockResolvedValue(new Response(oversized, {
- headers: { "content-type": "application/json" },
- }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
- .rejects.toThrow("preview response is too large")
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("rejects a bodyless YouTube oEmbed response", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, {
- headers: { "content-type": "application/json" },
- })))
-
- await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
- .rejects.toThrow("preview response has no body")
- })
-
- it("rejects YouTube oEmbed JSON without a meaningful title", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({
- provider_name: "YouTube",
- author_name: "Example creator",
- }), { headers: { "content-type": "application/json" } })))
-
- await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
- .rejects.toMatchObject({
- message: "YouTube oEmbed metadata missing",
- stage: "metadata_parse",
- code: "metadata_missing",
- httpStatus: 200,
- })
- })
-
- it("classifies malformed provider JSON as metadata parsing", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{", {
- headers: { "content-type": "application/json" },
- })))
-
- await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
- .rejects.toMatchObject({
- stage: "metadata_parse",
- code: "metadata_parse_failed",
- httpStatus: 200,
- })
- })
-
- it.each([
- "https://youtube.example.org/watch?v=dQw4w9WgXcQ",
- "https://notyoutube.com/watch?v=dQw4w9WgXcQ",
- "https://www.youtube.com/",
- "https://www.youtube.com/@alookai",
- "https://www.youtube.com/watch?v=too-short",
- ])("does not use oEmbed for a non-video YouTube shape: %s", async (url) => {
- const fetchMock = vi.fn().mockResolvedValue(new Response(
- "<html><head><meta property='og:title' content='Generic HTML'></head></html>",
- { headers: { "content-type": "text/html" } },
- ))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview(url)).resolves.toMatchObject({ title: "Generic HTML" })
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(fetchMock.mock.calls[0]?.[0]).toBe(new URL(url).href)
- })
-
- it("does not follow an oEmbed redirect, including one toward a private target", async () => {
- const cancel = vi.fn()
- const redirectBody = new ReadableStream<Uint8Array>({ cancel })
- const fetchMock = vi.fn().mockResolvedValue(new Response(redirectBody, {
- status: 302,
- headers: { location: "http://127.0.0.1/metadata" },
- }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
- .rejects.toThrow("YouTube oEmbed rejected request")
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("rejects and cancels an oEmbed response with the wrong MIME type", async () => {
- const cancel = vi.fn()
- const body = new ReadableStream<Uint8Array>({ cancel })
- const fetchMock = vi.fn().mockResolvedValue(new Response(body, {
- headers: { "content-type": "text/html" },
- }))
- vi.stubGlobal("fetch", fetchMock)
-
- const error = await fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ").catch((caught) => caught)
-
- expect(error).toBeInstanceOf(LinkPreviewFetchError)
- expect(error).toMatchObject({
- message: "YouTube oEmbed response is not JSON",
- stage: "provider_metadata_fetch",
- code: "unexpected_content_type",
- httpStatus: 200,
- })
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("sanitizes and caps malicious oEmbed text without returning remote HTML or media", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({
- title: `Safe\u202E<script>${"x".repeat(200)}`,
- provider_name: `You\u0007Tube${"y".repeat(100)}`,
- author_name: `Creator\u202E${"z".repeat(100)}`,
- html: "<iframe src='https://attacker.invalid'></iframe>",
- thumbnail_url: "https://attacker.invalid/image.png",
- }), { headers: { "content-type": "application/json" } })))
-
- const preview = await fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ")
-
- expect(preview.title).toHaveLength(160)
- expect(preview.siteName).toHaveLength(80)
- expect(preview.description).toHaveLength(80)
- expect(`${preview.title}${preview.siteName}${preview.description}`).not.toMatch(/[\u0007\u202E]/)
- expect(preview).not.toHaveProperty("html")
- expect(preview).not.toHaveProperty("thumbnail_url")
- })
-
- it("applies the single total timeout while waiting for YouTube oEmbed", async () => {
- vi.useFakeTimers()
- vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
- init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true })
- })))
-
- const preview = fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ")
- const rejected = expect(preview).rejects.toMatchObject({
- message: "aborted",
- stage: "provider_metadata_fetch",
- code: "timeout",
- })
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_LIMITS.timeoutMs)
-
- await rejected
- })
-
- it("follows bounded manual redirects, revalidates them, and sanitizes metadata", async () => {
- const fetchMock = vi.fn()
- .mockResolvedValueOnce(new Response(null, {
- status: 302,
- headers: { location: "https://www.example.com/final" },
- }))
- .mockResolvedValueOnce(new Response(
- "<html><head>"
- + "<meta property='og:site_name' content=' Example Site '>"
- + "<meta property='og:title' content='Safe\u202E title'>"
- + "<meta name='description' content=' A useful description '>"
- + "</head><body>ignored</body></html>",
- { headers: { "content-type": "text/html; charset=utf-8" } },
- ))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://example.com/start#fragment")).resolves.toEqual({
- url: "https://example.com/start",
- hostname: "example.com",
- title: "Safe title",
- description: "A useful description",
- siteName: "Example Site",
- })
- expect(fetchMock).toHaveBeenCalledTimes(2)
- expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
- method: "GET",
- redirect: "manual",
- referrerPolicy: "no-referrer",
- })
- })
-
- it("rejects a redirect that moves to a private target before fetching it", async () => {
- const fetchMock = vi.fn().mockResolvedValue(new Response(null, {
- status: 302,
- headers: { location: "http://127.0.0.1/admin" },
- }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://example.com/start"))
- .rejects.toThrow("non-public preview host")
- expect(fetchMock).toHaveBeenCalledTimes(1)
- })
-
- it("rejects and cancels a redirect without a location", async () => {
- const cancel = vi.fn()
- const body = new ReadableStream<Uint8Array>({ cancel })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, { status: 302 })))
-
- await expect(fetchLinkPreview("https://example.com/start"))
- .rejects.toThrow("invalid preview redirect")
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("revalidates every redirect hop before the next fetch", async () => {
- const fetchMock = vi.fn()
- .mockResolvedValueOnce(new Response(null, {
- status: 302,
- headers: { location: "https://example.org/second" },
- }))
- .mockResolvedValueOnce(new Response(null, {
- status: 302,
- headers: { location: "http://127.0.0.1/admin" },
- }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://example.com/start"))
- .rejects.toThrow("non-public preview host")
- expect(fetchMock).toHaveBeenCalledTimes(2)
- })
-
- it("caps redirect chains and cancels every unused redirect body", async () => {
- const cancel = vi.fn()
- const redirectBody = () => new ReadableStream<Uint8Array>({ cancel })
- const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(redirectBody(), {
- status: 302,
- headers: { location: "https://example.com/again" },
- })))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchLinkPreview("https://example.com/start"))
- .rejects.toThrow("too many preview redirects")
- expect(fetchMock).toHaveBeenCalledTimes(LINK_PREVIEW_LIMITS.maxRedirects + 1)
- expect(cancel).toHaveBeenCalledTimes(LINK_PREVIEW_LIMITS.maxRedirects + 1)
- })
-
- it("parses the bounded head of a large page instead of rejecting its body size", async () => {
- const head = "<html><head><meta property='og:title' content='Large page'></head>"
- const oversized = head + "x".repeat(LINK_PREVIEW_LIMITS.maxHtmlBytes * 2)
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(oversized, {
- headers: {
- "content-type": "text/html",
- "content-length": String(oversized.length),
- },
- })))
-
- await expect(fetchLinkPreview("https://github.com/alookai/alook/pull/1"))
- .resolves.toMatchObject({ title: "Large page", hostname: "github.com" })
- })
-
- it("stops a chunked response without content-length at the actual byte ceiling", async () => {
- const encoder = new TextEncoder()
- const cancel = vi.fn()
- const first = encoder.encode("<html><head><meta property='og:title' content='Chunked page'>")
- const fill = encoder.encode("x".repeat(16 * 1024))
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(first)
- },
- pull(controller) {
- controller.enqueue(fill)
- },
- cancel,
- })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, {
- headers: { "content-type": "text/html" },
- })))
-
- await expect(fetchLinkPreview("https://example.com/chunked"))
- .resolves.toMatchObject({ title: "Chunked page" })
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("uses one timeout budget while waiting for response headers", async () => {
- vi.useFakeTimers()
- vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
- init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true })
- })))
-
- const preview = fetchLinkPreview("https://example.com/slow-headers")
- const rejected = expect(preview).rejects.toThrow("aborted")
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_LIMITS.timeoutMs)
-
- await rejected
- })
-
- it("uses the same timeout budget while a streamed body stalls", async () => {
- vi.useFakeTimers()
- const encoder = new TextEncoder()
- vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => Promise.resolve(new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(encoder.encode("<html><head><meta property='og:title' content='Slow'>"))
- init?.signal?.addEventListener("abort", () => controller.error(new Error("aborted")), { once: true })
- },
- }),
- { headers: { "content-type": "text/html" } },
- ))))
-
- const preview = fetchLinkPreview("https://example.com/slow-body")
- const rejected = expect(preview).rejects.toThrow("aborted")
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_LIMITS.timeoutMs)
-
- await rejected
- })
-
- it("rejects a bodyless HTML response", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, {
- headers: { "content-type": "text/html" },
- })))
-
- await expect(fetchLinkPreview("https://example.com/bodyless"))
- .rejects.toThrow("preview response has no body")
- })
-
- it("rejects and cancels a non-success HTML response", async () => {
- const cancel = vi.fn()
- const body = new ReadableStream<Uint8Array>({ cancel })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, { status: 503 })))
-
- await expect(fetchLinkPreview("https://example.com/unavailable"))
- .rejects.toMatchObject({
- message: "preview origin rejected request",
- stage: "document_fetch",
- code: "upstream_http_status",
- httpStatus: 503,
- })
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("rejects non-HTML responses", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", {
- headers: { "content-type": "application/json" },
- })))
-
- await expect(fetchLinkPreview("https://example.com/data"))
- .rejects.toThrow("preview response is not HTML")
- })
-
- it("falls back to Twitter Card metadata when Open Graph tags are absent", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
- "<html><head>"
- + "<meta name='twitter:title' content='Twitter-only title'>"
- + "<meta name='twitter:description' content='Twitter-only description'>"
- + "</head></html>",
- { headers: { "content-type": "text/html" } },
- )))
-
- await expect(fetchLinkPreview("https://example.com/twitter-only")).resolves.toMatchObject({
- title: "Twitter-only title",
- description: "Twitter-only description",
- })
- })
-
- it("selects the first public HTTPS Open Graph image resolved against the final page", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
- "<html><head>"
- + "<meta property='og:title' content='With image'>"
- + "<meta property='og:image' content='/assets/card.png#fragment'>"
- + "</head></html>",
- { headers: { "content-type": "text/html" } },
- )))
-
- await expect(fetchLinkPreview("https://example.com/post")).resolves.toMatchObject({
- title: "With image",
- thumbnailSource: "https://example.com/assets/card.png",
- })
- })
-
- it("falls back to a Twitter image without exposing insecure or private candidates", async () => {
- const html = (image: string) => "<html><head>"
- + "<meta name='twitter:title' content='Twitter-only'>"
- + `<meta name='twitter:image' content='${image}'>`
- + "</head></html>"
-
- for (const [image, expected] of [
- ["https://cdn.example.org/card.webp", "https://cdn.example.org/card.webp"],
- ["http://cdn.example.org/card.webp", undefined],
- ["https://127.0.0.1/card.webp", undefined],
- ] as const) {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(html(image), {
- headers: { "content-type": "text/html" },
- })))
- const preview = await fetchLinkPreview("https://example.com/twitter-image")
- expect(preview.thumbnailSource).toBe(expected)
- }
- })
-
- it("removes controls and bidi markers and caps every returned field", async () => {
- const title = `T\u202E${"a".repeat(200)}`
- const description = `D\u0007${"b".repeat(400)}`
- const siteName = `S${"c".repeat(100)}`
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
- `<html><head><meta property='og:title' content='${title}'>`
- + `<meta property='og:description' content='${description}'>`
- + `<meta property='og:site_name' content='${siteName}'></head></html>`,
- { headers: { "content-type": "text/html" } },
- )))
-
- const preview = await fetchLinkPreview("https://example.com/capped")
-
- expect(preview.title).toHaveLength(160)
- expect(preview.description).toHaveLength(320)
- expect(preview.siteName).toHaveLength(80)
- expect(`${preview.title}${preview.description}${preview.siteName}`).not.toMatch(/[\u0007\u202E]/)
- })
-
- it("rejects an HTML page with no meaningful preview metadata", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
- "<html><head></head><body>Untitled</body></html>",
- { headers: { "content-type": "text/html" } },
- )))
-
- await expect(fetchLinkPreview("https://example.com/untitled"))
- .rejects.toMatchObject({
- message: "preview metadata missing",
- stage: "metadata_parse",
- code: "metadata_missing",
- })
- })
-
- it("classifies an HTML metadata parser failure", async () => {
- vi.spyOn(linkPreviewMobile, "getPreviewFromContent")
- .mockRejectedValueOnce(new Error("parser failed"))
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
- "<html><head><title>Example</title></head></html>",
- { headers: { "content-type": "text/html" } },
- )))
-
- await expect(fetchLinkPreview("https://example.com/parser-failure"))
- .rejects.toMatchObject({
- message: "parser failed",
- stage: "metadata_parse",
- code: "metadata_parse_failed",
- })
- })
-})
diff --git a/src/web/src/lib/community/link-preview-fetch.ts b/src/web/src/lib/community/link-preview-fetch.ts
deleted file mode 100644
index 6d71fa511..000000000
--- a/src/web/src/lib/community/link-preview-fetch.ts
+++ /dev/null
@@ -1,441 +0,0 @@
-import { isIP } from "node:net"
-import { getPreviewFromContent } from "link-preview-js/mobile"
-import type { LinkPreview } from "./link-preview"
-
-export type FetchedLinkPreview = LinkPreview & { thumbnailSource?: string }
-
-export type LinkPreviewFetchStage = "provider_metadata_fetch" | "document_fetch" | "metadata_parse"
-
-export class LinkPreviewFetchError extends Error {
- readonly name = "LinkPreviewFetchError"
-
- constructor(
- message: string,
- readonly stage: LinkPreviewFetchStage,
- readonly code: string,
- readonly httpStatus?: number,
- ) {
- super(message)
- }
-}
-
-const MAX_URL_LENGTH = 2_048
-const MAX_HTML_BYTES = 128 * 1024
-const MAX_OEMBED_BYTES = 16 * 1024
-const MAX_REDIRECTS = 3
-const TOTAL_TIMEOUT_MS = 3_000
-const YOUTUBE_VIDEO_ID_RE = /^[A-Za-z0-9_-]{11}$/
-const YOUTUBE_HOSTS = new Set([
- "youtube.com",
- "www.youtube.com",
- "m.youtube.com",
- "music.youtube.com",
-])
-const YOUTUBE_NOCOOKIE_HOSTS = new Set([
- "youtube-nocookie.com",
- "www.youtube-nocookie.com",
-])
-const CONTROL_AND_BIDI_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g
-const SPECIAL_HOST_SUFFIXES = [
- ".localhost",
- ".local",
- ".internal",
- ".home.arpa",
- ".test",
- ".invalid",
- ".example",
- ".onion",
-]
-
-function ipv4Bytes(hostname: string): number[] | null {
- /* istanbul ignore next -- caller only invokes this after isIP(hostname) === 4 */
- if (isIP(hostname) !== 4) return null
- const bytes = hostname.split(".").map(Number)
- return bytes.length === 4 && bytes.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255)
- ? bytes
- : null
-}
-
-function ipv6Words(hostname: string): number[] | null {
- const host = hostname.replace(/^\[|\]$/g, "")
- /* istanbul ignore next -- caller only invokes this after isIP(host) === 6 */
- if (isIP(host) !== 6) return null
- const [leftRaw, rightRaw] = host.split("::")
- const left = leftRaw ? leftRaw.split(":") : []
- const right = rightRaw ? rightRaw.split(":") : []
- const missing = 8 - left.length - right.length
- /* istanbul ignore next -- isIP(host) === 6 guarantees a valid eight-word expansion */
- if (missing < 0 || (!host.includes("::") && missing !== 0)) return null
- const parts = [...left, ...Array.from({ length: missing }, () => "0"), ...right]
- const words = parts.map((part) => Number.parseInt(part || "0", 16))
- return words.length === 8 && words.every((word) => Number.isInteger(word) && word >= 0 && word <= 0xffff)
- ? words
- : null
-}
-
-function isPublicIpv4(bytes: number[]): boolean {
- const [a, b, c] = bytes
- if (a === 0 || a === 10 || a === 127 || a >= 224) return false
- if (a === 100 && b >= 64 && b <= 127) return false
- if (a === 169 && b === 254) return false
- if (a === 172 && b >= 16 && b <= 31) return false
- if (a === 192 && b === 168) return false
- if (a === 192 && b === 0 && (c === 0 || c === 2)) return false
- if (a === 192 && b === 88 && c === 99) return false
- if (a === 198 && (b === 18 || b === 19)) return false
- if (a === 198 && b === 51 && c === 100) return false
- if (a === 203 && b === 0 && c === 113) return false
- return true
-}
-
-function isPublicIpv6(words: number[]): boolean {
- // IPv4-mapped IPv6 must inherit the embedded IPv4 decision.
- if (words.slice(0, 5).every((word) => word === 0) && words[5] === 0xffff) {
- return isPublicIpv4([
- words[6] >> 8,
- words[6] & 0xff,
- words[7] >> 8,
- words[7] & 0xff,
- ])
- }
-
- // Only globally-routable unicast (2000::/3), excluding special-use ranges.
- if ((words[0] & 0xe000) !== 0x2000) return false
- if (words[0] === 0x2001) {
- const second = words[1]
- if (second === 0x0000 || second === 0x0002 || second === 0x000d || second === 0x0db8) return false
- if ((second & 0xfff0) === 0x0010) return false
- }
- // 6to4 can tunnel to an embedded private IPv4 destination.
- if (words[0] === 0x2002) return false
- return true
-}
-
-function isSpecialHostname(hostname: string): boolean {
- const host = hostname.toLowerCase().replace(/\.$/, "")
- if (host === "localhost") return true
- return SPECIAL_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))
-}
-
-/** Parse, canonicalize, and reject targets outside the public HTTP(S) web. */
-export function normalizePublicPreviewUrl(input: string): URL {
- if (!input || input.length > MAX_URL_LENGTH) throw new Error("invalid preview URL")
- let url: URL
- try {
- url = new URL(input)
- } catch {
- throw new Error("invalid preview URL")
- }
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("unsupported preview protocol")
- if (url.username || url.password || url.port) throw new Error("unsupported preview authority")
- if (!url.hostname || isSpecialHostname(url.hostname)) throw new Error("non-public preview host")
-
- const host = url.hostname.replace(/^\[|\]$/g, "")
- const ipVersion = isIP(host)
- if (ipVersion === 4 && !isPublicIpv4(ipv4Bytes(host)!)) throw new Error("non-public preview host")
- if (ipVersion === 6 && !isPublicIpv6(ipv6Words(host)!)) throw new Error("non-public preview host")
-
- url.hash = ""
- return url
-}
-
-function cleanText(value: unknown, maxLength: number): string | undefined {
- if (typeof value !== "string") return undefined
- const cleaned = value
- .replace(CONTROL_AND_BIDI_RE, "")
- .replace(/\s+/g, " ")
- .trim()
- if (!cleaned) return undefined
- return Array.from(cleaned).slice(0, maxLength).join("")
-}
-
-function cleanThumbnailSource(value: unknown, base: URL): string | undefined {
- if (typeof value !== "string" || !value) return undefined
- try {
- const source = normalizePublicPreviewUrl(new URL(value, base).href)
- return source.protocol === "https:" ? source.href : undefined
- } catch {
- return undefined
- }
-}
-
-function youtubeVideoId(url: URL): string | null {
- const host = url.hostname.toLowerCase()
- let candidate: string | null = null
- if (host === "youtu.be" && /^\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) {
- candidate = url.pathname.split("/")[1] ?? null
- } else if (YOUTUBE_HOSTS.has(host) && url.pathname === "/watch") {
- candidate = url.searchParams.get("v")
- } else if (YOUTUBE_HOSTS.has(host) && /^\/(?:shorts|embed|live)\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) {
- candidate = url.pathname.split("/")[2] ?? null
- } else if (YOUTUBE_NOCOOKIE_HOSTS.has(host) && /^\/embed\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) {
- candidate = url.pathname.split("/")[2] ?? null
- }
- return candidate && YOUTUBE_VIDEO_ID_RE.test(candidate) ? candidate : null
-}
-
-async function readBoundedText(response: Response, maxBytes: number): Promise<string> {
- if (!response.body) throw new Error("preview response has no body")
-
- const reader = response.body.getReader()
- const decoder = new TextDecoder()
- let text = ""
- let total = 0
- try {
- while (true) {
- const { done, value } = await reader.read()
- if (done) break
- const remaining = maxBytes - total
- if (value.byteLength > remaining) {
- await reader.cancel()
- throw new Error("preview response is too large")
- }
- total += value.byteLength
- text += decoder.decode(value, { stream: true })
- }
- } finally {
- reader.releaseLock()
- }
- return text + decoder.decode()
-}
-
-async function fetchYouTubeOEmbed(original: URL, videoId: string, signal: AbortSignal): Promise<FetchedLinkPreview> {
- // The destination is fixed rather than derived from user input. The source
- // URL is only an encoded oEmbed parameter, so it cannot steer the fetch.
- const endpoint = new URL("https://www.youtube.com/oembed")
- endpoint.searchParams.set("url", `https://www.youtube.com/watch?v=${videoId}`)
- endpoint.searchParams.set("format", "json")
- const response = await fetch(endpoint.href, {
- method: "GET",
- redirect: "error",
- signal,
- headers: { Accept: "application/json" },
- referrerPolicy: "no-referrer",
- })
- if (!response.ok) {
- await response.body?.cancel().catch(() => {})
- throw new LinkPreviewFetchError(
- "YouTube oEmbed rejected request",
- "provider_metadata_fetch",
- "upstream_http_status",
- response.status,
- )
- }
- const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
- if (!/^application\/(?:[\w.+-]+\+)?json(?:;|$)/.test(contentType)) {
- await response.body?.cancel().catch(() => {})
- throw new LinkPreviewFetchError(
- "YouTube oEmbed response is not JSON",
- "provider_metadata_fetch",
- "unexpected_content_type",
- response.status,
- )
- }
-
- let record: Record<string, unknown>
- try {
- record = JSON.parse(await readBoundedText(response, MAX_OEMBED_BYTES)) as Record<string, unknown>
- } catch (error) {
- const message = error instanceof Error ? error.message : "provider metadata parse failed"
- throw new LinkPreviewFetchError(
- message,
- "metadata_parse",
- signal.aborted ? "timeout" : "metadata_parse_failed",
- response.status,
- )
- }
- const title = cleanText(record.title, 160)
- if (!title) {
- throw new LinkPreviewFetchError(
- "YouTube oEmbed metadata missing",
- "metadata_parse",
- "metadata_missing",
- response.status,
- )
- }
- const siteName = cleanText(record.provider_name, 80) ?? "YouTube"
- const authorName = cleanText(record.author_name, 80)
- const thumbnailSource = cleanThumbnailSource(record.thumbnail_url, original)
- return {
- url: original.href,
- hostname: original.hostname,
- title,
- siteName,
- ...(authorName ? { description: authorName } : {}),
- ...(thumbnailSource ? { thumbnailSource } : {}),
- }
-}
-
-async function readBoundedHtml(response: Response): Promise<string> {
- if (!response.body) throw new Error("preview response has no body")
-
- const reader = response.body.getReader()
- const decoder = new TextDecoder()
- let html = ""
- let total = 0
- try {
- while (true) {
- const { done, value } = await reader.read()
- if (done) break
-
- const remaining = MAX_HTML_BYTES - total
- const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value
- total += chunk.byteLength
- html += decoder.decode(chunk, { stream: true })
-
- // Metadata belongs in <head>. Stop as soon as it is complete, and also
- // stop at the byte ceiling instead of rejecting otherwise-valid pages
- // whose full body is large (GitHub PR pages routinely exceed the cap).
- if (/<\/head\s*>/i.test(html) || total === MAX_HTML_BYTES) {
- await reader.cancel()
- break
- }
- }
- } finally {
- reader.releaseLock()
- }
- return html + decoder.decode()
-}
-
-function isRedirect(status: number): boolean {
- return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
-}
-
-async function fetchHtml(start: URL, signal: AbortSignal): Promise<{ html: string; finalUrl: URL; contentType: string }> {
- let current = start
- for (let redirects = 0; ; redirects += 1) {
- const response = await fetch(current.href, {
- method: "GET",
- redirect: "manual",
- signal,
- headers: {
- Accept: "text/html,application/xhtml+xml",
- "User-Agent": "Alook-Link-Preview/1.0",
- },
- referrerPolicy: "no-referrer",
- })
-
- if (isRedirect(response.status)) {
- await response.body?.cancel().catch(() => {})
- if (redirects === MAX_REDIRECTS) {
- throw new LinkPreviewFetchError(
- "too many preview redirects",
- "document_fetch",
- "redirect_limit",
- response.status,
- )
- }
- const location = response.headers.get("location")
- if (!location) {
- throw new LinkPreviewFetchError(
- "invalid preview redirect",
- "document_fetch",
- "invalid_redirect",
- response.status,
- )
- }
- current = normalizePublicPreviewUrl(new URL(location, current).href)
- continue
- }
- if (!response.ok) {
- await response.body?.cancel().catch(() => {})
- throw new LinkPreviewFetchError(
- "preview origin rejected request",
- "document_fetch",
- "upstream_http_status",
- response.status,
- )
- }
- const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
- if (!/^text\/html(?:;|$)|^application\/xhtml\+xml(?:;|$)/.test(contentType)) {
- await response.body?.cancel().catch(() => {})
- throw new LinkPreviewFetchError(
- "preview response is not HTML",
- "document_fetch",
- "unexpected_content_type",
- response.status,
- )
- }
- return { html: await readBoundedHtml(response), finalUrl: current, contentType }
- }
-}
-
-/**
- * Fetch one public page within a single hard budget and return sanitized text
- * plus an internal, revalidated image candidate. The caller must never expose
- * thumbnailSource; it is only input to the same-origin thumbnail manifest.
- */
-export async function fetchLinkPreview(input: string): Promise<FetchedLinkPreview> {
- const original = normalizePublicPreviewUrl(input)
- const controller = new AbortController()
- const timer = setTimeout(() => controller.abort(), TOTAL_TIMEOUT_MS)
- let stage: LinkPreviewFetchStage = "document_fetch"
- try {
- const youtubeId = youtubeVideoId(original)
- if (youtubeId) {
- stage = "provider_metadata_fetch"
- return await fetchYouTubeOEmbed(original, youtubeId, controller.signal)
- }
- stage = "document_fetch"
- const { html, finalUrl, contentType } = await fetchHtml(original, controller.signal)
- stage = "metadata_parse"
- const parsed = await getPreviewFromContent({
- url: finalUrl.href,
- data: html,
- headers: { "content-type": contentType },
- }, {
- imagesPropertyType: "og",
- // link-preview-js covers Open Graph + ordinary title/description but
- // not pages that expose Twitter Card tags only. Fill only its gaps.
- onResponse: (response, doc) => ({
- ...response,
- title: response.title
- || doc("meta[name='twitter:title'],meta[property='twitter:title']").first().attr("content")
- || "",
- description: response.description
- || doc("meta[name='twitter:description'],meta[property='twitter:description']").first().attr("content"),
- images: response.images.length > 0
- ? response.images
- : [doc("meta[name='twitter:image'],meta[property='twitter:image']").first().attr("content")]
- .filter((value): value is string => Boolean(value)),
- }),
- })
- const record = parsed as Record<string, unknown>
- const parsedTitle = cleanText(record.title, 160)
- const description = cleanText(record.description, 320)
- const siteName = cleanText(record.siteName, 80)
- const thumbnailSource = Array.isArray(record.images)
- ? cleanThumbnailSource(record.images[0], finalUrl)
- : undefined
- if (!parsedTitle && !description) {
- throw new LinkPreviewFetchError("preview metadata missing", "metadata_parse", "metadata_missing")
- }
- const title = parsedTitle ?? siteName ?? original.hostname
- return {
- url: original.href,
- hostname: original.hostname,
- title,
- ...(description ? { description } : {}),
- ...(siteName ? { siteName } : {}),
- ...(thumbnailSource ? { thumbnailSource } : {}),
- }
- } catch (error) {
- if (error instanceof LinkPreviewFetchError) throw error
- const message = error instanceof Error ? error.message : "link preview fetch failed"
- const code = controller.signal.aborted
- ? "timeout"
- : stage === "metadata_parse"
- ? "metadata_parse_failed"
- : "network_or_body_failed"
- throw new LinkPreviewFetchError(message, stage, code)
- } finally {
- clearTimeout(timer)
- }
-}
-
-export const LINK_PREVIEW_LIMITS = {
- maxHtmlBytes: MAX_HTML_BYTES,
- maxOEmbedBytes: MAX_OEMBED_BYTES,
- maxRedirects: MAX_REDIRECTS,
- timeoutMs: TOTAL_TIMEOUT_MS,
-} as const
diff --git a/src/web/src/lib/community/link-preview-thumbnail.test.ts b/src/web/src/lib/community/link-preview-thumbnail.test.ts
deleted file mode 100644
index b6ab49f94..000000000
--- a/src/web/src/lib/community/link-preview-thumbnail.test.ts
+++ /dev/null
@@ -1,676 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest"
-import {
- LINK_PREVIEW_THUMBNAIL_LIMITS,
- LinkPreviewThumbnailFailure,
- fetchAndTransformLinkPreviewThumbnail,
- isFreshLinkPreviewThumbnailObject,
- linkPreviewPageDigest,
- linkPreviewThumbnailManifestKey,
- linkPreviewThumbnailNegativeKey,
- linkPreviewThumbnailObjectKey,
- linkPreviewThumbnailObjectMetadata,
- linkPreviewThumbnailUrl,
- normalizePublicImageUrl,
- readLinkPreviewThumbnailManifest,
- writeLinkPreviewThumbnailManifest,
- type LinkPreviewThumbnailManifest,
-} from "./link-preview-thumbnail"
-
-afterEach(() => {
- vi.useRealTimers()
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
-})
-
-function bytesStream(bytes: Uint8Array, cancel?: () => void): ReadableStream<Uint8Array> {
- return new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(bytes)
- controller.close()
- },
- cancel,
- })
-}
-
-function mockImages(args: {
- format?: string
- width?: number
- height?: number
- output?: Uint8Array
- outputType?: string
- outputError?: unknown
- contentTypeError?: unknown
-} = {}) {
- const transform = vi.fn()
- const output = vi.fn()
- const transformer = {
- transform: (...values: unknown[]) => {
- transform(...values)
- return transformer
- },
- output: async (...values: unknown[]) => {
- output(...values)
- if (args.outputError !== undefined) throw args.outputError
- const transformed = args.output ?? new Uint8Array([1, 2, 3])
- return {
- contentType: () => {
- if (args.contentTypeError !== undefined) throw args.contentTypeError
- return args.outputType ?? "image/webp"
- },
- image: () => bytesStream(transformed),
- response: () => new Response(transformed),
- }
- },
- }
- const binding = {
- info: vi.fn().mockResolvedValue({
- format: args.format ?? "image/jpeg",
- fileSize: 3,
- width: args.width ?? 1200,
- height: args.height ?? 630,
- }),
- input: vi.fn(() => transformer),
- } as unknown as ImagesBinding
- return { binding, output, transform }
-}
-
-function response(body = new Uint8Array([0xff, 0xd8, 0xff]), init: ResponseInit = {}): Response {
- return new Response(body, {
- ...init,
- headers: { "content-type": "image/jpeg", ...init.headers },
- })
-}
-
-describe("link preview thumbnail addressing and manifests", () => {
- it("derives only fixed digest paths and keys", async () => {
- const digest = await linkPreviewPageDigest("https://example.com/")
- expect(digest).toMatch(/^[a-f0-9]{64}$/)
- expect(linkPreviewThumbnailUrl(digest)).toBe(`/api/community/link-preview/thumbnail/${digest}`)
- expect(linkPreviewThumbnailManifestKey(digest)).toBe(`link-preview-thumbnails/v1/${digest}/manifest.json`)
- expect(linkPreviewThumbnailObjectKey(digest)).toBe(`link-preview-thumbnails/v1/${digest}/thumbnail.webp`)
- expect(linkPreviewThumbnailNegativeKey(digest, "b".repeat(64)))
- .toBe(`link-preview-thumbnail-negative:v1:${digest}:${"b".repeat(64)}`)
- expect(() => linkPreviewThumbnailUrl("../source")).toThrow("invalid thumbnail digest")
- })
-
- it("accepts only normalized public HTTPS image candidates", () => {
- expect(normalizePublicImageUrl("/og.png#private", new URL("https://example.com/post")).href)
- .toBe("https://example.com/og.png")
- expect(() => normalizePublicImageUrl("http://example.com/og.png")).toThrow("must use HTTPS")
- expect(() => normalizePublicImageUrl("https://127.0.0.1/og.png")).toThrow("non-public")
- expect(() => normalizePublicImageUrl("https://user:[email protected]/og.png")).toThrow("authority")
- expect(() => normalizePublicImageUrl("https://example.com:8443/og.png")).toThrow("authority")
- })
-
- it("writes and reads one strongly-bound, expiring private manifest", async () => {
- const put = vi.fn().mockResolvedValue(undefined)
- const pageDigest = "a".repeat(64)
- const manifest = await writeLinkPreviewThumbnailManifest({
- bucket: { put } as Pick<R2Bucket, "put">,
- pageDigest,
- sourceUrl: "https://images.example.com/og.png#fragment",
- now: 1_000,
- })
- expect(manifest).toMatchObject({
- version: 1,
- pageDigest,
- sourceUrl: "https://images.example.com/og.png",
- expiresAt: 1_000 + LINK_PREVIEW_THUMBNAIL_LIMITS.manifestTtlMs,
- })
- expect(manifest.sourceDigest).toMatch(/^[a-f0-9]{64}$/)
- const stored = put.mock.calls[0]?.[1] as string
- const object = {
- size: new TextEncoder().encode(stored).byteLength,
- body: bytesStream(new TextEncoder().encode(stored)),
- text: vi.fn().mockResolvedValue(stored),
- }
- await expect(readLinkPreviewThumbnailManifest({
- bucket: { get: vi.fn().mockResolvedValue(object) } as unknown as Pick<R2Bucket, "get">,
- pageDigest,
- now: 2_000,
- })).resolves.toEqual(manifest)
- })
-
- it("rejects invalid manifest writes and supports the default clock", async () => {
- await expect(writeLinkPreviewThumbnailManifest({
- bucket: { put: vi.fn() } as Pick<R2Bucket, "put">,
- pageDigest: "../source",
- sourceUrl: "https://example.com/image.jpg",
- })).rejects.toThrow("invalid thumbnail digest")
-
- const before = Date.now()
- const manifest = await writeLinkPreviewThumbnailManifest({
- bucket: { put: vi.fn().mockResolvedValue(undefined) } as Pick<R2Bucket, "put">,
- pageDigest: "a".repeat(64),
- sourceUrl: "https://example.com/image.jpg",
- })
- expect(manifest.expiresAt).toBeGreaterThanOrEqual(before + LINK_PREVIEW_THUMBNAIL_LIMITS.manifestTtlMs)
- })
-
- it.each([
- ["missing", null],
- ["oversized", { size: 4097, body: bytesStream(new Uint8Array([1])), text: vi.fn() }],
- ["malformed", { size: 1, body: bytesStream(new Uint8Array([1])), text: vi.fn().mockResolvedValue("{") }],
- ["mismatched", { size: 100, body: bytesStream(new Uint8Array([1])), text: vi.fn().mockResolvedValue(JSON.stringify({ version: 1, pageDigest: "b".repeat(64), sourceUrl: "https://example.com/a.jpg", sourceDigest: "c".repeat(64), expiresAt: 9_999 })) }],
- ["expired", { size: 100, body: bytesStream(new Uint8Array([1])), text: vi.fn().mockResolvedValue(JSON.stringify({ version: 1, pageDigest: "a".repeat(64), sourceUrl: "https://example.com/a.jpg", sourceDigest: "c".repeat(64), expiresAt: 1 })) }],
- ])("fails closed for a %s manifest", async (_label, object) => {
- await expect(readLinkPreviewThumbnailManifest({
- bucket: { get: vi.fn().mockResolvedValue(object) } as unknown as Pick<R2Bucket, "get">,
- pageDigest: "a".repeat(64),
- now: 2,
- })).resolves.toBeNull()
- })
-
- it("rejects invalid, non-record, and source-digest-mismatched manifests", async () => {
- const get = vi.fn()
- await expect(readLinkPreviewThumbnailManifest({
- bucket: { get } as unknown as Pick<R2Bucket, "get">,
- pageDigest: "../source",
- })).resolves.toBeNull()
- expect(get).not.toHaveBeenCalled()
-
- for (const stored of [
- "null",
- JSON.stringify({
- version: 1,
- pageDigest: "a".repeat(64),
- sourceUrl: "https://example.com/a.jpg",
- sourceDigest: "c".repeat(64),
- expiresAt: 9_999,
- }),
- ]) {
- await expect(readLinkPreviewThumbnailManifest({
- bucket: {
- get: vi.fn().mockResolvedValue({
- size: stored.length,
- body: bytesStream(new TextEncoder().encode(stored)),
- text: vi.fn().mockResolvedValue(stored),
- }),
- } as unknown as Pick<R2Bucket, "get">,
- pageDigest: "a".repeat(64),
- now: 1,
- })).resolves.toBeNull()
- }
- })
-
- it("swallows a failed oversized-manifest body cancellation", async () => {
- const cancel = vi.fn().mockRejectedValue(new Error("already closed"))
- await expect(readLinkPreviewThumbnailManifest({
- bucket: {
- get: vi.fn().mockResolvedValue({ size: 4097, body: { cancel } }),
- } as unknown as Pick<R2Bucket, "get">,
- pageDigest: "a".repeat(64),
- })).resolves.toBeNull()
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("serves only a fresh WebP object matching the current source digest", () => {
- const manifest = { sourceDigest: "a".repeat(64) } as LinkPreviewThumbnailManifest
- const object = {
- size: 123,
- httpMetadata: { contentType: "image/webp" },
- customMetadata: { sourceDigest: "a".repeat(64), expiresAt: "2000" },
- } as unknown as R2ObjectBody
- expect(isFreshLinkPreviewThumbnailObject(object, manifest, 1_000)).toBe(true)
- expect(isFreshLinkPreviewThumbnailObject({ ...object, size: 512 * 1024 + 1 } as R2ObjectBody, manifest, 1_000)).toBe(false)
- expect(isFreshLinkPreviewThumbnailObject({ ...object, customMetadata: { ...object.customMetadata, sourceDigest: "b".repeat(64) } } as R2ObjectBody, manifest, 1_000)).toBe(false)
- expect(isFreshLinkPreviewThumbnailObject(object, manifest, 2_000)).toBe(false)
- })
-})
-
-describe("fetchAndTransformLinkPreviewThumbnail", () => {
- it.each([
- ["image/jpeg", "image/jpeg"],
- ["image/png", "image/png"],
- ["image/webp", "image/webp"],
- ])("accepts a bounded static %s and applies the one fixed profile", async (declared, decoded) => {
- const images = mockImages({ format: decoded })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(new Uint8Array([1, 2, 3]), {
- headers: { "content-type": declared },
- })))
-
- await expect(fetchAndTransformLinkPreviewThumbnail("https://images.example.com/og", images.binding))
- .resolves.toEqual(new Uint8Array([1, 2, 3]))
- expect(images.transform).toHaveBeenCalledWith({ width: 640, height: 360, fit: "cover" })
- expect(images.output).toHaveBeenCalledWith({ format: "image/webp", quality: 78, anim: false })
- })
-
- it("follows at most three redirects, cancels them, and revalidates every HTTPS hop", async () => {
- const cancel = vi.fn()
- const fetchMock = vi.fn()
- .mockResolvedValueOnce(new Response(new ReadableStream<Uint8Array>({ cancel }), {
- status: 302,
- headers: { location: "https://cdn.example.com/second" },
- }))
- .mockResolvedValueOnce(response())
- vi.stubGlobal("fetch", fetchMock)
-
- await fetchAndTransformLinkPreviewThumbnail("https://images.example.com/start", mockImages().binding)
-
- expect(fetchMock).toHaveBeenCalledTimes(2)
- expect(cancel).toHaveBeenCalledOnce()
- expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
- redirect: "manual",
- credentials: "omit",
- referrerPolicy: "no-referrer",
- })
- })
-
- it.each([
- ["HTTP downgrade", "http://example.com/image.jpg", "must use HTTPS"],
- ["private redirect", "https://127.0.0.1/image.jpg", "non-public"],
- ])("rejects a %s before the next fetch", async (_label, location, message) => {
- const cancel = vi.fn()
- const fetchMock = vi.fn().mockResolvedValue(new Response(new ReadableStream<Uint8Array>({ cancel }), {
- status: 302,
- headers: { location },
- }))
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/start", mockImages().binding))
- .rejects.toThrow(message)
- expect(fetchMock).toHaveBeenCalledOnce()
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it("rejects a missing redirect location and a fourth redirect, canceling every body", async () => {
- const missingCancel = vi.fn()
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(new ReadableStream<Uint8Array>({ cancel: missingCancel }), { status: 302 })))
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/start", mockImages().binding))
- .rejects.toThrow("invalid thumbnail redirect")
- expect(missingCancel).toHaveBeenCalledOnce()
-
- const cancel = vi.fn()
- const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(new ReadableStream<Uint8Array>({ cancel }), {
- status: 302,
- headers: { location: "https://example.com/again" },
- })))
- vi.stubGlobal("fetch", fetchMock)
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/start", mockImages().binding))
- .rejects.toThrow("too many thumbnail redirects")
- expect(fetchMock).toHaveBeenCalledTimes(4)
- expect(cancel).toHaveBeenCalledTimes(4)
- })
-
- it.each([
- ["bodyless", new Response(null, { headers: { "content-type": "image/jpeg" } }), "no body"],
- ["non-success", response(undefined, { status: 503 }), "rejected request"],
- ["missing MIME", new Response(new Uint8Array([1])), "unsupported thumbnail MIME"],
- ["wrong MIME", response(undefined, { headers: { "content-type": "image/gif" } }), "unsupported thumbnail MIME"],
- ["declared oversize", response(undefined, { headers: { "content-type": "image/jpeg", "content-length": String(5 * 1024 * 1024 + 1) } }), "too large"],
- ["unsafe declared length", response(undefined, { headers: { "content-type": "image/jpeg", "content-length": "9".repeat(400) } }), "too large"],
- ["empty body", response(new Uint8Array()), "empty"],
- ])("rejects a %s upstream response", async (_label, upstream, message) => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(upstream))
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/image", mockImages().binding))
- .rejects.toThrow(message)
- })
-
- it("stream-counts and cancels an oversized body without content-length", async () => {
- const cancel = vi.fn()
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(new Uint8Array(LINK_PREVIEW_THUMBNAIL_LIMITS.maxSourceBytes + 1))
- },
- cancel,
- })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, {
- headers: { "content-type": "image/jpeg" },
- })))
-
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/image", mockImages().binding))
- .rejects.toThrow("too large")
- expect(cancel).toHaveBeenCalledOnce()
- })
-
- it.each([
- ["SVG", "image/svg+xml", 100, 100, "image/jpeg"],
- ["GIF", "image/gif", 100, 100, "image/jpeg"],
- ["MIME mismatch", "image/png", 100, 100, "image/jpeg"],
- ["oversized side", "image/jpeg", 8193, 1, "image/jpeg"],
- ["oversized area", "image/jpeg", 8000, 2001, "image/jpeg"],
- ])("rejects decoded %s before transformation", async (_label, format, width, height, declared) => {
- const images = mockImages({ format, width, height })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(undefined, {
- headers: { "content-type": declared },
- })))
-
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/image", images.binding)).rejects.toThrow()
- expect(images.transform).not.toHaveBeenCalled()
- })
-
- it("rejects APNG and animated WebP before transformation", async () => {
- const apng = new Uint8Array([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
- 0, 0, 0, 0, 0x61, 0x63, 0x54, 0x4c, 0, 0, 0, 0,
- ])
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(apng, { headers: { "content-type": "image/png" } })))
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/apng", mockImages({ format: "image/png" }).binding))
- .rejects.toThrow("animated thumbnail")
-
- const animatedWebp = new Uint8Array([
- 0x52, 0x49, 0x46, 0x46, 10, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
- 0x56, 0x50, 0x38, 0x58, 1, 0, 0, 0, 0x02, 0,
- ])
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(animatedWebp, { headers: { "content-type": "image/webp" } })))
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/animated", mockImages({ format: "image/webp" }).binding))
- .rejects.toThrow("animated thumbnail")
-
- const animChunkWebp = new Uint8Array([
- 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
- 0x41, 0x4e, 0x49, 0x4d, 0, 0, 0, 0,
- ])
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(animChunkWebp, { headers: { "content-type": "image/webp" } })))
- await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/anim-chunk", mockImages({ format: "image/webp" }).binding))
- .rejects.toThrow("animated thumbnail")
- })
-
- it.each([
- [
- "a malformed PNG chunk",
- "image/png",
- new Uint8Array([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
- 0, 0, 0, 20, 0x74, 0x45, 0x58, 0x74, 0, 0, 0, 0,
- ]),
- ],
- [
- "a malformed WebP chunk",
- "image/webp",
- new Uint8Array([
- 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
- 0x56, 0x50, 0x38, 0x20, 20, 0, 0, 0,
- ]),
- ],
- ])("fails safely while scanning %s", async (_label, mime, bytes) => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(bytes, {
- headers: { "content-type": mime },
- })))
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/static",
- mockImages({ format: mime }).binding,
- )).resolves.toEqual(new Uint8Array([1, 2, 3]))
- })
-
- it.each([
- [
- "a static PNG ending at IDAT",
- "image/png",
- new Uint8Array([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
- 0, 0, 0, 0, 0x49, 0x44, 0x41, 0x54, 0, 0, 0, 0,
- ]),
- ],
- [
- "a static PNG with only an ancillary chunk",
- "image/png",
- new Uint8Array([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
- 0, 0, 0, 0, 0x74, 0x45, 0x58, 0x74, 0, 0, 0, 0,
- ]),
- ],
- [
- "a static WebP chunk",
- "image/webp",
- new Uint8Array([
- 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
- 0x56, 0x50, 0x38, 0x20, 0, 0, 0, 0,
- ]),
- ],
- ])("accepts %s as non-animated", async (_label, mime, bytes) => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(bytes, {
- headers: { "content-type": mime },
- })))
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/static",
- mockImages({ format: mime }).binding,
- )).resolves.toEqual(new Uint8Array([1, 2, 3]))
- })
-
- it("rejects a wrong or oversized transformed output", async () => {
- vi.stubGlobal("fetch", vi.fn().mockImplementation(() => Promise.resolve(response())))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/image",
- mockImages({ outputType: "image/png" }).binding,
- )).rejects.toMatchObject({
- stage: "transform",
- disposition: "deterministic",
- code: "transform_mime",
- message: "thumbnail transform returned wrong MIME",
- })
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/image",
- mockImages({ output: new Uint8Array(LINK_PREVIEW_THUMBNAIL_LIMITS.maxOutputBytes + 1) }).binding,
- )).rejects.toMatchObject({
- stage: "transform",
- disposition: "deterministic",
- code: "transform_size",
- message: "thumbnail response is too large",
- })
- })
-
- it("rejects decoded image info without raster dimensions", async () => {
- const images = mockImages()
- vi.mocked(images.binding.info).mockResolvedValue({
- format: "image/svg+xml",
- fileSize: 3,
- })
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response()))
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/image",
- images.binding,
- )).rejects.toThrow("unsupported decoded thumbnail format")
- })
-
- it("applies the three-second budget across a stalled source read", async () => {
- vi.useFakeTimers()
- vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => Promise.resolve(new Response(
- new ReadableStream<Uint8Array>({
- start(controller) {
- init?.signal?.addEventListener("abort", () => controller.error(new Error("aborted")), { once: true })
- },
- }),
- { headers: { "content-type": "image/jpeg" } },
- ))))
-
- const result = fetchAndTransformLinkPreviewThumbnail("https://example.com/slow", mockImages().binding)
- .catch((error: unknown) => error)
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_THUMBNAIL_LIMITS.sourceTimeoutMs)
- await expect(result).resolves.toMatchObject({
- stage: "source",
- disposition: "transient",
- code: "source_timeout",
- })
- })
-
- it("rejects before reading when source headers resolve after the source budget", async () => {
- vi.useFakeTimers()
- let resolveFetch!: (response: Response) => void
- vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => {
- resolveFetch = resolve
- })))
-
- const result = fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/late-headers",
- mockImages().binding,
- )
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_THUMBNAIL_LIMITS.sourceTimeoutMs)
- resolveFetch(response())
-
- await expect(result).rejects.toMatchObject({
- stage: "source",
- disposition: "transient",
- code: "source_timeout",
- })
- })
-
- it("clears the source deadline before a valid Images operation uses its own five-second budget", async () => {
- vi.useFakeTimers()
- vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => {
- setTimeout(() => resolve(response()), LINK_PREVIEW_THUMBNAIL_LIMITS.sourceTimeoutMs - 100)
- })))
- const images = mockImages()
- vi.mocked(images.binding.info).mockImplementation(() => new Promise((resolve) => {
- setTimeout(() => resolve({ format: "image/jpeg", fileSize: 3, width: 1200, height: 630 }), 4_000)
- }))
-
- const result = fetchAndTransformLinkPreviewThumbnail("https://example.com/slow-valid", images.binding)
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_THUMBNAIL_LIMITS.sourceTimeoutMs - 100)
- await vi.advanceTimersByTimeAsync(4_000)
-
- await expect(result).resolves.toEqual(new Uint8Array([1, 2, 3]))
- })
-
- it("bounds Images at five seconds and observes a late platform rejection", async () => {
- vi.useFakeTimers()
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response()))
- const images = mockImages()
- vi.mocked(images.binding.info).mockImplementation(() => new Promise((_resolve, reject) => {
- setTimeout(() => reject(Object.assign(new Error("late"), { code: 9523 })), 6_000)
- }))
-
- const result = fetchAndTransformLinkPreviewThumbnail("https://example.com/slow-images", images.binding)
- .catch((error: unknown) => error)
- await vi.advanceTimersByTimeAsync(LINK_PREVIEW_THUMBNAIL_LIMITS.imagesTimeoutMs)
- await expect(result).resolves.toMatchObject({
- stage: "inspect",
- disposition: "transient",
- code: "inspect_timeout",
- })
- await vi.advanceTimersByTimeAsync(1_000)
- })
-
- it("classifies deterministic input rejection and transient service failures", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(undefined, {
- headers: { "content-type": "image/gif" },
- })))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/wrong-mime",
- mockImages().binding,
- )).rejects.toMatchObject({
- stage: "source",
- disposition: "deterministic",
- code: "source_mime",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
-
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(undefined, { status: 503 })))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/unavailable",
- mockImages().binding,
- )).rejects.toMatchObject({
- stage: "source",
- disposition: "transient",
- code: "source_http_503",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
-
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(undefined, { status: 429 })))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/rate-limited",
- mockImages().binding,
- )).rejects.toMatchObject({
- stage: "source",
- disposition: "transient",
- code: "source_http_429",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
-
- vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new DOMException("aborted", "AbortError")))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/aborted",
- mockImages().binding,
- )).rejects.toMatchObject({
- stage: "source",
- disposition: "transient",
- code: "source_aborted",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
-
- vi.stubGlobal("fetch", vi.fn().mockRejectedValue("unknown"))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/unknown",
- mockImages().binding,
- )).rejects.toMatchObject({
- stage: "source",
- disposition: "transient",
- code: "source_error",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
-
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response()))
- const images = mockImages()
- vi.mocked(images.binding.info).mockRejectedValue(Object.assign(new Error("service"), { code: 9523 }))
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/images-error",
- images.binding,
- )).rejects.toMatchObject({
- stage: "inspect",
- disposition: "transient",
- code: "inspect_9523",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
- })
-
- it("classifies transform rejections, preserves typed failures, and defaults unknown errors to transient", async () => {
- vi.stubGlobal("fetch", vi.fn().mockImplementation(() => Promise.resolve(response())))
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/transform-error",
- mockImages({ outputError: Object.assign(new Error("service"), { code: 9523 }) }).binding,
- )).rejects.toMatchObject({
- stage: "transform",
- disposition: "transient",
- code: "transform_9523",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
-
- const typed = new LinkPreviewThumbnailFailure({
- stage: "transform",
- disposition: "transient",
- code: "transform_typed",
- elapsedMs: 1,
- message: "typed",
- })
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/typed-transform-error",
- mockImages({ outputError: typed }).binding,
- )).rejects.toBe(typed)
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "https://example.com/unknown-transform-error",
- mockImages({ contentTypeError: "unknown" }).binding,
- )).rejects.toMatchObject({
- stage: "transform",
- disposition: "transient",
- code: "transform_error",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
- })
-
- it("classifies an invalid initial source URL before outbound work", async () => {
- const fetchMock = vi.fn()
- vi.stubGlobal("fetch", fetchMock)
-
- await expect(fetchAndTransformLinkPreviewThumbnail(
- "http://example.com/image.jpg",
- mockImages().binding,
- )).rejects.toMatchObject({
- stage: "source",
- disposition: "deterministic",
- code: "source_url",
- } satisfies Partial<LinkPreviewThumbnailFailure>)
- expect(fetchMock).not.toHaveBeenCalled()
- })
-
- it("builds exact 24-hour R2 object metadata", () => {
- const manifest = { sourceDigest: "a".repeat(64) } as LinkPreviewThumbnailManifest
- expect(linkPreviewThumbnailObjectMetadata(manifest, 1_000)).toEqual({
- httpMetadata: {
- contentType: "image/webp",
- cacheControl: "private, max-age=21600, immutable",
- contentDisposition: "inline",
- },
- customMetadata: {
- sourceDigest: "a".repeat(64),
- expiresAt: String(1_000 + LINK_PREVIEW_THUMBNAIL_LIMITS.thumbnailTtlMs),
- },
- })
- })
-})
diff --git a/src/web/src/lib/community/link-preview-thumbnail.ts b/src/web/src/lib/community/link-preview-thumbnail.ts
deleted file mode 100644
index 6f4375840..000000000
--- a/src/web/src/lib/community/link-preview-thumbnail.ts
+++ /dev/null
@@ -1,677 +0,0 @@
-import { normalizePublicPreviewUrl } from "./link-preview-fetch"
-
-const THUMBNAIL_VERSION = 1
-const THUMBNAIL_PREFIX = "link-preview-thumbnails/v1"
-const MAX_SOURCE_BYTES = 5 * 1024 * 1024
-const MAX_OUTPUT_BYTES = 512 * 1024
-const MAX_MANIFEST_BYTES = 4 * 1024
-const MAX_REDIRECTS = 3
-const SOURCE_TIMEOUT_MS = 3_000
-const IMAGES_TIMEOUT_MS = 5_000
-const MAX_DIMENSION = 8_192
-const MAX_AREA = 16_000_000
-const THUMBNAIL_WIDTH = 640
-const THUMBNAIL_HEIGHT = 360
-const THUMBNAIL_QUALITY = 78
-const MANIFEST_TTL_MS = 6 * 60 * 60 * 1_000
-const THUMBNAIL_TTL_MS = 24 * 60 * 60 * 1_000
-const TOKEN_RE = /^[a-f0-9]{64}$/
-const ALLOWED_MIME = new Set(["image/jpeg", "image/png", "image/webp"])
-
-export type LinkPreviewThumbnailManifest = {
- version: 1
- pageDigest: string
- sourceUrl: string
- sourceDigest: string
- expiresAt: number
-}
-
-export type LinkPreviewThumbnailFailureStage = "source" | "inspect" | "transform" | "storage"
-export type LinkPreviewThumbnailFailureDisposition = "deterministic" | "transient"
-
-export class LinkPreviewThumbnailFailure extends Error {
- readonly stage: LinkPreviewThumbnailFailureStage
- readonly disposition: LinkPreviewThumbnailFailureDisposition
- readonly code: string
- readonly elapsedMs: number
-
- constructor(args: {
- stage: LinkPreviewThumbnailFailureStage
- disposition: LinkPreviewThumbnailFailureDisposition
- code: string
- elapsedMs: number
- message: string
- }) {
- super(args.message)
- this.name = "LinkPreviewThumbnailFailure"
- this.stage = args.stage
- this.disposition = args.disposition
- this.code = args.code
- this.elapsedMs = args.elapsedMs
- }
-}
-
-function failure(args: {
- stage: LinkPreviewThumbnailFailureStage
- disposition: LinkPreviewThumbnailFailureDisposition
- code: string
- startedAt: number
- message: string
-}): LinkPreviewThumbnailFailure {
- return new LinkPreviewThumbnailFailure({
- stage: args.stage,
- disposition: args.disposition,
- code: args.code,
- elapsedMs: Math.max(0, Date.now() - args.startedAt),
- message: args.message,
- })
-}
-
-function stablePlatformCode(error: unknown, fallback: string): string {
- if (error instanceof LinkPreviewThumbnailFailure) return error.code
- if (error instanceof DOMException && error.name === "AbortError") return `${fallback}_aborted`
- if (typeof error === "object" && error !== null) {
- const value = error as { code?: unknown; name?: unknown }
- if ((typeof value.code === "string" || typeof value.code === "number")
- && /^[a-zA-Z0-9_.-]{1,64}$/.test(String(value.code))) {
- return `${fallback}_${String(value.code).toLowerCase()}`
- }
- if (typeof value.name === "string" && /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(value.name)) {
- return `${fallback}_${value.name.toLowerCase()}`
- }
- }
- return `${fallback}_error`
-}
-
-async function withDeadline<T>(
- promise: Promise<T>,
- timeoutMs: number,
- onTimeout: () => LinkPreviewThumbnailFailure,
-): Promise<T> {
- let timer: ReturnType<typeof setTimeout> | undefined
- const timeout = new Promise<never>((_resolve, reject) => {
- timer = setTimeout(() => reject(onTimeout()), timeoutMs)
- })
- promise.catch(() => {})
- try {
- return await Promise.race([promise, timeout])
- } finally {
- if (timer !== undefined) clearTimeout(timer)
- }
-}
-
-function streamFromBytes(bytes: Uint8Array): ReadableStream<Uint8Array> {
- return new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(bytes)
- controller.close()
- },
- })
-}
-
-async function sha256Hex(value: string): Promise<string> {
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
-}
-
-export async function linkPreviewPageDigest(canonicalPageUrl: string): Promise<string> {
- return sha256Hex(canonicalPageUrl)
-}
-
-export function linkPreviewThumbnailUrl(pageDigest: string): string {
- if (!TOKEN_RE.test(pageDigest)) throw new Error("invalid thumbnail digest")
- return `/api/community/link-preview/thumbnail/${pageDigest}`
-}
-
-export function linkPreviewThumbnailManifestKey(pageDigest: string): string {
- return `${THUMBNAIL_PREFIX}/${pageDigest}/manifest.json`
-}
-
-export function linkPreviewThumbnailObjectKey(pageDigest: string): string {
- return `${THUMBNAIL_PREFIX}/${pageDigest}/thumbnail.webp`
-}
-
-export function linkPreviewThumbnailNegativeKey(pageDigest: string, sourceDigest: string): string {
- return `link-preview-thumbnail-negative:v1:${pageDigest}:${sourceDigest}`
-}
-
-export function isLinkPreviewThumbnailDigest(value: string | undefined): value is string {
- return typeof value === "string" && TOKEN_RE.test(value)
-}
-
-export function normalizePublicImageUrl(input: string, base?: URL): URL {
- const resolved = base ? new URL(input, base) : new URL(input)
- const normalized = normalizePublicPreviewUrl(resolved.href)
- if (normalized.protocol !== "https:") throw new Error("thumbnail source must use HTTPS")
- return normalized
-}
-
-export async function writeLinkPreviewThumbnailManifest(args: {
- bucket: Pick<R2Bucket, "put">
- pageDigest: string
- sourceUrl: string
- now?: number
-}): Promise<LinkPreviewThumbnailManifest> {
- if (!isLinkPreviewThumbnailDigest(args.pageDigest)) throw new Error("invalid thumbnail digest")
- const sourceUrl = normalizePublicImageUrl(args.sourceUrl).href
- const now = args.now ?? Date.now()
- const manifest: LinkPreviewThumbnailManifest = {
- version: THUMBNAIL_VERSION,
- pageDigest: args.pageDigest,
- sourceUrl,
- sourceDigest: await sha256Hex(sourceUrl),
- expiresAt: now + MANIFEST_TTL_MS,
- }
- await args.bucket.put(
- linkPreviewThumbnailManifestKey(args.pageDigest),
- JSON.stringify(manifest),
- {
- httpMetadata: { contentType: "application/json" },
- customMetadata: {
- version: String(THUMBNAIL_VERSION),
- pageDigest: args.pageDigest,
- sourceDigest: manifest.sourceDigest,
- expiresAt: String(manifest.expiresAt),
- },
- },
- )
- return manifest
-}
-
-function manifestRecord(value: unknown): Record<string, unknown> | null {
- return value !== null && typeof value === "object" && !Array.isArray(value)
- ? value as Record<string, unknown>
- : null
-}
-
-export async function readLinkPreviewThumbnailManifest(args: {
- bucket: Pick<R2Bucket, "get">
- pageDigest: string
- now?: number
-}): Promise<LinkPreviewThumbnailManifest | null> {
- if (!isLinkPreviewThumbnailDigest(args.pageDigest)) return null
- const object = await args.bucket.get(linkPreviewThumbnailManifestKey(args.pageDigest))
- if (!object) return null
- if (object.size <= 0 || object.size > MAX_MANIFEST_BYTES) {
- await object.body.cancel().catch(() => {})
- return null
- }
- try {
- const record = manifestRecord(JSON.parse(await object.text()))
- if (!record
- || record.version !== THUMBNAIL_VERSION
- || record.pageDigest !== args.pageDigest
- || typeof record.sourceUrl !== "string"
- || typeof record.sourceDigest !== "string"
- || !TOKEN_RE.test(record.sourceDigest)
- || typeof record.expiresAt !== "number"
- || !Number.isSafeInteger(record.expiresAt)
- || record.expiresAt <= (args.now ?? Date.now())) {
- return null
- }
- const sourceUrl = normalizePublicImageUrl(record.sourceUrl).href
- if (await sha256Hex(sourceUrl) !== record.sourceDigest) return null
- return {
- version: THUMBNAIL_VERSION,
- pageDigest: args.pageDigest,
- sourceUrl,
- sourceDigest: record.sourceDigest,
- expiresAt: record.expiresAt,
- }
- } catch {
- return null
- }
-}
-
-export function isFreshLinkPreviewThumbnailObject(
- object: R2ObjectBody,
- manifest: LinkPreviewThumbnailManifest,
- now = Date.now(),
-): boolean {
- const expiresAt = Number(object.customMetadata?.expiresAt)
- return object.size > 0
- && object.size <= MAX_OUTPUT_BYTES
- && object.httpMetadata?.contentType === "image/webp"
- && object.customMetadata?.sourceDigest === manifest.sourceDigest
- && Number.isSafeInteger(expiresAt)
- && expiresAt > now
-}
-
-function isRedirect(status: number): boolean {
- return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
-}
-
-function abortError(): Error {
- return new DOMException("thumbnail request timed out", "AbortError")
-}
-
-async function withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
- if (signal.aborted) throw abortError()
- let rejectAbort!: (reason?: unknown) => void
- const aborted = new Promise<never>((_resolve, reject) => {
- rejectAbort = reject
- })
- const onAbort = () => rejectAbort(abortError())
- signal.addEventListener("abort", onAbort, { once: true })
- try {
- return await Promise.race([promise, aborted])
- } finally {
- signal.removeEventListener("abort", onAbort)
- }
-}
-
-async function readBoundedBytes(
- body: ReadableStream<Uint8Array> | null,
- maxBytes: number,
- signal: AbortSignal,
- args: {
- stage: LinkPreviewThumbnailFailureStage
- disposition: LinkPreviewThumbnailFailureDisposition
- missingBodyCode: string
- sizeCode: string
- startedAt: number
- },
-): Promise<Uint8Array> {
- if (!body) {
- throw failure({
- stage: args.stage,
- disposition: "transient",
- code: args.missingBodyCode,
- startedAt: args.startedAt,
- message: "thumbnail response has no body",
- })
- }
- const reader = body.getReader()
- const chunks: Uint8Array[] = []
- let total = 0
- try {
- while (true) {
- const { done, value } = await withAbort(reader.read(), signal)
- if (done) break
- total += value.byteLength
- if (total > maxBytes) {
- await reader.cancel().catch(() => {})
- throw failure({
- stage: args.stage,
- disposition: args.disposition,
- code: args.sizeCode,
- startedAt: args.startedAt,
- message: "thumbnail response is too large",
- })
- }
- chunks.push(value)
- }
- } catch (error) {
- await reader.cancel().catch(() => {})
- throw error
- } finally {
- reader.releaseLock()
- }
- if (total === 0) {
- throw failure({
- stage: args.stage,
- disposition: args.disposition,
- code: args.sizeCode,
- startedAt: args.startedAt,
- message: "thumbnail response is empty",
- })
- }
- const bytes = new Uint8Array(total)
- let offset = 0
- for (const chunk of chunks) {
- bytes.set(chunk, offset)
- offset += chunk.byteLength
- }
- return bytes
-}
-
-function declaredContentLength(response: Response): number | null {
- const raw = response.headers.get("content-length")
- if (!raw || !/^\d+$/.test(raw)) return null
- const value = Number(raw)
- return Number.isSafeInteger(value) ? value : Number.POSITIVE_INFINITY
-}
-
-async function fetchThumbnailSource(start: URL, signal: AbortSignal): Promise<{
- bytes: Uint8Array
- contentType: string
-}> {
- const startedAt = Date.now()
- let current = start
- for (let redirects = 0; ; redirects += 1) {
- const response = await fetch(current.href, {
- method: "GET",
- redirect: "manual",
- signal,
- credentials: "omit",
- headers: {
- Accept: "image/jpeg,image/png,image/webp",
- "User-Agent": "Alook-Link-Preview-Thumbnail/1.0",
- },
- referrerPolicy: "no-referrer",
- })
- if (isRedirect(response.status)) {
- await response.body?.cancel().catch(() => {})
- if (redirects === MAX_REDIRECTS) {
- throw failure({
- stage: "source",
- disposition: "deterministic",
- code: "source_redirect_limit",
- startedAt,
- message: "too many thumbnail redirects",
- })
- }
- const location = response.headers.get("location")
- if (!location) {
- throw failure({
- stage: "source",
- disposition: "deterministic",
- code: "source_redirect_missing",
- startedAt,
- message: "invalid thumbnail redirect",
- })
- }
- try {
- current = normalizePublicImageUrl(location, current)
- } catch (error) {
- throw failure({
- stage: "source",
- disposition: "deterministic",
- code: "source_redirect_rejected",
- startedAt,
- message: error instanceof Error ? error.message : "invalid thumbnail redirect",
- })
- }
- continue
- }
- if (!response.ok) {
- await response.body?.cancel().catch(() => {})
- const deterministic = response.status >= 400
- && response.status < 500
- && response.status !== 408
- && response.status !== 429
- throw failure({
- stage: "source",
- disposition: deterministic ? "deterministic" : "transient",
- code: `source_http_${response.status}`,
- startedAt,
- message: "thumbnail origin rejected request",
- })
- }
- const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
- if (!ALLOWED_MIME.has(contentType)) {
- await response.body?.cancel().catch(() => {})
- throw failure({
- stage: "source",
- disposition: "deterministic",
- code: "source_mime",
- startedAt,
- message: "unsupported thumbnail MIME",
- })
- }
- if ((declaredContentLength(response) ?? 0) > MAX_SOURCE_BYTES) {
- await response.body?.cancel().catch(() => {})
- throw failure({
- stage: "source",
- disposition: "deterministic",
- code: "source_size",
- startedAt,
- message: "thumbnail response is too large",
- })
- }
- return {
- bytes: await readBoundedBytes(response.body, MAX_SOURCE_BYTES, signal, {
- stage: "source",
- disposition: "deterministic",
- missingBodyCode: "source_body_missing",
- sizeCode: "source_size",
- startedAt,
- }),
- contentType,
- }
- }
-}
-
-function ascii(bytes: Uint8Array, offset: number, length: number): string {
- return String.fromCharCode(...bytes.subarray(offset, offset + length))
-}
-
-function isAnimatedPng(bytes: Uint8Array): boolean {
- const pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
- if (bytes.length < 8 || pngSignature.some((byte, index) => bytes[index] !== byte)) return false
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
- let offset = 8
- while (offset + 12 <= bytes.length) {
- const length = view.getUint32(offset)
- const end = offset + 12 + length
- if (end > bytes.length) return false
- const type = ascii(bytes, offset + 4, 4)
- if (type === "acTL") return true
- if (type === "IDAT" || type === "IEND") return false
- offset = end
- }
- return false
-}
-
-function isAnimatedWebp(bytes: Uint8Array): boolean {
- if (bytes.length < 12 || ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") return false
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
- let offset = 12
- while (offset + 8 <= bytes.length) {
- const type = ascii(bytes, offset, 4)
- const length = view.getUint32(offset + 4, true)
- const dataStart = offset + 8
- const end = dataStart + length
- if (end > bytes.length) return false
- if (type === "ANIM" || type === "ANMF") return true
- if (type === "VP8X" && length >= 1 && (bytes[dataStart]! & 0x02) !== 0) return true
- offset = end + (length % 2)
- }
- return false
-}
-
-function decodedMime(format: string): string | null {
- const normalized = format.toLowerCase()
- if (normalized === "image/jpeg" || normalized === "jpeg" || normalized === "jpg") return "image/jpeg"
- if (normalized === "image/png" || normalized === "png") return "image/png"
- if (normalized === "image/webp" || normalized === "webp") return "image/webp"
- return null
-}
-
-async function transformThumbnail(
- images: ImagesBinding,
- bytes: Uint8Array,
- declaredMime: string,
- activeStage: { current: "inspect" | "transform" },
- signal: AbortSignal,
-): Promise<Uint8Array> {
- const startedAt = Date.now()
- let info
- try {
- info = await withAbort(images.info(streamFromBytes(bytes)), signal)
- } catch (error) {
- if (error instanceof LinkPreviewThumbnailFailure) throw error
- throw failure({
- stage: "inspect",
- disposition: "transient",
- code: stablePlatformCode(error, "inspect"),
- startedAt,
- message: "thumbnail inspection failed",
- })
- }
- if (!("width" in info) || !("height" in info)) {
- throw failure({
- stage: "inspect",
- disposition: "deterministic",
- code: "inspect_format",
- startedAt,
- message: "unsupported decoded thumbnail format",
- })
- }
- const actualMime = decodedMime(info.format)
- if (!actualMime || actualMime !== declaredMime) {
- throw failure({
- stage: "inspect",
- disposition: "deterministic",
- code: "inspect_mime",
- startedAt,
- message: "thumbnail MIME mismatch",
- })
- }
- if ((actualMime === "image/png" && isAnimatedPng(bytes))
- || (actualMime === "image/webp" && isAnimatedWebp(bytes))) {
- throw failure({
- stage: "inspect",
- disposition: "deterministic",
- code: "inspect_animation",
- startedAt,
- message: "animated thumbnail rejected",
- })
- }
- if (!Number.isSafeInteger(info.width)
- || !Number.isSafeInteger(info.height)
- || info.width <= 0
- || info.height <= 0
- || info.width > MAX_DIMENSION
- || info.height > MAX_DIMENSION
- || info.width * info.height > MAX_AREA) {
- throw failure({
- stage: "inspect",
- disposition: "deterministic",
- code: "inspect_dimensions",
- startedAt,
- message: "thumbnail dimensions exceed limit",
- })
- }
-
- activeStage.current = "transform"
- const transformStartedAt = Date.now()
- let output
- try {
- output = await withAbort(images
- .input(streamFromBytes(bytes))
- .transform({ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT, fit: "cover" })
- .output({ format: "image/webp", quality: THUMBNAIL_QUALITY, anim: false }), signal)
- } catch (error) {
- if (error instanceof LinkPreviewThumbnailFailure) throw error
- throw failure({
- stage: "transform",
- disposition: "transient",
- code: stablePlatformCode(error, "transform"),
- startedAt: transformStartedAt,
- message: "thumbnail transform failed",
- })
- }
- if (output.contentType() !== "image/webp") {
- throw failure({
- stage: "transform",
- disposition: "deterministic",
- code: "transform_mime",
- startedAt: transformStartedAt,
- message: "thumbnail transform returned wrong MIME",
- })
- }
- return readBoundedBytes(output.image(), MAX_OUTPUT_BYTES, signal, {
- stage: "transform",
- disposition: "deterministic",
- missingBodyCode: "transform_body_missing",
- sizeCode: "transform_size",
- startedAt: transformStartedAt,
- })
-}
-
-export async function fetchAndTransformLinkPreviewThumbnail(
- sourceUrl: string,
- images: ImagesBinding,
-): Promise<Uint8Array> {
- const sourceStartedAt = Date.now()
- let source: URL
- try {
- source = normalizePublicImageUrl(sourceUrl)
- } catch (error) {
- throw failure({
- stage: "source",
- disposition: "deterministic",
- code: "source_url",
- startedAt: sourceStartedAt,
- message: error instanceof Error ? error.message : "invalid thumbnail source",
- })
- }
- const controller = new AbortController()
- const timer = setTimeout(() => controller.abort(), SOURCE_TIMEOUT_MS)
- let fetched: { bytes: Uint8Array; contentType: string }
- try {
- fetched = await fetchThumbnailSource(source, controller.signal)
- } catch (error) {
- if (error instanceof LinkPreviewThumbnailFailure) throw error
- const timeout = controller.signal.aborted
- throw failure({
- stage: "source",
- disposition: "transient",
- code: timeout ? "source_timeout" : stablePlatformCode(error, "source"),
- startedAt: sourceStartedAt,
- message: timeout ? "thumbnail request timed out" : "thumbnail source request failed",
- })
- } finally {
- clearTimeout(timer)
- }
-
- const imagesStartedAt = Date.now()
- const imagesController = new AbortController()
- const activeStage: { current: "inspect" | "transform" } = { current: "inspect" }
- try {
- return await withDeadline(
- transformThumbnail(images, fetched.bytes, fetched.contentType, activeStage, imagesController.signal),
- IMAGES_TIMEOUT_MS,
- () => {
- queueMicrotask(() => imagesController.abort())
- return failure({
- stage: activeStage.current,
- disposition: "transient",
- code: `${activeStage.current}_timeout`,
- startedAt: imagesStartedAt,
- message: "thumbnail Images operation timed out",
- })
- },
- )
- } catch (error) {
- if (error instanceof LinkPreviewThumbnailFailure) throw error
- throw failure({
- stage: activeStage.current,
- disposition: "transient",
- code: stablePlatformCode(error, activeStage.current),
- startedAt: imagesStartedAt,
- message: "thumbnail Images operation failed",
- })
- }
-}
-
-export function linkPreviewThumbnailObjectMetadata(manifest: LinkPreviewThumbnailManifest, now = Date.now()) {
- return {
- httpMetadata: {
- contentType: "image/webp",
- cacheControl: "private, max-age=21600, immutable",
- contentDisposition: "inline",
- },
- customMetadata: {
- sourceDigest: manifest.sourceDigest,
- expiresAt: String(now + THUMBNAIL_TTL_MS),
- },
- } satisfies R2PutOptions
-}
-
-export const LINK_PREVIEW_THUMBNAIL_LIMITS = {
- maxSourceBytes: MAX_SOURCE_BYTES,
- maxOutputBytes: MAX_OUTPUT_BYTES,
- maxRedirects: MAX_REDIRECTS,
- sourceTimeoutMs: SOURCE_TIMEOUT_MS,
- imagesTimeoutMs: IMAGES_TIMEOUT_MS,
- maxDimension: MAX_DIMENSION,
- maxArea: MAX_AREA,
- width: THUMBNAIL_WIDTH,
- height: THUMBNAIL_HEIGHT,
- quality: THUMBNAIL_QUALITY,
- manifestTtlMs: MANIFEST_TTL_MS,
- thumbnailTtlMs: THUMBNAIL_TTL_MS,
- prefix: THUMBNAIL_PREFIX,
-} as const
diff --git a/src/web/src/lib/community/link-preview.test.ts b/src/web/src/lib/community/link-preview.test.ts
deleted file mode 100644
index b750d07cc..000000000
--- a/src/web/src/lib/community/link-preview.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, expect, it } from "vitest"
-import { extractLinkPreviewUrl } from "./link-preview"
-
-describe("extractLinkPreviewUrl", () => {
- it("selects the first eligible URL and strips fragments", () => {
- expect(extractLinkPreviewUrl(
- "first https://example.com/path#section then https://example.org/later",
- )).toBe("https://example.com/path")
- })
-
- it("keeps prose punctuation outside the selected URL", () => {
- expect(extractLinkPreviewUrl("See (https://github.com/alookai/alook/pull/1)."))
- .toBe("https://github.com/alookai/alook/pull/1")
- })
-
- it("skips invite action-card URLs and selects the next ordinary link", () => {
- expect(extractLinkPreviewUrl(
- "https://alook.ai/c/invite/abcdef https://x.com/alook/status/123",
- )).toBe("https://x.com/alook/status/123")
- })
-
- it("returns null when the message has no eligible public-web URL", () => {
- expect(extractLinkPreviewUrl("no link here /c/invite/abcdef ftp://example.com"))
- .toBeNull()
- })
-})
diff --git a/src/web/src/lib/community/link-preview.ts b/src/web/src/lib/community/link-preview.ts
deleted file mode 100644
index 02992023a..000000000
--- a/src/web/src/lib/community/link-preview.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-export type LinkPreview = {
- url: string
- hostname: string
- title: string
- description?: string
- siteName?: string
- thumbnailUrl?: string
-}
-
-const URL_CANDIDATE_RE = /https?:\/\/[^\s<>"']+/gi
-const TRAILING_PROSE_RE = /[.,!?;:'"\)\]\}]+$/
-const INVITE_PATH_RE = /^\/c\/invite\/[A-Za-z0-9_-]{6,64}\/?$/
-
-/**
- * Returns at most one ordinary public-web URL for a message preview. The raw
- * message remains untouched; this is only a cheap selector for the lazy card.
- * Alook invite URLs keep their dedicated action card and are skipped here.
- */
-export function extractLinkPreviewUrl(text: string): string | null {
- for (const match of text.matchAll(URL_CANDIDATE_RE)) {
- const candidate = match[0]?.replace(TRAILING_PROSE_RE, "")
- if (!candidate) continue
- try {
- const url = new URL(candidate)
- if (url.protocol !== "http:" && url.protocol !== "https:") continue
- if (INVITE_PATH_RE.test(url.pathname)) continue
- url.hash = ""
- return url.href
- } catch {
- // Keep scanning: malformed prose before a valid URL must not suppress it.
- }
- }
- return null
-}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 13ed2839d..3a692b483 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -82,8 +82,6 @@ export const tid = {
imageLightboxLoading: "community-image-lightbox-loading",
imageLightboxError: "community-image-lightbox-error",
imageLightboxRetry: "community-image-lightbox-retry",
- linkPreviewCard: "community-link-preview-card",
- linkPreviewThumbnail: "community-link-preview-thumbnail",
message: (id: string) => `community-message-${id}`,
messageImage: (id: string, index: number) => `community-message-image-${id}-${index}`,
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index e779737c8..137d132e8 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -139,11 +139,6 @@ describe("communityKeys", () => {
"message",
"m1",
])
- expect(communityKeys.linkPreview("https://example.com/")).toEqual([
- "community",
- "link-preview",
- "https://example.com/",
- ])
})
it("keeps report polling specific to one report and outside the bots-list cache", () => {
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 14c410981..6fd3ffe0c 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -53,10 +53,6 @@ export const communityKeys = {
// have — the id/serverId only comes back with the response.
inviteInfo: (token: string) =>
[...communityKeys.all, "invite-info", token] as const,
- // Independent lazy unfurl. The full normalized URL is safe in the
- // per-browser query cache; server KV keys hash it before persistence.
- linkPreview: (url: string) =>
- [...communityKeys.all, "link-preview", url] as const,
// ── Channel-scoped resources ────────────────────────────────────────────
// Message list roots are keyed by channelId so paginated pages nest under
diff --git a/src/web/src/test/architecture/link-preview-runtime-config.test.ts b/src/web/src/test/architecture/link-preview-runtime-config.test.ts
deleted file mode 100644
index 15ff26a3e..000000000
--- a/src/web/src/test/architecture/link-preview-runtime-config.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { readFileSync } from "node:fs"
-import { fileURLToPath } from "node:url"
-import { describe, expect, it } from "vitest"
-import { RATE_LIMITS } from "../../../../shared/src/lib/rate-limits"
-
-describe("link preview Worker network boundary", () => {
- it("deploys global fetch through the public Internet boundary", () => {
- const wranglerPath = fileURLToPath(new URL("../../../wrangler.toml", import.meta.url))
- const config = readFileSync(wranglerPath, "utf8")
- const flags = config.match(/^compatibility_flags\s*=\s*\[([^\]]+)\]/m)?.[1] ?? ""
-
- expect(flags).toContain('"nodejs_compat"')
- expect(flags).toContain('"global_fetch_strictly_public"')
- expect(config).toMatch(/^\[images\]\nbinding\s*=\s*"IMAGES"$/m)
- expect(RATE_LIMITS["community:linkPreviewThumbnail"]).toEqual({
- windowMs: 60_000,
- max: 120,
- })
- })
-
- it("fails every Web production artifact path closed on the R2 lifecycle preflight", () => {
- const webPackagePath = fileURLToPath(new URL("../../../package.json", import.meta.url))
- const rootPackagePath = fileURLToPath(new URL("../../../../../package.json", import.meta.url))
- const webPackage = JSON.parse(readFileSync(webPackagePath, "utf8")) as {
- scripts: Record<string, string>
- }
- const rootPackage = JSON.parse(readFileSync(rootPackagePath, "utf8")) as {
- scripts: Record<string, string>
- }
-
- expect(webPackage.scripts.deploy).toMatch(/^pnpm preflight:link-preview-thumbnails && /)
- expect(webPackage.scripts.upload).toMatch(/^pnpm preflight:link-preview-thumbnails && /)
- expect(rootPackage.scripts["deploy:web"])
- .toMatch(/^pnpm --filter @alook\/web preflight:link-preview-thumbnails && /)
- })
-})
diff --git a/src/web/test-runtime/worker.runtime.test.ts b/src/web/test-runtime/worker.runtime.test.ts
index f1b99158f..649c765f7 100644
--- a/src/web/test-runtime/worker.runtime.test.ts
+++ b/src/web/test-runtime/worker.runtime.test.ts
@@ -9,15 +9,6 @@ const worker = (exports as unknown as {
default: { fetch(request: Request): Promise<Response> }
}).default
-function byteStream(bytes: Uint8Array): ReadableStream<Uint8Array> {
- return new ReadableStream({
- start(controller) {
- controller.enqueue(bytes)
- controller.close()
- },
- })
-}
-
describe("Web workerd runtime", () => {
it("loads production migrations and local storage bindings", async () => {
const schema = await runtimeEnv.DB.prepare(
@@ -36,23 +27,6 @@ describe("Web workerd runtime", () => {
await runtimeEnv.CACHE_KV.delete(kvKey)
})
- it("decodes and transforms a raster through the configured Images binding", async () => {
- const png = Uint8Array.from(
- atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="),
- (char) => char.charCodeAt(0),
- )
- const info = await runtimeEnv.IMAGES.info(byteStream(png))
- expect(info).toMatchObject({ format: "image/png", width: 1, height: 1 })
-
- const output = await runtimeEnv.IMAGES
- .input(byteStream(png))
- .transform({ width: 640, height: 360, fit: "cover" })
- .output({ format: "image/webp", quality: 78, anim: false })
- expect(output.contentType()).toBe("image/webp")
- const transformed = new Uint8Array(await new Response(output.image()).arrayBuffer())
- expect(transformed.byteLength).toBeGreaterThan(0)
- })
-
it.each(["/", "/pricing", "/apiary"])(
"adds browser and CDN revalidation headers to public route %s",
async (pathname) => {
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index 60174278a..4db1bfef6 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -1,7 +1,7 @@
name = "alook-web"
main = "custom-worker.ts"
compatibility_date = "2026-04-09"
-compatibility_flags = ["nodejs_compat", "global_fetch_strictly_public"]
+compatibility_flags = ["nodejs_compat"]
# Disable esbuild keep_names — otherwise __name(...) wrappers leak into
# stringified inline scripts (ThemeScript, next-themes) and throw
# "__name is not defined" at runtime in the browser.
@@ -62,9 +62,6 @@ bucket_name = "alook-emails"
binding = "COMMUNITY_MEDIA"
bucket_name = "alook-community-media"
-[images]
-binding = "IMAGES"
-
[[r2_buckets]]
binding = "BUG_REPORTS"
bucket_name = "alook-bug-reports"