@invisi-labs/primitives 1.2.0 → 1.2.2

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.
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ __export(src_exports, {
31
31
  D_IDENT: () => D_IDENT,
32
32
  D_NOTE: () => D_NOTE,
33
33
  D_NULL: () => D_NULL,
34
+ DeliveryAuthenticationError: () => DeliveryAuthenticationError,
34
35
  DeliveryDecryptionError: () => DeliveryDecryptionError,
35
36
  Detector: () => Detector,
36
37
  Disclosure: () => Disclosure,
@@ -1142,6 +1143,14 @@ function validateDeliveryCiphertext(value, kind) {
1142
1143
  return data;
1143
1144
  }
1144
1145
 
1146
+ // src/delivery/errors.ts
1147
+ var DeliveryAuthenticationError = class extends Error {
1148
+ constructor(cause) {
1149
+ super("delivery authentication failed", { cause });
1150
+ this.name = "DeliveryAuthenticationError";
1151
+ }
1152
+ };
1153
+
1145
1154
  // src/delivery/envelope.ts
1146
1155
  var import_secp256k13 = require("@noble/curves/secp256k1");
1147
1156
 
@@ -1349,7 +1358,11 @@ async function open(key, envelope, context2, headerByte, role, payloadKey = fals
1349
1358
  },
1350
1359
  aes,
1351
1360
  buffer(data.slice(62))
1352
- );
1361
+ ).catch((error) => {
1362
+ if (error instanceof Error && error.name === "OperationError")
1363
+ throw new DeliveryAuthenticationError(error);
1364
+ throw error;
1365
+ });
1353
1366
  return new Uint8Array(decrypted);
