iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / cloud-clients / src / keys.tsmain at aacbc74

// keys.ts — THE CLOUD'S KEY, AND WHAT DERIVES FROM IT. One P-256 private key (`CLOUD_KEY`, a JWK)
// is the Cloud: it signs what the Cloud sends to a deployment (signed.ts). Two more keys derive
// from it, so the Cloud has one secret of its own and no table of anything:
//
//   the seal key    a token the Cloud hands back, or keeps for its bot, is sealed under it
//   the proof key   says where the Cloud sent a code, and what an operator's link may open
import { base64url, signerOf } from "./signed.ts";

const encoder = new TextEncoder();

export async function keysOf(cloudKey: string) {
  const jwk = JSON.parse(cloudKey) as JsonWebKey;
  const root = await crypto.subtle.importKey(
    "raw",
    Buffer.from(jwk.d!, "base64url"),
    "HKDF",
    false,
    ["deriveKey"],
  );
  const derived = (info: string, algorithm: SubtleCryptoImportKeyAlgorithm, usages: string[]) =>
    crypto.subtle.deriveKey(
      { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: encoder.encode(info) },
      root,
      algorithm,
      false,
      usages,
    );
  return {
    signer: await signerOf(jwk),
    sealKey: await derived("iterate-cloud/seal", { name: "AES-GCM", length: 256 }, [
      "encrypt",
      "decrypt",
    ]),
    proofKey: await derived("iterate-cloud/proof", { name: "HMAC", hash: "SHA-256", length: 256 }, [
      "sign",
      "verify",
    ]),
  };
}

/** A token as it is sealed: the token, and whose it is. A deployment's refresh token names the
 *  deployment, the client and the person at the provider it is for (`by`); the bot's own tokens
 *  name the client alone. `accounts` is what the person agreed the deployment may be connected to
 *  (worker.ts `begin`): each refresh connects those and no other. A token sealed before that
 *  choice existed names none, and stands for every account the person administers. `after` names
 *  the kept answer this token came in (`keptBy`): a refresh that shows the token ends that copy. */
type Held = {
  token: string;
  mind: string;
  client: string;
  by?: string;
  accounts?: string[];
  after?: string;
};

export async function seal<Sealed = Held>(key: CryptoKey, held: Sealed): Promise<string> {
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const sealed = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv },
    key,
    encoder.encode(JSON.stringify(held)),
  );
  return `sealed.${base64url(iv)}.${base64url(sealed)}`;
}

export async function unseal<Sealed = Held>(
  key: CryptoKey,
  sealed: string,
): Promise<Sealed | null> {
  try {
    const [, iv = "", text = ""] = sealed.split(".");
    const opened = await crypto.subtle.decrypt(
      { name: "AES-GCM", iv: Buffer.from(iv, "base64url") },
      key,
      Buffer.from(text, "base64url"),
    );
    return JSON.parse(new TextDecoder().decode(opened)) as Sealed;
  } catch {
    return null;
  }
}

/** A REFRESH'S ANSWER, KEPT FOR A RETRY (worker.ts `token`): the name of its row and the key it is
 *  sealed under both come from the refresh token that was spent for it. The Cloud keeps neither,
 *  so the row opens for a request that shows that token again, and for nothing else. */
export async function keptBy(spent: string, client: string, mind: string) {
  const digest = (what: string) =>
    crypto.subtle.digest(
      "SHA-256",
      encoder.encode(`iterate-cloud/kept-${what}\n${client}\n${mind}\n${spent}`),
    );
  return {
    name: base64url(await digest("name")),
    key: await crypto.subtle.importKey("raw", await digest("key"), "AES-GCM", false, [
      "encrypt",
      "decrypt",
    ]),
  };
}

/** A value only the Cloud can make for one bot's connect until `until`: the link's proof, and the
 *  PKCE verifier of the consent it starts, which then needs no memory. */
export const botProofOf = async (
  key: CryptoKey,
  what: "link" | "verifier",
  name: string,
  until: number,
) =>
  base64url(
    await crypto.subtle.sign("HMAC", key, encoder.encode(`bot-${what}\n${name}\n${until}`)),
  );

/** An operator's link to connect the bot's account of the client `name` (scripts/bot-link.ts):
 *  good for ten minutes, and made by someone who holds the Cloud's key. */
export async function botLinkOf(cloudKey: string, origin: string, name: string): Promise<string> {
  const until = Date.now() + 10 * 60_000;
  const { proofKey } = await keysOf(cloudKey);
  return `${origin}/clients/${name}/bot?until=${until}&proof=${await botProofOf(proofKey, "link", name, until)}`;
}