@abraca/dabra 1.1.2 → 1.2.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.
@@ -7071,15 +7071,60 @@ const ristretto255_oprf = createORPF({
7071
7071
  /**
7072
7072
  * CryptoIdentityKeystore
7073
7073
  *
7074
- * Per-device Ed25519 keypair, private key protected by WebAuthn PRF + AES-256-GCM.
7075
- * Stored in IndexedDB under "abracadabra:identity" / "identity" / key "current".
7076
- *
7077
- * No private key is ever shared between devices. Each device generates its own
7078
- * keypair, encrypts the private key with the PRF output from its own WebAuthn
7079
- * credential, and stores the ciphertext in IndexedDB.
7080
- *
7081
- * Dependencies: @noble/ed25519, @noble/hashes (for HKDF)
7082
- */
7074
+ * Per-user Ed25519 keypair derived deterministically from a synced WebAuthn
7075
+ * passkey's PRF extension output. The same passkey on any device produces the
7076
+ * same identity — no private key storage needed.
7077
+ *
7078
+ * Derivation chain:
7079
+ * Synced Passkey PRF(constant salt) HKDF-SHA256 → Ed25519 seed → keypair
7080
+ *
7081
+ * IndexedDB is used only as a lightweight cache for the public key and
7082
+ * credential ID. Loss of IndexedDB is non-catastrophic — a passkey assertion
7083
+ * re-derives everything.
7084
+ *
7085
+ * Dependencies: @noble/ed25519, @noble/hashes (for HKDF), @noble/curves (for X25519)
7086
+ */
7087
+ /**
7088
+ * Fixed PRF eval salt. Must be constant across all devices so the same synced
7089
+ * passkey produces the same PRF output everywhere.
7090
+ *
7091
+ * Value: SHA-256("abracadabra-prf-salt-v1"), precomputed.
7092
+ */
7093
+ const PRF_SALT = new Uint8Array([
7094
+ 183,
7095
+ 121,
7096
+ 65,
7097
+ 162,
7098
+ 231,
7099
+ 133,
7100
+ 29,
7101
+ 250,
7102
+ 94,
7103
+ 193,
7104
+ 171,
7105
+ 182,
7106
+ 80,
7107
+ 26,
7108
+ 92,
7109
+ 133,
7110
+ 117,
7111
+ 253,
7112
+ 62,
7113
+ 63,
7114
+ 146,
7115
+ 201,
7116
+ 225,
7117
+ 167,
7118
+ 78,
7119
+ 186,
7120
+ 113,
7121
+ 252,
7122
+ 242,
7123
+ 177,
7124
+ 18,
7125
+ 207
7126
+ ]);
7127
+ const HKDF_INFO$2 = new TextEncoder().encode("abracadabra-identity-v1");
7083
7128
  function toBase64url(bytes) {
7084
7129
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
7085
7130
  }
@@ -7091,61 +7136,88 @@ function fromBase64url(b64) {
7091
7136
  }
7092
7137
  const DB_NAME = "abracadabra:identity";
7093
7138
  const STORE_NAME = "identity";
7094
- const RECORD_KEY = "current";
7095
- const HKDF_INFO$2 = new TextEncoder().encode("abracadabra-identity-v1");
7096
7139
  function openDb$4() {
7097
7140
  return new Promise((resolve, reject) => {
7098
- const req = indexedDB.open(DB_NAME, 1);
7141
+ const req = indexedDB.open(DB_NAME, 2);
7099
7142
  req.onupgradeneeded = () => {
7100
- req.result.createObjectStore(STORE_NAME);
7143
+ const db = req.result;
7144
+ if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
7101
7145
  };
7102
7146
  req.onsuccess = () => resolve(req.result);
7103
7147
  req.onerror = () => reject(req.error);
7104
7148
  });
7105
7149
  }
7106
- async function dbGet(db) {
7150
+ async function dbGetAll(db) {
7107
7151
  return new Promise((resolve, reject) => {
7108
- const req = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).get(RECORD_KEY);
7152
+ const store = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME);
7153
+ const results = [];
7154
+ const req = store.openCursor();
7155
+ req.onsuccess = () => {
7156
+ const cursor = req.result;
7157
+ if (cursor) {
7158
+ results.push({
7159
+ key: cursor.key,
7160
+ value: cursor.value
7161
+ });
7162
+ cursor.continue();
7163
+ } else resolve(results);
7164
+ };
7165
+ req.onerror = () => reject(req.error);
7166
+ });
7167
+ }
7168
+ async function dbGet(db, key) {
7169
+ return new Promise((resolve, reject) => {
7170
+ const req = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).get(key);
7109
7171
  req.onsuccess = () => resolve(req.result);
7110
7172
  req.onerror = () => reject(req.error);
7111
7173
  });
7112
7174
  }
