@muhkoo/connect 0.10.11-alpha.0 → 0.10.13-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2867,7 +2867,7 @@ async function signMessage(message, privateKey) {
2867
2867
  * pre-hash fed into the OPRF, so even if the OPRF key ever leaked, guesses still
2868
2868
  * pay the scrypt cost.
2869
2869
  */
2870
- const TE$1 = new TextEncoder();
2870
+ const TE$2 = new TextEncoder();
2871
2871
  // Interactive-login scrypt params (~100ms on a laptop). N must be a power of 2.
2872
2872
  const SCRYPT = { N: 1 << 15, r: 8, p: 1, dkLen: 32 };
2873
2873
  /** 32 random bytes - the master seed for a brand-new identity. */
@@ -2876,17 +2876,17 @@ function randomSeed() {
2876
2876
  }
2877
2877
  /** Memory-hard pre-hash of the password - the OPRF input. Salted by username. */
2878
2878
  function passwordPreHash(username, password) {
2879
- return scrypt(TE$1.encode(password), TE$1.encode("muhkoo-vault-v1:" + username.toLowerCase()), SCRYPT);
2879
+ return scrypt(TE$2.encode(password), TE$2.encode("muhkoo-vault-v1:" + username.toLowerCase()), SCRYPT);
2880
2880
  }
2881
2881
  /** HKDF the 64-byte OPRF output into a non-extractable AES-256-GCM wrap key. */
2882
2882
  async function wrapKeyFromOprf(oprfOutput) {
2883
2883
  const prk = await crypto.subtle.importKey("raw", oprfOutput, { name: "HKDF" }, false, ["deriveKey"]);
2884
- return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: TE$1.encode("muhkoo-vault-wrap") }, prk, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
2884
+ return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: TE$2.encode("muhkoo-vault-wrap") }, prk, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
2885
2885
  }
2886
2886
  /** HKDF arbitrary 32-byte key material (e.g. a passkey PRF output) into an AES-GCM wrap key. */
2887
2887
  async function wrapKeyFromBytes(keyMaterial, info) {
2888
2888
  const prk = await crypto.subtle.importKey("raw", keyMaterial, { name: "HKDF" }, false, ["deriveKey"]);
2889
- return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: TE$1.encode(info) }, prk, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
2889
+ return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(), info: TE$2.encode(info) }, prk, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
2890
2890
  }
2891
2891
  async function wrapSeed(seed, key) {
2892
2892
  const iv = crypto.getRandomValues(new Uint8Array(12));
@@ -2930,9 +2930,32 @@ function fromBase64(b64) {
2930
2930
  * seed) while moving credential entry onto the Muhkoo origin. The envelope is
2931
2931
  * versioned so a future per-app-key handoff (v2) can swap in without a protocol
2932
2932
  * change.
2933
+ *
2934
+ * ## v2 — device pairing (TV / no-redirect handoff)
2935
+ *
2936
+ * v1's K_t rides in the redirect URL *fragment*, which works only because the
2937
+ * receiving app is a browser page that can read `location.hash`. A TV app has
2938
+ * no redirect to receive: it polls. So v2 keeps the *entire* v1 shape — the
2939
+ * server relays a sealed envelope it cannot read — and replaces only the key
2940
+ * agreement:
2941
+ *
2942
+ * - the TV generates an ephemeral P-256 ECDH keypair in memory and publishes
2943
+ * the public half ({@link generateDevicePairingKeypair});
2944
+ * - the hosted page (the component that already holds the unlocked seed and
2945
+ * already owns sealing) seals *to that public key* with a fresh ephemeral
2946
+ * keypair of its own ({@link sealSeedToDevice}) — ECDH → HKDF-SHA256 →
2947
+ * AES-256-GCM;
2948
+ * - the TV recovers the seed with its private key
2949
+ * ({@link unsealSeedFromDevice}).
2950
+ *
2951
+ * The server stores and relays the v2 envelope byte-for-byte, exactly as it
2952
+ * does for v1, and can read neither. The one thing ECDH cannot supply is proof
2953
+ * that the public key the hosted page sealed to is *the TV's* rather than an
2954
+ * attacker's — that is what {@link pairingVerificationCode} is for, and it is
2955
+ * the only MITM defence in the flow (see the entropy note on that function).
2933
2956
  */
2934
- const TE = new TextEncoder();
2935
- const TD = new TextDecoder();
2957
+ const TE$1 = new TextEncoder();
2958
+ const TD$1 = new TextDecoder();
2936
2959
  /** Seal the master seed under a fresh one-time key for the redirect handoff. */
2937
2960
  async function sealSeed(seed) {
2938
2961
  const ktRaw = crypto.getRandomValues(new Uint8Array(32));
@@ -2941,13 +2964,13 @@ async function sealSeed(seed) {
2941
2964
  const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, seed));
2942
2965
  const envelope = { v: 1, iv: toBase64(iv), ct: toBase64(ct) };
2943
2966
  return {
2944
- sealedKeys: toBase64(TE.encode(JSON.stringify(envelope))),
2967
+ sealedKeys: toBase64(TE$1.encode(JSON.stringify(envelope))),
2945
2968
  fragmentKey: base64UrlEncode(ktRaw),
2946
2969
  };
2947
2970
  }
2948
2971
  /** Recover the master seed from the sealed envelope + the fragment key. */
2949
2972
  async function unsealSeed(sealedKeys, fragmentKey) {
2950
- const envelope = JSON.parse(TD.decode(fromBase64(sealedKeys)));
2973
+ const envelope = JSON.parse(TD$1.decode(fromBase64(sealedKeys)));
2951
2974
  if (envelope.v !== 1)
2952
2975
  throw new Error(`Unsupported handoff envelope version ${envelope.v}`);
2953
2976
  const ktRaw = base64UrlDecode(fragmentKey);
@@ -2955,10 +2978,240 @@ async function unsealSeed(sealedKeys, fragmentKey) {
2955
2978
  const seed = await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64(envelope.iv) }, key, fromBase64(envelope.ct));
2956
2979
  return new Uint8Array(seed);
2957
2980
  }