1354
1367
  } finally {
1355
1368
  localKey.fill(0);
@@ -2220,35 +2233,34 @@ var WalletAuthorization = class _WalletAuthorization {
2220
2233
 
2221
2234
  // src/wallet/wallet-object.ts
2222
2235
  var WalletAddress = class {
2223
- #address;
2236
+ #ownerAddress;
2237
+ #receivingKeys;
2224
2238
  constructor(address) {
2225
- this.#address = address;
2239
+ this.#receivingKeys = address.getReceivingKeys();
2240
+ this.#ownerAddress = address.ownerAddress;
2226
2241
  }
2227
2242
  get ownerAddress() {
2228
- return this.#address.ownerAddress;
2243
+ return this.#ownerAddress;
2229
2244
  }
2230
2245
  get viewingPublicKey() {
2231
- return this.#address.viewingPublicKey;
2246
+ return this.#receivingKeys.viewingPublicKey.slice();
2232
2247
  }
2233
2248
  get clueKey() {
2234
- return this.#address.clueKey;
2249
+ return this.#receivingKeys.clueKey.slice();
2235
2250
  }
2236
- /** Complete 0i receiving address. Owner-only wallets must first resolve their receiving keys. */
2251
+ /** Encode the complete public receiving material on demand. */
2237
2252
  getAddress() {
2238
- if (this.#address.kind !== "long") {
2239
- throw new MissingCapabilityError("resolved receiving keys");
2240
- }
2241
- return this.#address.toString();
2253
+ return encodeLongAddress({ ownerAddress: this.#ownerAddress, ...this.#receivingKeys });
2242
2254
  }
2243
2255
  getReceivingAddress() {
2244
- return this.#address;
2256
+ return ReceivingAddress.from({ ownerAddress: this.#ownerAddress, ...this.#receivingKeys });
2245
2257
  }
2246
2258
  /** Nullifiers derive from public identity and do not grant spending authority. */
2247
2259
  exportNullifier() {
2248
2260
  return NullifierCapability.fromIdentity(this.ownerAddress);
2249
2261
  }
2250
2262
  toJSON() {
2251
- return { ownerAddress: this.ownerAddress, address: this.#address.toString() };
2263
+ return { ownerAddress: this.ownerAddress, address: this.getAddress() };
2252
2264
  }
2253
2265
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2254
2266
  return this.toJSON();
@@ -2259,7 +2271,7 @@ var Wallet = class _Wallet extends WalletAddress {
2259
2271
  super(address);
2260
2272
  Object.freeze(this);
2261
2273
  }
2262
- /** Parse a complete 0i address or an EVM owner address without network access. */
2274
+ /** Parse complete 0i receiving material without network access. */
2263
2275
  static fromAddress(address) {
2264
2276
  if (typeof address !== "string" && !(address instanceof ReceivingAddress)) {
2265
2277
  throw new TypeError("expected a validated receiving address");
@@ -2358,10 +2370,25 @@ function checkedPlaintext(plaintext, codec) {
2358
2370
  throw new Error("invalid plaintext length");
2359
2371
  return plaintext.slice();
2360
2372
  }
2361
- function authenticatedDecryptor(wallet, decryptor) {
2362
- const ownerAddress = wallet.ownerAddress;
2373
+ function authenticatedDecryptor(owner2, decryptor, expectedKeys) {
2374
+ const ownerAddress = ReceivingAddress.fromIdentity(owner2).ownerAddress;
2375
+ const receivingKeys3 = expectedKeys ? {
2376
+ viewingPublicKey: expectedKeys.viewingPublicKey.slice(),
2377
+ clueKey: expectedKeys.clueKey.slice()
2378
+ } : void 0;
2363
2379
  return {
2364
2380
  ownerAddress,
2381
+ async detectCandidates(candidates) {
2382
+ if (!decryptor.detect) return candidates.map(() => "candidate");
2383
+ const result = await decryptor.detect(structuredClone(candidates));
2384
+ if (!result || BigInt(result.ownerAddress) !== BigInt(ownerAddress) || !Array.isArray(result.results) || result.results.length !== candidates.length || result.results.some(
2385
+ (value) => !["candidate", "not-recipient", "unresolved"].includes(value)
2386
+ ))
2387
+ throw new DeliveryDecryptionError(
2388
+ new Error("invalid detection batch or wrong account")
2389
+ );
2390
+ return [...result.results];
2391
+ },
2365
2392
  async decryptNote(envelope, context2) {
2366
2393
  context2 = { ...context2 };
2367
2394
  try {
@@ -2369,6 +2396,11 @@ function authenticatedDecryptor(wallet, decryptor) {
2369
2396
  const full = { ...context2, ownerAddress };
2370
2397
  const plaintext = await decryptor.decryptNote(bytes3.slice(), { ...full });
2371
2398
  if (plaintext === null) return null;
2399
+ if (!(plaintext instanceof Uint8Array)) {
2400
+ if (plaintext?.status === "authentication-failed")
2401
+ throw new DeliveryAuthenticationError();
2402
+ throw new Error("invalid decryption result");
2403
+ }
2372
2404
  const codec = deliveryCodec(bytes3[0]);
2373
2405
  if (codec.kind !== "funds") throw new Error("unexpected envelope kind");
2374
2406
  const note = codec.decode(checkedPlaintext(plaintext, codec), full);
@@ -2377,6 +2409,7 @@ function authenticatedDecryptor(wallet, decryptor) {
2377
2409
  await noteCommitment(full, note);
2378
2410
  return note;
2379
2411
  } catch (cause) {
2412
+ if (cause instanceof DeliveryAuthenticationError) throw cause;
2380
2413
  throw new DeliveryDecryptionError(cause);
2381
2414
  }
2382
2415
  },
@@ -2387,20 +2420,26 @@ function authenticatedDecryptor(wallet, decryptor) {
2387
2420
  const full = { ...context2, ownerAddress };
2388
2421
  const plaintext = await decryptor.decryptCredit(bytes3.slice(), { ...full });
2389
2422
  if (plaintext === null) return null;
2423
+ if (!(plaintext instanceof Uint8Array)) {
2424
+ if (plaintext?.status === "authentication-failed")
2425
+ throw new DeliveryAuthenticationError();
2426
+ throw new Error("invalid decryption result");
2427
+ }
2390
2428
  const codec = deliveryCodec(bytes3[0]);
2391
2429
  if (codec.kind !== "credit") throw new Error("unexpected envelope kind");
2392
2430
  const state = codec.decode(checkedPlaintext(plaintext, codec), full);
2393
2431
  const identity2 = context2.role === "owner" ? state.note.ownerWalletIdentity : state.note.spenderWalletIdentity;
2394
2432
  if (BigInt(identity2) !== BigInt(ownerAddress) || state.note.tokenAddress !== context2.tokenAddress)
2395
2433
  throw new Error("decrypted credit context mismatch");
2396
- if (wallet.getReceivingAddress().kind === "long") {
2434
+ if (receivingKeys3) {
2397
2435
  const keys = context2.role === "owner" ? state.ownerReceivingKeys : state.spenderReceivingKeys;
2398
- if ((0, import_utils6.bytesToHex)(keys.viewingPublicKey) !== (0, import_utils6.bytesToHex)(wallet.viewingPublicKey))
2436
+ if ((0, import_utils6.bytesToHex)(keys.viewingPublicKey) !== (0, import_utils6.bytesToHex)(receivingKeys3.viewingPublicKey))
2399
2437
  throw new Error("decrypted credit receiving key mismatch");
2400
2438
  }
2401
2439
  await creditCommitment(full, state.note);
2402
2440
  return state;
2403
2441
  } catch (cause) {
2442
+ if (cause instanceof DeliveryAuthenticationError) throw cause;
2404
2443
  throw new DeliveryDecryptionError(cause);
2405
2444
  }
2406
2445
  }
@@ -2511,17 +2550,24 @@ function validateWalletRequest(request) {
2511
2550
  }
2512
2551
  var retainedWallets = /* @__PURE__ */ new WeakMap();
2513
2552
  function prepareWalletRequest(wallet, id, method, params) {
2514
- if (!(wallet instanceof Wallet)) throw new TypeError("public Wallet required");
2553
+ if (!(wallet instanceof Wallet) && typeof wallet !== "string")
2554
+ throw new TypeError("ownerAddress or public Wallet required");
2555
+ const ownerAddress = ReceivingAddress.fromIdentity(
2556
+ typeof wallet === "string" ? wallet : wallet.ownerAddress
2557
+ ).ownerAddress;
2515
2558
  const request = structuredClone({
2516
2559
  version: 1,
2517
2560
  id,
2518
- ownerAddress: wallet.ownerAddress.toLowerCase(),
2561
+ ownerAddress,
2519
2562
  method,
2520
2563
  params
2521
2564
  });
2522
2565
  validateWalletRequest(request);
2523
2566
  const prepared = freeze({ request });
2524
- retainedWallets.set(prepared, wallet);
2567
+ retainedWallets.set(
2568
+ prepared,
2569
+ wallet instanceof Wallet ? { ownerAddress, viewingPublicKey: wallet.viewingPublicKey, clueKey: wallet.clueKey } : { ownerAddress }
2570
+ );
2525
2571
  return prepared;
2526
2572
  }
2527
2573
  async function acceptWalletResponse(prepared, response) {
@@ -2548,7 +2594,7 @@ async function acceptResponse(prepared, response) {
2548
2594
  walletBytes(result.clueKey, 32);
2549
2595
  if (await computeOwnerAddress(result.spendingPublicKey) !== request.ownerAddress)
2550
2596
  throw new Error("wallet public identity mismatch");
2551
- if (wallet.getReceivingAddress().kind === "long" && (walletHex(wallet.viewingPublicKey) !== result.viewingPublicKey || walletHex(wallet.clueKey) !== result.clueKey))
2597
+ if (wallet.viewingPublicKey && wallet.clueKey && (walletHex(wallet.viewingPublicKey) !== result.viewingPublicKey || walletHex(wallet.clueKey) !== result.clueKey))
2552
2598
  throw new Error("wallet receiving key mismatch");
2553
2599
  ReceivingAddress.from({
2554
2600
  ownerAddress: request.ownerAddress,
@@ -2577,10 +2623,14 @@ async function acceptResponse(prepared, response) {
2577
2623
  const typed = request;
2578
2624
  const context2 = walletDecryptionContext(typed);
2579
2625
  const plaintext = walletBytes(result.plaintext);
2580
- const viewing = authenticatedDecryptor(wallet, {
2581
- decryptNote: async () => plaintext,
2582
- decryptCredit: async () => plaintext
2583
- });
2626
+ const viewing = authenticatedDecryptor(
2627
+ request.ownerAddress,
2628
+ {
2629
+ decryptNote: async () => plaintext,
2630
+ decryptCredit: async () => plaintext
2631
+ },
2632
+ wallet.viewingPublicKey && wallet.clueKey ? { viewingPublicKey: wallet.viewingPublicKey, clueKey: wallet.clueKey } : void 0
2633
+ );
2584
2634
  return typed.method === "wallet.decryptNote" ? viewing.decryptNote(typed.params.envelope, context2) : viewing.decryptCredit(typed.params.envelope, context2);
2585
2635
  }
2586
2636
  return result;
@@ -2690,6 +2740,7 @@ function provenanceIntentHash(originalRequestHash) {
2690
2740
  D_IDENT,
2691
2741
  D_NOTE,
2692
2742
  D_NULL,
2743
+ DeliveryAuthenticationError,
2693
2744
  DeliveryDecryptionError,
2694
2745
  Detector,
2695
2746
  Disclosure,