@muhkoo/connect 0.10.12-alpha.0 → 0.10.14-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));
@@ -2954,8 +2954,8 @@ function fromBase64(b64) {
2954
2954
  * attacker's — that is what {@link pairingVerificationCode} is for, and it is
2955
2955
  * the only MITM defence in the flow (see the entropy note on that function).
2956
2956
  */
2957
- const TE = new TextEncoder();
2958
- const TD = new TextDecoder();
2957
+ const TE$1 = new TextEncoder();
2958
+ const TD$1 = new TextDecoder();
2959
2959
  /** Seal the master seed under a fresh one-time key for the redirect handoff. */
2960
2960
  async function sealSeed(seed) {
2961
2961
  const ktRaw = crypto.getRandomValues(new Uint8Array(32));
@@ -2964,13 +2964,13 @@ async function sealSeed(seed) {
2964
2964
  const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, seed));
2965
2965
  const envelope = { v: 1, iv: toBase64(iv), ct: toBase64(ct) };
2966
2966
  return {
2967
- sealedKeys: toBase64(TE.encode(JSON.stringify(envelope))),
2967
+ sealedKeys: toBase64(TE$1.encode(JSON.stringify(envelope))),
2968
2968
  fragmentKey: base64UrlEncode(ktRaw),
2969
2969
  };
2970
2970
  }
2971
2971
  /** Recover the master seed from the sealed envelope + the fragment key. */
2972
2972
  async function unsealSeed(sealedKeys, fragmentKey) {
2973
- const envelope = JSON.parse(TD.decode(fromBase64(sealedKeys)));
2973
+ const envelope = JSON.parse(TD$1.decode(fromBase64(sealedKeys)));
2974
2974
  if (envelope.v !== 1)
2975
2975
  throw new Error(`Unsupported handoff envelope version ${envelope.v}`);
2976
2976
  const ktRaw = base64UrlDecode(fragmentKey);
@@ -3048,7 +3048,7 @@ async function sealSeedToDevice(seed, devicePublicKeyB64) {
3048
3048
  const iv = crypto.getRandomValues(new Uint8Array(12));
3049
3049
  const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, seed));
3050
3050
  const envelope = { v: 2, epk: toBase64(epkRaw), iv: toBase64(iv), ct: toBase64(ct) };
3051
- return toBase64(TE.encode(JSON.stringify(envelope)));
3051
+ return toBase64(TE$1.encode(JSON.stringify(envelope)));
3052
3052
  }
3053
3053
  /**
3054
3054
  * (Device side) Recover the master seed from a v2 envelope using the ephemeral
@@ -3064,7 +3064,7 @@ async function sealSeedToDevice(seed, devicePublicKeyB64) {
3064
3064
  * recipient matters. A device always holds both halves, so this costs nothing.
3065
3065
  */
3066
3066
  async function unsealSeedFromDevice(sealedKeys, privateKey, devicePublicKeyB64) {
3067
- const envelope = JSON.parse(TD.decode(fromBase64Loose(sealedKeys)));
3067
+ const envelope = JSON.parse(TD$1.decode(fromBase64Loose(sealedKeys)));
3068
3068
  if (envelope.v !== 2)
3069
3069
  throw new Error(`Unsupported device-handoff envelope version ${envelope.v}`);
3070
3070
  const devicePubRaw = decodePairingPublicKey(devicePublicKeyB64);
@@ -3124,7 +3124,7 @@ async function pairingVerificationCode(devicePublicKeyB64) {
3124
3124
  const bits = new Uint8Array(await crypto.subtle.deriveBits({
3125
3125
  name: "PBKDF2",
3126
3126
  hash: "SHA-256",
3127
- salt: TE.encode(PAIRING_CODE_DOMAIN),
3127
+ salt: TE$1.encode(PAIRING_CODE_DOMAIN),
3128
3128
  iterations: PAIRING_CODE_ITERATIONS,
3129
3129
  }, material, 256));
3130
3130
  // Rejection-sample so all 30 symbols are equally likely. 256 is not a
@@ -3171,7 +3171,7 @@ async function pairingVerificationCode(devicePublicKeyB64) {
3171
3171
  async function deriveDeviceSealKey(priv, pub, epkRaw, devicePubRaw, usages) {
3172
3172
  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: pub }, priv, 256));
3173
3173
  const prk = await crypto.subtle.importKey("raw", shared, { name: "HKDF" }, false, ["deriveBits"]);
3174
- const label = TE.encode(HKDF_INFO_V2);
3174
+ const label = TE$1.encode(HKDF_INFO_V2);
3175
3175
  const info = new Uint8Array(label.length + devicePubRaw.length);
3176
3176
  info.set(label, 0);
3177
3177
  info.set(devicePubRaw, label.length);
@@ -3211,7 +3211,7 @@ function fromBase64Loose(s) {
3211
3211
  /** Generate a PKCE verifier + S256 challenge for the authorize→token exchange. */
3212
3212
  async function generatePkce() {
3213
3213
  const codeVerifier = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)));
3214
- 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)));
3215
3215
  return { codeVerifier, codeChallenge: base64UrlEncode(digest) };
3216
3216
  }
3217
3217
  /** A random URL-safe value for the OAuth `state` (CSRF binding on the callback). */
