Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

wake-token.ts

68 lines3.9 KB

1import { createHmac, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto'
2import { SubscriptionCipher } from './subscription-crypto.js'
3import type { SubscriptionKeyring } from './subscription-crypto.js'
4​
5export interface WakeTokenIdentity {
6 readonly installationId: string
7 readonly servingEpoch: string
8 readonly tenantId: string
9 readonly subscriptionId: string
10 readonly name: string
11 readonly wakeId: string
12 readonly generation: number
13 readonly kind: 'webhook' | 'pull-wake'
15export interface WakeTokenClaims extends WakeTokenIdentity {
16 readonly v: 2
17 readonly issuedAt: number
18 readonly nonce: string
20const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
21function valid(value: unknown): value is WakeTokenClaims {
22 if (!value || typeof value !== 'object' || Array.isArray(value)) return false
23 const claims = value as Record<string, unknown>
24 return claims.v === 2 && ['installationId', 'servingEpoch', 'subscriptionId', 'wakeId'].every((key) => typeof claims[key] === 'string' && UUID.test(claims[key]))
25 && typeof claims.tenantId === 'string' && !!claims.tenantId && claims.tenantId.isWellFormed() && Buffer.byteLength(claims.tenantId) <= 512
26 && typeof claims.name === 'string' && !!claims.name && claims.name.isWellFormed() && Buffer.byteLength(claims.name) <= 2048
27 && typeof claims.generation === 'number' && Number.isSafeInteger(claims.generation) && claims.generation >= 1
28 && (claims.kind === 'webhook' || claims.kind === 'pull-wake')
29 && typeof claims.issuedAt === 'number' && Number.isSafeInteger(claims.issuedAt) && claims.issuedAt >= 0
30 && typeof claims.nonce === 'string' && /^[A-Za-z0-9_-]{22}$/.test(claims.nonce)
32​
33/** Signed identity survives wake pruning. Database time still fences live leases. */
34export class WakeTokens {
35 private readonly keys = new Map<string, Buffer>()
36 private readonly current: string
37 constructor(ring: SubscriptionKeyring) {
38 new SubscriptionCipher(ring) // Keep key validation identical to encryption.
39 this.current = ring.currentKeyId
40 for (const [id, bytes] of Object.entries(ring.keys)) this.keys.set(id,
41 Buffer.from(hkdfSync('sha256', bytes, Buffer.from('durable-streams-neon'), Buffer.from('wake-token-v2'), 32)))
42 }
43 sign(identity: WakeTokenIdentity): string {
44 const claims: WakeTokenClaims = { v: 2, installationId: identity.installationId, servingEpoch: identity.servingEpoch,
45 tenantId: identity.tenantId, subscriptionId: identity.subscriptionId, name: identity.name, wakeId: identity.wakeId,
46 generation: identity.generation, kind: identity.kind, issuedAt: Date.now(), nonce: randomBytes(16).toString('base64url') }
47 if (!valid(claims)) throw new TypeError('Invalid wake token identity')
48 const message = `dsw.2.${this.current}.${Buffer.from(JSON.stringify(claims)).toString('base64url')}`
49 const token = `${message}.${createHmac('sha256', this.keys.get(this.current)!).update(message).digest('base64url')}`
50 if (token.length > 8192) throw new RangeError('Wake token exceeds the header budget')
51 return token
52 }
53 verify(token: string): WakeTokenClaims | undefined {
54 if (token.length > 8192) return undefined
55 const match = /^dsw\.2\.([A-Za-z0-9_-]{1,128})\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]{43})$/.exec(token)
56 if (!match) return undefined
57 const key = this.keys.get(match[1]!)
58 if (!key) return undefined
59 const signature = Buffer.from(match[3]!, 'base64url')
60 if (signature.toString('base64url') !== match[3]) return undefined
61 const expected = createHmac('sha256', key).update(token.slice(0, token.lastIndexOf('.'))).digest()
62 if (signature.length !== expected.length || !timingSafeEqual(signature, expected)) return undefined
63 const bytes = Buffer.from(match[2]!, 'base64url')
64 if (bytes.toString('base64url') !== match[2]) return undefined
65 try { const claims: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); return valid(claims) ? claims : undefined }
66 catch { return undefined }
67 }