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

subscription-crypto.ts

111 lines6.9 KB

1import { createCipheriv, createDecipheriv, createHash, createPrivateKey, generateKeyPairSync, randomBytes, sign } from 'node:crypto'
2import type { JsonWebKey } from 'node:crypto'
3import type { Pool } from 'pg'
4import { validateSchema } from './path.js'
5import { transaction } from './transaction.js'
6import { StorageCompatibilityError } from './errors.js'
7​
8export interface SubscriptionKeyring {
9 readonly currentKeyId: string
10 readonly keys: Readonly<Record<string, Uint8Array>>
12export function parseSubscriptionKeyring(json: string): SubscriptionKeyring {
13 let value: { currentKeyId?: unknown; keys?: unknown }
14 try { value = JSON.parse(json) as typeof value } catch { throw new TypeError('Invalid subscription keyring JSON') }
15 if (!value || typeof value.currentKeyId !== 'string' || !value.keys || typeof value.keys !== 'object' || Array.isArray(value.keys)) throw new TypeError('Invalid subscription keyring')
16 const keys: Record<string, Buffer> = Object.create(null) as Record<string, Buffer>
17 for (const [id, encoded] of Object.entries(value.keys)) {
18 if (typeof encoded !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(encoded)) throw new TypeError('Keyring keys must be canonical base64-encoded 32-byte values')
19 const bytes = Buffer.from(encoded, 'base64')
20 if (bytes.toString('base64') !== encoded) throw new TypeError('Noncanonical base64 keyring value')
21 keys[id] = bytes
22 }
23 const ring = { currentKeyId: value.currentKeyId, keys }
24 new SubscriptionCipher(ring)
25 return ring
27export class SubscriptionCipher {
28 private readonly keys = new Map<string, Buffer>()
29 private readonly current: string
30 constructor(ring: SubscriptionKeyring) {
31 if (!/^[A-Za-z0-9_-]{1,128}$/.test(ring.currentKeyId)) throw new TypeError('Invalid wrapping key ID')
32 for (const [id, bytes] of Object.entries(ring.keys)) {
33 if (!/^[A-Za-z0-9_-]{1,128}$/.test(id) || bytes.byteLength !== 32) throw new TypeError('Subscription wrapping keys must have 32 bytes')
34 this.keys.set(id, Buffer.from(bytes))
35 }
36 if (!this.keys.has(ring.currentKeyId)) throw new TypeError('Current subscription wrapping key is absent')
37 this.current = ring.currentKeyId
38 }
39 encrypt(bytes: Uint8Array, aad: string): Buffer {
40 const id = Buffer.from(this.current)
41 const iv = randomBytes(12)
42 const cipher = createCipheriv('aes-256-gcm', this.keys.get(this.current)!, iv)
43 cipher.setAAD(Buffer.from(aad))
44 const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()])
45 return Buffer.concat([Buffer.from('NDSE1'), Buffer.from([id.length]), id, iv, cipher.getAuthTag(), encrypted])
46 }
47 decrypt(envelope: Buffer, aad: string): Buffer {
48 const n = envelope[5] ?? 0
49 if (envelope.length < 34 + n || !envelope.subarray(0, 5).equals(Buffer.from('NDSE1')) || !n) throw new StorageCompatibilityError('Invalid encrypted subscription envelope')
50 const key = this.keys.get(envelope.toString('utf8', 6, 6 + n))
51 if (!key) throw new StorageCompatibilityError('Subscription wrapping key is unavailable; restore the configured keyring')
52 const decipher = createDecipheriv('aes-256-gcm', key, envelope.subarray(6 + n, 18 + n))
53 decipher.setAAD(Buffer.from(aad))
54 decipher.setAuthTag(envelope.subarray(18 + n, 34 + n))
55 return Buffer.concat([decipher.update(envelope.subarray(34 + n)), decipher.final()])
56 }
58export interface InitializeSubscriptionsOptions {
59 readonly schema?: string
60 readonly keyring: SubscriptionKeyring
61 /** Retain old public keys. This explicitly rotates the active signing key. */
62 readonly rotateSigningKey?: boolean
64export async function initializeSubscriptions(pool: Pool, options: InitializeSubscriptionsOptions): Promise<{ kid: string }> {
65 const schema = validateSchema(options.schema ?? 'durable_streams')
66 const cipher = new SubscriptionCipher(options.keyring)
67 return transaction(pool, {}, async (client) => {
68 await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`durable-streams:signing:${schema}`])
69 const installation = await client.query<{ id: string }>(`SELECT id FROM ${schema}.installation`)
70 if (installation.rows.length !== 1) throw new StorageCompatibilityError('Missing installation identity')
71 const existing = await client.query<{ kid: string }>(`SELECT kid FROM ${schema}.webhook_signing_keys WHERE active`)
72 if (existing.rows[0] && !options.rotateSigningKey) return existing.rows[0]
73 const pair = generateKeyPairSync('ed25519')
74 const publicJwk = pair.publicKey.export({ format: 'jwk' })
75 const kid = `ds_${createHash('sha256').update(JSON.stringify({ crv: publicJwk.crv, kty: publicJwk.kty, x: publicJwk.x })).digest('base64url')}`
76 const der = pair.privateKey.export({ format: 'der', type: 'pkcs8' })
77 const encrypted = cipher.encrypt(der, `${installation.rows[0]!.id}:signing:${kid}`)
78 der.fill(0)
79 await client.query(`UPDATE ${schema}.webhook_signing_keys SET active = false WHERE active`)
80 await client.query(`INSERT INTO ${schema}.webhook_signing_keys (kid, public_jwk, private_key, active) VALUES ($1, $2, $3, true)`,
81 [kid, { ...publicJwk, kid, alg: 'EdDSA', use: 'sig' }, encrypted])
82 return { kid }
83 })
85export class SubscriptionSigner {
86 private readonly schema: string
87 private readonly cipher: SubscriptionCipher
88 constructor(private readonly pool: Pool, schema: string, ring: SubscriptionKeyring) { this.schema = validateSchema(schema); this.cipher = new SubscriptionCipher(ring) }
89 async active(): Promise<string> {
90 const key = await this.pool.query<{ kid: string }>(`SELECT kid FROM ${this.schema}.webhook_signing_keys WHERE active`)
91 if (!key.rows[0]) throw new StorageCompatibilityError('Run initializeSubscriptions before enabling webhook subscriptions')
92 return key.rows[0].kid
93 }
94 async jwks(): Promise<{ keys: readonly JsonWebKey[] }> {
95 const result = await this.pool.query<{ public_jwk: JsonWebKey }>(`SELECT public_jwk FROM ${this.schema}.webhook_signing_keys ORDER BY created_at, kid`)
96 if (!result.rows.length) throw new StorageCompatibilityError('Run initializeSubscriptions before serving JWKS')
97 return { keys: result.rows.map((row) => row.public_jwk) }
98 }
99 async signature(body: Buffer): Promise<string> {
100 const result = await this.pool.query<{ kid: string; private_key: Buffer; installation_id: string }>(`SELECT k.kid, k.private_key, i.id AS installation_id
101 FROM ${this.schema}.webhook_signing_keys k CROSS JOIN ${this.schema}.installation i WHERE k.active`)
102 const row = result.rows[0]
103 if (!row) throw new StorageCompatibilityError('No active webhook signing key')
104 const der = this.cipher.decrypt(row.private_key, `${row.installation_id}:signing:${row.kid}`)
105 const key = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' })
106 der.fill(0)
107 const timestamp = String(Math.floor(Date.now() / 1000))
108 const signature = sign(null, Buffer.concat([Buffer.from(`${timestamp}.`), body]), key).toString('base64url')
109 return `t=${timestamp},kid=${row.kid},ed25519=${signature}`
110 }