Cotton code
79 lines · 4.0 KB · TypeScriptRaw
/** * A JOB'S CREDENTIAL (JOBS OUT 1, assets/design/shared/JOBS-OUT.md). A background job beside the account object * reaches it only through the object's own door, the HTTP routes a phone reaches, carrying this and nothing else. * *     j1.<b64url(claim JSON)>.<b64url(HMAC-SHA256(JOB_TOKEN_KEY, "cotton-job-v1\n" + claim JSON))> * * The claim names one account object (`slug`), one kind of job, one thing it works on (a mail account), the * generation of that thing (a new one each time the mailbox is given; gone when it is removed), and an expiry. * Only the account object mints one, when it schedules the job; the job never holds JOB_TOKEN_KEY (src/jobs/run.ts * hands it a narrowed environment), so it cannot make another or widen its own. */export type JobKind = "mail_fetch" | "step:media_drop" | "step:artwork" | "step:book_files" | "step:calendar_sync" | "step:changes" | "step:acts" | "step:prompts" | "step:sweeps" | "step:storage_count" | "step:order_shadow" | "step:send";/** Every kind a credential may name (a step job's kind is `step:<its kind>`, src/jobs/step_job.ts). */export const JOB_KINDS: readonly JobKind[] = ["mail_fetch", "step:media_drop", "step:artwork", "step:book_files", "step:calendar_sync", "step:changes", "step:acts", "step:prompts", "step:sweeps", "step:storage_count", "step:order_shadow", "step:send"];export interface JobClaim {  v: 1;  slug: string;  kind: JobKind;  /** What the job works on: a mail account id, or a step job's kind. */  account: string;  /** The thing's generation: a token for an earlier giving of the mailbox opens nothing. */  gen: string;  /** The scheduled message's own nonce: `begin` uses it up, so one message begins one run at most. */  nonce: string;  /** Expiry, ms since the epoch. */  exp: number;}const LABEL = "cotton-job-v1\n";const enc = new TextEncoder();const b64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const unb64 = (text: string) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));/** Whether a key is usable: at least 32 characters (a 32-byte key in base64url is 43). */export function usableKey(raw: string | undefined): raw is string {  return typeof raw === "string" && raw.length >= 32;}function hmacKey(raw: string): Promise<CryptoKey> {  return crypto.subtle.importKey("raw", enc.encode(raw), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);}export async function mintJobToken(raw: string | undefined, claim: JobClaim): Promise<string> {  if (!usableKey(raw)) throw new Error("no JOB_TOKEN_KEY: no job can be given a credential");  const body = JSON.stringify(claim);  const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(raw), enc.encode(LABEL + body)));  return `j1.${b64(enc.encode(body))}.${b64(sig)}`;}/** The claim a token carries, or null: malformed, badly signed, or past its expiry. */export async function openJobToken(raw: string | undefined, token: string, now: number): Promise<JobClaim | null> {  if (!usableKey(raw)) return null;  const m = /^j1\.([A-Za-z0-9_-]{1,2048})\.([A-Za-z0-9_-]{43})$/.exec(token);  if (!m) return null;  let body: string;  let sig: Uint8Array;  try {    body = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(unb64(m[1]!));    sig = unb64(m[2]!);  } catch {    return null;  }  if (!(await crypto.subtle.verify("HMAC", await hmacKey(raw), sig, enc.encode(LABEL + body)))) return null;  let claim: JobClaim;  try {    claim = JSON.parse(body) as JobClaim;  } catch {    return null;  }  const ok = claim && claim.v === 1 && typeof claim.slug === "string" && JOB_KINDS.includes(claim.kind) && typeof claim.account === "string" && typeof claim.gen === "string" && typeof claim.nonce === "string" && Number.isFinite(claim.exp);  if (!ok || claim.exp <= now) return null;  return claim;}/** The header a job's request carries its credential in. */export const JOB_AUTH = "authorization";export const JOB_SCHEME = "CottonJob ";