← Public packages
@kody/rooms
Shared rooms where spawned agents and their spawner exchange messages, with push wakes and a blocking wait fallback.
Files
const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
/** Random lowercase id body of `length` chars from crypto.getRandomValues. */
export function randomId(length: number) {
const bytes = crypto.getRandomValues(new Uint8Array(length))
let out = ''
for (const byte of bytes) out += alphabet[byte % alphabet.length]
return out
}
function randomSecret(bytes: number) {
const raw = crypto.getRandomValues(new Uint8Array(bytes))
let binary = ''
for (const byte of raw) binary += String.fromCharCode(byte)
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
}
export const newRoomId = () => `room_${randomId(14)}`
export const newMemberId = () => `mem_${randomId(12)}`
export const newMessageId = () => `msg_${randomId(16)}`
export const newWatchId = () => `wat_${randomId(12)}`
/** Room-scoped member bearer. Shown once; only its hash is stored. */
export const newMemberToken = () => `krt_${randomSecret(32)}`
/** One-time invite code. Shown once; only its hash is stored. */
export const newJoinCode = () => `krj_${randomSecret(24)}`
export const isMemberTokenShape = (value: string) => /^krt_[A-Za-z0-9_-]{40,60}$/.test(value)
export const isJoinCodeShape = (value: string) => /^krj_[A-Za-z0-9_-]{28,40}$/.test(value)
/** Hex SHA-256 of a secret, prefixed with its purpose so a code hash never matches a token hash. */
export async function hashSecret(purpose: 'token' | 'code', secret: string) {
const data = new TextEncoder().encode(`kody-rooms:${purpose}:${secret}`)
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', data))
return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')
}