SPB Git

Repository Public

record.ts 7.6 KB 112 lines typescript

1// SPV1 record envelope (§3), attachments (§4) and relay/link sharing (§9).2import { type Bytes, b64u, concat, ctx, fromUtf8, random, unb64u, utf8 } from "./bytes.ts";3import { aeadOpen, aeadSeal, hkdf, hpkeOpen, hpkeSeal, sha256, sign, verify } from "./primitives.ts";4import type { AccountKeys } from "./keys.ts";56export type RecordType = "item" | "vault-meta" | "collection";7export const RECORD_TYPES: readonly RecordType[] = ["item", "vault-meta", "collection"];8export interface Envelope { v: 1; alg: 1; kid: number; salt: string; nonce: string; ct: string }9export interface RecordRef { vaultId: string; recordId: string; type: RecordType; rev: number }1011const PAD = 256;12export const MAX_RECORD_PLAINTEXT = 1024 * 1024;1314export function pad(json: string): Bytes {15  const raw = utf8(json);16  if (raw.length > MAX_RECORD_PLAINTEXT) throw new Error("record too large");17  const out = new Uint8Array(Math.max(PAD, Math.ceil(raw.length / PAD) * PAD)).fill(0x20);18  out.set(raw);19  return out;20}2122const recordAad = (r: RecordRef, kid: number) => ctx("record", r.vaultId, r.recordId, r.type, r.rev, kid);23const recordKey = (vk: Bytes, salt: Bytes) => hkdf(vk, salt, ctx("record-key"));2425export async function sealRecord(vk: Bytes, kid: number, ref: RecordRef, value: unknown, rnd?: { salt: Bytes; nonce: Bytes }): Promise<Envelope> {26  if (!Number.isInteger(ref.rev) || ref.rev < 1) throw new Error("rev must be a positive integer");27  const salt = rnd?.salt ?? random(32), nonce = rnd?.nonce ?? random(12);28  const ct = await aeadSeal(await recordKey(vk, salt), nonce, pad(JSON.stringify(value)), recordAad(ref, kid));29  return { v: 1, alg: 1, kid, salt: b64u(salt), nonce: b64u(nonce), ct: b64u(ct) };30}3132export function checkEnvelope(e: unknown): asserts e is Envelope {33  const x = e as Envelope;34  if (!x || typeof x !== "object" || x.v !== 1 || x.alg !== 1) throw new Error("unsupported envelope version");35  if (!Number.isInteger(x.kid) || x.kid < 1) throw new Error("invalid key id");36  if (unb64u(x.salt).length !== 32 || unb64u(x.nonce).length !== 12) throw new Error("invalid envelope sizes");37  const n = unb64u(x.ct).length;38  if (n < 16 + PAD || (n - 16) % PAD !== 0 || n > MAX_RECORD_PLAINTEXT + 16 + PAD) throw new Error("invalid ciphertext size");39}4041/** `keyFor(kid)` returns the vault key of that epoch. Throws "authentication failed" on any mismatch. */42export async function openRecord<T = unknown>(keyFor: (kid: number) => Bytes | undefined, ref: RecordRef, e: unknown): Promise<T> {43  checkEnvelope(e);44  const vk = keyFor(e.kid);45  if (!vk) throw new Error(`vault key epoch ${e.kid} unavailable`);46  const pt = await aeadOpen(await recordKey(vk, unb64u(e.salt)), unb64u(e.nonce), unb64u(e.ct), recordAad(ref, e.kid));47  return JSON.parse(fromUtf8(pt)) as T;48}4950// ── Attachments ───────────────────────────────────────────────────────────────────────────────────────────────5152export const CHUNK = 1024 * 1024;53export interface AttachmentRef { id: string; key: string; prefix: string; size: number; chunks: number; sha256: string; name: string; mime: string }5455const chunkNonce = (prefix: Bytes, i: number) => concat(prefix, new Uint8Array([i >>> 24, (i >>> 16) & 255, (i >>> 8) & 255, i & 255]));56const chunkAad = (id: string, i: number, total: number) => ctx("chunk", id, i, i === total - 1 ? "1" : "0", total);57export const chunkCount = (size: number) => Math.max(1, Math.ceil(size / CHUNK));5859export async function sealChunk(key: Bytes, prefix: Bytes, id: string, i: number, total: number, data: Bytes): Promise<Bytes> {60  if (prefix.length !== 8) throw new Error("prefix must be 8 bytes");61  if (data.length > CHUNK || (i < total - 1 && data.length !== CHUNK)) throw new Error("invalid chunk size");62  return aeadSeal(key, chunkNonce(prefix, i), data, chunkAad(id, i, total));63}64export const openChunk = (key: Bytes, prefix: Bytes, id: string, i: number, total: number, data: Bytes): Promise<Bytes> =>65  aeadOpen(key, chunkNonce(prefix, i), data, chunkAad(id, i, total));6667export async function newAttachment(id: string, name: string, mime: string, plaintext: Bytes): Promise<{ ref: AttachmentRef; chunks: Bytes[] }> {68  const key = random(32), prefix = random(8), total = chunkCount(plaintext.length), chunks: Bytes[] = [];69  for (let i = 0; i < total; i++) chunks.push(await sealChunk(key, prefix, id, i, total, plaintext.subarray(i * CHUNK, (i + 1) * CHUNK)));70  return { ref: { id, key: b64u(key), prefix: b64u(prefix), size: plaintext.length, chunks: total, sha256: b64u(await sha256(plaintext)), name, mime }, chunks };71}7273export async function openAttachment(ref: AttachmentRef, chunks: Bytes[]): Promise<Bytes> {74  if (chunks.length !== ref.chunks) throw new Error("attachment chunk count mismatch");75  const key = unb64u(ref.key), prefix = unb64u(ref.prefix), parts: Bytes[] = [];76  for (let i = 0; i < chunks.length; i++) parts.push(await openChunk(key, prefix, ref.id, i, ref.chunks, chunks[i]!));77  const pt = concat(...parts);78  if (pt.length !== ref.size || b64u(await sha256(pt)) !== ref.sha256) throw new Error("attachment integrity check failed");79  return pt;80}8182// ── Relay (account to account) ────────────────────────────────────────────────────────────────────────────────8384export interface RelayBox { ct: string; sig: string }8586export async function sealRelay(sender: AccountKeys, shareId: string, senderId: string, recipientId: string, recipientEncPub: Bytes, value: unknown): Promise<RelayBox> {87  const ct = await hpkeSeal(recipientEncPub, ctx("relay", shareId, senderId, recipientId), pad(JSON.stringify(value)));88  return { ct: b64u(ct), sig: b64u(await sign(sender.sig.privateKey, ctx("relay-sig", shareId, b64u(await sha256(ct))))) };89}9091export async function openRelay<T = unknown>(recipient: AccountKeys, shareId: string, senderId: string, recipientId: string, senderSigPub: Bytes, box: RelayBox): Promise<T> {92  const ct = unb64u(box.ct);93  if (!(await verify(senderSigPub, ctx("relay-sig", shareId, b64u(await sha256(ct))), unb64u(box.sig)))) throw new Error("share signature invalid");94  return JSON.parse(fromUtf8(await hpkeOpen(recipient.enc, ctx("relay", shareId, senderId, recipientId), ct))) as T;95}9697// ── Public link (secret in the URL fragment) ──────────────────────────────────────────────────────────────────9899export async function linkKeys(secret: Bytes, shareId: string): Promise<{ key: Bytes; auth: string; authHash: string }> {100  if (secret.length !== 32) throw new Error("link secret must be 32 bytes");101  const auth = await hkdf(secret, new Uint8Array(0), ctx("link-auth", shareId));102  return { key: await hkdf(secret, new Uint8Array(0), ctx("link-key", shareId)), auth: b64u(auth), authHash: b64u(await sha256(auth)) };103}104export async function sealLink(secret: Bytes, shareId: string, value: unknown, nonce: Bytes = random(12)): Promise<string> {105  const { key } = await linkKeys(secret, shareId);106  return b64u(concat(nonce, await aeadSeal(key, nonce, pad(JSON.stringify(value)), ctx("link", shareId))));107}108export async function openLink<T = unknown>(secret: Bytes, shareId: string, box: string): Promise<T> {109  const raw = unb64u(box), { key } = await linkKeys(secret, shareId);110  return JSON.parse(fromUtf8(await aeadOpen(key, raw.slice(0, 12), raw.slice(12), ctx("link", shareId)))) as T;111}112
Files main
Menu

Theme