Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

crypto.ts

83 lines · 3.7 KB · TypeScript
/**
 * Web Push message encryption (RFC 8291, aes128gcm content coding from
 * RFC 8188) with WebCrypto only. Runs in the Kody package runtime.
 *
 * Inputs are the browser's subscription keys (`p256dh`, `auth`), which are
 * public per-device values, not secrets. A fresh ECDH key pair and salt are
 * made for every message.
 */

const enc = new TextEncoder()

/** Bytes backed by a plain ArrayBuffer, which WebCrypto's types require. */
export type Bytes = Uint8Array<ArrayBuffer>

export function b64urlDecode(text: string): Bytes {
	const pad = text.length % 4 === 0 ? '' : '='.repeat(4 - (text.length % 4))
	const bin = atob(text.replace(/-/g, '+').replace(/_/g, '/') + pad)
	const out = new Uint8Array(bin.length)
	for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
	return out
}

export function b64urlEncode(bytes: Bytes): string {
	let bin = ''
	for (const b of bytes) bin += String.fromCharCode(b)
	return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

export function concat(...parts: Bytes[]): Bytes {
	const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
	let at = 0
	for (const p of parts) {
		out.set(p, at)
		at += p.length
	}
	return out
}

export async function hkdf(salt: Bytes, ikm: Bytes, info: Bytes, length: number): Promise<Bytes> {
	const key = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits'])
	const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, length * 8)
	return new Uint8Array(bits)
}

/** Largest plaintext that fits one 4096-byte record (4096 - 16 tag - 1 delimiter - header overhead margin). */
export const MAX_PLAINTEXT_BYTES = 3800

export type PushKeys = { p256dh: string; auth: string }

/**
 * Encrypt `plaintext` for one subscription. Returns the full request body
 * (header + one record) for `Content-Encoding: aes128gcm`.
 */
export async function encryptPushPayload(keys: PushKeys, input: Uint8Array, opts: { salt?: Bytes; serverKeys?: CryptoKeyPair } = {}): Promise<Bytes> {
	const plaintext: Bytes = new Uint8Array(input)
	if (plaintext.length > MAX_PLAINTEXT_BYTES) throw new Error(`push payload too large (${plaintext.length} bytes)`)
	const uaPublic = b64urlDecode(keys.p256dh)
	const authSecret = b64urlDecode(keys.auth)
	if (uaPublic.length !== 65 || uaPublic[0] !== 4) throw new Error('bad p256dh key')
	if (authSecret.length !== 16) throw new Error('bad auth secret')

	const server = opts.serverKeys ?? ((await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'])) as CryptoKeyPair)
	const asPublic = new Uint8Array(await crypto.subtle.exportKey('raw', server.publicKey))
	const uaKey = await crypto.subtle.importKey('raw', uaPublic, { name: 'ECDH', namedCurve: 'P-256' }, false, [])
	const ecdhSecret = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: uaKey }, server.privateKey, 256))

	const keyInfo = concat(enc.encode('WebPush: info\0'), uaPublic, asPublic)
	const ikm = await hkdf(authSecret, ecdhSecret, keyInfo, 32)
	const salt = opts.salt ?? crypto.getRandomValues(new Uint8Array(16))
	const cek = await hkdf(salt, ikm, enc.encode('Content-Encoding: aes128gcm\0'), 16)
	const nonce = await hkdf(salt, ikm, enc.encode('Content-Encoding: nonce\0'), 12)

	const padded = concat(plaintext, new Uint8Array([2]))
	const aesKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt'])
	const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, aesKey, padded))

	const header = new Uint8Array(16 + 4 + 1 + asPublic.length)
	header.set(salt, 0)
	new DataView(header.buffer).setUint32(16, 4096)
	header[20] = asPublic.length
	header.set(asPublic, 21)
	return concat(header, cipher)
}