|
| 1 | +/** |
| 2 | + * Slug-history redirect plugin. |
| 3 | + * |
| 4 | + * Serves 301s for non-expired SlugHistory entries per |
| 5 | + * specs/behaviors/slug-handles.md → "Mutability and redirects". Pattern- |
| 6 | + * matches the slug-bearing SPA paths on every non-/api/* GET; for live- |
| 7 | + * missing slugs that have a SlugHistory entry, redirects to the canonical |
| 8 | + * URL with the suffix preserved. |
| 9 | + * |
| 10 | + * Spec edge cases handled: |
| 11 | + * - **Live wins** — if `oldSlug` is currently a live entity of the same |
| 12 | + * type (someone took the freed slug), no redirect. |
| 13 | + * - **Multi-hop chains** — A → B → C resolves to C in one response via |
| 14 | + * in-process chain follow, capped at MAX_HOPS to short-circuit |
| 15 | + * pathological inputs. |
| 16 | + * - **Expired entries** — past-`expiresAt` records are dropped at index |
| 17 | + * time (`indexSlugHistory`) so the lookup naturally misses. |
| 18 | + * - **Tag namespace** — `/tags/:namespace/:slug` rewrites the slug while |
| 19 | + * preserving the namespace; the SlugHistory key is `tag:<slug>` |
| 20 | + * regardless of namespace (matches the schema's lookup shape). |
| 21 | + * |
| 22 | + * Plugin order: registered after `services` (decorates `inMemoryState`) |
| 23 | + * and before `static-web` (which owns the SPA fallthrough notFoundHandler). |
| 24 | + */ |
| 25 | +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; |
| 26 | +import fp from 'fastify-plugin'; |
| 27 | + |
| 28 | +import type { SlugHistory } from '@cfp/shared/schemas'; |
| 29 | + |
| 30 | +import { slugHistoryKey, type InMemoryState } from '../store/memory/state.js'; |
| 31 | + |
| 32 | +const MAX_HOPS = 8; |
| 33 | + |
| 34 | +type EntityType = SlugHistory['entityType']; |
| 35 | + |
| 36 | +/** |
| 37 | + * Pattern descriptor for a slug-bearing path. Each pattern declares the |
| 38 | + * regex that extracts the slug component(s) and a function that rebuilds |
| 39 | + * the URL once we've resolved any renames. |
| 40 | + */ |
| 41 | +interface RoutePattern { |
| 42 | + /** Entity type that the slug-history lookup keys on. */ |
| 43 | + readonly entityType: EntityType; |
| 44 | + /** |
| 45 | + * Regex against `path` (origin-relative; query stripped). Must contain a |
| 46 | + * single capture group for the slug component, except `tag` which captures |
| 47 | + * (namespace, slug). |
| 48 | + */ |
| 49 | + readonly match: RegExp; |
| 50 | + /** Live-entity check — returns the canonical slug if this slug is live, else null. */ |
| 51 | + readonly liveIndex: (state: InMemoryState, slug: string) => boolean; |
| 52 | + /** Rebuild the path with the resolved slug substituted in place of the original. */ |
| 53 | + readonly rebuild: (match: RegExpExecArray, resolvedSlug: string) => string; |
| 54 | +} |
| 55 | + |
| 56 | +const patterns: readonly RoutePattern[] = [ |
| 57 | + // /projects/<slug>/buzz/<buzzSlug>... — both legs are renamable. The deeper |
| 58 | + // match runs first so we attempt to resolve both buzz and project; either |
| 59 | + // can independently redirect. |
| 60 | + // (Currently no slug-history writer for buzz, but the spec includes 'buzz' |
| 61 | + // in SlugHistory.entityType so the plumbing supports it.) |
| 62 | + { |
| 63 | + entityType: 'buzz', |
| 64 | + match: /^\/projects\/([^/]+)\/buzz\/([^/]+)(\/.*)?$/, |
| 65 | + liveIndex: (state, slug) => { |
| 66 | + // Buzz slugs are keyed by `${projectId}:${buzzSlug}` in the live index; |
| 67 | + // since we don't have the projectId at this point cheaply, treat the |
| 68 | + // slug as missing-from-live whenever a slug-history record exists. |
| 69 | + // This is the spec-permitted behavior: if a freed buzz slug was taken |
| 70 | + // by a different project, the slug-history record points away anyway. |
| 71 | + void state; |
| 72 | + void slug; |
| 73 | + return false; |
| 74 | + }, |
| 75 | + rebuild: (m, resolved) => `/projects/${m[1]}/buzz/${resolved}${m[3] ?? ''}`, |
| 76 | + }, |
| 77 | + { |
| 78 | + entityType: 'project', |
| 79 | + match: /^\/projects\/([^/]+)(\/.*)?$/, |
| 80 | + liveIndex: (state, slug) => state.projectIdBySlug.has(slug), |
| 81 | + rebuild: (m, resolved) => `/projects/${resolved}${m[2] ?? ''}`, |
| 82 | + }, |
| 83 | + { |
| 84 | + entityType: 'person', |
| 85 | + match: /^\/members\/([^/]+)(\/.*)?$/, |
| 86 | + liveIndex: (state, slug) => state.personIdBySlug.has(slug), |
| 87 | + rebuild: (m, resolved) => `/members/${resolved}${m[2] ?? ''}`, |
| 88 | + }, |
| 89 | + { |
| 90 | + entityType: 'tag', |
| 91 | + // Capture namespace + slug; namespace stays unchanged in the rebuild. |
| 92 | + match: /^\/tags\/([^/]+)\/([^/]+)(\/.*)?$/, |
| 93 | + liveIndex: (state, slug) => { |
| 94 | + // Tags are uniquely keyed by `(namespace, slug)`; we look up `tag:<slug>` |
| 95 | + // in slug-history regardless of namespace. Live-check checks any |
| 96 | + // namespace match — if the slug is in use by ANY namespace it counts |
| 97 | + // as "live wins". Tags rarely collide across namespaces so this is |
| 98 | + // conservative. |
| 99 | + for (const handle of state.tagIdByHandle.keys()) { |
| 100 | + if (handle.endsWith(`.${slug}`)) return true; |
| 101 | + } |
| 102 | + return false; |
| 103 | + }, |
| 104 | + rebuild: (m, resolved) => `/tags/${m[1]}/${resolved}${m[3] ?? ''}`, |
| 105 | + }, |
| 106 | +]; |
| 107 | + |
| 108 | +/** |
| 109 | + * Follow the slug-history chain in-process up to MAX_HOPS, stopping at the |
| 110 | + * first slug that is live (or absent from slug-history). Returns null when |
| 111 | + * no rewriting is needed (slug already live, or no slug-history entry, or |
| 112 | + * the chain bottoms out at the same slug). |
| 113 | + */ |
| 114 | +function resolveSlug( |
| 115 | + state: InMemoryState, |
| 116 | + pattern: RoutePattern, |
| 117 | + startSlug: string, |
| 118 | +): string | null { |
| 119 | + // Live first — never redirect away from a slug that's currently a real entity. |
| 120 | + if (pattern.liveIndex(state, startSlug)) return null; |
| 121 | + |
| 122 | + let current = startSlug; |
| 123 | + for (let hop = 0; hop < MAX_HOPS; hop++) { |
| 124 | + const entry = state.slugHistory.get(slugHistoryKey(pattern.entityType, current)); |
| 125 | + if (!entry) { |
| 126 | + // No more slug-history to follow. Return null if we never moved. |
| 127 | + return current === startSlug ? null : current; |
| 128 | + } |
| 129 | + if (entry.newSlug === current) { |
| 130 | + // Defensive: pathological self-loop. |
| 131 | + return current === startSlug ? null : current; |
| 132 | + } |
| 133 | + current = entry.newSlug; |
| 134 | + // If the chain has reached a live slug, we're done — return it. |
| 135 | + if (pattern.liveIndex(state, current)) return current; |
| 136 | + } |
| 137 | + // Chain too long — log + bail. The first hop's destination is what we return. |
| 138 | + return current === startSlug ? null : current; |
| 139 | +} |
| 140 | + |
| 141 | +async function slugRedirectPlugin(fastify: FastifyInstance): Promise<void> { |
| 142 | + fastify.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => { |
| 143 | + if (request.method !== 'GET' && request.method !== 'HEAD') return; |
| 144 | + // Strip query before pattern-matching; preserve it for the rebuilt URL. |
| 145 | + const url = request.url; |
| 146 | + if (url.startsWith('/api/')) return; |
| 147 | + const queryIdx = url.indexOf('?'); |
| 148 | + const path = queryIdx === -1 ? url : url.slice(0, queryIdx); |
| 149 | + const query = queryIdx === -1 ? '' : url.slice(queryIdx); |
| 150 | + |
| 151 | + const state = fastify.inMemoryState; |
| 152 | + |
| 153 | + for (const pattern of patterns) { |
| 154 | + const m = pattern.match.exec(path); |
| 155 | + if (!m) continue; |
| 156 | + // For the tag pattern the captured slug is in group 2; everywhere else |
| 157 | + // it's group 1. (Buzz pattern's renamable leg is also group 2.) |
| 158 | + const slugGroup = pattern.entityType === 'tag' || pattern.entityType === 'buzz' ? 2 : 1; |
| 159 | + const slug = m[slugGroup]; |
| 160 | + if (!slug) continue; |
| 161 | + |
| 162 | + const resolved = resolveSlug(state, pattern, slug); |
| 163 | + if (!resolved) continue; |
| 164 | + |
| 165 | + const newPath = pattern.rebuild(m, resolved); |
| 166 | + const target = newPath + query; |
| 167 | + // 5-minute cache: the redirect itself may expire when the 90-day |
| 168 | + // window does; a short cache balances perf with not lying to clients |
| 169 | + // about a permanent-looking redirect. |
| 170 | + await reply |
| 171 | + .code(301) |
| 172 | + .header('Location', target) |
| 173 | + .header('Cache-Control', 'public, max-age=300') |
| 174 | + .send(); |
| 175 | + return; |
| 176 | + } |
| 177 | + }); |
| 178 | +} |
| 179 | + |
| 180 | +export default fp(slugRedirectPlugin, { |
| 181 | + name: 'slug-redirect', |
| 182 | + dependencies: ['services'], |
| 183 | +}); |
0 commit comments