Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/rooms

Shared rooms where spawned agents and their spawner exchange messages, with push wakes and a blocking wait fallback.

FollowForkOpen app

Files

seal.ts

37 lines · 1.8 KB · TypeScript
import { RoomError } from './errors.ts'

/** Encrypts agent-owned wake secrets at rest. `aad` binds a blob to one member. */
export type Sealer = {
	seal(plain: string, aad: string): Promise<string>
	open(blob: string, aad: string): Promise<string>
}

const toB64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes))
const fromB64 = (text: string) => Uint8Array.from(atob(text), (char) => char.charCodeAt(0))

/** AES-256-GCM sealer over 32 bytes of key material (e.g. an HMAC derived from a Kody secret). */
export async function aesSealer(material: Uint8Array): Promise<Sealer> {
	if (material.length < 32) throw new RoomError('unavailable', 'Wake key encryption material is too short.')
	const key = await crypto.subtle.importKey('raw', material.slice(0, 32), 'AES-GCM', false, ['encrypt', 'decrypt'])
	const encoder = new TextEncoder()
	return {
		async seal(plain, aad) {
			const iv = crypto.getRandomValues(new Uint8Array(12))
			const data = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(aad) }, key, encoder.encode(plain)))
			return `v1.${toB64(iv)}.${toB64(data)}`
		},
		async open(blob, aad) {
			const [version, iv, data] = blob.split('.')
			if (version !== 'v1' || !iv || !data) throw new RoomError('unavailable', 'Sealed wake data is unreadable.')
			const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64(iv), additionalData: encoder.encode(aad) }, key, fromB64(data))
			return new TextDecoder().decode(plain)
		},
	}
}

/** Parse a hex string (an HMAC signature) into bytes. */
export function hexBytes(hex: string) {
	const clean = hex.trim().replace(/^sha256=/, '')
	if (!/^[0-9a-f]{64,}$/i.test(clean)) throw new RoomError('unavailable', 'Wake key encryption material is not hex.')
	return Uint8Array.from(clean.match(/../g)!, (pair) => parseInt(pair, 16))
}