2981
+ // ---- v2: ECDH device pairing ----------------------------------------------
2982
+ //
2983
+ // Deliberately a SEPARATE unseal entry point rather than one `unsealSeed` that
2984
+ // dispatches on `envelope.v`. The two versions do not just differ in envelope
2985
+ // shape — their *second argument* is a different kind of thing entirely (v1: a
2986
+ // base64url string plucked out of a URL fragment; v2: a non-extractable
2987
+ // `CryptoKey`). Overloading one function on a `string | CryptoKey` union would
2988
+ // buy nothing at the call sites (each caller statically knows which flow it is
2989
+ // in) while adding a narrowing branch to the v1 path, which is live in
2990
+ // production hosted auth. Each function still validates `v` and rejects the
2991
+ // other version's envelope, so a mis-routed envelope fails loudly rather than
2992
+ // being interpreted under the wrong scheme.
2993
+ /** P-256 curve parameters for the pairing ECDH. */
2994
+ const PAIRING_CURVE = { name: "ECDH", namedCurve: "P-256" };
2995
+ /**
2996
+ * HKDF `info` for the v2 seal. Versioned and domain-separated: v1 derives no
2997
+ * key at all (K_t is raw random), so no v1 key can ever collide with this, and
2998
+ * a future v3 must pick a new label rather than reuse this one.
2999
+ */
3000
+ const HKDF_INFO_V2 = "muhkoo/hosted-handoff/v2/device-seal";
3001
+ /** Domain separator for {@link pairingVerificationCode} — distinct from the seal KDF. */
3002
+ const PAIRING_CODE_DOMAIN = "muhkoo/hosted-handoff/v2/pairing-code";
3003
+ /**
3004
+ * Alphabet for the pairing verification code: 30 symbols, every confusable pair
3005
+ * removed in BOTH directions — no `0`/`O`, no `1`/`I`/`L`, and no `U` (which is
3006
+ * read as `V` on the low-resolution, far-viewed type a TV renders). Because the
3007
+ * user compares this string across two screens by eye, unambiguity beats the
3008
+ * convenience of a power-of-two alphabet; the derivation below rejection-samples
3009
+ * to avoid the modulo bias that costs us.
3010
+ */
3011
+ const PAIRING_CODE_ALPHABET = "ABCDEFGHJKMNPQRSTVWXYZ23456789";
3012
+ /** Length of the pairing verification code, in characters. 30^8 ≈ 39.3 bits. */
3013
+ const PAIRING_CODE_LENGTH = 8;
3014
+ /**
3015
+ * PBKDF2 iterations for the verification code. This is NOT protecting a
3016
+ * password — it is a deliberate work factor on an attacker precomputing codes.
3017
+ * See {@link pairingVerificationCode}.
3018
+ */
3019
+ const PAIRING_CODE_ITERATIONS = 200_000;
3020
+ /**
3021
+ * (Device side) Generate the ephemeral P-256 ECDH keypair for one pairing
3022
+ * attempt. Call this once per attempt and throw it away when the attempt ends —
3023
+ * reusing a keypair across attempts would let an old, observed ciphertext be
3024
+ * decrypted by whoever later obtains the key.
3025
+ */
3026
+ async function generateDevicePairingKeypair() {
3027
+ const pair = (await crypto.subtle.generateKey(PAIRING_CURVE, false, ["deriveBits"]));
3028
+ const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
3029
+ return { publicKeyB64: toBase64(raw), privateKey: pair.privateKey };
3030
+ }
3031
+ /**
3032
+ * (Hosted-page side) Seal the master seed *to a device's* pairing public key.
3033
+ *
3034
+ * A fresh ephemeral keypair is generated per call and its public half is
3035
+ * carried in the envelope (`epk`), so sealing the same seed to the same device
3036
+ * twice yields unrelated ciphertext — and the sealer retains nothing that could
3037
+ * later reopen the envelope.
3038
+ *
3039
+ * Returns the v2 `sealedKeys` string, which slots into exactly the same server
3040
+ * field as v1: relayed verbatim, never read.
3041
+ */
3042
+ async function sealSeedToDevice(seed, devicePublicKeyB64) {
3043
+ const devicePubRaw = decodePairingPublicKey(devicePublicKeyB64);
3044
+ const devicePub = await importPairingPublicKey(devicePubRaw);
3045
+ const ephemeral = (await crypto.subtle.generateKey(PAIRING_CURVE, false, ["deriveBits"]));
3046
+ const epkRaw = new Uint8Array(await crypto.subtle.exportKey("raw", ephemeral.publicKey));
3047
+ const key = await deriveDeviceSealKey(ephemeral.privateKey, devicePub, epkRaw, devicePubRaw, ["encrypt"]);
3048
+ const iv = crypto.getRandomValues(new Uint8Array(12));
3049
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, seed));
3050
+ const envelope = { v: 2, epk: toBase64(epkRaw), iv: toBase64(iv), ct: toBase64(ct) };
3051
+ return toBase64(TE$1.encode(JSON.stringify(envelope)));
3052
+ }
3053
+ /**
3054
+ * (Device side) Recover the master seed from a v2 envelope using the ephemeral
3055
+ * private key from {@link generateDevicePairingKeypair}.
3056
+ *
3057
+ * Throws on any tamper: a substituted `epk` yields a different shared secret
3058
+ * (or fails point validation outright), and any edit to `iv`/`ct` fails the
3059
+ * AES-GCM tag. There is no path that returns partially-authenticated bytes.
3060
+ *
3061
+ * `devicePublicKeyB64` is the caller's OWN public half (from
3062
+ * {@link generateDevicePairingKeypair}). It is required, not optional, because
3063
+ * it is mixed into the KDF — see {@link deriveDeviceSealKey} for why binding the
3064
+ * recipient matters. A device always holds both halves, so this costs nothing.
3065
+ */
3066
+ async function unsealSeedFromDevice(sealedKeys, privateKey, devicePublicKeyB64) {
3067
+ const envelope = JSON.parse(TD$1.decode(fromBase64Loose(sealedKeys)));
3068
+ if (envelope.v !== 2)
3069
+ throw new Error(`Unsupported device-handoff envelope version ${envelope.v}`);
3070
+ const devicePubRaw = decodePairingPublicKey(devicePublicKeyB64);
3071
+ const epkRaw = decodePairingPublicKey(envelope.epk);
3072
+ const epk = await importPairingPublicKey(epkRaw);
3073
+ const key = await deriveDeviceSealKey(privateKey, epk, epkRaw, devicePubRaw, ["decrypt"]);
3074
+ const seed = await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64Loose(envelope.iv) }, key, fromBase64Loose(envelope.ct));
3075
+ return new Uint8Array(seed);
3076
+ }
3077
+ /**
3078
+ * Short code derived deterministically from the device's pairing public key,
3079
+ * displayed on BOTH the TV and the approving browser so the human can confirm
3080
+ * they match before approving.
3081
+ *
3082
+ * ## What this is worth (be honest about it)
3083
+ *
3084
+ * ~39.3 bits (30^8), rendered in an unambiguous 30-symbol alphabet and grouped
3085
+ * as `XXXX-XXXX` for comparison. Alongside the recipient-key binding in
3086
+ * {@link deriveDeviceSealKey}, this is what stops a substituted device key: the
3087
+ * KDF rejects a *negated* key, and this code is what a human uses to reject a
3088
+ * wholly *attacker-generated* one, which the crypto cannot detect on its own —
3089
+ * ECDH proves nothing about WHOSE public key it is.
3090
+ *
3091
+ * Two attacks, and what each actually costs:
3092
+ *
3093
+ * 1. **Online grind.** Generate keypairs until one's code equals the honest
3094
+ * TV's. ~2^39 trials. Naively that reads as "keygen + hash", but a real
3095
+ * attacker never generates keys: walking `P_{i+1} = P_i + G` while tracking
3096
+ * `d_i = d_0 + i` makes each trial one point-add plus one derivation. With
3097
+ * a plain hash that is well under a core-day — which is why this uses
3098
+ * PBKDF2-SHA256 at {@link PAIRING_CODE_ITERATIONS} iterations instead. The
3099
+ * work factor applies per trial, pushing the same grind to the order of
3100
+ * 10^5 core-days. The target is also only learned when pairing starts, so
3101
+ * the grind is online against the pairing TTL (keep it minutes).
3102
+ * 2. **Precomputed table.** The reason this is not a plain hash. A table over
3103
+ * candidate keys is computed once and reused forever; with SHA-256 that is
3104
+ * cheap enough to be the preferred attack. The iteration count multiplies
3105
+ * the table's build cost by the same 2 * 10^5.
3106
+ *
3107
+ * Neither is a proof of security, and an adversary with ASIC-scale hardware
3108
+ * changes these numbers. If the margin is ever judged insufficient, raise
3109
+ * {@link PAIRING_CODE_LENGTH} — 10 characters buys ~49 bits for two more
3110
+ * characters of human comparison, and is display-only: it does not touch the
3111
+ * envelope or the wire format.
3112
+ *
3113
+ * The cost is paid once per pairing, on two idle devices, so ~200k iterations
3114
+ * is imperceptible here in a way it would not be on a hot path.
3115
+ */
3116
+ async function pairingVerificationCode(devicePublicKeyB64) {
3117
+ const pubRaw = decodePairingPublicKey(devicePublicKeyB64);
3118
+ const material = await crypto.subtle.importKey("raw", pubRaw, { name: "PBKDF2" }, false, [
3119
+ "deriveBits",
3120
+ ]);
3121
+ // Enough bytes that rejection sampling (below) effectively never runs dry:
3122
+ // each byte is rejected with p = 16/256, so 32 bytes yields 8 symbols with
3123
+ // overwhelming probability.
3124
+ const bits = new Uint8Array(await crypto.subtle.deriveBits({
3125
+ name: "PBKDF2",
3126
+ hash: "SHA-256",
3127
+ salt: TE$1.encode(PAIRING_CODE_DOMAIN),
3128
+ iterations: PAIRING_CODE_ITERATIONS,
3129
+ }, material, 256));
3130
+ // Rejection-sample so all 30 symbols are equally likely. 256 is not a
3131
+ // multiple of 30, so a plain modulo would over-weight the first 16 symbols.
3132
+ const n = PAIRING_CODE_ALPHABET.length;
3133
+ const limit = Math.floor(256 / n) * n; // 240
3134
+ let out = "";
3135
+ for (let i = 0; i < bits.length && out.length < PAIRING_CODE_LENGTH; i++) {
3136
+ if (bits[i] >= limit)
3137
+ continue;
3138
+ out += PAIRING_CODE_ALPHABET[bits[i] % n];
3139
+ }
3140
+ if (out.length < PAIRING_CODE_LENGTH) {
3141
+ // Astronomically unlikely (p < 2^-40); fail loudly rather than return a
3142
+ // short code that two screens would still "agree" on.
3143
+ throw new Error("Pairing code derivation ran out of entropy.");
3144
+ }
3145
+ // Grouped for human comparison — the format the spec and both UIs display.
3146
+ return out.slice(0, 4) + "-" + out.slice(4);
3147
+ }
3148
+ // ---- v2 internals ----------------------------------------------------------
3149
+ /**
3150
+ * ECDH → HKDF-SHA256 → AES-256-GCM key.
3151
+ *
3152
+ * The raw ECDH output is never used as a key directly; it is extracted+expanded
3153
+ * with BOTH public keys mixed in:
3154
+ *
3155
+ * - the sender's ephemeral key as HKDF **salt**, and
3156
+ * - the recipient's device key appended to the HKDF **info**.
3157
+ *
3158
+ * Binding the recipient is not decoration. P-256 ECDH returns only the shared
3159
+ * point's x-coordinate, and negating a public key — `(x, y)` → `(x, p−y)`, which
3160
+ * is still on the curve and which ANYONE can compute from the published key —
3161
+ * yields the SAME x. So without the recipient in the KDF, a seal addressed to
3162
+ * the negated key still decrypts under the honest private key, even though that
3163
+ * negated key displays a DIFFERENT {@link pairingVerificationCode}. That would
3164
+ * leave the human code as the only thing rejecting a substituted recipient.
3165
+ * Mixing `devicePubRaw` in makes the substitution fail in the crypto layer,
3166
+ * where it belongs.
3167
+ *
3168
+ * (The salt is load-bearing for the same reason — it is what makes a swapped
3169
+ * `epk` derive a different key. Do not "simplify" either input away.)
3170
+ */
3171
+ async function deriveDeviceSealKey(priv, pub, epkRaw, devicePubRaw, usages) {
3172
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: pub }, priv, 256));
3173
+ const prk = await crypto.subtle.importKey("raw", shared, { name: "HKDF" }, false, ["deriveBits"]);
3174
+ const label = TE$1.encode(HKDF_INFO_V2);
3175
+ const info = new Uint8Array(label.length + devicePubRaw.length);
3176
+ info.set(label, 0);
3177
+ info.set(devicePubRaw, label.length);
3178
+ const okm = await crypto.subtle.deriveBits({
3179
+ name: "HKDF",
3180
+ hash: "SHA-256",
3181
+ salt: epkRaw,
3182
+ info: info,
3183
+ }, prk, 256);
3184
+ return crypto.subtle.importKey("raw", okm, { name: "AES-GCM" }, false, usages);
3185
+ }
3186
+ /** Decode + shape-check a raw SEC1 uncompressed P-256 public key. */
3187
+ function decodePairingPublicKey(b64) {
3188
+ if (typeof b64 !== "string" || b64.length === 0) {
3189
+ throw new Error("Pairing public key must be a non-empty base64 string.");
3190
+ }
3191
+ const raw = fromBase64Loose(b64);
3192
+ if (raw.length !== 65 || raw[0] !== 0x04) {
3193
+ throw new Error("Pairing public key must be a 65-byte uncompressed P-256 point.");
3194
+ }
3195
+ return raw;
3196
+ }
3197
+ /** Import a raw P-256 point for ECDH. Rejects points that are not on the curve. */
3198
+ function importPairingPublicKey(raw) {
3199
+ return crypto.subtle.importKey("raw", raw, PAIRING_CURVE, false, []);
3200
+ }
3201
+ /**
3202
+ * Base64 decode that also accepts the URL-safe alphabet and missing padding —
3203
+ * pairing public keys may travel through query strings, QR payloads, or JSON
3204
+ * depending on the client, and rejecting a key over `-` vs `+` would be a
3205
+ * miserable failure mode to debug.
3206
+ */
3207
+ function fromBase64Loose(s) {
3208
+ const norm = s.replace(/-/g, "+").replace(/_/g, "/");
3209
+ return fromBase64(norm.padEnd(Math.ceil(norm.length / 4) * 4, "="));
3210
+ }
2958
3211
  /** Generate a PKCE verifier + S256 challenge for the authorize→token exchange. */
2959
3212
  async function generatePkce() {
2960
3213
  const codeVerifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)));
2961
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", TE.encode(codeVerifier)));
3214
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", TE$1.encode(codeVerifier)));
2962
3215
  return { codeVerifier, codeChallenge: base64UrlEncode(digest) };
2963
3216
  }
2964
3217
  /** A random URL-safe value for the OAuth `state` (CSRF binding on the callback). */