7113
- async function dbPut(db, value) {
7175
+ async function dbPut(db, key, value) {
7114
7176
  return new Promise((resolve, reject) => {
7115
- const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).put(value, RECORD_KEY);
7177
+ const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).put(value, key);
7116
7178
  req.onsuccess = () => resolve();
7117
7179
  req.onerror = () => reject(req.error);
7118
7180
  });
7119
7181
  }
7120
- async function dbDelete(db) {
7182
+ async function dbClear(db) {
7121
7183
  return new Promise((resolve, reject) => {
7122
- const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).delete(RECORD_KEY);
7184
+ const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).clear();
7123
7185
  req.onsuccess = () => resolve();
7124
7186
  req.onerror = () => reject(req.error);
7125
7187
  });
7126
7188
  }
7127
- async function deriveAesKey(prfOutput, salt) {
7128
- const keyBytes = hkdf(sha256, new Uint8Array(prfOutput), salt, HKDF_INFO$2, 32);
7129
- return crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
7189
+ /** Derive a 32-byte Ed25519 seed from raw PRF output. */
7190
+ function deriveEd25519Seed(prfOutput) {
7191
+ return hkdf(sha256, new Uint8Array(prfOutput), PRF_SALT, HKDF_INFO$2, 32);
7192
+ }
7193
+ function extractPrfOutput(credential) {
7194
+ const prfOutput = credential.getClientExtensionResults()?.prf?.results?.first;
7195
+ if (!prfOutput) throw new Error("WebAuthn PRF extension not available on this authenticator. A PRF-capable platform authenticator (e.g. iCloud Keychain) is required.");
7196
+ return prfOutput;
7130
7197
  }
7131
7198
  var CryptoIdentityKeystore = class {
7132
7199
  /**
7133
- * One-time setup for a device: generates an Ed25519 keypair, creates a
7134
- * WebAuthn credential with PRF extension, encrypts the private key, and
7135
- * stores everything in IndexedDB.
7136
- *
7137
- * Returns the base64url-encoded public key. The caller must register this
7138
- * key with the server via POST /auth/register (first device) or
7139
- * POST /auth/keys (additional device).
7200
+ * Check whether the platform supports WebAuthn with PRF extension.
7201
+ * Call this before offering the "Secure with Passkey" option.
7202
+ */
7203
+ static async isPrfAvailable() {
7204
+ if (typeof window === "undefined" || !window.PublicKeyCredential) return false;
7205
+ try {
7206
+ if (!await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()) return false;
7207
+ return true;
7208
+ } catch {
7209
+ return false;
7210
+ }
7211
+ }
7212
+ /**
7213
+ * Create a synced discoverable passkey and derive the Ed25519 identity from
7214
+ * its PRF output. The passkey is stored in the platform credential manager
7215
+ * (e.g. iCloud Keychain) and syncs across devices automatically.
7140
7216
  *
7141
- * @param username - The user's account name.
7142
- * @param rpId - WebAuthn relying party ID (e.g. "example.com").
7143
- * @param rpName - Human-readable relying party name.
7217
+ * Returns the base64url-encoded public key, X25519 public key, and credential ID.
7218
+ * The caller must register the public key with the server.
7144
7219
  */
7145
7220
  async register(username, rpId, rpName) {
7146
- const privateKey = ed.utils.randomPrivateKey();
7147
- const publicKey = await ed.getPublicKeyAsync(privateKey);
7148
- const salt = crypto.getRandomValues(new Uint8Array(32));
7149
7221
  const credential = await navigator.credentials.create({ publicKey: {
7150
7222
  challenge: crypto.getRandomValues(new Uint8Array(32)),
7151
7223
  rp: {
@@ -7164,151 +7236,198 @@ var CryptoIdentityKeystore = class {
7164
7236
  alg: -257,
7165
7237
  type: "public-key"
7166
7238
  }],
7167
- authenticatorSelection: { userVerification: "required" },
7168
- extensions: { prf: { eval: { first: salt.buffer } } }
7239
+ authenticatorSelection: {
7240
+ residentKey: "required",
7241
+ requireResidentKey: true,
7242
+ userVerification: "required"
7243
+ },
7244
+ extensions: { prf: { eval: { first: PRF_SALT.buffer } } }
7169
7245
  } });
7170
- if (!credential) throw new Error("WebAuthn credential creation failed");
7171
- const prfOutput = credential.getClientExtensionResults()?.prf?.results?.first;
7172
- if (!prfOutput) throw new Error("WebAuthn PRF extension not available on this authenticator. A PRF-capable authenticator (e.g. platform authenticator with PRF support) is required.");
7173
- const aesKey = await deriveAesKey(prfOutput, salt);
7174
- const iv = crypto.getRandomValues(new Uint8Array(12));
7175
- const encryptedPrivateKey = await crypto.subtle.encrypt({
7176
- name: "AES-GCM",
7177
- iv
7178
- }, aesKey, privateKey);
7246
+ if (!credential) throw new Error("WebAuthn credential creation cancelled");
7247
+ const seed = deriveEd25519Seed(extractPrfOutput(credential));
7248
+ const publicKey = await ed.getPublicKeyAsync(seed);
7249
+ const publicKeyB64 = toBase64url(publicKey);
7250
+ const x25519PubB64 = toBase64url(ed25519.utils.toMontgomery(publicKey));
7251
+ const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
7179
7252
  const db = await openDb$4();
7180
- await dbPut(db, {
7253
+ await dbPut(db, credentialIdB64, {
7181
7254
  username,
7182
- publicKey: toBase64url(publicKey),
7183
- encryptedPrivateKey,
7184
- iv,
7185
- salt,
7255
+ publicKey: publicKeyB64,
7186
7256
  credentialId: credential.rawId
7187
7257
  });
7188
7258
  db.close();
7189
- const x25519Pub = ed25519.utils.toMontgomery(publicKey);
7259
+ seed.fill(0);
7190
7260
  return {
7191
- publicKey: toBase64url(publicKey),
7192
- x25519PublicKey: toBase64url(x25519Pub)
7261
+ publicKey: publicKeyB64,
7262
+ x25519PublicKey: x25519PubB64,
7263
+ credentialId: credentialIdB64
7193
7264
  };
7194
7265
  }
7195
7266
  /**
7196
- * Sign a base64url-encoded challenge using the stored Ed25519 private key.
7197
- *
7198
- * This triggers a WebAuthn assertion (biometric / PIN prompt) to unlock the
7199
- * private key via PRF → HKDF → AES-GCM decryption. The private key is
7200
- * wiped from memory after signing.
7267
+ * Sign a base64url-encoded challenge using the Ed25519 key derived from
7268
+ * a passkey assertion. Triggers a WebAuthn prompt (biometric / PIN).
7201
7269
  *
7202
7270
  * @param challengeB64 - base64url-encoded challenge bytes from the server.
7271
+ * @param credentialIdHint - optional credential ID to select a specific passkey.
7203
7272
  * @returns base64url-encoded Ed25519 signature (64 bytes).
7204
7273
  */
7205
- async sign(challengeB64) {
7206
- const db = await openDb$4();
7207
- const stored = await dbGet(db);
7208
- db.close();
7209
- if (!stored) throw new Error("No identity stored. Call register() first.");
7210
- const assertion = await navigator.credentials.get({ publicKey: {
7211
- challenge: crypto.getRandomValues(new Uint8Array(32)),
7212
- allowCredentials: [{
7213
- id: stored.credentialId,
7214
- type: "public-key"
7215
- }],
7216
- userVerification: "required",
7217
- extensions: { prf: { eval: { first: stored.salt.buffer } } }
7218
- } });
7219
- if (!assertion) throw new Error("WebAuthn assertion failed");
7220
- const prfOutput = assertion.getClientExtensionResults()?.prf?.results?.first;
7221
- if (!prfOutput) throw new Error("PRF output not available from authenticator");
7222
- const aesKey = await deriveAesKey(prfOutput, stored.salt);
7223
- const privateKeyBytes = await crypto.subtle.decrypt({
7224
- name: "AES-GCM",
7225
- iv: stored.iv
7226
- }, aesKey, stored.encryptedPrivateKey);
7227
- const privateKey = new Uint8Array(privateKeyBytes);
7228
- const challengeBytes = fromBase64url(challengeB64);
7229
- const signature = await ed.signAsync(challengeBytes, privateKey);
7230
- privateKey.fill(0);
7231
- return toBase64url(signature);
7232
- }
7233
- /** Returns the stored base64url public key, or null if no identity exists. */
7234
- async getPublicKey() {
7235
- const db = await openDb$4();
7236
- const stored = await dbGet(db);
7237
- db.close();
7238
- return stored?.publicKey ?? null;
7274
+ async sign(challengeB64, credentialIdHint) {
7275
+ const { seed } = await this._assertAndDerive(credentialIdHint);
7276
+ try {
7277
+ const challengeBytes = fromBase64url(challengeB64);
7278
+ return toBase64url(await ed.signAsync(challengeBytes, seed));
7279
+ } finally {
7280
+ seed.fill(0);
7281
+ }
7239
7282
  }
7240
7283
  /**
7241
- * Returns the locally-stored internal username label, or null if no identity exists.
7284
+ * Returns the cached base64url public key, or null if no identity is cached.
7242
7285
  *
7243
- * This is NOT the auth identifier (the public key is). It can be used as a
7244
- * hint when calling POST /auth/register, or displayed before the user sets
7245
- * a real display name via PATCH /users/me.
7286
+ * Does NOT trigger a WebAuthn prompt. If the cache is empty (e.g. IndexedDB
7287
+ * cleared), returns null the identity can be recovered via sign() or
7288
+ * a fresh register() with the same synced passkey.
7246
7289
  */
7247
- async getUsername() {
7290
+ async getPublicKey(credentialIdHint) {
7248
7291
  const db = await openDb$4();
7249
- const stored = await dbGet(db);
7250
- db.close();
7251
- return stored?.username ?? null;
7292
+ try {
7293
+ if (credentialIdHint) return (await dbGet(db, credentialIdHint))?.publicKey ?? null;
7294
+ const all = await dbGetAll(db);
7295
+ return all.length > 0 ? all[0].value.publicKey : null;
7296
+ } finally {
7297
+ db.close();
7298
+ }
7252
7299
  }
7253
- /** Returns true if an identity is stored in IndexedDB. */
7300
+ /**
7301
+ * Returns the locally-cached username label, or null if no identity is cached.
7302
+ */
7303
+ async getUsername(credentialIdHint) {
7304
+ const db = await openDb$4();
7305
+ try {
7306
+ if (credentialIdHint) return (await dbGet(db, credentialIdHint))?.username ?? null;
7307
+ const all = await dbGetAll(db);
7308
+ return all.length > 0 ? all[0].value.username : null;
7309
+ } finally {
7310
+ db.close();
7311
+ }
7312
+ }
7313
+ /** Returns true if an identity is cached in IndexedDB. */
7254
7314
  async hasIdentity() {
7255
7315
  const db = await openDb$4();
7256
- const stored = await dbGet(db);
7257
- db.close();
7258
- return stored !== void 0;
7316
+ try {
7317
+ return (await dbGetAll(db)).length > 0;
7318
+ } finally {
7319
+ db.close();
7320
+ }
7259
7321
  }
7260
- /** Remove the stored identity from IndexedDB. */
7322
+ /** Remove cached identity record(s) from IndexedDB. The passkey itself
7323
+ * remains in the platform credential store. */
7261
7324
  async clear() {
7262
7325
  const db = await openDb$4();
7263
- await dbDelete(db);
7326
+ await dbClear(db);
7264
7327
  db.close();
7265
7328
  }
7266
7329
  /**
7267
- * Returns the X25519 public key derived from the stored Ed25519 private key.
7268
- * Does NOT require WebAuthn — computed from the stored encrypted key... actually
7269
- * we derive from the Ed25519 public key directly (Montgomery form), no decryption needed
7270
- * since nobleEd25519Curves.utils.toMontgomery only needs the public key.
7271
- * Returns null if no identity is stored.
7330
+ * Returns the X25519 public key derived from the cached Ed25519 public key.
7331
+ * Does NOT require WebAuthn — computed from the cached public key only.
7332
+ * Returns null if no identity is cached.
7272
7333
  */
7273
7334
  async getX25519PublicKey() {
7274
7335
  const db = await openDb$4();
7275
- const stored = await dbGet(db);
7276
- db.close();
7277
- if (!stored) return null;
7278
- const edPub = fromBase64url(stored.publicKey);
7279
- return ed25519.utils.toMontgomery(edPub);
7336
+ try {
7337
+ const all = await dbGetAll(db);
7338
+ if (all.length === 0) return null;
7339
+ const edPub = fromBase64url(all[0].value.publicKey);
7340
+ return ed25519.utils.toMontgomery(edPub);
7341
+ } finally {
7342
+ db.close();
7343
+ }
7280
7344
  }
7281
7345
  /**
7282
- * Returns the X25519 private key derived from the stored Ed25519 private key.
7283
- * Requires WebAuthn assertion to decrypt the private key.
7346
+ * Returns the X25519 private key derived from the Ed25519 seed.
7347
+ * Requires a WebAuthn assertion to get the PRF output.
7284
7348
  * The caller MUST wipe the returned Uint8Array after use.
7285
7349
  */
7286
- async getX25519PrivateKey() {
7350
+ async getX25519PrivateKey(credentialIdHint) {
7351
+ const { seed } = await this._assertAndDerive(credentialIdHint);
7352
+ try {
7353
+ return ed25519.utils.toMontgomerySecret(seed);
7354
+ } finally {
7355
+ seed.fill(0);
7356
+ }
7357
+ }
7358
+ /**
7359
+ * Trigger a WebAuthn assertion to derive (or re-derive) the identity and
7360
+ * update the IndexedDB cache. Returns the public key and credential ID.
7361
+ *
7362
+ * Use this when the cache is empty but you need the public key before
7363
+ * signing (e.g. to send it to the server for the challenge request).
7364
+ */
7365
+ async deriveIdentity(credentialIdHint) {
7366
+ const { seed, publicKeyB64, credentialIdB64 } = await this._assertAndDerive(credentialIdHint);
7367
+ seed.fill(0);
7368
+ return {
7369
+ publicKey: publicKeyB64,
7370
+ credentialId: credentialIdB64
7371
+ };
7372
+ }
7373
+ /**
7374
+ * List all cached credential IDs. Useful for account switching UI.
7375
+ */
7376
+ async listCachedIdentities() {
7287
7377
  const db = await openDb$4();
7288
- const stored = await dbGet(db);
7289
- db.close();
7290
- if (!stored) throw new Error("No identity stored. Call register() first.");
7378
+ try {
7379
+ return (await dbGetAll(db)).map(({ key, value }) => ({
7380
+ credentialId: key,
7381
+ publicKey: value.publicKey,
7382
+ username: value.username
7383
+ }));
7384
+ } finally {
7385
+ db.close();
7386
+ }
7387
+ }
7388
+ /**
7389
+ * Perform a WebAuthn assertion with PRF, derive the Ed25519 seed, and
7390
+ * update the IndexedDB cache. Returns the seed (caller MUST wipe it).
7391
+ */
7392
+ async _assertAndDerive(credentialIdHint) {
7393
+ const allowCredentials = [];
7394
+ if (credentialIdHint) allowCredentials.push({
7395
+ id: fromBase64url(credentialIdHint),
7396
+ type: "public-key"
7397
+ });
7398
+ else try {
7399
+ const db = await openDb$4();
7400
+ const all = await dbGetAll(db);
7401
+ db.close();
7402
+ for (const { value } of all) allowCredentials.push({
7403
+ id: value.credentialId,
7404
+ type: "public-key"
7405
+ });
7406
+ } catch {}
7291
7407
  const assertion = await navigator.credentials.get({ publicKey: {
7292
7408
  challenge: crypto.getRandomValues(new Uint8Array(32)),
7293
- allowCredentials: [{
7294
- id: stored.credentialId,
7295
- type: "public-key"
7296
- }],
7409
+ ...allowCredentials.length > 0 ? { allowCredentials } : {},
7297
7410
  userVerification: "required",
7298
- extensions: { prf: { eval: { first: stored.salt.buffer } } }
7411
+ extensions: { prf: { eval: { first: PRF_SALT.buffer } } }
7299
7412
  } });
7300
- if (!assertion) throw new Error("WebAuthn assertion failed");
7301
- const prfOutput = assertion.getClientExtensionResults()?.prf?.results?.first;
7302
- if (!prfOutput) throw new Error("PRF output not available from authenticator");
7303
- const aesKey = await deriveAesKey(prfOutput, stored.salt);
7304
- const privateKeyBytes = await crypto.subtle.decrypt({
7305
- name: "AES-GCM",
7306
- iv: stored.iv
7307
- }, aesKey, stored.encryptedPrivateKey);
7308
- const edPrivKey = new Uint8Array(privateKeyBytes);
7309
- const x25519Priv = ed25519.utils.toMontgomerySecret(edPrivKey);
7310
- edPrivKey.fill(0);
7311
- return x25519Priv;
7413
+ if (!assertion) throw new Error("WebAuthn assertion cancelled");
7414
+ const seed = deriveEd25519Seed(extractPrfOutput(assertion));
7415
+ const publicKeyB64 = toBase64url(await ed.getPublicKeyAsync(seed));
7416
+ const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
7417
+ try {
7418
+ const db = await openDb$4();
7419
+ await dbPut(db, credentialIdB64, {
7420
+ username: (await dbGet(db, credentialIdB64))?.username ?? "",
7421
+ publicKey: publicKeyB64,
7422
+ credentialId: assertion.rawId
7423
+ });
7424
+ db.close();
7425
+ } catch {}
7426
+ return {
7427
+ seed,
7428
+ publicKeyB64,
7429
+ credentialIdB64
7430
+ };
7312
7431
  }
7313
7432
  };
7314
7433
 
@@ -8443,7 +8562,7 @@ var BackgroundSyncManager = class extends EventEmitter {
8443
8562
  concurrency: opts?.concurrency ?? 2,
8444
8563
  syncTimeout: opts?.syncTimeout ?? 15e3,
8445
8564
  prefetchFiles: opts?.prefetchFiles ?? true,
8446
- throttleMs: opts?.throttleMs ?? 50,
8565
+ throttleMs: opts?.throttleMs ?? 200,
8447
8566
  maxRetries: opts?.maxRetries ?? 2
8448
8567
  };
8449
8568
  let serverOrigin = "default";