@@ -3233,7 +3233,7 @@ function base64UrlDecode(s) {
3233
3233
  * expect (and isn't serving a stale cached bundle). Keep this in sync with
3234
3234
  * `package.json` `version`.
3235
3235
  */
3236
- const VERSION = "0.10.12-alpha.0";
3236
+ const VERSION = "0.10.14-alpha.0";
3237
3237
 
3238
3238
  /**
3239
3239
  * `HttpClient` — the one place the unified {@link Client} talks to the
@@ -3769,6 +3769,30 @@ function rpIdUsableForOrigin(rpId, host) {
3769
3769
  return false;
3770
3770
  return h === rpId || h.endsWith(`.${rpId}`);
3771
3771
  }
3772
+ /**
3773
+ * Would {@link AuthNamespace.loginWithPasskey} accept a factor recorded with
3774
+ * this `rpId`, from `host`?
3775
+ *
3776
+ * This is deliberately NOT the same as {@link rpIdUsableForOrigin}. That answers
3777
+ * a raw WebAuthn question and is `false` for a missing rpId. But a factor with
3778
+ * NO recorded rpId predates per-origin enrolment, and `loginWithPasskey`
3779
+ * resolves it as `params.rpId ?? host` — so it IS usable, from anywhere.
3780
+ *
3781
+ * Callers deciding "should I even try a passkey here?" must use this one.
3782
+ * Reaching for `rpIdUsableForOrigin` instead silently excludes every legacy
3783
+ * passkey holder, which has locked real users out of production twice.
3784
+ *
3785
+ * The `?? host` fallback applies to nullish only, matching `loginWithPasskey`:
3786
+ * an empty-string rpId stays unusable rather than resolving to the host.
3787
+ */
3788
+ function passkeyUsableFromOrigin(rpId, host) {
3789
+ const h = host ?? defaultRpId();
3790
+ if (!h)
3791
+ return false;
3792
+ if (rpId == null)
3793
+ return true;
3794
+ return rpIdUsableForOrigin(rpId, h);
3795
+ }
3772
3796
  /** Thrown when the account's passkey belongs to a different origin. Callers
3773
3797
  * should treat this as "no passkey here" and fall back to another factor. */
3774
3798
  class PasskeyOriginError extends Error {
@@ -3846,9 +3870,376 @@ async function evaluatePasskeyPrf(rpId, credentialId, salt) {
3846
3870
  return new Uint8Array(results.first);
3847
3871
  }
3848
3872
 
3873
+ /**
3874
+ * `deviceStore` — at-rest persistence for a paired device (the TV).
3875
+ *
3876
+ * A device that has completed {@link HostedAuth.startDevicePairing} holds the
3877
+ * account's **master seed**. Android WebView has no WebAuthn, so the passkey
3878
+ * wrapping used elsewhere isn't available, and re-pairing on every cold start
3879
+ * is not acceptable UX for a set-top box. So the seed is persisted, encrypted:
3880
+ *
3881
+ * | Item | Where | Form |
3882
+ * | ------------------------ | ------------------------------------ | ---- |
3883
+ * | wrapping key | IndexedDB (`muhkoo.device.v1`) | `CryptoKey`, AES-GCM-256, **non-extractable** |
3884
+ * | device identity keypair | IndexedDB (`muhkoo.device.v1`) | `CryptoKeyPair`, ECDSA P-256, private half **non-extractable** |
3885
+ * | sealed identity blob | localStorage `muhkoo.tv.identity.v1` | `{"v":1,"iv":…,"ct":…}` over `JSON{username, commitment, seed(b64), pairedAt}` |
3886
+ *
3887
+ * The split is deliberate — ciphertext in one backend, key in another, and the
3888
+ * key non-extractable so JS can *use* it but not export it.
3889
+ *
3890
+ * ## Be honest about what this is worth
3891
+ *
3892
+ * **This is obfuscation, not protection.** It raises the cost of a casual
3893
+ * `localStorage` dump to "nothing useful", and that is all:
3894
+ *
3895
+ * - **XSS on the device origin** cannot *exfiltrate* the wrapping key (it is
3896
+ * non-extractable) but can absolutely call `decrypt` and read the seed. The
3897
+ * only mitigation is that there is no third-party script in the shell —
3898
+ * enforce a strict CSP with no `unsafe-inline`, no CDN, no remote fonts.
3899
+ * - **ADB / root / a backup extraction / a forensic image recovers the seed.**
3900
+ * The IndexedDB LevelDB files hold the AES key bytes in the clear; WebCrypto
3901
+ * "non-extractable" is a JS-API boundary, not an OS one. **A stolen device is
3902
+ * a stolen identity.**
3903
+ *
3904
+ * That is not an implementation shortcut, it is the shape of the problem: any
3905
+ * wrapping key usable without user interaction lives somewhere equally readable
3906
+ * on a keyboard-less device with no hardware key store exposed to WebView.
3907
+ * Reduce the blast radius with `android:allowBackup="false"`,
3908
+ * `android:debuggable="false"`, a strict CSP, and by storing *only* the 32-byte
3909
+ * seed + username + commitment (never a session token, never a recovery phrase).
3910
+ *
3911
+ * ## Documented upgrade path — no protocol change
3912
+ *
3913
+ * If the native shell exposes a Keystore bridge:
3914
+ *
3915
+ * ```java
3916
+ * @JavascriptInterface public String wrap(String b64plain); // AES-GCM, StrongBox when present
3917
+ * @JavascriptInterface public String unwrap(String b64cipher);
3918
+ * ```
3919
+ *
3920
+ * this module prefers `globalThis.MuhkooKeystore` automatically and falls back
3921
+ * to the WebCrypto scheme otherwise. The Keystore key is hardware-backed and
3922
+ * non-exportable at the OS level, so a copied filesystem image alone becomes
3923
+ * useless. Nothing on the wire, in the endpoint contracts, or in the SDK surface
3924
+ * changes — only the two functions below do, internally.
3925
+ *
3926
+ * ## Degradation
3927
+ *
3928
+ * Nothing here throws at import time. On a runtime with neither backend (SSR,
3929
+ * Workers, Node) the module still loads: {@link loadDeviceIdentity} returns
3930
+ * `null`, {@link persistDeviceIdentity} throws a typed
3931
+ * {@link DeviceStoreUnavailableError} the caller can swallow, and
3932
+ * {@link deviceIdentityKey} falls back to an **in-memory** keypair for the
3933
+ * lifetime of the process (so pairing still works; the device is just never
3934
+ * recognised as "known" on a later run).
3935
+ */
3936
+ const TE = new TextEncoder();
3937
+ const TD = new TextDecoder();
3938
+ /** localStorage key holding the AES-GCM-sealed identity blob. */
3939
+ const DEVICE_IDENTITY_STORAGE_KEY = "muhkoo.tv.identity.v1";
3940
+ /** IndexedDB database holding the non-extractable keys. */
3941
+ const DEVICE_KEY_DB_NAME = "muhkoo.device.v1";
3942
+ const DEVICE_KEY_STORE = "keys";
3943
+ const WRAP_KEY_ID = "wrap";
3944
+ const IDENTITY_KEY_ID = "identity";
3945
+ /** Thrown when persistence is impossible (no IndexedDB and/or no localStorage). */
3946
+ class DeviceStoreUnavailableError extends Error {
3947
+ constructor(what) {
3948
+ super(`Device identity can't be persisted here: ${what}. ` +
3949
+ "Pairing still works, but this device will have to pair again after a restart.");
3950
+ this.name = "DeviceStoreUnavailableError";
3951
+ }
3952
+ }
3953
+ let injectedKeys;
3954
+ let injectedBlobs;
3955
+ let injectedKeystore;
3956
+ /** Memoized so a pairing attempt and its follow-up touch use one keypair. */
3957
+ let identityMemo = null;
3958
+ let identityEphemeral = false;
3959
+ /**
3960
+ * Point the store at explicit backends (or `null` to force "unavailable"), and
3961
+ * reset the memoized device keypair. Testing / embedding seam — pass `{}` to
3962
+ * restore the default browser backends.
3963
+ */
3964
+ function configureDeviceStore(opts = {}) {
3965
+ injectedKeys = opts.keys;
3966
+ injectedBlobs = opts.blobs;
3967
+ injectedKeystore = opts.keystore;
3968
+ identityMemo = null;
3969
+ identityEphemeral = false;
3970
+ }
3971
+ /**
3972
+ * True when {@link deviceIdentityKey} had to fall back to an in-memory keypair
3973
+ * because no key vault was available. Such a device can pair, but will never be
3974
+ * recognised as "known" afterwards (so approval always needs a fresh factor).
3975
+ */
3976
+ function deviceIdentityIsEphemeral() {
3977
+ return identityEphemeral;
3978
+ }
3979
+ // ---- public API ------------------------------------------------------------
3980
+ /**
3981
+ * The device's **persistent** ECDSA P-256 identity keypair, created on first
3982
+ * call. This is not a browser fingerprint — it is a key, and every
3983
+ * `POST /api/auth/device/code` proves possession of it. Without that proof,
3984
+ * "known device" would be an unauthenticated string anyone could claim in order
3985
+ * to skip the approver's re-authentication.
3986
+ *
3987
+ * The private half is non-extractable and never leaves IndexedDB as bytes.
3988
+ */
3989
+ async function deviceIdentityKey() {
3990
+ if (!identityMemo)
3991
+ identityMemo = loadOrCreateIdentityKey();
3992
+ try {
3993
+ return await identityMemo;
3994
+ }
3995
+ catch (e) {
3996
+ identityMemo = null; // don't cache a failure
3997
+ throw e;
3998
+ }
3999
+ }
4000
+ /** `base64url(SHA-256(raw SEC1 device identity public key))` — 43 chars. */
4001
+ async function deviceFingerprint() {
4002
+ const pair = await deviceIdentityKey();
4003
+ return fingerprintOf(pair.publicKey);
4004
+ }
4005
+ /** Whether a sealed identity blob exists. Cheap: no crypto, no IndexedDB, no network. */
4006
+ async function hasDeviceIdentity() {
4007
+ return blobStore()?.get(DEVICE_IDENTITY_STORAGE_KEY) != null;
4008
+ }
4009
+ /**
4010
+ * Seal and store the identity. Throws {@link DeviceStoreUnavailableError} when
4011
+ * there is nowhere to put it — callers should treat that as "this device won't
4012
+ * resume", not as a pairing failure.
4013
+ */
4014
+ async function persistDeviceIdentity(v) {
4015
+ if (!(v?.seed instanceof Uint8Array) || v.seed.length !== 32) {
4016
+ throw new Error("persistDeviceIdentity: expected a 32-byte seed.");
4017
+ }
4018
+ const blobs = blobStore();
4019
+ if (!blobs)
4020
+ throw new DeviceStoreUnavailableError("no localStorage");
4021
+ const plain = TE.encode(JSON.stringify({
4022
+ username: v.username,
4023
+ commitment: v.commitment,
4024
+ seed: toBase64(v.seed),
4025
+ pairedAt: v.pairedAt,
4026
+ }));
4027
+ const bridge = keystoreBridge();
4028
+ let envelope;
4029
+ if (bridge) {
4030
+ envelope = { v: 1, ks: 1, ct: await bridge.wrap(toBase64(plain)) };
4031
+ }
4032
+ else {
4033
+ const key = await wrapKey(true);
4034
+ if (!key)
4035
+ throw new DeviceStoreUnavailableError("no IndexedDB for the wrapping key");
4036
+ const iv = crypto.getRandomValues(new Uint8Array(12));
4037
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, key, plain));
4038
+ envelope = { v: 1, iv: toBase64(iv), ct: toBase64(ct) };
4039
+ }
4040
+ blobs.set(DEVICE_IDENTITY_STORAGE_KEY, JSON.stringify(envelope));
4041
+ }
4042
+ /**
4043
+ * Recover the persisted identity, or `null` when there is none / it can't be
4044
+ * opened (wiped IndexedDB, a different browser profile, a corrupted blob).
4045
+ * Never throws — a cold start with unreadable storage must fall back to a fresh
4046
+ * pairing, not to an error screen.
4047
+ */
4048
+ async function loadDeviceIdentity() {
4049
+ const blobs = blobStore();
4050
+ const raw = blobs?.get(DEVICE_IDENTITY_STORAGE_KEY);
4051
+ if (!raw)
4052
+ return null;
4053
+ try {
4054
+ const envelope = JSON.parse(raw);
4055
+ if (envelope?.v !== 1)
4056
+ return null;
4057
+ let plain;
4058
+ const bridge = keystoreBridge();
4059
+ if (envelope.ks === 1) {
4060
+ if (!bridge)
4061
+ return null; // sealed by the native shell; nothing else can open it
4062
+ plain = fromBase64(await bridge.unwrap(envelope.ct));
4063
+ }
4064
+ else {
4065
+ const key = await wrapKey(false);
4066
+ if (!key || !envelope.iv)
4067
+ return null;
4068
+ plain = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64(envelope.iv) }, key, fromBase64(envelope.ct)));
4069
+ }
4070
+ const parsed = JSON.parse(TD.decode(plain));
4071
+ if (!parsed?.username || !parsed?.commitment || !parsed?.seed)
4072
+ return null;
4073
+ const seed = fromBase64(parsed.seed);
4074
+ if (seed.length !== 32)
4075
+ return null;
4076
+ return {
4077
+ username: parsed.username,
4078
+ commitment: parsed.commitment,
4079
+ seed,
4080
+ pairedAt: typeof parsed.pairedAt === "number" ? parsed.pairedAt : 0,
4081
+ };
4082
+ }
4083
+ catch {
4084
+ return null;
4085
+ }
4086
+ }
4087
+ /**
4088
+ * Wipe everything: the sealed blob **and** the whole key database — so the
4089
+ * wrapping key never outlives the ciphertext it opens, and the device identity
4090
+ * key is regenerated (a re-pair is then correctly treated as a new device).
4091
+ */
4092
+ async function clearDeviceIdentity() {
4093
+ identityMemo = null;
4094
+ identityEphemeral = false;
4095
+ try {
4096
+ blobStore()?.remove(DEVICE_IDENTITY_STORAGE_KEY);
4097
+ }
4098
+ catch { /* nothing to remove */ }
4099
+ try {
4100
+ await keyVault()?.destroy();
4101
+ }
4102
+ catch { /* already gone */ }
4103
+ }
4104
+ async function fingerprintOf(publicKey) {
4105
+ const raw = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
4106
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", raw));
4107
+ return toBase64(digest).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4108
+ }
4109
+ async function loadOrCreateIdentityKey() {
4110
+ const vault = keyVault();
4111
+ if (vault) {
4112
+ const existing = (await vault.get(IDENTITY_KEY_ID));
4113
+ if (existing?.privateKey && existing?.publicKey) {
4114
+ identityEphemeral = false;
4115
+ return existing;
4116
+ }
4117
+ }
4118
+ // `extractable: false` applies to the PRIVATE half only — WebCrypto always
4119
+ // allows exporting a public key, which is what the fingerprint needs.
4120
+ const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]));
4121
+ if (vault) {
4122
+ try {
4123
+ await vault.put(IDENTITY_KEY_ID, pair);
4124
+ identityEphemeral = false;
4125
+ return pair;
4126
+ }
4127
+ catch { /* structured clone refused / quota — fall through */ }
4128
+ }
4129
+ // No durable home: keep it for this process only. Pairing still works; the
4130
+ // device just won't be recognised next boot.
4131
+ identityEphemeral = true;
4132
+ return pair;
4133
+ }
4134
+ /**
4135
+ * The AES-GCM wrapping key. `create` generates + stores one when absent;
4136
+ * otherwise a missing key means the blob is unopenable (return null, not throw).
4137
+ */
4138
+ async function wrapKey(create) {
4139
+ const vault = keyVault();
4140
+ if (!vault)
4141
+ return null;
4142
+ const existing = (await vault.get(WRAP_KEY_ID));
4143
+ if (existing)
4144
+ return existing;
4145
+ if (!create)
4146
+ return null;
4147
+ const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
4148
+ await vault.put(WRAP_KEY_ID, key);
4149
+ return key;
4150
+ }
4151
+ function keystoreBridge() {
4152
+ if (injectedKeystore !== undefined)
4153
+ return injectedKeystore;
4154
+ const ks = globalThis.MuhkooKeystore;
4155
+ return typeof ks?.wrap === "function" && typeof ks?.unwrap === "function" ? ks : null;
4156
+ }
4157
+ function blobStore() {
4158
+ if (injectedBlobs !== undefined)
4159
+ return injectedBlobs;
4160
+ try {
4161
+ const ls = globalThis.localStorage;
4162
+ if (!ls)
4163
+ return null;
4164
+ ls.getItem("muhkoo.__probe__"); // Safari private mode throws on access, not on typeof
4165
+ return {
4166
+ get: (k) => ls.getItem(k),
4167
+ set: (k, v) => ls.setItem(k, v),
4168
+ remove: (k) => ls.removeItem(k),
4169
+ };
4170
+ }
4171
+ catch {
4172
+ return null;
4173
+ }
4174
+ }
4175
+ function keyVault() {
4176
+ if (injectedKeys !== undefined)
4177
+ return injectedKeys;
4178
+ const idb = globalThis.indexedDB;
4179
+ if (!idb)
4180
+ return null;
4181
+ return indexedDbVault(idb);
4182
+ }
4183
+ /** Minimal promise wrapper over one object store. Opened per operation — these
4184
+ * are cold-start-rare calls, and holding a connection open would block the
4185
+ * `deleteDatabase` that `clearDeviceIdentity` needs to win. */
4186
+ function indexedDbVault(idb) {
4187
+ const open = () => new Promise((resolve, reject) => {
4188
+ const req = idb.open(DEVICE_KEY_DB_NAME, 1);
4189
+ req.onupgradeneeded = () => {
4190
+ const db = req.result;
4191
+ if (!db.objectStoreNames.contains(DEVICE_KEY_STORE))
4192
+ db.createObjectStore(DEVICE_KEY_STORE);
4193
+ };
4194
+ req.onsuccess = () => resolve(req.result);
4195
+ req.onerror = () => reject(req.error);
4196
+ req.onblocked = () => reject(new Error("IndexedDB open blocked"));
4197
+ });
4198
+ return {
4199
+ async get(id) {
4200
+ const db = await open();
4201
+ try {
4202
+ return await new Promise((resolve, reject) => {
4203
+ const req = db.transaction(DEVICE_KEY_STORE, "readonly").objectStore(DEVICE_KEY_STORE).get(id);
4204
+ req.onsuccess = () => resolve(req.result ?? null);
4205
+ req.onerror = () => reject(req.error);
4206
+ });
4207
+ }
4208
+ finally {
4209
+ db.close();
4210
+ }
4211
+ },
4212
+ async put(id, value) {
4213
+ const db = await open();
4214
+ try {
4215
+ await new Promise((resolve, reject) => {
4216
+ const tx = db.transaction(DEVICE_KEY_STORE, "readwrite");
4217
+ tx.objectStore(DEVICE_KEY_STORE).put(value, id);
4218
+ tx.oncomplete = () => resolve();
4219
+ tx.onerror = () => reject(tx.error);
4220
+ tx.onabort = () => reject(tx.error);
4221
+ });
4222
+ }
4223
+ finally {
4224
+ db.close();
4225
+ }
4226
+ },
4227
+ destroy() {
4228
+ return new Promise((resolve, reject) => {
4229
+ const req = idb.deleteDatabase(DEVICE_KEY_DB_NAME);
4230
+ req.onsuccess = () => resolve();
4231
+ req.onerror = () => reject(req.error);
4232
+ // A live connection elsewhere would block the delete; the blob is
4233
+ // already gone by then, so don't hang the sign-out on it.
4234
+ req.onblocked = () => resolve();
4235
+ });
4236
+ },
4237
+ };
4238
+ }
4239
+
3849
4240
  /**
3850
4241
  * `client.auth.hosted` — centralized hosted auth (auth.muhkoo.dev).
3851
- * AUTH_HOSTED_PLAN.md.
4242
+ * AUTH_HOSTED_PLAN.md; TV device pairing per `muhkoo/auth/docs/tv-device-pairing-spec.md`.
3852
4243
  *
3853
4244
  * Two sides share this class:
3854
4245
  * - **Developer apps** call {@link login} (redirect to the hosted page) and
@@ -3864,8 +4255,98 @@ async function evaluatePasskeyPrf(rpId, credentialId, salt) {
3864
4255
  * page → (user authenticates) → POST /api/auth/grant → redirect_uri?code&state#k=<K_t>
3865
4256
  * app → POST /api/auth/token {code, code_verifier} → {sessionToken, sealedKeys}
3866
4257
  * → unseal sealedKeys with K_t → master seed → session ready
4258
+ *
4259
+ * ## Device pairing (v2 — TVs and other keyboard-less devices)
4260
+ *
4261
+ * The redirect flow above is unchanged and remains the fallback for anything
4262
+ * with a browser and a keyboard. A device with no redirect to receive instead
4263
+ * displays a code and **polls**:
4264
+ *
4265
+ * TV → {@link startDevicePairing} → shows `userCode` + `verificationCode`
4266
+ * user → opens auth.muhkoo.dev/link, signs in, {@link lookupDevicePairing}
4267
+ * user → compares the verification code on both screens,
4268
+ * {@link approveDevicePairing} seals the seed TO the TV's public key
4269
+ * TV → {@link waitForDevicePairing} → unseal → own ZK session → persisted
4270
+ *
4271
+ * Same invariant as v1: the accelerator relays a sealed envelope it cannot read.
4272
+ * Only the key agreement changes (ECDH to a key the TV generated, instead of a
4273
+ * one-time key delivered in a URL fragment a TV can't receive).
3867
4274
  */