@@ -2980,7 +3233,7 @@ function base64UrlDecode(s) {
2980
3233
  * expect (and isn't serving a stale cached bundle). Keep this in sync with
2981
3234
  * `package.json` `version`.
2982
3235
  */
2983
- const VERSION = "0.10.11-alpha.0";
3236
+ const VERSION = "0.10.13-alpha.0";
2984
3237
 
2985
3238
  /**
2986
3239
  * `HttpClient` — the one place the unified {@link Client} talks to the
@@ -3593,9 +3846,376 @@ async function evaluatePasskeyPrf(rpId, credentialId, salt) {
3593
3846
  return new Uint8Array(results.first);
3594
3847
  }
3595
3848
 
3849
+ /**
3850
+ * `deviceStore` — at-rest persistence for a paired device (the TV).
3851
+ *
3852
+ * A device that has completed {@link HostedAuth.startDevicePairing} holds the
3853
+ * account's **master seed**. Android WebView has no WebAuthn, so the passkey
3854
+ * wrapping used elsewhere isn't available, and re-pairing on every cold start
3855
+ * is not acceptable UX for a set-top box. So the seed is persisted, encrypted:
3856
+ *
3857
+ * | Item | Where | Form |
3858
+ * | ------------------------ | ------------------------------------ | ---- |
3859
+ * | wrapping key | IndexedDB (`muhkoo.device.v1`) | `CryptoKey`, AES-GCM-256, **non-extractable** |
3860
+ * | device identity keypair | IndexedDB (`muhkoo.device.v1`) | `CryptoKeyPair`, ECDSA P-256, private half **non-extractable** |
3861
+ * | sealed identity blob | localStorage `muhkoo.tv.identity.v1` | `{"v":1,"iv":…,"ct":…}` over `JSON{username, commitment, seed(b64), pairedAt}` |
3862
+ *
3863
+ * The split is deliberate — ciphertext in one backend, key in another, and the
3864
+ * key non-extractable so JS can *use* it but not export it.
3865
+ *
3866
+ * ## Be honest about what this is worth
3867
+ *
3868
+ * **This is obfuscation, not protection.** It raises the cost of a casual
3869
+ * `localStorage` dump to "nothing useful", and that is all:
3870
+ *
3871
+ * - **XSS on the device origin** cannot *exfiltrate* the wrapping key (it is
3872
+ * non-extractable) but can absolutely call `decrypt` and read the seed. The
3873
+ * only mitigation is that there is no third-party script in the shell —
3874
+ * enforce a strict CSP with no `unsafe-inline`, no CDN, no remote fonts.
3875
+ * - **ADB / root / a backup extraction / a forensic image recovers the seed.**
3876
+ * The IndexedDB LevelDB files hold the AES key bytes in the clear; WebCrypto
3877
+ * "non-extractable" is a JS-API boundary, not an OS one. **A stolen device is
3878
+ * a stolen identity.**
3879
+ *
3880
+ * That is not an implementation shortcut, it is the shape of the problem: any
3881
+ * wrapping key usable without user interaction lives somewhere equally readable
3882
+ * on a keyboard-less device with no hardware key store exposed to WebView.
3883
+ * Reduce the blast radius with `android:allowBackup="false"`,
3884
+ * `android:debuggable="false"`, a strict CSP, and by storing *only* the 32-byte
3885
+ * seed + username + commitment (never a session token, never a recovery phrase).
3886
+ *
3887
+ * ## Documented upgrade path — no protocol change
3888
+ *
3889
+ * If the native shell exposes a Keystore bridge:
3890
+ *
3891
+ * ```java
3892
+ * @JavascriptInterface public String wrap(String b64plain); // AES-GCM, StrongBox when present
3893
+ * @JavascriptInterface public String unwrap(String b64cipher);
3894
+ * ```
3895
+ *
3896
+ * this module prefers `globalThis.MuhkooKeystore` automatically and falls back
3897
+ * to the WebCrypto scheme otherwise. The Keystore key is hardware-backed and
3898
+ * non-exportable at the OS level, so a copied filesystem image alone becomes
3899
+ * useless. Nothing on the wire, in the endpoint contracts, or in the SDK surface
3900
+ * changes — only the two functions below do, internally.
3901
+ *
3902
+ * ## Degradation
3903
+ *
3904
+ * Nothing here throws at import time. On a runtime with neither backend (SSR,
3905
+ * Workers, Node) the module still loads: {@link loadDeviceIdentity} returns
3906
+ * `null`, {@link persistDeviceIdentity} throws a typed
3907
+ * {@link DeviceStoreUnavailableError} the caller can swallow, and
3908
+ * {@link deviceIdentityKey} falls back to an **in-memory** keypair for the
3909
+ * lifetime of the process (so pairing still works; the device is just never
3910
+ * recognised as "known" on a later run).
3911
+ */
3912
+ const TE = new TextEncoder();
3913
+ const TD = new TextDecoder();
3914
+ /** localStorage key holding the AES-GCM-sealed identity blob. */
3915
+ const DEVICE_IDENTITY_STORAGE_KEY = "muhkoo.tv.identity.v1";
3916
+ /** IndexedDB database holding the non-extractable keys. */
3917
+ const DEVICE_KEY_DB_NAME = "muhkoo.device.v1";
3918
+ const DEVICE_KEY_STORE = "keys";
3919
+ const WRAP_KEY_ID = "wrap";
3920
+ const IDENTITY_KEY_ID = "identity";
3921
+ /** Thrown when persistence is impossible (no IndexedDB and/or no localStorage). */
3922
+ class DeviceStoreUnavailableError extends Error {
3923
+ constructor(what) {
3924
+ super(`Device identity can't be persisted here: ${what}. ` +
3925
+ "Pairing still works, but this device will have to pair again after a restart.");
3926
+ this.name = "DeviceStoreUnavailableError";
3927
+ }
3928
+ }
3929
+ let injectedKeys;
3930
+ let injectedBlobs;
3931
+ let injectedKeystore;
3932
+ /** Memoized so a pairing attempt and its follow-up touch use one keypair. */
3933
+ let identityMemo = null;
3934
+ let identityEphemeral = false;
3935
+ /**
3936
+ * Point the store at explicit backends (or `null` to force "unavailable"), and
3937
+ * reset the memoized device keypair. Testing / embedding seam — pass `{}` to
3938
+ * restore the default browser backends.
3939
+ */
3940
+ function configureDeviceStore(opts = {}) {
3941
+ injectedKeys = opts.keys;
3942
+ injectedBlobs = opts.blobs;
3943
+ injectedKeystore = opts.keystore;
3944
+ identityMemo = null;
3945
+ identityEphemeral = false;
3946
+ }
3947
+ /**
3948
+ * True when {@link deviceIdentityKey} had to fall back to an in-memory keypair
3949
+ * because no key vault was available. Such a device can pair, but will never be
3950
+ * recognised as "known" afterwards (so approval always needs a fresh factor).
3951
+ */
3952
+ function deviceIdentityIsEphemeral() {
3953
+ return identityEphemeral;
3954
+ }
3955
+ // ---- public API ------------------------------------------------------------
3956
+ /**
3957
+ * The device's **persistent** ECDSA P-256 identity keypair, created on first
3958
+ * call. This is not a browser fingerprint — it is a key, and every
3959
+ * `POST /api/auth/device/code` proves possession of it. Without that proof,
3960
+ * "known device" would be an unauthenticated string anyone could claim in order
3961
+ * to skip the approver's re-authentication.
3962
+ *
3963
+ * The private half is non-extractable and never leaves IndexedDB as bytes.
3964
+ */
3965
+ async function deviceIdentityKey() {
3966
+ if (!identityMemo)
3967
+ identityMemo = loadOrCreateIdentityKey();
3968
+ try {
3969
+ return await identityMemo;
3970
+ }
3971
+ catch (e) {
3972
+ identityMemo = null; // don't cache a failure
3973
+ throw e;
3974
+ }
3975
+ }
3976
+ /** `base64url(SHA-256(raw SEC1 device identity public key))` — 43 chars. */
3977
+ async function deviceFingerprint() {
3978
+ const pair = await deviceIdentityKey();
3979
+ return fingerprintOf(pair.publicKey);
3980
+ }
3981
+ /** Whether a sealed identity blob exists. Cheap: no crypto, no IndexedDB, no network. */
3982
+ async function hasDeviceIdentity() {
3983
+ return blobStore()?.get(DEVICE_IDENTITY_STORAGE_KEY) != null;
3984
+ }
3985
+ /**
3986
+ * Seal and store the identity. Throws {@link DeviceStoreUnavailableError} when
3987
+ * there is nowhere to put it — callers should treat that as "this device won't
3988
+ * resume", not as a pairing failure.
3989
+ */
3990
+ async function persistDeviceIdentity(v) {
3991
+ if (!(v?.seed instanceof Uint8Array) || v.seed.length !== 32) {
3992
+ throw new Error("persistDeviceIdentity: expected a 32-byte seed.");
3993
+ }
3994
+ const blobs = blobStore();
3995
+ if (!blobs)
3996
+ throw new DeviceStoreUnavailableError("no localStorage");
3997
+ const plain = TE.encode(JSON.stringify({
3998
+ username: v.username,
3999
+ commitment: v.commitment,
4000
+ seed: toBase64(v.seed),
4001
+ pairedAt: v.pairedAt,
4002
+ }));
4003
+ const bridge = keystoreBridge();
4004
+ let envelope;
4005
+ if (bridge) {
4006
+ envelope = { v: 1, ks: 1, ct: await bridge.wrap(toBase64(plain)) };
4007
+ }
4008
+ else {
4009
+ const key = await wrapKey(true);
4010
+ if (!key)
4011
+ throw new DeviceStoreUnavailableError("no IndexedDB for the wrapping key");
4012
+ const iv = crypto.getRandomValues(new Uint8Array(12));
4013
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, plain));
4014
+ envelope = { v: 1, iv: toBase64(iv), ct: toBase64(ct) };
4015
+ }
4016
+ blobs.set(DEVICE_IDENTITY_STORAGE_KEY, JSON.stringify(envelope));
4017
+ }
4018
+ /**
4019
+ * Recover the persisted identity, or `null` when there is none / it can't be
4020
+ * opened (wiped IndexedDB, a different browser profile, a corrupted blob).
4021
+ * Never throws — a cold start with unreadable storage must fall back to a fresh
4022
+ * pairing, not to an error screen.
4023
+ */
4024
+ async function loadDeviceIdentity() {
4025
+ const blobs = blobStore();
4026
+ const raw = blobs?.get(DEVICE_IDENTITY_STORAGE_KEY);
4027
+ if (!raw)
4028
+ return null;
4029
+ try {
4030
+ const envelope = JSON.parse(raw);
4031
+ if (envelope?.v !== 1)
4032
+ return null;
4033
+ let plain;
4034
+ const bridge = keystoreBridge();
4035
+ if (envelope.ks === 1) {
4036
+ if (!bridge)
4037
+ return null; // sealed by the native shell; nothing else can open it
4038
+ plain = fromBase64(await bridge.unwrap(envelope.ct));
4039
+ }
4040
+ else {
4041
+ const key = await wrapKey(false);
4042
+ if (!key || !envelope.iv)
4043
+ return null;
4044
+ plain = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64(envelope.iv) }, key, fromBase64(envelope.ct)));
4045
+ }
4046
+ const parsed = JSON.parse(TD.decode(plain));
4047
+ if (!parsed?.username || !parsed?.commitment || !parsed?.seed)
4048
+ return null;
4049
+ const seed = fromBase64(parsed.seed);
4050
+ if (seed.length !== 32)
4051
+ return null;
4052
+ return {
4053
+ username: parsed.username,
4054
+ commitment: parsed.commitment,
4055
+ seed,
4056
+ pairedAt: typeof parsed.pairedAt === "number" ? parsed.pairedAt : 0,
4057
+ };
4058
+ }
4059
+ catch {
4060
+ return null;
4061
+ }
4062
+ }
4063
+ /**
4064
+ * Wipe everything: the sealed blob **and** the whole key database — so the
4065
+ * wrapping key never outlives the ciphertext it opens, and the device identity
4066
+ * key is regenerated (a re-pair is then correctly treated as a new device).
4067
+ */
4068
+ async function clearDeviceIdentity() {
4069
+ identityMemo = null;
4070
+ identityEphemeral = false;
4071
+ try {
4072
+ blobStore()?.remove(DEVICE_IDENTITY_STORAGE_KEY);
4073
+ }
4074
+ catch { /* nothing to remove */ }
4075
+ try {
4076
+ await keyVault()?.destroy();
4077
+ }
4078
+ catch { /* already gone */ }
4079
+ }
4080
+ async function fingerprintOf(publicKey) {
4081
+ const raw = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
4082
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", raw));
4083
+ return toBase64(digest).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4084
+ }
4085
+ async function loadOrCreateIdentityKey() {
4086
+ const vault = keyVault();
4087
+ if (vault) {
4088
+ const existing = (await vault.get(IDENTITY_KEY_ID));
4089
+ if (existing?.privateKey && existing?.publicKey) {
4090
+ identityEphemeral = false;
4091
+ return existing;
4092
+ }
4093
+ }
4094
+ // `extractable: false` applies to the PRIVATE half only — WebCrypto always
4095
+ // allows exporting a public key, which is what the fingerprint needs.
4096
+ const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]));
4097
+ if (vault) {
4098
+ try {
4099
+ await vault.put(IDENTITY_KEY_ID, pair);
4100
+ identityEphemeral = false;
4101
+ return pair;
4102
+ }
4103
+ catch { /* structured clone refused / quota — fall through */ }
4104
+ }
4105
+ // No durable home: keep it for this process only. Pairing still works; the
4106
+ // device just won't be recognised next boot.
4107
+ identityEphemeral = true;
4108
+ return pair;
4109
+ }
4110
+ /**
4111
+ * The AES-GCM wrapping key. `create` generates + stores one when absent;
4112
+ * otherwise a missing key means the blob is unopenable (return null, not throw).
4113
+ */
4114
+ async function wrapKey(create) {
4115
+ const vault = keyVault();
4116
+ if (!vault)
4117
+ return null;
4118
+ const existing = (await vault.get(WRAP_KEY_ID));
4119
+ if (existing)
4120
+ return existing;
4121
+ if (!create)
4122
+ return null;
4123
+ const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
4124
+ await vault.put(WRAP_KEY_ID, key);
4125
+ return key;
4126
+ }
4127
+ function keystoreBridge() {
4128
+ if (injectedKeystore !== undefined)
4129
+ return injectedKeystore;
4130
+ const ks = globalThis.MuhkooKeystore;
4131
+ return typeof ks?.wrap === "function" && typeof ks?.unwrap === "function" ? ks : null;
4132
+ }
4133
+ function blobStore() {
4134
+ if (injectedBlobs !== undefined)
4135
+ return injectedBlobs;
4136
+ try {
4137
+ const ls = globalThis.localStorage;
4138
+ if (!ls)
4139
+ return null;
4140
+ ls.getItem("muhkoo.__probe__"); // Safari private mode throws on access, not on typeof
4141
+ return {
4142
+ get: (k) => ls.getItem(k),
4143
+ set: (k, v) => ls.setItem(k, v),
4144
+ remove: (k) => ls.removeItem(k),
4145
+ };
4146
+ }
4147
+ catch {
4148
+ return null;
4149
+ }
4150
+ }
4151
+ function keyVault() {
4152
+ if (injectedKeys !== undefined)
4153
+ return injectedKeys;
4154
+ const idb = globalThis.indexedDB;
4155
+ if (!idb)
4156
+ return null;
4157
+ return indexedDbVault(idb);
4158
+ }
4159
+ /** Minimal promise wrapper over one object store. Opened per operation — these
4160
+ * are cold-start-rare calls, and holding a connection open would block the
4161
+ * `deleteDatabase` that `clearDeviceIdentity` needs to win. */
4162
+ function indexedDbVault(idb) {
4163
+ const open = () => new Promise((resolve, reject) => {
4164
+ const req = idb.open(DEVICE_KEY_DB_NAME, 1);
4165
+ req.onupgradeneeded = () => {
4166
+ const db = req.result;
4167
+ if (!db.objectStoreNames.contains(DEVICE_KEY_STORE))
4168
+ db.createObjectStore(DEVICE_KEY_STORE);
4169
+ };
4170
+ req.onsuccess = () => resolve(req.result);
4171
+ req.onerror = () => reject(req.error);
4172
+ req.onblocked = () => reject(new Error("IndexedDB open blocked"));
4173
+ });
4174
+ return {
4175
+ async get(id) {
4176
+ const db = await open();
4177
+ try {
4178
+ return await new Promise((resolve, reject) => {
4179
+ const req = db.transaction(DEVICE_KEY_STORE, "readonly").objectStore(DEVICE_KEY_STORE).get(id);
4180
+ req.onsuccess = () => resolve(req.result ?? null);
4181
+ req.onerror = () => reject(req.error);
4182
+ });
4183
+ }
4184
+ finally {
4185
+ db.close();
4186
+ }
4187
+ },
4188
+ async put(id, value) {
4189
+ const db = await open();
4190
+ try {
4191
+ await new Promise((resolve, reject) => {
4192
+ const tx = db.transaction(DEVICE_KEY_STORE, "readwrite");
4193
+ tx.objectStore(DEVICE_KEY_STORE).put(value, id);
4194
+ tx.oncomplete = () => resolve();
4195
+ tx.onerror = () => reject(tx.error);
4196
+ tx.onabort = () => reject(tx.error);
4197
+ });
4198
+ }
4199
+ finally {
4200
+ db.close();
4201
+ }
4202
+ },
4203
+ destroy() {
4204
+ return new Promise((resolve, reject) => {
4205
+ const req = idb.deleteDatabase(DEVICE_KEY_DB_NAME);
4206
+ req.onsuccess = () => resolve();
4207
+ req.onerror = () => reject(req.error);
4208
+ // A live connection elsewhere would block the delete; the blob is
4209
+ // already gone by then, so don't hang the sign-out on it.
4210
+ req.onblocked = () => resolve();
4211
+ });
4212
+ },
4213
+ };
4214
+ }
4215
+
3596
4216
  /**
3597
4217
  * `client.auth.hosted` — centralized hosted auth (auth.muhkoo.dev).
3598
- * AUTH_HOSTED_PLAN.md.
4218
+ * AUTH_HOSTED_PLAN.md; TV device pairing per `muhkoo/auth/docs/tv-device-pairing-spec.md`.
3599
4219
  *
3600
4220
  * Two sides share this class:
3601
4221
  * - **Developer apps** call {@link login} (redirect to the hosted page) and
@@ -3611,8 +4231,98 @@ async function evaluatePasskeyPrf(rpId, credentialId, salt) {
3611
4231
  * page → (user authenticates) → POST /api/auth/grant → redirect_uri?code&state#k=<K_t>
3612
4232
  * app → POST /api/auth/token {code, code_verifier} → {sessionToken, sealedKeys}
3613
4233
  * → unseal sealedKeys with K_t → master seed → session ready
4234
+ *
4235
+ * ## Device pairing (v2 — TVs and other keyboard-less devices)
4236
+ *
4237
+ * The redirect flow above is unchanged and remains the fallback for anything
4238
+ * with a browser and a keyboard. A device with no redirect to receive instead
4239
+ * displays a code and **polls**:
4240
+ *
4241
+ * TV → {@link startDevicePairing} → shows `userCode` + `verificationCode`
4242
+ * user → opens auth.muhkoo.dev/link, signs in, {@link lookupDevicePairing}
4243
+ * user → compares the verification code on both screens,
4244
+ * {@link approveDevicePairing} seals the seed TO the TV's public key
4245
+ * TV → {@link waitForDevicePairing} → unseal → own ZK session → persisted
4246
+ *
4247
+ * Same invariant as v1: the accelerator relays a sealed envelope it cannot read.
4248
+ * Only the key agreement changes (ECDH to a key the TV generated, instead of a
4249
+ * one-time key delivered in a URL fragment a TV can't receive).
3614
4250
  */
