Open History to see the last commit
1import { createHash } from 'node:crypto'
2import { StreamError } from './errors.js'
3
4export interface SubscriptionConfig {
5 readonly type: 'webhook' | 'pull-wake'
6 readonly pattern: string | null
7 readonly streams: readonly string[]
8 readonly webhook: { readonly url: string } | null
9 readonly wake_stream: string | null
10 readonly lease_ttl_ms: number
11 readonly description: string | null
12}
13export function relativeStreamPath(input: unknown): string {
14 if (typeof input !== 'string' || !input.isWellFormed() || Buffer.byteLength(input) > 2048 || input.split('/').some((part) => !part || part === '.' || part === '..' || /[\\\u0000-\u001f\u007f]/.test(part) || /%[a-f0-9]{2}/i.test(part)) || input.split('/')[0] === '__ds') throw new StreamError(400, 'INVALID_STREAM_PATH', 'Expected a canonical stream-root-relative application path')
15 return input
16}
17export function globExpression(pattern: string): string {
18 if (!pattern || !pattern.isWellFormed() || Buffer.byteLength(pattern) > 2048 || /[\\\u0000-\u001f\u007f]/.test(pattern)) throw new StreamError(400, 'INVALID_PATTERN', 'Invalid stream pattern')
19 const segments = pattern.split('/')
20 if (segments.some((part) => !part || part === '.' || part === '..' || (part.includes('**') && part !== '**'))) throw new StreamError(400, 'INVALID_PATTERN', 'Invalid stream pattern segments')
21 const parts = segments.filter((part, i) => part !== '**' || segments[i - 1] !== '**')
22 let expression = '^'
23 for (let i = 0; i < parts.length; i++) {
24 const part = parts[i]!
25 if (part === '**') expression += i === 0 ? (parts.length === 1 ? '.*' : '(?:[^/]+/)*') : i === parts.length - 1 ? '(?:/[^/]+)*' : '(?:/[^/]+)*/'
26 else {
27 if (i && parts[i - 1] !== '**') expression += '/'
28 expression += part.split('*').map((literal) => literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')
29 }
30 }
31 return `${expression}$`
32}
33
34/** Bounded dynamic programming avoids JavaScript regex backtracking on
35 * caller-provided wildcard patterns. PostgreSQL uses the equivalent ARE. */
36export function globMatches(pattern: string, path: string): boolean {
37 const patterns = pattern.split('/'), paths = path.split('/')
38 let previous = new Uint8Array(paths.length + 1)
39 previous[0] = 1
40 const segment = (pattern: string, value: string) => {
41 let p = 0, v = 0, star = -1, checkpoint = 0
42 while (v < value.length) {
43 if (p < pattern.length && pattern[p] !== '*' && pattern[p] === value[v]) { p++; v++ }
44 else if (pattern[p] === '*') { star = p++; checkpoint = v }
45 else if (star >= 0) { p = star + 1; v = ++checkpoint }
46 else return false
47 }
48 while (pattern[p] === '*') p++
49 return p === pattern.length
50 }
51 for (const part of patterns) {
52 const current = new Uint8Array(paths.length + 1)
53 if (part === '**') {
54 current[0] = previous[0]!
55 for (let i = 1; i <= paths.length; i++) current[i] = previous[i]! || current[i - 1]!
56 } else for (let i = 1; i <= paths.length; i++) if (previous[i - 1] && segment(part, paths[i - 1]!)) current[i] = 1
57 previous = current
58 }
59 return previous[paths.length] === 1
60}
61export function normalizeSubscription(input: unknown): { config: SubscriptionConfig; hash: string; regex: string | null } {
62 const invalid = () => new StreamError(400, 'INVALID_SUBSCRIPTION', 'Invalid subscription configuration')
63 if (!input || typeof input !== 'object' || Array.isArray(input)) throw invalid()
64 const raw = input as Record<string, unknown>
65 if (!['webhook', 'pull-wake'].includes(String(raw.type))) throw invalid()
66 const pattern = raw.pattern === undefined ? null : typeof raw.pattern === 'string' ? raw.pattern : (() => { throw invalid() })()
67 const regex = pattern === null ? null : globExpression(pattern)
68 if (raw.streams !== undefined && !Array.isArray(raw.streams)) throw invalid()
69 const streams = [...new Set((raw.streams as unknown[] | undefined ?? []).map(relativeStreamPath))].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))
70 if (pattern === null && !streams.length) throw invalid()
71 const ttl = raw.lease_ttl_ms ?? 30_000
72 if (typeof ttl !== 'number' || !Number.isSafeInteger(ttl) || ttl < 1000 || ttl > 600_000) throw invalid()
73 if (raw.description !== undefined && (typeof raw.description !== 'string' || !raw.description.isWellFormed() || Buffer.byteLength(raw.description) > 4096 || raw.description.includes('\0'))) throw invalid()
74 let webhook: { url: string } | null = null
75 let wakeStream: string | null = null
76 if (raw.type === 'webhook') {
77 if (!raw.webhook || typeof raw.webhook !== 'object' || typeof (raw.webhook as Record<string, unknown>).url !== 'string') throw invalid()
78 let url: URL
79 try { url = new URL((raw.webhook as { url: string }).url) } catch { throw new StreamError(400, 'WEBHOOK_URL_REJECTED', 'Invalid webhook URL') }
80 webhook = { url: url.href }
81 if (raw.wake_stream !== undefined && raw.wake_stream !== null) throw invalid()
82 } else {
83 wakeStream = relativeStreamPath(raw.wake_stream)
84 if (raw.webhook !== undefined && raw.webhook !== null) throw invalid()
85 if (streams.includes(wakeStream) || (pattern && globMatches(pattern, wakeStream))) throw new StreamError(400, 'SELF_WAKE', 'A pull-wake stream cannot subscribe to its own wake channel')
86 }
87 const config: SubscriptionConfig = { type: raw.type as SubscriptionConfig['type'], pattern, streams, webhook, wake_stream: wakeStream, lease_ttl_ms: ttl, description: raw.description as string | undefined ?? null }
88 return { config, regex, hash: createHash('sha256').update(JSON.stringify(config)).digest('hex') }
89}
90export interface ControlRoute { readonly name?: string; readonly action: 'jwks' | 'subscription' | 'streams' | 'member' | 'claim' | 'ack' | 'release' | 'callback' | 'unknown'; readonly member?: string; readonly path: string }
91export function subscriptionRoute(url: URL, basePath: string): ControlRoute | null {
92 const root = `${basePath}/__ds`
93 if (url.pathname !== root && !url.pathname.startsWith(`${root}/`)) return null
94 const parts = url.pathname.slice(root.length + 1).split('/')
95 const unknown: ControlRoute = { action: 'unknown', path: '__ds' }
96 if (parts.length === 1 && parts[0] === 'jwks.json') return { action: 'jwks', path: '__ds/jwks.json' }
97 if (parts[0] !== 'subscriptions' || !parts[1]) return unknown
98 let name: string
99 try { name = decodeURIComponent(parts[1]) } catch { throw new StreamError(400, 'INVALID_SUBSCRIPTION_ID', 'Invalid subscription identifier') }
100 if (!name || Buffer.byteLength(name) > 512 || /[/\\\u0000-\u001f\u007f]/.test(name)) throw new StreamError(400, 'INVALID_SUBSCRIPTION_ID', 'Invalid subscription identifier')
101 const path = `__ds/subscriptions/${name}`
102 if (parts.length === 2) return { name, action: 'subscription', path }
103 if (parts[2] === 'streams' && parts.length > 3) {
104 let member: string
105 try { member = relativeStreamPath(decodeURIComponent(parts.slice(3).join('/'))) } catch { throw new StreamError(400, 'INVALID_STREAM_PATH', 'Invalid explicit stream path') }
106 return { name, action: 'member', member, path: `${path}/streams/${member}` }
107 }
108 if (parts.length === 3 && ['streams', 'claim', 'ack', 'release', 'callback'].includes(parts[2]!)) return { name, action: parts[2] as ControlRoute['action'], path: `${path}/${parts[2]}` }
109 return unknown
110}