3868
4275
  const PKCE_STORE_KEY = "muhkoo.hosted.pkce";
4276
+ // ---- device pairing: constants (tv-device-pairing-spec.md §4.5, §9) --------
4277
+ /** RFC-8628-style backoff step applied on every `slow_down` (spec §9.1). */
4278
+ const SLOW_DOWN_STEP_S = 5;
4279
+ /** Ceiling for the transport-failure backoff, so a flaky TV Wi-Fi still recovers. */
4280
+ const MAX_BACKOFF_INTERVAL_S = 30;
4281
+ /** Consecutive transport failures tolerated before giving up on a pairing. */
4282
+ const MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
4283
+ /** Server-sanitized anyway; clipped here so the request is never rejected for it. */
4284
+ const DEVICE_LABEL_MAX = 64;
4285
+ /** §4.4 signing-input prefixes. Changing either breaks server verification. */
4286
+ const DEVICE_PAIR_SIG_PREFIX = "muhkoo-device-pair-v1";
4287
+ const DEVICE_TOUCH_SIG_PREFIX = "muhkoo-device-touch-v1";
4288
+ /**
4289
+ * Any terminal failure of the pairing flow.
4290
+ *
4291
+ * `.reason` drives the device's UI state machine; `.code` carries the server's
4292
+ * machine error code verbatim (spec §6.7) for the cases the reason collapses —
4293
+ * e.g. `consent_required`, `too_many_devices`, `key_mismatch` all arrive as
4294
+ * `reason: "error"` with a distinct `.code`.
4295
+ */
4296
+ class DevicePairingError extends Error {
4297
+ reason;
4298
+ /** Machine code from the error envelope (`{error, message}`), when there was one. */
4299
+ code;
4300
+ status;
4301
+ /** Seconds, from `Retry-After`, when the server sent one. */
4302
+ retryAfter;
4303
+ /** Any extra fields the error envelope carried (e.g. `version`). */
4304
+ details;
4305
+ constructor(reason, opts = {}) {
4306
+ super(opts.message ?? DEFAULT_PAIRING_MESSAGES[reason]);
4307
+ this.name = "DevicePairingError";
4308
+ this.reason = reason;
4309
+ this.code = opts.code;
4310
+ this.status = opts.status;
4311
+ this.retryAfter = opts.retryAfter;
4312
+ this.details = opts.details;
4313
+ if (opts.cause !== undefined)
4314
+ this.cause = opts.cause;
4315
+ }
4316
+ }
4317
+ const DEFAULT_PAIRING_MESSAGES = {
4318
+ denied: "Sign-in was declined on the other device.",
4319
+ expired: "That code expired. Get a new code and try again.",
4320
+ aborted: "Pairing was cancelled.",
4321
+ rate_limited: "Too many attempts — wait a moment and start again.",
4322
+ network: "Couldn't reach Muhkoo. Check the connection and try again.",
4323
+ commitment_mismatch: "The account handed back doesn't match the key material — pairing aborted. " +
4324
+ "Do not sign in on this device; report it.",
4325
+ account_mismatch: "This device was previously signed in as a different account.",
4326
+ reauth_required: "Confirm it's you before approving a new device.",
4327
+ invalid_user_code: `Codes are ${PAIRING_CODE_LENGTH} characters from ${PAIRING_CODE_ALPHABET} — no O, I, L, U, 0 or 1.`,
4328
+ error: "Device pairing failed.",
4329
+ };
4330
+ /**
4331
+ * Approving a **new** device needs a recently authenticated approver (spec
4332
+ * §10.7, `FRESH_AUTH_MAX_AGE_MS`). The hosted page catches this, prompts for a
4333
+ * password / passkey / Google factor, and retries the approval.
4334
+ *
4335
+ * Server-enforced, not a UI convention — `requiresReauth` on
4336
+ * {@link DevicePairingRequest} is only the hint.
4337
+ */
4338
+ class ReauthRequiredError extends DevicePairingError {
4339
+ /** How long ago the approver's session authenticated, in seconds. */
4340
+ authAgeSeconds;
4341
+ /** The freshness window the server enforces, in seconds. */
4342
+ maxAgeSeconds;
4343
+ constructor(opts = {}) {
4344
+ super("reauth_required", { message: opts.message, code: "reauth_required", status: opts.status ?? 401 });
4345
+ this.name = "ReauthRequiredError";
4346
+ this.authAgeSeconds = opts.authAgeSeconds;
4347
+ this.maxAgeSeconds = opts.maxAgeSeconds;
4348
+ }
4349
+ }
3869
4350
  class HostedAuth {
3870
4351
  deps;
3871
4352
  constructor(deps) {
@@ -3963,6 +4444,571 @@ class HostedAuth {
3963
4444
  url.hash = `k=${fragmentKey}`;
3964
4445
  return url.toString();
3965
4446
  }
4447
+ // =========================================================================
4448
+ // Device pairing — device (TV) side
4449
+ // =========================================================================
4450
+ /**
4451
+ * (Device side) Begin pairing. Generates the ephemeral ECDH keypair, ensures
4452
+ * a persistent device identity key exists, signs a possession proof over it,
4453
+ * and calls `POST /api/auth/device/code`.
4454
+ *
4455
+ * Display `userCode` (large, monospace) **and** `verificationCode`, then call
4456
+ * {@link waitForDevicePairing}. The verification code returned here is
4457
+ * computed locally from this device's own public key — the server also
4458
+ * returns a copy, which is ignored on purpose: trusting it would forfeit the
4459
+ * entire MITM binding (spec §6.1, §10.1).
4460
+ */
4461
+ async startDevicePairing(opts) {
4462
+ if (!opts?.appId)
4463
+ throw new DevicePairingError("error", { message: "startDevicePairing: `appId` is required." });
4464
+ const pairing = await generateDevicePairingKeypair();
4465
+ const identityKey = await deviceIdentityKey();
4466
+ const deviceIdentityKeyB64 = await exportPublicKeyBase64(identityKey.publicKey);
4467
+ const issuedAt = Date.now();
4468
+ const signature = await signMessage([DEVICE_PAIR_SIG_PREFIX, opts.appId, pairing.publicKeyB64, String(issuedAt)].join("|"), identityKey.privateKey);
4469
+ const res = await this.deviceApi("POST", "/api/auth/device/code", {
4470
+ app_id: opts.appId,
4471
+ device_public_key: pairing.publicKeyB64,
4472
+ device_identity_key: deviceIdentityKeyB64,
4473
+ device_signature: signature,
4474
+ issued_at: issuedAt,
4475
+ device_label: (opts.label ?? defaultDeviceLabel()).slice(0, DEVICE_LABEL_MAX),
4476
+ });
4477
+ this.throwForStatus(res);
4478
+ const body = res.body;
4479
+ if (!body?.device_code || !body?.user_code) {
4480
+ throw new DevicePairingError("error", { message: "Device pairing start returned no code." });
4481
+ }
4482
+ const expiresIn = numberOr(body.expires_in, 600);
4483
+ const verificationUri = body.verification_uri || `${this.deps.authBaseUrl}/link`;
4484
+ return {
4485
+ deviceCode: body.device_code,
4486
+ userCode: body.user_code,
4487
+ // LOCAL derivation — never `body.verification_code`.
4488
+ verificationCode: await pairingVerificationCode(pairing.publicKeyB64),
4489
+ verificationUri,
4490
+ verificationUriComplete: body.verification_uri_complete
4491
+ || `${verificationUri}?code=${encodeURIComponent(body.user_code)}`,
4492
+ expiresAt: Date.now() + expiresIn * 1000,
4493
+ interval: numberOr(body.interval, 5),
4494
+ privateKey: pairing.privateKey,
4495
+ devicePublicKeyB64: pairing.publicKeyB64,
4496
+ };
4497
+ }
4498
+ /**
4499
+ * (Device side) One poll of `POST /api/auth/device/token`.
4500
+ *
4501
+ * On `"approved"` this does the whole tail of the flow before returning: it
4502
+ * unseals the envelope with the ephemeral private key, derives the identity,
4503
+ * **verifies the commitment matches** (spec §10.8 — mandatory, and the check
4504
+ * that makes a substituted seed loud rather than silent), mints the device's
4505
+ * OWN long-lived ZK session, registers the device via `PUT /api/auth/devices`,
4506
+ * and persists the identity for cold starts.
4507
+ *
4508
+ * Prefer {@link waitForDevicePairing}; use this only for a custom loop. A
4509
+ * transport failure REJECTS (the caller decides whether to retry); protocol
4510
+ * outcomes resolve as a status.
4511
+ */
4512
+ async pollDevicePairing(session) {
4513
+ this.assertLive(session);
4514
+ const res = await this.deviceApi("POST", "/api/auth/device/token", { device_code: session.deviceCode });
4515
+ if (res.status === 429 && res.code === "slow_down") {
4516
+ const interval = numberOr(res.body?.interval, session.interval + SLOW_DOWN_STEP_S);
4517
+ return { status: "slow_down", interval, retryAfter: res.retryAfter ?? interval };
4518
+ }
4519
+ // `expired_token` is deliberately uniform server-side for unknown /
4520
+ // expired / already-redeemed codes, so all three land here.
4521
+ if (res.status === 401 && res.code === "expired_token")
4522
+ return { status: "expired" };
4523
+ if (res.status === 403 && res.code === "access_denied")
4524
+ return { status: "denied" };
4525
+ this.throwForStatus(res);
4526
+ const body = res.body;
4527
+ if (body?.status === "pending") {
4528
+ return {
4529
+ status: "pending",
4530
+ interval: numberOr(body.interval, session.interval),
4531
+ expiresIn: numberOr(body.expires_in, Math.max(0, Math.round((session.expiresAt - Date.now()) / 1000))),
4532
+ };
4533
+ }
4534
+ if (body?.status === "denied")
4535
+ return { status: "denied" };
4536
+ if (body?.status === "expired")
4537
+ return { status: "expired" };
4538
+ if (body?.status !== "approved") {
4539
+ throw new DevicePairingError("error", { message: `Unexpected pairing status "${body?.status}".` });
4540
+ }
4541
+ if (!body.sealed_keys || !body.username || !body.commitment) {
4542
+ throw new DevicePairingError("error", { message: "Approved pairing was missing its sealed payload." });
4543
+ }
4544
+ const user = await this.adoptSealedSeed(session, {
4545
+ sealedKeys: body.sealed_keys,
4546
+ username: body.username,
4547
+ commitment: body.commitment,
4548
+ });
4549
+ return { status: "approved", user };
4550
+ }
4551
+ /**
4552
+ * (Device side) Poll to completion with the interval + `slow_down` backoff of
4553
+ * spec §9.
4554
+ *
4555
+ * The server's `interval` is authoritative: on `slow_down` the client moves to
4556
+ * `max(serverInterval, own + 5, retryAfter)` so the two can't drift into a
4557
+ * permanent slow_down loop. Sleeps carry ±10 % jitter so a rack of devices
4558
+ * restarted together doesn't synchronise, and the loop stops at `expiresAt`
4559
+ * without waiting for the server to say so.
4560
+ *
4561
+ * Resolves with the signed-in user, or rejects with {@link DevicePairingError}.
4562
+ */
4563
+ async waitForDevicePairing(session, opts = {}) {
4564
+ let interval = session.interval;
4565
+ let consecutiveNetworkErrors = 0;
4566
+ for (;;) {
4567
+ if (opts.signal?.aborted)
4568
+ throw new DevicePairingError("aborted");
4569
+ this.assertLive(session);
4570
+ const remaining = session.expiresAt - Date.now();
4571
+ if (remaining <= 0)
4572
+ throw new DevicePairingError("expired");
4573
+ opts.onTick?.(remaining, interval);
4574
+ const jitter = 1 + (Math.random() * 0.2 - 0.1);
4575
+ await this.sleep(Math.min(interval * 1000 * jitter, remaining), opts.signal);
4576
+ let result;
4577
+ try {
4578
+ result = await this.pollDevicePairing(session);
4579
+ consecutiveNetworkErrors = 0;
4580
+ }
4581
+ catch (e) {
4582
+ // A protocol verdict (denied, budget exhausted, a failed
4583
+ // commitment check) is terminal — it must NOT be swallowed by the
4584
+ // transport-retry arm the way the spec's reference loop would.
4585
+ if (e instanceof DevicePairingError)
4586
+ throw e;
4587
+ // Transport failure: a TV's Wi-Fi drops constantly, and the
4588
+ // pairing stays valid server-side until it expires. Back off.
4589
+ if (++consecutiveNetworkErrors > MAX_CONSECUTIVE_NETWORK_ERRORS) {
4590
+ throw new DevicePairingError("network", { cause: e });
4591
+ }
4592
+ interval = Math.min(interval * 2, MAX_BACKOFF_INTERVAL_S);
4593
+ continue;
4594
+ }
4595
+ switch (result.status) {
4596
+ case "pending":
4597
+ interval = result.interval; // server-authoritative
4598
+ break;
4599
+ case "slow_down":
4600
+ interval = Math.max(result.interval, interval + SLOW_DOWN_STEP_S, result.retryAfter);
4601
+ break;
4602
+ case "approved":
4603
+ return result.user;
4604
+ case "denied":
4605
+ throw new DevicePairingError("denied");
4606
+ case "expired":
4607
+ throw new DevicePairingError("expired");
4608
+ }
4609
+ }
4610
+ }
4611
+ /**
4612
+ * (Device side) Abandon an attempt. Marks the session dead so an in-flight
4613
+ * {@link waitForDevicePairing} rejects with `aborted` on its next tick, and
4614
+ * clears the device code.
4615
+ *
4616
+ * The ephemeral `CryptoKey` cannot be zeroed from JS — dropping the last
4617
+ * reference to `session` is what makes it unrecoverable, so don't keep the
4618
+ * object around. Deliberately does NOT notify the server: the pairing is
4619
+ * single-use and expires on its own, and an unauthenticated "cancel" endpoint
4620
+ * would just be another way to grief someone else's pending code.
4621
+ */
4622
+ cancelDevicePairing(session) {
4623
+ if (!session)
4624
+ return;
4625
+ cancelledPairings.add(session);
4626
+ session.deviceCode = "";
4627
+ }
4628
+ /**
4629
+ * (Device side) Cold-start path. Reads the persisted device identity,
4630
+ * re-derives the ZK identity from the stored seed, mints a fresh session, and
4631
+ * touches `PUT /api/auth/devices`.
4632
+ *
4633
+ * Returns `null` when nothing is persisted, when the blob doesn't derive its
4634
+ * own pinned commitment (corrupt/tampered storage), or when the account no
4635
+ * longer accepts the identity — call {@link startDevicePairing} then.
4636
+ */
4637
+ async resumeDeviceSession() {
4638
+ const persisted = await loadDeviceIdentity();
4639
+ if (!persisted)
4640
+ return null;
4641
+ try {
4642
+ const identity = await deriveIdentityFromSeed(persisted.seed);
4643
+ const commitment = await commitmentFor(identity);
4644
+ // Storage integrity: the seed must still derive the commitment it was
4645
+ // stored with. A mismatch means the blob was swapped, not that the
4646
+ // account changed — refuse it rather than authenticate as someone else.
4647
+ if (commitment !== persisted.commitment)
4648
+ return null;
4649
+ const user = await this.mintSession(persisted.username, identity, persisted.seed, { rememberMe: true });
4650
+ await this.touchPairedDevice();
4651
+ return user;
4652
+ }
4653
+ catch {
4654
+ return null;
4655
+ }
4656
+ }
4657
+ /** (Device side) Wipe the persisted seed, the device identity key, and the session. */
4658
+ async forgetDeviceSession() {
4659
+ await clearDeviceIdentity();
4660
+ await this.deps.session.clear();
4661
+ }
4662
+ /** (Device side) Whether a persisted device identity exists. Cheap: no crypto, no network. */
4663
+ async hasDeviceSession() {
4664
+ return hasDeviceIdentity();
4665
+ }
4666
+ // =========================================================================
4667
+ // Device pairing — approver (hosted page) side
4668
+ // =========================================================================
4669
+ /**
4670
+ * (Hosted page) Resolve a typed `user_code` into the pending request.
4671
+ * Session-authed.
4672
+ *
4673
+ * `verificationCode` is recomputed here from the returned device key — the
4674
+ * server's copy is discarded. Both screens must show independently derived
4675
+ * values or the comparison proves nothing.
4676
+ */
4677
+ async lookupDevicePairing(userCode) {
4678
+ const code = formatUserCode(canonicalUserCode(userCode));
4679
+ const res = await this.deviceApi("POST", "/api/auth/device/lookup", { user_code: code }, true);
4680
+ this.throwForStatus(res);
4681
+ const body = res.body;
4682
+ if (!body?.device_public_key) {
4683
+ throw new DevicePairingError("error", { message: "Pairing lookup returned no device key." });
4684
+ }
4685
+ const isKnown = body.is_known_device === true;
4686
+ return {
4687
+ userCode: body.user_code || code,
4688
+ devicePublicKeyB64: body.device_public_key,
4689
+ verificationCode: await pairingVerificationCode(body.device_public_key),
4690
+ deviceFingerprint: body.device_fingerprint ?? "",
4691
+ deviceLabel: body.device_label ?? "TV",
4692
+ appId: body.app_id ?? "",
4693
+ appLabel: body.app_label ?? "",
4694
+ isKnownDevice: isKnown,
4695
+ requiresReauth: body.requires_reauth ?? !isKnown,
4696
+ expiresAt: Date.now() + numberOr(body.expires_in, 0) * 1000,
4697
+ };
4698
+ }
4699
+ /**
4700
+ * (Hosted page) Seal the in-memory seed to the device's public key and post
4701
+ * the ciphertext. Requires an unlocked seed — the user just authenticated
4702
+ * here — exactly like {@link completeAuthorize}. The server stores and relays
4703
+ * the envelope verbatim and can't read it.
4704
+ *
4705
+ * Show the user the verification code and the device label FIRST, and only
4706
+ * call this on an explicit tap. Throws {@link ReauthRequiredError} when the
4707
+ * account's last authentication is too old for a new device; the page should
4708
+ * prompt for a factor and retry. A stale legal agreement arrives as
4709
+ * `DevicePairingError` with `.code === "consent_required"` and
4710
+ * `.details.version`.
4711
+ */
4712
+ async approveDevicePairing(req, opts = {}) {
4713
+ const seed = this.deps.session.seed;
4714
+ if (!this.deps.session.token || !seed) {
4715
+ throw new DevicePairingError("error", { message: "Authenticate the user before approving a device." });
4716
+ }
4717
+ if (!req?.devicePublicKeyB64) {
4718
+ throw new DevicePairingError("error", { message: "approveDevicePairing: the request has no device key." });
4719
+ }
4720
+ const code = formatUserCode(canonicalUserCode(req.userCode));
4721
+ const sealedKeys = await sealSeedToDevice(seed, req.devicePublicKeyB64);
4722
+ const res = await this.deviceApi("POST", "/api/auth/device/approve", {
4723
+ user_code: code,
4724
+ device_public_key: req.devicePublicKeyB64,
4725
+ sealed_keys: sealedKeys,
4726
+ device_label: (opts.label ?? req.deviceLabel ?? "").slice(0, DEVICE_LABEL_MAX) || undefined,
4727
+ }, true);
4728
+ this.throwForStatus(res);
4729
+ return { deviceId: String(res.body?.device_id ?? req.deviceFingerprint ?? "") };
4730
+ }
4731
+ /**
4732
+ * (Hosted page) Refuse a pairing. No re-auth and no consent gate — declining
4733
+ * must never be harder than accepting. Leaves a tombstone so the device is
4734
+ * told "declined" rather than an indistinguishable "expired".
4735
+ */
4736
+ async denyDevicePairing(userCode) {
4737
+ const code = formatUserCode(canonicalUserCode(userCode));
4738
+ const res = await this.deviceApi("POST", "/api/auth/device/deny", { user_code: code }, true);
4739
+ this.throwForStatus(res);
4740
+ }
4741
+ // =========================================================================
4742
+ // Device pairing — paired-device management
4743
+ // =========================================================================
4744
+ /**
4745
+ * The account's paired devices. Session-authed.
4746
+ *
4747
+ * UI copy note (spec §10.6): removing a device forces a full re-approval next
4748
+ * time, but be careful what you promise. It does NOT sign the device out —
4749
+ * the server returns `session_revoked: false`, and that session runs until it
4750
+ * expires — and it cannot take back the master seed the device already holds.
4751
+ * Users assume "remove" means "locked out immediately"; it does not.
4752
+ */
4753
+ async listPairedDevices() {
4754
+ const res = await this.deviceApi("GET", "/api/auth/devices", undefined, true);
4755
+ this.throwForStatus(res);
4756
+ const rows = res.body?.devices ?? [];
4757
+ return rows.map((raw) => {
4758
+ const d = raw;
4759
+ return {
4760
+ id: d.id ?? "",
4761
+ label: d.label ?? "",
4762
+ appId: d.app_id ?? "",
4763
+ pairedAt: numberOr(d.paired_at, 0),
4764
+ lastSeenAt: numberOr(d.last_seen_at, 0),
4765
+ activeSession: d.active_session === true,
4766
+ };
4767
+ });
4768
+ }
4769
+ /**
4770
+ * Un-pair a device. Session-authed.
4771
+ *
4772
+ * It stops being a "known" device, so pairing it again needs full approval
4773
+ * with a fresh factor. It does NOT end that device's current session — the
4774
+ * server reports `session_revoked: false` — and it cannot take back the
4775
+ * master seed the device already holds. Do not write UI copy promising an
4776
+ * immediate sign-out; users will assume it and be wrong.
4777
+ */
4778
+ async revokePairedDevice(id) {
4779
+ if (!id)
4780
+ throw new DevicePairingError("error", { message: "revokePairedDevice: `id` is required." });
4781
+ const res = await this.deviceApi("DELETE", "/api/auth/devices", { id }, true);
4782
+ this.throwForStatus(res);
4783
+ }
4784
+ // ---- device pairing internals -------------------------------------------
4785
+ /**
4786
+ * The whole tail of an approved pairing: unseal → derive → **verify** →
4787
+ * authenticate → register → persist. Split out of `pollDevicePairing` so the
4788
+ * ordering (and the two refusals) stay readable.
4789
+ */
4790
+ async adoptSealedSeed(session, payload) {
4791
+ let seed;
4792
+ try {
4793
+ seed = await unsealSeedFromDevice(payload.sealedKeys, session.privateKey, session.devicePublicKeyB64);
4794
+ }
4795
+ catch (e) {
4796
+ throw new DevicePairingError("commitment_mismatch", {
4797
+ message: "The sealed key material couldn't be opened on this device — pairing aborted.",
4798
+ cause: e,
4799
+ });
4800
+ }
4801
+ const identity = await deriveIdentityFromSeed(seed);
4802
+ const commitment = await commitmentFor(identity);
4803
+ // §10.8, mandatory: the seed we were handed must derive the commitment the
4804
+ // server claims. A compromised API can seal an attacker-controlled seed to
4805
+ // this device (§10.2) — this is the check that makes that loud.
4806
+ if (commitment !== payload.commitment) {
4807
+ throw new DevicePairingError("commitment_mismatch", {
4808
+ details: { expected: payload.commitment, derived: commitment },
4809
+ });
4810
+ }
4811
+ // §10.2 detection 2 — commitment pinning across re-pairs. A device that
4812
+ // was signed in as someone else must fail closed, not silently switch.
4813
+ const pinned = await loadDeviceIdentity();
4814
+ if (pinned && pinned.commitment !== commitment) {
4815
+ throw new DevicePairingError("account_mismatch", {
4816
+ details: { pinnedUsername: pinned.username, offeredUsername: payload.username },
4817
+ });
4818
+ }
4819
+ // The device mints its OWN session rather than sharing the approver's, so
4820
+ // revoking the TV doesn't sign out the phone that approved it.
4821
+ const user = await this.mintSession(payload.username, identity, seed, { rememberMe: true });
4822
+ // Both are best-effort: the user IS signed in at this point, and failing
4823
+ // the whole pairing over a bookkeeping call would be worse than degrading.
4824
+ await this.touchPairedDevice();
4825
+ try {
4826
+ await persistDeviceIdentity({ username: user.username, commitment, seed, pairedAt: Date.now() });
4827
+ }
4828
+ catch (e) {
4829
+ appLoggerWarn("device identity could not be persisted; this device will pair again after a restart", e);
4830
+ }
4831
+ return user;
4832
+ }
4833
+ /**
4834
+ * Run the standard ZK challenge → Groth16 proof → authenticate round-trip for
4835
+ * an identity derived from a seed the caller already holds, and store the
4836
+ * resulting session.
4837
+ *
4838
+ * Identical to `ZkAuth.login()`'s tail (`proveAndStore`) — same challenge,
4839
+ * same circuit, same signature — so the commitment is byte-identical to
4840
+ * `zk.login(username, password)` by construction. No new endpoint, no circuit
4841
+ * change, no alternative derivation.
4842
+ *
4843
+ * (Spec §7 puts this on `AuthNamespace` as `loginWithSeed`; see the report —
4844
+ * it lives here because `AuthNamespace.ts` was out of scope for this change,
4845
+ * and `proveAndStore` is private.)
4846
+ */
4847
+ async mintSession(username, identity, seed, opts = {}) {
4848
+ const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);
4849
+ const challenge = await this.deps.auth.getChallenge(username);
4850
+ const { proof, publicSignals, commitment } = await generateAuthProof({
4851
+ secretHex: identity.secretHex,
4852
+ saltHex: identity.saltHex,
4853
+ ecdsaPubHex,
4854
+ nonceHex: challenge.nonce,
4855
+ circuits: this.circuits(),
4856
+ });
4857
+ const signature = await signMessage(JSON.stringify(proof), identity.ecdsaKeyPair.privateKey);
4858
+ const result = await this.deps.auth.authenticate({
4859
+ challengeId: challenge.challengeId,
4860
+ proof: {
4861
+ commitment,
4862
+ // The accelerator expects the original hex nonce, not the
4863
+ // field-reduced version fed into the circuit.
4864
+ nonce: challenge.nonce,
4865
+ response: { proof, publicSignals },
4866
+ signature,
4867
+ },
4868
+ rememberMe: opts.rememberMe,
4869
+ });
4870
+ await this.deps.session.setSession({ token: result.token, username: result.username, commitment });
4871
+ this.deps.session.setIdentity(identity);
4872
+ this.deps.session.setSeed(seed);
4873
+ return { username: result.username, commitment };
4874
+ }
4875
+ /**
4876
+ * `PUT /api/auth/devices` — the device checks in after each self-login so the
4877
+ * security page can show "last seen" and revoke the right session. Never
4878
+ * creates a record (only approve does), so a 404 here is expected on a device
4879
+ * whose pairing was revoked. Best-effort by design.
4880
+ */
4881
+ async touchPairedDevice() {
4882
+ try {
4883
+ const identityKey = await deviceIdentityKey();
4884
+ const fingerprint = await deviceFingerprint();
4885
+ const issuedAt = Date.now();
4886
+ const signature = await signMessage([DEVICE_TOUCH_SIG_PREFIX, fingerprint, String(issuedAt)].join("|"), identityKey.privateKey);
4887
+ await this.deviceApi("PUT", "/api/auth/devices", {
4888
+ fingerprint,
4889
+ issued_at: issuedAt,
4890
+ device_signature: signature,
4891
+ }, true);
4892
+ }
4893
+ catch (e) {
4894
+ appLoggerWarn("device check-in failed", e);
4895
+ }
4896
+ }
4897
+ /** Reject a session that {@link cancelDevicePairing} has retired. */
4898
+ assertLive(session) {
4899
+ if (!session || cancelledPairings.has(session) || !session.deviceCode) {
4900
+ throw new DevicePairingError("aborted");
4901
+ }
4902
+ }
4903
+ sleep(ms, signal) {
4904
+ if (this.deps.sleep)
4905
+ return this.deps.sleep(ms, signal);
4906
+ return new Promise((resolve, reject) => {
4907
+ const timer = setTimeout(() => {
4908
+ signal?.removeEventListener("abort", onAbort);
4909
+ resolve();
4910
+ }, ms);
4911
+ const onAbort = () => {
4912
+ clearTimeout(timer);
4913
+ reject(new DevicePairingError("aborted"));
4914
+ };
4915
+ if (signal?.aborted)
4916
+ return onAbort();
4917
+ signal?.addEventListener("abort", onAbort, { once: true });
4918
+ });
4919
+ }
4920
+ /**
4921
+ * One round-trip to a `/api/auth/device*` endpoint. Never throws on a non-2xx
4922
+ * — the poll path has to inspect 401/403/429 itself — so callers that don't
4923
+ * want that follow up with {@link throwForStatus}.
4924
+ */
4925
+ async deviceApi(method, path, body, withSession = false) {
4926
+ const headers = {};
4927
+ if (body !== undefined)
4928
+ headers["Content-Type"] = "application/json";
4929
+ if (withSession) {
4930
+ const token = this.deps.session.token;
4931
+ if (!token)
4932
+ throw new DevicePairingError("error", { code: "unauthorized", status: 401, message: "Sign in first." });
4933
+ // X-Muhkoo-Session, not `Authorization: Bearer` — the accelerator's
4934
+ // session resolver prefers it and raw SPA fetches must use it.
4935
+ headers["X-Muhkoo-Session"] = token;
4936
+ }
4937
+ const fetchFn = this.deps.fetch ?? globalThis.fetch?.bind(globalThis);
4938
+ if (typeof fetchFn !== "function")
4939
+ throw new Error("HostedAuth: no fetch available.");
4940
+ const res = await fetchFn(`${this.apiBase()}${path}`, {
4941
+ method,
4942
+ headers,
4943
+ body: body === undefined ? undefined : JSON.stringify(body),
4944
+ });
4945
+ let parsed = null;
4946
+ try {
4947
+ parsed = await res.json();
4948
+ }
4949
+ catch { /* empty or non-JSON body */ }
4950
+ const envelope = (parsed ?? {});
4951
+ const retryAfterHeader = Number(res.headers?.get?.("Retry-After"));
4952
+ return {
4953
+ status: res.status,
4954
+ ok: res.ok,
4955
+ body: parsed,
4956
+ code: res.ok || typeof envelope.error !== "string" ? undefined : envelope.error,
4957
+ message: typeof envelope.message === "string"
4958
+ ? envelope.message
4959
+ : typeof envelope.error === "string" ? envelope.error : undefined,
4960
+ retryAfter: Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader : null,
4961
+ };
4962
+ }
4963
+ /** Turn a non-2xx device-endpoint response into the right typed error. */
4964
+ throwForStatus(res) {
4965
+ if (res.ok)
4966
+ return;
4967
+ const details = (res.body ?? undefined);
4968
+ if (res.code === "reauth_required") {
4969
+ throw new ReauthRequiredError({
4970
+ message: res.message,
4971
+ status: res.status,
4972
+ authAgeSeconds: numberOrUndefined(details?.auth_age_seconds),
4973
+ maxAgeSeconds: numberOrUndefined(details?.max_age_seconds),
4974
+ });
4975
+ }
4976
+ throw new DevicePairingError(reasonForCode(res.code, res.status), {
4977
+ message: res.message,
4978
+ code: res.code,
4979
+ status: res.status,
4980
+ retryAfter: res.retryAfter ?? undefined,
4981
+ details,
4982
+ });
4983
+ }
4984
+ /**
4985
+ * Accelerator origin for the device endpoints.
4986
+ *
4987
+ * Prefers the explicit dep. Falls back to the {@link AuthClient}'s own base
4988
+ * URL, because `AuthNamespace` builds `HostedAuth` without one today and a
4989
+ * hard-coded default would silently point a staging or local build at
4990
+ * production. Last resort: map the auth SPA host (`auth.…` → `api.…`).
4991
+ */
4992
+ apiBase() {
4993
+ const explicit = this.deps.apiBaseUrl;
4994
+ if (explicit)
4995
+ return explicit.replace(/\/+$/, "");
4996
+ const fromAuthClient = this.deps.auth?.baseUrl;
4997
+ if (typeof fromAuthClient === "string" && fromAuthClient)
4998
+ return fromAuthClient.replace(/\/+$/, "");
4999
+ try {
5000
+ const url = new URL(this.deps.authBaseUrl);
5001
+ url.hostname = url.hostname.replace(/^auth\./, "api.");
5002
+ url.pathname = "";
5003
+ return url.toString().replace(/\/+$/, "");
5004
+ }
5005
+ catch {
5006
+ throw new Error("HostedAuth: can't resolve the accelerator base URL — pass `apiBaseUrl`.");
5007
+ }
5008
+ }
5009
+ circuits() {
5010
+ return this.deps.circuits ?? defaultCircuitUrls(this.apiBase());
5011
+ }
3966
5012
  // ---- internals ----------------------------------------------------------
3967
5013
  location() {
3968
5014
  const loc = globalThis.location;
@@ -3999,6 +5045,92 @@ class HostedAuth {
3999
5045
  h.replaceState(null, "", loc.pathname);
4000
5046
  }
4001
5047
  }
5048
+ // ---- device pairing: module helpers ----------------------------------------
5049
+ /** Sessions retired by {@link HostedAuth.cancelDevicePairing}. Weak so a dropped
5050
+ * session is collectable — this must not become a leak on a device that runs
5051
+ * for months. */
5052
+ const cancelledPairings = new WeakSet();
5053
+ /**
5054
+ * Map a server error code to the reason the device's state machine branches on.
5055
+ * Codes with no dedicated reason land on `"error"` and stay readable through
5056
+ * {@link DevicePairingError.code}.
5057
+ */
5058
+ function reasonForCode(code, status) {
5059
+ switch (code) {
5060
+ case "expired_token":
5061
+ case "pairing_not_found":
5062
+ return "expired";
5063
+ case "access_denied":
5064
+ return "denied";
5065
+ case "slow_down":
5066
+ case "rate_limited":
5067
+ case "too_many_requests":
5068
+ return "rate_limited";
5069
+ case "reauth_required":
5070
+ return "reauth_required";
5071
+ case "invalid_user_code":
5072
+ return "invalid_user_code";
5073
+ default:
5074
+ return status === 429 ? "rate_limited" : "error";
5075
+ }
5076
+ }
5077
+ /**
5078
+ * Canonicalize a typed `user_code`: uppercase, drop whitespace and `-`.
5079
+ *
5080
+ * We deliberately do NOT guess (`O → 0`, `I → 1`, …). Both members of every
5081
+ * confusable pair are excluded from the alphabet, so a typed `O` is a genuine
5082
+ * misread — telling the user is more useful than silently resolving it.
5083
+ */
5084
+ function canonicalUserCode(input) {
5085
+ const code = String(input ?? "").toUpperCase().replace(/[\s-]/g, "");
5086
+ if (code.length !== PAIRING_CODE_LENGTH)
5087
+ throw new DevicePairingError("invalid_user_code");
5088
+ for (const ch of code) {
5089
+ if (!PAIRING_CODE_ALPHABET.includes(ch))
5090
+ throw new DevicePairingError("invalid_user_code");
5091
+ }
5092
+ return code;
5093
+ }
5094
+ /** Group a canonical code for display and for the wire: `"K7QD3MXR"` → `"K7QD-3MXR"`. */
5095
+ function formatUserCode(canonical) {
5096
+ const half = Math.ceil(canonical.length / 2);
5097
+ return `${canonical.slice(0, half)}-${canonical.slice(half)}`;
5098
+ }
5099
+ /** Poseidon commitment for an identity — the value the server stores. */
5100
+ async function commitmentFor(identity) {
5101
+ const ecdsaPubHex = await exportPublicKeyHex(identity.ecdsaKeyPair.publicKey);
5102
+ return buildCommitment(identity.secretHex, identity.saltHex, ecdsaPubHex);
5103
+ }
5104
+ /**
5105
+ * A label the approver can recognise, guessed from the user agent. Android TV
5106
+ * user agents are famously uninformative, so this is a coarse family name —
5107
+ * §6.4 lets the approver rename the device at approval time.
5108
+ */
5109
+ function defaultDeviceLabel() {
5110
+ const ua = globalThis.navigator?.userAgent ?? "";
5111
+ if (/AFT[A-Z]/i.test(ua))
5112
+ return "Fire TV";
5113
+ if (/Android.*TV|GoogleTV|Chromecast/i.test(ua))
5114
+ return "Android TV";
5115
+ if (/AppleTV|tvOS/i.test(ua))
5116
+ return "Apple TV";
5117
+ if (/Tizen|Web0S|WebOS|SMART-TV|BRAVIA|HbbTV|NetCast/i.test(ua))
5118
+ return "Smart TV";
5119
+ return "TV";
5120
+ }
5121
+ function numberOr(v, fallback) {
5122
+ return typeof v === "number" && Number.isFinite(v) ? v : fallback;
5123
+ }
5124
+ function numberOrUndefined(v) {
5125
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
5126
+ }
5127
+ /** Non-fatal diagnostics. The SDK logger is optional, so never let it throw. */
5128
+ function appLoggerWarn(message, err) {
5129
+ try {
5130
+ globalThis.appLogger?.warn?.(`[hosted-auth] ${message}:`, err instanceof Error ? err.message : err);
5131
+ }
5132
+ catch { /* diagnostics must never break the flow */ }
5133
+ }
4002
5134
 
4003
5135
  /**
4004
5136
  * `client.auth` — user authentication, exposed today through the `zk`
@@ -4215,7 +5347,34 @@ class ZkAuth {
4215
5347
  return { user, unlocked: true };
4216
5348
  try {
4217
5349
  const factors = await this.listFactors();
4218
- if (factors.some((f) => f.type === "passkey")) {
5350
+ // Only auto-attempt when a passkey is usable from THIS origin.
5351
+ //
5352
+ // Passkeys are per-origin, and an account's passkey may belong to a
5353
+ // different host entirely (hosted-auth enrolment records
5354
+ // `auth.muhkoo.dev`, so a user who added a passkey there is
5355
+ // mismatched on every app host). Attempting anyway means
5356
+ // `loginWithPasskey` does an unauthenticated vault read for a
5357
+ // passkey this origin doesn't have. Today that returns a decoy with
5358
+ // no `prfSalt`, so it fails the guard before touching WebAuthn — the
5359
+ // silence is incidental. Once the decoy is reshaped to be
5360
+ // indistinguishable (it must carry `prfSalt` to stop being an
5361
+ // account-enumeration oracle) that same call would sail through and
5362
+ // fire a modal `navigator.credentials.get()` at page load, on every
5363
+ // boot, for a credential that does not exist. `resume()` is awaited
5364
+ // inside every app's readiness gate, so that dialog lands on the
5365
+ // splash screen before the user has asked for anything.
5366
+ //
5367
+ // `listFactors` is session-authenticated and returns real records,
5368
+ // so decoys never appear here — this reads true rpIds.
5369
+ //
5370
+ // `passkeyUsableFromOrigin`, NOT `rpIdUsableForOrigin`: a factor
5371
+ // with no recorded rpId predates per-origin enrolment and is still
5372
+ // usable (`loginWithPasskey` resolves it as `params.rpId ?? host`).
5373
+ // The raw predicate is false for undefined, so using it here would
5374
+ // skip exactly those users — the regression that locked legacy
5375
+ // passkey holders out of production twice.
5376
+ const host = defaultRpId();
5377
+ if (factors.some((f) => f.type === "passkey" && passkeyUsableFromOrigin(f.rpId, host))) {
4219
5378
  await this.loginWithPasskey(user.username);
4220
5379
  }
4221
5380
  }
@@ -4650,7 +5809,18 @@ class AuthNamespace {
4650
5809
  hosted;
4651
5810
  constructor(deps) {
4652
5811
  this.zk = new ZkAuth(deps);
4653
- this.hosted = new HostedAuth({ auth: deps.auth, session: deps.session, authBaseUrl: deps.authBaseUrl });
5812
+ this.hosted = new HostedAuth({
5813
+ auth: deps.auth,
5814
+ session: deps.session,
5815
+ authBaseUrl: deps.authBaseUrl,
5816
+ // Forwarded explicitly so device pairing resolves the accelerator
5817
+ // origin and the circuit assets the SAME way the rest of the client
5818
+ // does. Without these, `HostedAuth` falls back to reading
5819
+ // `AuthClient.baseUrl` reflectively and to `defaultCircuitUrls`,
5820
+ // which silently ignores an app's `ClientOptions.circuits` override.
5821
+ apiBaseUrl: deps.apiBaseUrl,
5822
+ circuits: deps.circuits,
5823
+ });
4654
5824
  }
4655
5825
  /** Convenience pass-through: the currently signed-in user, or `null`. */
4656
5826
  get user() {
@@ -11530,7 +12700,11 @@ class Client {
11530
12700
  const authClient = new AuthClient({ baseUrl: this.baseUrl, fetch: this.http.fetch });
11531
12701
  const wsBaseUrl = toWsBase(this.baseUrl);
11532
12702
  const authBaseUrl = (options.authBaseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/+$/, "");
11533
- this.auth = new AuthNamespace({ auth: authClient, circuits, session: this.session, authBaseUrl });
12703
+ this.auth = new AuthNamespace({
12704
+ auth: authClient, circuits, session: this.session, authBaseUrl,
12705
+ // The accelerator origin, for `auth.hosted`'s device-pairing endpoints.
12706
+ apiBaseUrl: this.baseUrl,
12707
+ });
11534
12708
  const deferShardUpload = offlineEnabled
11535
12709
  ? (hash) => this.offline.deferShardUpload(hash)
11536
12710
  : undefined;
@@ -12488,5 +13662,5 @@ var bundledLoader = /*#__PURE__*/Object.freeze({
12488
13662
  default: loadRsWasm
12489
13663
  });
12490
13664
 
12491
- 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, PAIRING_CODE_ALPHABET, PAIRING_CODE_LENGTH, 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, generateDevicePairingKeypair, generateId, generatePkce, getIPAddress, getId, getMuhkooAppDescriptor, getSubtle, initBn128Wasm, initRsWasm, initializeCircuits, isNewer, isNumber, isOfflineCapable, isP2pCapable, isProvisional, log, manifestToStat, materializeRow, mergeMap, mergeMessage, mergeRegister, messageKey, pack, padHandle, pairingVerificationCode, 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 };
13665
+ 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, passkeyUsableFromOrigin, 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 };
12492
13666
  //# sourceMappingURL=index.js.map