3615
4251
  const PKCE_STORE_KEY = "muhkoo.hosted.pkce";
4252
+ // ---- device pairing: constants (tv-device-pairing-spec.md §4.5, §9) --------
4253
+ /** RFC-8628-style backoff step applied on every `slow_down` (spec §9.1). */
4254
+ const SLOW_DOWN_STEP_S = 5;
4255
+ /** Ceiling for the transport-failure backoff, so a flaky TV Wi-Fi still recovers. */
4256
+ const MAX_BACKOFF_INTERVAL_S = 30;
4257
+ /** Consecutive transport failures tolerated before giving up on a pairing. */
4258
+ const MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
4259
+ /** Server-sanitized anyway; clipped here so the request is never rejected for it. */
4260
+ const DEVICE_LABEL_MAX = 64;
4261
+ /** §4.4 signing-input prefixes. Changing either breaks server verification. */
4262
+ const DEVICE_PAIR_SIG_PREFIX = "muhkoo-device-pair-v1";
4263
+ const DEVICE_TOUCH_SIG_PREFIX = "muhkoo-device-touch-v1";
4264
+ /**
4265
+ * Any terminal failure of the pairing flow.
4266
+ *
4267
+ * `.reason` drives the device's UI state machine; `.code` carries the server's
4268
+ * machine error code verbatim (spec §6.7) for the cases the reason collapses —
4269
+ * e.g. `consent_required`, `too_many_devices`, `key_mismatch` all arrive as
4270
+ * `reason: "error"` with a distinct `.code`.
4271
+ */
4272
+ class DevicePairingError extends Error {
4273
+ reason;
4274
+ /** Machine code from the error envelope (`{error, message}`), when there was one. */
4275
+ code;
4276
+ status;
4277
+ /** Seconds, from `Retry-After`, when the server sent one. */
4278
+ retryAfter;
4279
+ /** Any extra fields the error envelope carried (e.g. `version`). */
4280
+ details;
4281
+ constructor(reason, opts = {}) {
4282
+ super(opts.message ?? DEFAULT_PAIRING_MESSAGES[reason]);
4283
+ this.name = "DevicePairingError";
4284
+ this.reason = reason;
4285
+ this.code = opts.code;
4286
+ this.status = opts.status;
4287
+ this.retryAfter = opts.retryAfter;
4288
+ this.details = opts.details;
4289
+ if (opts.cause !== undefined)
4290
+ this.cause = opts.cause;
4291
+ }
4292
+ }
4293
+ const DEFAULT_PAIRING_MESSAGES = {
4294
+ denied: "Sign-in was declined on the other device.",
4295
+ expired: "That code expired. Get a new code and try again.",
4296
+ aborted: "Pairing was cancelled.",
4297
+ rate_limited: "Too many attempts — wait a moment and start again.",
4298
+ network: "Couldn't reach Muhkoo. Check the connection and try again.",
4299
+ commitment_mismatch: "The account handed back doesn't match the key material — pairing aborted. " +
4300
+ "Do not sign in on this device; report it.",
4301
+ account_mismatch: "This device was previously signed in as a different account.",
4302
+ reauth_required: "Confirm it's you before approving a new device.",
4303
+ invalid_user_code: `Codes are ${PAIRING_CODE_LENGTH} characters from ${PAIRING_CODE_ALPHABET} — no O, I, L, U, 0 or 1.`,
4304
+ error: "Device pairing failed.",
4305
+ };
4306
+ /**
4307
+ * Approving a **new** device needs a recently authenticated approver (spec
4308
+ * §10.7, `FRESH_AUTH_MAX_AGE_MS`). The hosted page catches this, prompts for a
4309
+ * password / passkey / Google factor, and retries the approval.
4310
+ *
4311
+ * Server-enforced, not a UI convention — `requiresReauth` on
4312
+ * {@link DevicePairingRequest} is only the hint.
4313
+ */
4314
+ class ReauthRequiredError extends DevicePairingError {
4315
+ /** How long ago the approver's session authenticated, in seconds. */
4316
+ authAgeSeconds;
4317
+ /** The freshness window the server enforces, in seconds. */
4318
+ maxAgeSeconds;
4319
+ constructor(opts = {}) {
4320
+ super("reauth_required", { message: opts.message, code: "reauth_required", status: opts.status ?? 401 });
4321
+ this.name = "ReauthRequiredError";
4322
+ this.authAgeSeconds = opts.authAgeSeconds;
4323
+ this.maxAgeSeconds = opts.maxAgeSeconds;
4324
+ }
4325
+ }
3616
4326
  class HostedAuth {
3617
4327
  deps;
3618
4328
  constructor(deps) {
@@ -3710,6 +4420,561 @@ class HostedAuth {
3710
4420
  url.hash = `k=${fragmentKey}`;
3711
4421
  return url.toString();
3712
4422
  }
4423
+ // =========================================================================
4424
+ // Device pairing — device (TV) side
4425
+ // =========================================================================
4426
+ /**
4427
+ * (Device side) Begin pairing. Generates the ephemeral ECDH keypair, ensures
4428
+ * a persistent device identity key exists, signs a possession proof over it,
4429
+ * and calls `POST /api/auth/device/code`.
4430
+ *
4431
+ * Display `userCode` (large, monospace) **and** `verificationCode`, then call
4432
+ * {@link waitForDevicePairing}. The verification code returned here is
4433
+ * computed locally from this device's own public key — the server also
4434
+ * returns a copy, which is ignored on purpose: trusting it would forfeit the
4435
+ * entire MITM binding (spec §6.1, §10.1).
4436
+ */
4437
+ async startDevicePairing(opts) {
4438
+ if (!opts?.appId)
4439
+ throw new DevicePairingError("error", { message: "startDevicePairing: `appId` is required." });
4440
+ const pairing = await generateDevicePairingKeypair();
4441
+ const identityKey = await deviceIdentityKey();
4442
+ const deviceIdentityKeyB64 = await exportPublicKeyBase64(identityKey.publicKey);
4443
+ const issuedAt = Date.now();
4444
+ const signature = await signMessage([DEVICE_PAIR_SIG_PREFIX, opts.appId, pairing.publicKeyB64, String(issuedAt)].join("|"), identityKey.privateKey);
4445
+ const res = await this.deviceApi("POST", "/api/auth/device/code", {
4446
+ app_id: opts.appId,
4447
+ device_public_key: pairing.publicKeyB64,
4448
+ device_identity_key: deviceIdentityKeyB64,
4449
+ device_signature: signature,
4450
+ issued_at: issuedAt,
4451
+ device_label: (opts.label ?? defaultDeviceLabel()).slice(0, DEVICE_LABEL_MAX),
4452
+ });
4453
+ this.throwForStatus(res);
4454
+ const body = res.body;
4455
+ if (!body?.device_code || !body?.user_code) {
4456
+ throw new DevicePairingError("error", { message: "Device pairing start returned no code." });
4457
+ }
4458
+ const expiresIn = numberOr(body.expires_in, 600);
4459
+ const verificationUri = body.verification_uri || `${this.deps.authBaseUrl}/link`;
4460
+ return {
4461
+ deviceCode: body.device_code,
4462
+ userCode: body.user_code,
4463
+ // LOCAL derivation — never `body.verification_code`.
4464
+ verificationCode: await pairingVerificationCode(pairing.publicKeyB64),
4465
+ verificationUri,
4466
+ verificationUriComplete: body.verification_uri_complete
4467
+ || `${verificationUri}?code=${encodeURIComponent(body.user_code)}`,
4468
+ expiresAt: Date.now() + expiresIn * 1000,
4469
+ interval: numberOr(body.interval, 5),
4470
+ privateKey: pairing.privateKey,
4471
+ devicePublicKeyB64: pairing.publicKeyB64,
4472
+ };
4473
+ }
4474
+ /**
4475
+ * (Device side) One poll of `POST /api/auth/device/token`.
4476
+ *
4477
+ * On `"approved"` this does the whole tail of the flow before returning: it
4478
+ * unseals the envelope with the ephemeral private key, derives the identity,
4479
+ * **verifies the commitment matches** (spec §10.8 — mandatory, and the check
4480
+ * that makes a substituted seed loud rather than silent), mints the device's
4481
+ * OWN long-lived ZK session, registers the device via `PUT /api/auth/devices`,
4482
+ * and persists the identity for cold starts.
4483
+ *
4484
+ * Prefer {@link waitForDevicePairing}; use this only for a custom loop. A
4485
+ * transport failure REJECTS (the caller decides whether to retry); protocol
4486
+ * outcomes resolve as a status.
4487
+ */
4488
+ async pollDevicePairing(session) {
4489
+ this.assertLive(session);
4490
+ const res = await this.deviceApi("POST", "/api/auth/device/token", { device_code: session.deviceCode });
4491
+ if (res.status === 429 && res.code === "slow_down") {
4492
+ const interval = numberOr(res.body?.interval, session.interval + SLOW_DOWN_STEP_S);
4493
+ return { status: "slow_down", interval, retryAfter: res.retryAfter ?? interval };
4494
+ }
4495
+ // `expired_token` is deliberately uniform server-side for unknown /
4496
+ // expired / already-redeemed codes, so all three land here.
4497
+ if (res.status === 401 && res.code === "expired_token")
4498
+ return { status: "expired" };
4499
+ if (res.status === 403 && res.code === "access_denied")
4500
+ return { status: "denied" };
4501
+ this.throwForStatus(res);
4502
+ const body = res.body;
4503
+ if (body?.status === "pending") {
4504
+ return {
4505
+ status: "pending",
4506
+ interval: numberOr(body.interval, session.interval),
4507
+ expiresIn: numberOr(body.expires_in, Math.max(0, Math.round((session.expiresAt - Date.now()) / 1000))),
4508
+ };
4509
+ }
4510
+ if (body?.status === "denied")
4511
+ return { status: "denied" };
4512
+ if (body?.status === "expired")
4513
+ return { status: "expired" };
4514
+ if (body?.status !== "approved") {
4515
+ throw new DevicePairingError("error", { message: `Unexpected pairing status "${body?.status}".` });
4516
+ }
4517
+ if (!body.sealed_keys || !body.username || !body.commitment) {
4518
+ throw new DevicePairingError("error", { message: "Approved pairing was missing its sealed payload." });
4519
+ }
4520
+ const user = await this.adoptSealedSeed(session, {
4521
+ sealedKeys: body.sealed_keys,
4522
+ username: body.username,
4523
+ commitment: body.commitment,
4524
+ });
4525
+ return { status: "approved", user };
4526
+ }
4527
+ /**
4528
+ * (Device side) Poll to completion with the interval + `slow_down` backoff of
4529
+ * spec §9.
4530
+ *
4531
+ * The server's `interval` is authoritative: on `slow_down` the client moves to
4532
+ * `max(serverInterval, own + 5, retryAfter)` so the two can't drift into a
4533
+ * permanent slow_down loop. Sleeps carry ±10 % jitter so a rack of devices
4534
+ * restarted together doesn't synchronise, and the loop stops at `expiresAt`
4535
+ * without waiting for the server to say so.
4536
+ *
4537
+ * Resolves with the signed-in user, or rejects with {@link DevicePairingError}.
4538
+ */
4539
+ async waitForDevicePairing(session, opts = {}) {
4540
+ let interval = session.interval;
4541
+ let consecutiveNetworkErrors = 0;
4542
+ for (;;) {
4543
+ if (opts.signal?.aborted)
4544
+ throw new DevicePairingError("aborted");
4545
+ this.assertLive(session);
4546
+ const remaining = session.expiresAt - Date.now();
4547
+ if (remaining <= 0)
4548
+ throw new DevicePairingError("expired");
4549
+ opts.onTick?.(remaining, interval);
4550
+ const jitter = 1 + (Math.random() * 0.2 - 0.1);
4551
+ await this.sleep(Math.min(interval * 1000 * jitter, remaining), opts.signal);
4552
+ let result;
4553
+ try {
4554
+ result = await this.pollDevicePairing(session);
4555
+ consecutiveNetworkErrors = 0;
4556
+ }
4557
+ catch (e) {
4558
+ // A protocol verdict (denied, budget exhausted, a failed
4559
+ // commitment check) is terminal — it must NOT be swallowed by the
4560
+ // transport-retry arm the way the spec's reference loop would.
4561
+ if (e instanceof DevicePairingError)
4562
+ throw e;
4563
+ // Transport failure: a TV's Wi-Fi drops constantly, and the
4564
+ // pairing stays valid server-side until it expires. Back off.
4565
+ if (++consecutiveNetworkErrors > MAX_CONSECUTIVE_NETWORK_ERRORS) {
4566
+ throw new DevicePairingError("network", { cause: e });
4567
+ }
4568
+ interval = Math.min(interval * 2, MAX_BACKOFF_INTERVAL_S);
4569
+ continue;
4570
+ }
4571
+ switch (result.status) {
4572
+ case "pending":
4573
+ interval = result.interval; // server-authoritative
4574
+ break;
4575
+ case "slow_down":
4576
+ interval = Math.max(result.interval, interval + SLOW_DOWN_STEP_S, result.retryAfter);
4577
+ break;
4578
+ case "approved":
4579
+ return result.user;
4580
+ case "denied":
4581
+ throw new DevicePairingError("denied");
4582
+ case "expired":
4583
+ throw new DevicePairingError("expired");
4584
+ }
4585
+ }
4586
+ }
4587
+ /**
4588
+ * (Device side) Abandon an attempt. Marks the session dead so an in-flight
4589
+ * {@link waitForDevicePairing} rejects with `aborted` on its next tick, and
4590
+ * clears the device code.
4591
+ *
4592
+ * The ephemeral `CryptoKey` cannot be zeroed from JS — dropping the last
4593
+ * reference to `session` is what makes it unrecoverable, so don't keep the
4594
+ * object around. Deliberately does NOT notify the server: the pairing is
4595
+ * single-use and expires on its own, and an unauthenticated "cancel" endpoint
4596
+ * would just be another way to grief someone else's pending code.
4597
+ */
4598
+ cancelDevicePairing(session) {
4599
+ if (!session)
4600
+ return;
4601
+ cancelledPairings.add(session);
4602
+ session.deviceCode = "";
4603
+ }
4604
+ /**
4605
+ * (Device side) Cold-start path. Reads the persisted device identity,
4606
+ * re-derives the ZK identity from the stored seed, mints a fresh session, and
4607
+ * touches `PUT /api/auth/devices`.
4608
+ *
4609
+ * Returns `null` when nothing is persisted, when the blob doesn't derive its
4610
+ * own pinned commitment (corrupt/tampered storage), or when the account no
4611
+ * longer accepts the identity — call {@link startDevicePairing} then.
4612
+ */
4613
+ async resumeDeviceSession() {
4614
+ const persisted = await loadDeviceIdentity();
4615
+ if (!persisted)
4616
+ return null;
4617
+ try {
4618
+ const identity = await deriveIdentityFromSeed(persisted.seed);
4619
+ const commitment = await commitmentFor(identity);
4620
+ // Storage integrity: the seed must still derive the commitment it was
4621
+ // stored with. A mismatch means the blob was swapped, not that the
4622
+ // account changed — refuse it rather than authenticate as someone else.
4623
+ if (commitment !== persisted.commitment)
4624
+ return null;
4625
+ const user = await this.mintSession(persisted.username, identity, persisted.seed, { rememberMe: true });
4626
+ await this.touchPairedDevice();
4627
+ return user;
4628
+ }
4629
+ catch {
4630
+ return null;
4631
+ }
4632
+ }
4633
+ /** (Device side) Wipe the persisted seed, the device identity key, and the session. */
4634
+ async forgetDeviceSession() {
4635
+ await clearDeviceIdentity();
4636
+ await this.deps.session.clear();
4637
+ }
4638
+ /** (Device side) Whether a persisted device identity exists. Cheap: no crypto, no network. */
4639
+ async hasDeviceSession() {
4640
+ return hasDeviceIdentity();
4641
+ }
4642
+ // =========================================================================
4643
+ // Device pairing — approver (hosted page) side
4644
+ // =========================================================================
4645
+ /**
4646
+ * (Hosted page) Resolve a typed `user_code` into the pending request.
4647
+ * Session-authed.
4648
+ *
4649
+ * `verificationCode` is recomputed here from the returned device key — the
4650
+ * server's copy is discarded. Both screens must show independently derived
4651
+ * values or the comparison proves nothing.
4652
+ */
4653
+ async lookupDevicePairing(userCode) {
4654
+ const code = formatUserCode(canonicalUserCode(userCode));
4655
+ const res = await this.deviceApi("POST", "/api/auth/device/lookup", { user_code: code }, true);
4656
+ this.throwForStatus(res);
4657
+ const body = res.body;
4658
+ if (!body?.device_public_key) {
4659
+ throw new DevicePairingError("error", { message: "Pairing lookup returned no device key." });
4660
+ }
4661
+ const isKnown = body.is_known_device === true;
4662
+ return {
4663
+ userCode: body.user_code || code,
4664
+ devicePublicKeyB64: body.device_public_key,
4665
+ verificationCode: await pairingVerificationCode(body.device_public_key),
4666
+ deviceFingerprint: body.device_fingerprint ?? "",
4667
+ deviceLabel: body.device_label ?? "TV",
4668
+ appId: body.app_id ?? "",
4669
+ appLabel: body.app_label ?? "",
4670
+ isKnownDevice: isKnown,
4671
+ requiresReauth: body.requires_reauth ?? !isKnown,
4672
+ expiresAt: Date.now() + numberOr(body.expires_in, 0) * 1000,
4673
+ };
4674
+ }
4675
+ /**
4676
+ * (Hosted page) Seal the in-memory seed to the device's public key and post
4677
+ * the ciphertext. Requires an unlocked seed — the user just authenticated
4678
+ * here — exactly like {@link completeAuthorize}. The server stores and relays
4679
+ * the envelope verbatim and can't read it.
4680
+ *
4681
+ * Show the user the verification code and the device label FIRST, and only
4682
+ * call this on an explicit tap. Throws {@link ReauthRequiredError} when the
4683
+ * account's last authentication is too old for a new device; the page should
4684
+ * prompt for a factor and retry. A stale legal agreement arrives as
4685
+ * `DevicePairingError` with `.code === "consent_required"` and
4686
+ * `.details.version`.
4687
+ */
4688
+ async approveDevicePairing(req, opts = {}) {
4689
+ const seed = this.deps.session.seed;
4690
+ if (!this.deps.session.token || !seed) {
4691
+ throw new DevicePairingError("error", { message: "Authenticate the user before approving a device." });
4692
+ }
4693
+ if (!req?.devicePublicKeyB64) {
4694
+ throw new DevicePairingError("error", { message: "approveDevicePairing: the request has no device key." });
4695
+ }
4696
+ const code = formatUserCode(canonicalUserCode(req.userCode));
4697
+ const sealedKeys = await sealSeedToDevice(seed, req.devicePublicKeyB64);
4698
+ const res = await this.deviceApi("POST", "/api/auth/device/approve", {
4699
+ user_code: code,
4700
+ device_public_key: req.devicePublicKeyB64,
4701
+ sealed_keys: sealedKeys,
4702
+ device_label: (opts.label ?? req.deviceLabel ?? "").slice(0, DEVICE_LABEL_MAX) || undefined,
4703
+ }, true);
4704
+ this.throwForStatus(res);
4705
+ return { deviceId: String(res.body?.device_id ?? req.deviceFingerprint ?? "") };
4706
+ }
4707
+ /**
4708
+ * (Hosted page) Refuse a pairing. No re-auth and no consent gate — declining
4709
+ * must never be harder than accepting. Leaves a tombstone so the device is
4710
+ * told "declined" rather than an indistinguishable "expired".
4711
+ */
4712
+ async denyDevicePairing(userCode) {
4713
+ const code = formatUserCode(canonicalUserCode(userCode));
4714
+ const res = await this.deviceApi("POST", "/api/auth/device/deny", { user_code: code }, true);
4715
+ this.throwForStatus(res);
4716
+ }
4717
+ // =========================================================================
4718
+ // Device pairing — paired-device management
4719
+ // =========================================================================
4720
+ /**
4721
+ * The account's paired devices. Session-authed.
4722
+ *
4723
+ * UI copy note (spec §10.6): removing a device signs it out and forces a full
4724
+ * re-approval, but it **does not take back the encryption key the device
4725
+ * already holds**. Say so — users will assume otherwise.
4726
+ */
4727
+ async listPairedDevices() {
4728
+ const res = await this.deviceApi("GET", "/api/auth/devices", undefined, true);
4729
+ this.throwForStatus(res);
4730
+ const rows = res.body?.devices ?? [];
4731
+ return rows.map((raw) => {
4732
+ const d = raw;
4733
+ return {
4734
+ id: d.id ?? "",
4735
+ label: d.label ?? "",
4736
+ appId: d.app_id ?? "",
4737
+ pairedAt: numberOr(d.paired_at, 0),
4738
+ lastSeenAt: numberOr(d.last_seen_at, 0),
4739
+ activeSession: d.active_session === true,
4740
+ };
4741
+ });
4742
+ }
4743
+ /** Remove a paired device and revoke its session. Session-authed. */
4744
+ async revokePairedDevice(id) {
4745
+ if (!id)
4746
+ throw new DevicePairingError("error", { message: "revokePairedDevice: `id` is required." });
4747
+ const res = await this.deviceApi("DELETE", "/api/auth/devices", { id }, true);
4748
+ this.throwForStatus(res);
4749
+ }
4750
+ // ---- device pairing internals -------------------------------------------
4751
+ /**
4752
+ * The whole tail of an approved pairing: unseal → derive → **verify** →
4753
+ * authenticate → register → persist. Split out of `pollDevicePairing` so the
4754
+ * ordering (and the two refusals) stay readable.
4755
+ */
4756
+ async adoptSealedSeed(session, payload) {
4757
+ let seed;
4758
+ try {
4759
+ seed = await unsealSeedFromDevice(payload.sealedKeys, session.privateKey, session.devicePublicKeyB64);
4760
+ }
4761
+ catch (e) {
4762
+ throw new DevicePairingError("commitment_mismatch", {
4763
+ message: "The sealed key material couldn't be opened on this device — pairing aborted.",
4764
+ cause: e,
4765
+ });
4766
+ }
4767
+ const identity = await deriveIdentityFromSeed(seed);
4768
+ const commitment = await commitmentFor(identity);
4769
+ // §10.8, mandatory: the seed we were handed must derive the commitment the
4770
+ // server claims. A compromised API can seal an attacker-controlled seed to
4771
+ // this device (§10.2) — this is the check that makes that loud.
4772
+ if (commitment !== payload.commitment) {
4773
+ throw new DevicePairingError("commitment_mismatch", {
4774
+ details: { expected: payload.commitment, derived: commitment },
4775
+ });
4776
+ }
4777
+ // §10.2 detection 2 — commitment pinning across re-pairs. A device that
4778
+ // was signed in as someone else must fail closed, not silently switch.
4779
+ const pinned = await loadDeviceIdentity();
4780
+ if (pinned && pinned.commitment !== commitment) {
4781
+ throw new DevicePairingError("account_mismatch", {
4782
+ details: { pinnedUsername: pinned.username, offeredUsername: payload.username },
4783
+ });
4784
+ }
4785
+ // The device mints its OWN session rather than sharing the approver's, so
4786
+ // revoking the TV doesn't sign out the phone that approved it.
4787
+ const user = await this.mintSession(payload.username, identity, seed, { rememberMe: true });
4788
+ // Both are best-effort: the user IS signed in at this point, and failing
4789
+ // the whole pairing over a bookkeeping call would be worse than degrading.
4790
+ await this.touchPairedDevice();
4791
+ try {
4792
+ await persistDeviceIdentity({ username: user.username, commitment, seed, pairedAt: Date.now() });
4793
+ }
4794
+ catch (e) {
4795
+ appLoggerWarn("device identity could not be persisted; this device will pair again after a restart", e);
4796
+ }
4797
+ return user;
4798
+ }
4799
+ /**
4800
+ * Run the standard ZK challenge → Groth16 proof → authenticate round-trip for
4801
+ * an identity derived from a seed the caller already holds, and store the
4802
+ * resulting session.
4803
+ *
4804
+ * Identical to `ZkAuth.login()`'s tail (`proveAndStore`) — same challenge,
4805
+ * same circuit, same signature — so the commitment is byte-identical to
4806
+ * `zk.login(username, password)` by construction. No new endpoint, no circuit
4807
+ * change, no alternative derivation.
4808
+ *
4809
+ * (Spec §7 puts this on `AuthNamespace` as `loginWithSeed`; see the report —
4810
+ * it lives here because `AuthNamespace.ts` was out of scope for this change,
4811
+ * and `proveAndStore` is private.)
4812
+ */
4813
+ async mintSession(username, identity, seed, opts = {}) {
4814
+ const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);
4815
+ const challenge = await this.deps.auth.getChallenge(username);
4816
+ const { proof, publicSignals, commitment } = await generateAuthProof({
4817
+ secretHex: identity.secretHex,
4818
+ saltHex: identity.saltHex,
4819
+ ecdsaPubHex,
4820
+ nonceHex: challenge.nonce,
4821
+ circuits: this.circuits(),
4822
+ });
4823
+ const signature = await signMessage(JSON.stringify(proof), identity.ecdsaKeyPair.privateKey);
4824
+ const result = await this.deps.auth.authenticate({
4825
+ challengeId: challenge.challengeId,
4826
+ proof: {
4827
+ commitment,
4828
+ // The accelerator expects the original hex nonce, not the
4829
+ // field-reduced version fed into the circuit.
4830
+ nonce: challenge.nonce,
4831
+ response: { proof, publicSignals },
4832
+ signature,
4833
+ },
4834
+ rememberMe: opts.rememberMe,
4835
+ });
4836
+ await this.deps.session.setSession({ token: result.token, username: result.username, commitment });
4837
+ this.deps.session.setIdentity(identity);
4838
+ this.deps.session.setSeed(seed);
4839
+ return { username: result.username, commitment };
4840
+ }
4841
+ /**
4842
+ * `PUT /api/auth/devices` — the device checks in after each self-login so the
4843
+ * security page can show "last seen" and revoke the right session. Never
4844
+ * creates a record (only approve does), so a 404 here is expected on a device
4845
+ * whose pairing was revoked. Best-effort by design.
4846
+ */
4847
+ async touchPairedDevice() {
4848
+ try {
4849
+ const identityKey = await deviceIdentityKey();
4850
+ const fingerprint = await deviceFingerprint();
4851
+ const issuedAt = Date.now();
4852
+ const signature = await signMessage([DEVICE_TOUCH_SIG_PREFIX, fingerprint, String(issuedAt)].join("|"), identityKey.privateKey);
4853
+ await this.deviceApi("PUT", "/api/auth/devices", {
4854
+ fingerprint,
4855
+ issued_at: issuedAt,
4856
+ device_signature: signature,
4857
+ }, true);
4858
+ }
4859
+ catch (e) {
4860
+ appLoggerWarn("device check-in failed", e);
4861
+ }
4862
+ }
4863
+ /** Reject a session that {@link cancelDevicePairing} has retired. */
4864
+ assertLive(session) {
4865
+ if (!session || cancelledPairings.has(session) || !session.deviceCode) {
4866
+ throw new DevicePairingError("aborted");
4867
+ }
4868
+ }
4869
+ sleep(ms, signal) {
4870
+ if (this.deps.sleep)
4871
+ return this.deps.sleep(ms, signal);
4872
+ return new Promise((resolve, reject) => {
4873
+ const timer = setTimeout(() => {
4874
+ signal?.removeEventListener("abort", onAbort);
4875
+ resolve();
4876
+ }, ms);
4877
+ const onAbort = () => {
4878
+ clearTimeout(timer);
4879
+ reject(new DevicePairingError("aborted"));
4880
+ };
4881
+ if (signal?.aborted)
4882
+ return onAbort();
4883
+ signal?.addEventListener("abort", onAbort, { once: true });
4884
+ });
4885
+ }
4886
+ /**
4887
+ * One round-trip to a `/api/auth/device*` endpoint. Never throws on a non-2xx
4888
+ * — the poll path has to inspect 401/403/429 itself — so callers that don't
4889
+ * want that follow up with {@link throwForStatus}.
4890
+ */
4891
+ async deviceApi(method, path, body, withSession = false) {
4892
+ const headers = {};
4893
+ if (body !== undefined)
4894
+ headers["Content-Type"] = "application/json";
4895
+ if (withSession) {
4896
+ const token = this.deps.session.token;
4897
+ if (!token)
4898
+ throw new DevicePairingError("error", { code: "unauthorized", status: 401, message: "Sign in first." });
4899
+ // X-Muhkoo-Session, not `Authorization: Bearer` — the accelerator's
4900
+ // session resolver prefers it and raw SPA fetches must use it.
4901
+ headers["X-Muhkoo-Session"] = token;
4902
+ }
4903
+ const fetchFn = this.deps.fetch ?? globalThis.fetch?.bind(globalThis);
4904
+ if (typeof fetchFn !== "function")
4905
+ throw new Error("HostedAuth: no fetch available.");
4906
+ const res = await fetchFn(`${this.apiBase()}${path}`, {
4907
+ method,
4908
+ headers,
4909
+ body: body === undefined ? undefined : JSON.stringify(body),
4910
+ });
4911
+ let parsed = null;
4912
+ try {
4913
+ parsed = await res.json();
4914
+ }
4915
+ catch { /* empty or non-JSON body */ }
4916
+ const envelope = (parsed ?? {});
4917
+ const retryAfterHeader = Number(res.headers?.get?.("Retry-After"));
4918
+ return {
4919
+ status: res.status,
4920
+ ok: res.ok,
4921
+ body: parsed,
4922
+ code: res.ok || typeof envelope.error !== "string" ? undefined : envelope.error,
4923
+ message: typeof envelope.message === "string"
4924
+ ? envelope.message
4925
+ : typeof envelope.error === "string" ? envelope.error : undefined,
4926
+ retryAfter: Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader : null,
4927
+ };
4928
+ }
4929
+ /** Turn a non-2xx device-endpoint response into the right typed error. */
4930
+ throwForStatus(res) {
4931
+ if (res.ok)
4932
+ return;
4933
+ const details = (res.body ?? undefined);
4934
+ if (res.code === "reauth_required") {
4935
+ throw new ReauthRequiredError({
4936
+ message: res.message,
4937
+ status: res.status,
4938
+ authAgeSeconds: numberOrUndefined(details?.auth_age_seconds),
4939
+ maxAgeSeconds: numberOrUndefined(details?.max_age_seconds),
4940
+ });
4941
+ }
4942
+ throw new DevicePairingError(reasonForCode(res.code, res.status), {
4943
+ message: res.message,
4944
+ code: res.code,
4945
+ status: res.status,
4946
+ retryAfter: res.retryAfter ?? undefined,
4947
+ details,
4948
+ });
4949
+ }
4950
+ /**
4951
+ * Accelerator origin for the device endpoints.
4952
+ *
4953
+ * Prefers the explicit dep. Falls back to the {@link AuthClient}'s own base
4954
+ * URL, because `AuthNamespace` builds `HostedAuth` without one today and a
4955
+ * hard-coded default would silently point a staging or local build at
4956
+ * production. Last resort: map the auth SPA host (`auth.…` → `api.…`).
4957
+ */
4958
+ apiBase() {
4959
+ const explicit = this.deps.apiBaseUrl;
4960
+ if (explicit)
4961
+ return explicit.replace(/\/+$/, "");
4962
+ const fromAuthClient = this.deps.auth?.baseUrl;
4963
+ if (typeof fromAuthClient === "string" && fromAuthClient)
4964
+ return fromAuthClient.replace(/\/+$/, "");
4965
+ try {
4966
+ const url = new URL(this.deps.authBaseUrl);
4967
+ url.hostname = url.hostname.replace(/^auth\./, "api.");
4968
+ url.pathname = "";
4969
+ return url.toString().replace(/\/+$/, "");
4970
+ }
4971
+ catch {
4972
+ throw new Error("HostedAuth: can't resolve the accelerator base URL — pass `apiBaseUrl`.");
4973
+ }
4974
+ }
4975
+ circuits() {
4976
+ return this.deps.circuits ?? defaultCircuitUrls(this.apiBase());
4977
+ }
3713
4978
  // ---- internals ----------------------------------------------------------
3714
4979
  location() {
3715
4980
  const loc = globalThis.location;
@@ -3746,6 +5011,92 @@ class HostedAuth {
3746
5011
  h.replaceState(null, "", loc.pathname);
3747
5012
  }
3748
5013
  }
5014
+ // ---- device pairing: module helpers ----------------------------------------
5015
+ /** Sessions retired by {@link HostedAuth.cancelDevicePairing}. Weak so a dropped
5016
+ * session is collectable — this must not become a leak on a device that runs
5017
+ * for months. */
5018
+ const cancelledPairings = new WeakSet();
5019
+ /**
5020
+ * Map a server error code to the reason the device's state machine branches on.
5021
+ * Codes with no dedicated reason land on `"error"` and stay readable through
5022
+ * {@link DevicePairingError.code}.
5023
+ */
5024
+ function reasonForCode(code, status) {
5025
+ switch (code) {
5026
+ case "expired_token":
5027
+ case "pairing_not_found":
5028
+ return "expired";
5029
+ case "access_denied":
5030
+ return "denied";
5031
+ case "slow_down":
5032
+ case "rate_limited":
5033
+ case "too_many_requests":
5034
+ return "rate_limited";
5035
+ case "reauth_required":
5036
+ return "reauth_required";
5037
+ case "invalid_user_code":
5038
+ return "invalid_user_code";
5039
+ default:
5040
+ return status === 429 ? "rate_limited" : "error";
5041
+ }
5042
+ }
5043
+ /**
5044
+ * Canonicalize a typed `user_code`: uppercase, drop whitespace and `-`.
5045
+ *
5046
+ * We deliberately do NOT guess (`O → 0`, `I → 1`, …). Both members of every
5047
+ * confusable pair are excluded from the alphabet, so a typed `O` is a genuine
5048
+ * misread — telling the user is more useful than silently resolving it.
5049
+ */
5050
+ function canonicalUserCode(input) {
5051
+ const code = String(input ?? "").toUpperCase().replace(/[\s-]/g, "");
5052
+ if (code.length !== PAIRING_CODE_LENGTH)
5053
+ throw new DevicePairingError("invalid_user_code");
5054
+ for (const ch of code) {
5055
+ if (!PAIRING_CODE_ALPHABET.includes(ch))
5056
+ throw new DevicePairingError("invalid_user_code");
5057
+ }
5058
+ return code;
5059
+ }
5060
+ /** Group a canonical code for display and for the wire: `"K7QD3MXR"` → `"K7QD-3MXR"`. */
5061
+ function formatUserCode(canonical) {
5062
+ const half = Math.ceil(canonical.length / 2);
5063
+ return `${canonical.slice(0, half)}-${canonical.slice(half)}`;
5064
+ }
5065
+ /** Poseidon commitment for an identity — the value the server stores. */
5066
+ async function commitmentFor(identity) {
5067
+ const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);
5068
+ return buildCommitment(identity.secretHex, identity.saltHex, ecdsaPubHex);
5069
+ }
5070
+ /**
5071
+ * A label the approver can recognise, guessed from the user agent. Android TV
5072
+ * user agents are famously uninformative, so this is a coarse family name —
5073
+ * §6.4 lets the approver rename the device at approval time.
5074
+ */
5075
+ function defaultDeviceLabel() {
5076
+ const ua = globalThis.navigator?.userAgent ?? "";
5077
+ if (/AFT[A-Z]/i.test(ua))
5078
+ return "Fire TV";
5079
+ if (/Android.*TV|GoogleTV|Chromecast/i.test(ua))
5080
+ return "Android TV";
5081
+ if (/AppleTV|tvOS/i.test(ua))
5082
+ return "Apple TV";
5083
+ if (/Tizen|Web0S|WebOS|SMART-TV|BRAVIA|HbbTV|NetCast/i.test(ua))
5084
+ return "Smart TV";
5085
+ return "TV";
5086
+ }
5087
+ function numberOr(v, fallback) {
5088
+ return typeof v === "number" && Number.isFinite(v) ? v : fallback;
5089
+ }
5090
+ function numberOrUndefined(v) {
5091
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
5092
+ }
5093
+ /** Non-fatal diagnostics. The SDK logger is optional, so never let it throw. */
5094
+ function appLoggerWarn(message, err) {
5095
+ try {
5096
+ globalThis.appLogger?.warn?.(`[hosted-auth] ${message}:`, err instanceof Error ? err.message : err);
5097
+ }
5098
+ catch { /* diagnostics must never break the flow */ }
5099
+ }
3749
5100
 
