SPB Git

Repository Public

bytes.ts 3.4 KB 76 lines typescript

1// SPV1 byte helpers: encodings and domain-separated context strings (docs/crypto-spec/SPV1.md §1).2export type Bytes = Uint8Array;34const enc = new TextEncoder();5const dec = new TextDecoder("utf-8", { fatal: true });67export const utf8 = (s: string): Bytes => enc.encode(s);8export const fromUtf8 = (b: Bytes): string => dec.decode(b);910export function concat(...parts: Bytes[]): Bytes {11  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));12  let o = 0;13  for (const p of parts) { out.set(p, o); o += p.length; }14  return out;15}1617export function b64u(b: Bytes): string {18  let s = "";19  for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000));20  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");21}2223export function unb64u(s: string): Bytes {24  if (typeof s !== "string" || !/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) throw new Error("invalid base64url");25  const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (s.length % 4)) % 4));26  const out = new Uint8Array(bin.length);27  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);28  return out;29}3031export const hex = (b: Bytes): string => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");32export function unhex(s: string): Bytes {33  if (!/^([0-9a-fA-F]{2})*$/.test(s)) throw new Error("invalid hex");34  const out = new Uint8Array(s.length / 2);35  for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(2 * i, 2 * i + 2), 16);36  return out;37}3839/** ctx(label, f1..fn) = "SPV1" ‖ (u16be len ‖ utf8) for each of label, f1..fn. */40export function ctx(label: string, ...fields: (string | number)[]): Bytes {41  const parts: Bytes[] = [utf8("SPV1")];42  for (const f of [label, ...fields]) {43    const b = utf8(typeof f === "number" ? String(f) : f);44    if (b.length > 0xffff) throw new Error("context field too long");45    parts.push(new Uint8Array([b.length >> 8, b.length & 0xff]), b);46  }47  return concat(...parts);48}4950export function random(n: number): Bytes {51  const b = new Uint8Array(n);52  crypto.getRandomValues(b);53  return b;54}5556/** Constant-time comparison of two byte strings of public length. */57export function ctEqual(a: Bytes, b: Bytes): boolean {58  if (a.length !== b.length) return false;59  let d = 0;60  for (let i = 0; i < a.length; i++) d |= a[i]! ^ b[i]!;61  return d === 0;62}6364export function uuid(): string { return crypto.randomUUID(); }65export const isUuid = (s: unknown): s is string => typeof s === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s);6667/** JSON with object keys sorted recursively: the form hashed by the audit chain (database JSON does not keep key order). */68export function canonicalJson(v: unknown): string {69  if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;70  if (v && typeof v === "object" && !(v instanceof Date)) return `{${Object.keys(v as object).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson((v as any)[k])}`).join(",")}}`;71  return JSON.stringify(v) ?? "null";72}73/** hash_n = SHA-256(canonicalJson([hash_{n-1}, accountId, at, deviceId, actor, kind, detail])), base64url. */74export const auditEntryInput = (prevHash: string, accountId: string, atIso: string, deviceId: string | null, actor: string, kind: string, detail: unknown) =>75  canonicalJson([prevHash, accountId, atIso, deviceId, actor, kind, detail]);76
Files main
Menu

Theme