3750
5101
  /**
3751
5102
  * `client.auth` — user authentication, exposed today through the `zk`
@@ -4397,7 +5748,18 @@ class AuthNamespace {
4397
5748
  hosted;
4398
5749
  constructor(deps) {
4399
5750
  this.zk = new ZkAuth(deps);
4400
- this.hosted = new HostedAuth({ auth: deps.auth, session: deps.session, authBaseUrl: deps.authBaseUrl });
5751
+ this.hosted = new HostedAuth({
5752
+ auth: deps.auth,
5753
+ session: deps.session,
5754
+ authBaseUrl: deps.authBaseUrl,
5755
+ // Forwarded explicitly so device pairing resolves the accelerator
5756
+ // origin and the circuit assets the SAME way the rest of the client
5757
+ // does. Without these, `HostedAuth` falls back to reading
5758
+ // `AuthClient.baseUrl` reflectively and to `defaultCircuitUrls`,
5759
+ // which silently ignores an app's `ClientOptions.circuits` override.
5760
+ apiBaseUrl: deps.apiBaseUrl,
5761
+ circuits: deps.circuits,
5762
+ });
4401
5763
  }
4402
5764
  /** Convenience pass-through: the currently signed-in user, or `null`. */
4403
5765
  get user() {
@@ -11277,7 +12639,11 @@ class Client {
11277
12639
  const authClient = new AuthClient({ baseUrl: this.baseUrl, fetch: this.http.fetch });
11278
12640
  const wsBaseUrl = toWsBase(this.baseUrl);
11279
12641
  const authBaseUrl = (options.authBaseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/+$/, "");
11280
- this.auth = new AuthNamespace({ auth: authClient, circuits, session: this.session, authBaseUrl });
12642
+ this.auth = new AuthNamespace({
12643
+ auth: authClient, circuits, session: this.session, authBaseUrl,
12644
+ // The accelerator origin, for `auth.hosted`'s device-pairing endpoints.
12645
+ apiBaseUrl: this.baseUrl,
12646
+ });
11281
12647
  const deferShardUpload = offlineEnabled
11282
12648
  ? (hash) => this.offline.deferShardUpload(hash)
11283
12649
  : undefined;
@@ -12235,5 +13601,5 @@ var bundledLoader = /*#__PURE__*/Object.freeze({
12235
13601
  default: loadRsWasm
12236
13602
  });
12237
13603
 
12238
- export { ACCESS_TOKEN_SCOPES, AES_GCM_IV_BYTES, AES_GCM_KEY_BYTES, AES_GCM_TAG_BYTES, AccessTokensNamespace, AgentsNamespace, AuthClient, AuthNamespace, AuthPublicInput, Authenticator, BlockEngine, BroadcastChannel, BroadcastChannelEvents, ChannelExistsError, ChannelNotFoundError, ChunkCipher, Client, ConnectivityManager, DEFAULT_BASE_URL, DEFAULT_FN_HOST_SUFFIX, DbCache, DbNamespace, DbTable, DoubleRatchet, DoubleRatchetCipher, DoubleRatchetManager, EncryptedSession, EventCore, EventCoreEvents, Field, Field as FieldElement, FileStorage, FunctionsNamespace, HLC, HashKnowledge, HttpClient, HttpError, IndexedDbStore, KEEPER_MEMBER_ID, KeyStore, KeyringClient, KvCache, KvNamespace, LocalEngineHost, LocalStorageSessionStore, Logger, MemorySessionStore, Message, Message as MessageDefault, MessageNamespace, MuhkooAgent, MuhkooDB, MuhkooFunction, MuhkooSpace, NoopStore, OfflineLockedError, OfflineManager, OutboundQueue, P2P_SUBJECT, PBKDF2_DEFAULT_ITERATIONS, PREIMAGE_POK_VERIFICATION_KEY, Packet, PasskeyOriginError, PeerExchange, PeerNetwork, PersonalSpaceClient, Poseidon, PreimagePoK, Ready, ReedSolomonCodec, Retry, Space as Room, SerializeMessage, SessionState, ShardCache, ShardClient, SharedSpaceClient, SnapshotNamespace, Space, SpaceCache, SpaceKeyring, SpaceNamespace, SpacePacketCipher, SpaceSignaler, StorageNamespace, SyncEngine, VERSION, VaultUnavailableError, WSTransport, WebRtcTransport, WorkerEngineHost, ZERO_HLC, ZkAuth, _accountId, _formatBytes, _messageId, _objectId, _packetId, _socketId, _userId, appLogger$1 as appLogger, assertType, base58Decode, base58Encode, buildCommitment, compareHlc, compilePrograms, concatBytes, decodeFromHex, decorators, decryptAesGcm, defaultCircuitUrls, defaultSessionStore, deleteBeatsWrite, deleteRegister, deriveAesKeyFromPassphrase, deriveBitsHkdf, deriveIdentity, deriveIdentityFromSeed, deriveMasterSeedFromPassword, deserialize, ejectAgentPrompt, ejectAgentTools, emptyMap, emptyRegister, encodeToHex, encryptAesGcm, exportPublicKeyBase64, exportPublicKeyHex, fromBase64$1 as fromBase64, fromBase64Url, fromHex, generateAuthProof, generateChecksum, generateId, generatePkce, getIPAddress, getId, getMuhkooAppDescriptor, getSubtle, initBn128Wasm, initRsWasm, initializeCircuits, isNewer, isNumber, isOfflineCapable, isP2pCapable, isProvisional, log, manifestToStat, materializeRow, mergeMap, mergeMessage, mergeRegister, messageKey, pack, padHandle, poseidonHash, protocol, provisionalHandle, quickVerify, randomBytes, randomState, rpIdUsableForOrigin, sealSeed, serialize, shardHash, signMessage, stableStringify, toBase64$1 as toBase64, toBase64Url, toField, toHex, tombstoneRow, unpack, unsealSeed, unwrapWithPassphrase, utf8Decode, utf8Encode, verify, verifyChecksum, verifyGroth16, verifyHashKnowledge, verifyPreimagePoK, wrapWithPassphrase, writeBeatsTombstone, writeColumns, writeRegister };
13604
+ export { ACCESS_TOKEN_SCOPES, AES_GCM_IV_BYTES, AES_GCM_KEY_BYTES, AES_GCM_TAG_BYTES, AccessTokensNamespace, AgentsNamespace, AuthClient, AuthNamespace, AuthPublicInput, Authenticator, BlockEngine, BroadcastChannel, BroadcastChannelEvents, ChannelExistsError, ChannelNotFoundError, ChunkCipher, Client, ConnectivityManager, DEFAULT_BASE_URL, DEFAULT_FN_HOST_SUFFIX, DEVICE_IDENTITY_STORAGE_KEY, DEVICE_KEY_DB_NAME, DbCache, DbNamespace, DbTable, DevicePairingError, DeviceStoreUnavailableError, DoubleRatchet, DoubleRatchetCipher, DoubleRatchetManager, EncryptedSession, EventCore, EventCoreEvents, Field, Field as FieldElement, FileStorage, FunctionsNamespace, HLC, HashKnowledge, HostedAuth, HttpClient, HttpError, IndexedDbStore, KEEPER_MEMBER_ID, KeyStore, KeyringClient, KvCache, KvNamespace, LocalEngineHost, LocalStorageSessionStore, Logger, MemorySessionStore, Message, Message as MessageDefault, MessageNamespace, MuhkooAgent, MuhkooDB, MuhkooFunction, MuhkooSpace, NoopStore, OfflineLockedError, OfflineManager, OutboundQueue, P2P_SUBJECT, PAIRING_CODE_ALPHABET, PAIRING_CODE_LENGTH, PBKDF2_DEFAULT_ITERATIONS, PREIMAGE_POK_VERIFICATION_KEY, Packet, PasskeyOriginError, PeerExchange, PeerNetwork, PersonalSpaceClient, Poseidon, PreimagePoK, Ready, ReauthRequiredError, ReedSolomonCodec, Retry, Space as Room, SerializeMessage, SessionState, ShardCache, ShardClient, SharedSpaceClient, SnapshotNamespace, Space, SpaceCache, SpaceKeyring, SpaceNamespace, SpacePacketCipher, SpaceSignaler, StorageNamespace, SyncEngine, VERSION, VaultUnavailableError, WSTransport, WebRtcTransport, WorkerEngineHost, ZERO_HLC, ZkAuth, _accountId, _formatBytes, _messageId, _objectId, _packetId, _socketId, _userId, appLogger$1 as appLogger, assertType, base58Decode, base58Encode, buildCommitment, canonicalUserCode, clearDeviceIdentity, compareHlc, compilePrograms, concatBytes, configureDeviceStore, decodeFromHex, decorators, decryptAesGcm, defaultCircuitUrls, defaultSessionStore, deleteBeatsWrite, deleteRegister, deriveAesKeyFromPassphrase, deriveBitsHkdf, deriveIdentity, deriveIdentityFromSeed, deriveMasterSeedFromPassword, deserialize, deviceFingerprint, deviceIdentityIsEphemeral, deviceIdentityKey, ejectAgentPrompt, ejectAgentTools, emptyMap, emptyRegister, encodeToHex, encryptAesGcm, exportPublicKeyBase64, exportPublicKeyHex, formatUserCode, fromBase64$1 as fromBase64, fromBase64Url, fromHex, generateAuthProof, generateChecksum, generateDevicePairingKeypair, generateId, generatePkce, getIPAddress, getId, getMuhkooAppDescriptor, getSubtle, hasDeviceIdentity, initBn128Wasm, initRsWasm, initializeCircuits, isNewer, isNumber, isOfflineCapable, isP2pCapable, isProvisional, loadDeviceIdentity, log, manifestToStat, materializeRow, mergeMap, mergeMessage, mergeRegister, messageKey, pack, padHandle, pairingVerificationCode, persistDeviceIdentity, poseidonHash, protocol, provisionalHandle, quickVerify, randomBytes, randomState, rpIdUsableForOrigin, sealSeed, sealSeedToDevice, serialize, shardHash, signMessage, stableStringify, toBase64$1 as toBase64, toBase64Url, toField, toHex, tombstoneRow, unpack, unsealSeed, unsealSeedFromDevice, unwrapWithPassphrase, utf8Decode, utf8Encode, verify, verifyChecksum, verifyGroth16, verifyHashKnowledge, verifyPreimagePoK, wrapWithPassphrase, writeBeatsTombstone, writeColumns, writeRegister };
12239
13605
  //# sourceMappingURL=index.js.map