@celo/buy-identity 0.3.1 → 0.4.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.
@@ -0,0 +1,90 @@
1
+ import type { Verification } from '@celo/buy-keystore';
2
+ import type { VerificationRequest } from './types.js';
3
+ /**
4
+ * The wire protocol between a client and a gateway that hosts the Self
5
+ * receiver for it (celo-org/cpay#63).
6
+ *
7
+ * These live in the shared package rather than beside either end because they
8
+ * describe a TRUST BOUNDARY. The gateway recovers a signature over
9
+ * `sessionMintMessage`; the client produces one. If the two strings ever drift
10
+ * the failure is a 401 with no indication that the message format is why, so
11
+ * there is exactly one definition and both sides import it.
12
+ *
13
+ * The challenge itself is deliberately NOT here: it is an HMAC under a secret
14
+ * only the gateway holds, and a client that could compute one could mint its
15
+ * own. The client receives a challenge and echoes it back, nothing more.
16
+ */
17
+ /** Where a client asks the gateway for a verification session. */
18
+ export declare const SELF_SESSION_ROUTE = "/self/session";
19
+ /** Where a client asks for a challenge to sign. */
20
+ export declare const SELF_CHALLENGE_ROUTE = "/self/session/challenge";
21
+ /** Where a verified wallet fetches its own attestation back. */
22
+ export declare const SELF_ATTESTATION_ROUTE = "/self/attestation";
23
+ /**
24
+ * What a wallet signs to mint a verification session.
25
+ *
26
+ * Domain-separated and versioned so a signature harvested here cannot be
27
+ * replayed as anything else, and bound to a CHALLENGE so it cannot be replayed
28
+ * as this either — without one the message is constant for a given
29
+ * (address, scope) and a single captured signature mints sessions forever.
30
+ */
31
+ export declare function sessionMintMessage(address: string, scope: string, challenge: string, gatewayOrigin: string): string;
32
+ /**
33
+ * What a wallet signs to fetch its own attestation back.
34
+ *
35
+ * A DIFFERENT prefix from `sessionMintMessage` on purpose. The two routes are
36
+ * signed by the same key for the same scope, so without domain separation a
37
+ * signature captured from one is a valid signature for the other.
38
+ *
39
+ * BOUND TO THE GATEWAY, which is what stops a relay. Any resource server can
40
+ * put its own URL in `selfRequirements.endpoint`, and the printed remedy tells
41
+ * the user to run `buy verify hosted --endpoint <that url>` — so a hostile one
42
+ * can proxy a real gateway's challenge, answer `verified` without any proof
43
+ * existing, and collect a signature. Without the origin in the string that
44
+ * signature is valid at the REAL gateway, and replaying it returns the
45
+ * victim's disclosed age, nationality, OFAC standing and raw proof payload.
46
+ * With it, a signature produced for one gateway is meaningless at another.
47
+ */
48
+ export declare function attestationFetchMessage(address: string, scope: string, challenge: string, gatewayOrigin: string): string;
49
+ /**
50
+ * The gateway origin a pinned receiver URL belongs to.
51
+ *
52
+ * The 402 pins the RECEIVER (`https://gw.example/self/api/verify`); the session
53
+ * and attestation routes hang off the gateway ROOT. Deriving one from the other
54
+ * means a client is never asked to configure two URLs that must agree.
55
+ */
56
+ export declare function gatewayOriginFor(receiverUrl: string): string;
57
+ export type MintedSession = {
58
+ readonly sessionId: string;
59
+ readonly endpoint: string;
60
+ readonly endpointType: VerificationRequest['endpointType'];
61
+ readonly scope: string;
62
+ readonly userDefinedData: string;
63
+ readonly disclosures?: {
64
+ readonly minimumAge?: number;
65
+ readonly ofac?: boolean;
66
+ };
67
+ };
68
+ /**
69
+ * The whole gateway handshake, with its I/O injected.
70
+ *
71
+ * Split from the command because the command's other half — resolving an
72
+ * account and loading its key — reaches the OS keyring, which a temporary
73
+ * `BUY_HOME` does NOT isolate. Everything security-relevant here is the
74
+ * protocol (which message is signed, whether a fresh challenge is taken, what
75
+ * happens when the session expires), so that part takes a `sign` function and
76
+ * can be exercised against a real gateway without touching a keychain.
77
+ */
78
+ export type HostedVerificationDeps = {
79
+ readonly origin: string;
80
+ readonly address: string;
81
+ readonly scope: string;
82
+ readonly sign: (message: string) => Promise<string>;
83
+ readonly timeoutMs: number;
84
+ readonly pollMs: number;
85
+ /** Called once the session exists, with everything a QR needs. */
86
+ readonly onSession?: (minted: MintedSession) => void | Promise<void>;
87
+ readonly now?: () => number;
88
+ readonly sleep?: (ms: number) => Promise<void>;
89
+ };
90
+ export declare function runHostedVerification(deps: HostedVerificationDeps): Promise<Verification>;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from './types.js';
2
2
  export * from './config.js';
3
3
  export * from './verify.js';
4
+ export * from './receiver.js';
5
+ export * from './hosted.js';
4
6
  export { renderQrToTerminal } from './qr.js';
package/dist/index.js CHANGED
@@ -46476,9 +46476,9 @@ function spelunk(object2, _path) {
46476
46476
 
46477
46477
  // ../../node_modules/.pnpm/ethers@6.16.0/node_modules/ethers/lib.esm/wallet/json-keystore.js
46478
46478
  var defaultPath = "m/44'/60'/0'/0/0";
46479
- function isKeystoreJson(json) {
46479
+ function isKeystoreJson(json2) {
46480
46480
  try {
46481
- const data4 = JSON.parse(json);
46481
+ const data4 = JSON.parse(json2);
46482
46482
  const version2 = data4.version != null ? parseInt(data4.version) : 0;
46483
46483
  if (version2 === 3) {
46484
46484
  return true;
@@ -46553,8 +46553,8 @@ function getDecryptKdfParams(data4) {
46553
46553
  }
46554
46554
  assertArgument(false, "unsupported key-derivation function", "kdf", kdf);
46555
46555
  }
46556
- function decryptKeystoreJsonSync(json, _password) {
46557
- const data4 = JSON.parse(json);
46556
+ function decryptKeystoreJsonSync(json2, _password) {
46557
+ const data4 = JSON.parse(json2);
46558
46558
  const password = getPassword(_password);
46559
46559
  const params = getDecryptKdfParams(data4);
46560
46560
  if (params.name === "pbkdf2") {
@@ -46574,8 +46574,8 @@ function stall3(duration) {
46574
46574
  }, duration);
46575
46575
  });
46576
46576
  }
46577
- async function decryptKeystoreJson(json, _password, progress) {
46578
- const data4 = JSON.parse(json);
46577
+ async function decryptKeystoreJson(json2, _password, progress) {
46578
+ const data4 = JSON.parse(json2);
46579
46579
  const password = getPassword(_password);
46580
46580
  const params = getDecryptKdfParams(data4);
46581
46581
  if (params.name === "pbkdf2") {
@@ -47124,9 +47124,9 @@ function getIndexedAccountPath(_index) {
47124
47124
  }
47125
47125
 
47126
47126
  // ../../node_modules/.pnpm/ethers@6.16.0/node_modules/ethers/lib.esm/wallet/json-crowdsale.js
47127
- function isCrowdsaleJson(json) {
47127
+ function isCrowdsaleJson(json2) {
47128
47128
  try {
47129
- const data4 = JSON.parse(json);
47129
+ const data4 = JSON.parse(json2);
47130
47130
  if (data4.encseed) {
47131
47131
  return true;
47132
47132
  }
@@ -47134,12 +47134,12 @@ function isCrowdsaleJson(json) {
47134
47134
  }
47135
47135
  return false;
47136
47136
  }
47137
- function decryptCrowdsaleJson(json, _password) {
47138
- const data4 = JSON.parse(json);
47137
+ function decryptCrowdsaleJson(json2, _password) {
47138
+ const data4 = JSON.parse(json2);
47139
47139
  const password = getPassword(_password);
47140
47140
  const address = getAddress(spelunk(data4, "ethaddr:string!"));
47141
47141
  const encseed = looseArrayify(spelunk(data4, "encseed:string!"));
47142
- assertArgument(encseed && encseed.length % 16 === 0, "invalid encseed", "json", json);
47142
+ assertArgument(encseed && encseed.length % 16 === 0, "invalid encseed", "json", json2);
47143
47143
  const key = getBytes(pbkdf2(password, password, 2e3, 32, "sha256")).slice(0, 16);
47144
47144
  const iv = encseed.slice(0, 16);
47145
47145
  const encryptedSeed = encseed.slice(16);
@@ -47221,16 +47221,16 @@ var Wallet = class _Wallet extends BaseWallet {
47221
47221
  * If %%progress%% is provided, it is called periodically during
47222
47222
  * decryption so that any UI can be updated.
47223
47223
  */
47224
- static async fromEncryptedJson(json, password, progress) {
47224
+ static async fromEncryptedJson(json2, password, progress) {
47225
47225
  let account = null;
47226
- if (isKeystoreJson(json)) {
47227
- account = await decryptKeystoreJson(json, password, progress);
47228
- } else if (isCrowdsaleJson(json)) {
47226
+ if (isKeystoreJson(json2)) {
47227
+ account = await decryptKeystoreJson(json2, password, progress);
47228
+ } else if (isCrowdsaleJson(json2)) {
47229
47229
  if (progress) {
47230
47230
  progress(0);
47231
47231
  await stall4(0);
47232
47232
  }
47233
- account = decryptCrowdsaleJson(json, password);
47233
+ account = decryptCrowdsaleJson(json2, password);
47234
47234
  if (progress) {
47235
47235
  progress(1);
47236
47236
  await stall4(0);
@@ -47245,12 +47245,12 @@ var Wallet = class _Wallet extends BaseWallet {
47245
47245
  * will lock up and freeze the UI during decryption, which may take
47246
47246
  * some time.
47247
47247
  */
47248
- static fromEncryptedJsonSync(json, password) {
47248
+ static fromEncryptedJsonSync(json2, password) {
47249
47249
  let account = null;
47250
- if (isKeystoreJson(json)) {
47251
- account = decryptKeystoreJsonSync(json, password);
47252
- } else if (isCrowdsaleJson(json)) {
47253
- account = decryptCrowdsaleJson(json, password);
47250
+ if (isKeystoreJson(json2)) {
47251
+ account = decryptKeystoreJsonSync(json2, password);
47252
+ } else if (isCrowdsaleJson(json2)) {
47253
+ account = decryptCrowdsaleJson(json2, password);
47254
47254
  } else {
47255
47255
  assertArgument(false, "invalid JSON wallet", "json", "[ REDACTED ]");
47256
47256
  }
@@ -48647,6 +48647,17 @@ function attributesFromDisclosures(req, disclosed) {
48647
48647
  }
48648
48648
  return attrs;
48649
48649
  }
48650
+ function decodeUserDefinedData(hex2) {
48651
+ if (hex2 === void 0) return void 0;
48652
+ const clean = hex2.startsWith("0x") ? hex2.slice(2) : hex2;
48653
+ if (clean === "") return void 0;
48654
+ if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(clean)) return void 0;
48655
+ try {
48656
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(clean, "hex"));
48657
+ } catch {
48658
+ return void 0;
48659
+ }
48660
+ }
48650
48661
  async function verifyProof(request, payload) {
48651
48662
  const configStore = new DefaultConfigStore({
48652
48663
  minimumAge: request.requirements.minimumAge,
@@ -48681,7 +48692,23 @@ async function verifyProof(request, payload) {
48681
48692
  attributes: attributesFromDisclosures(request.requirements, disclosed),
48682
48693
  proofHash: hashProof(payload),
48683
48694
  userIdentifier: result.userData?.userIdentifier,
48684
- nullifier
48695
+ nullifier,
48696
+ // Carried through from `userContextData`, whose sha256 the circuit commits
48697
+ // to as a public signal — so a value the VERIFIER placed in the request
48698
+ // comes back provably unmodified. That is what lets a receiver serving
48699
+ // many unknown callers tell which pending session a proof belongs to; a
48700
+ // single-session receiver never needed to ask, which is why this was
48701
+ // dropped on the floor until now.
48702
+ //
48703
+ // It arrives HEX-ENCODED, and it is worth being explicit about why. The
48704
+ // request side packs it with `ethers.solidityPacked([..., 'bytes'],
48705
+ // [..., toUtf8Bytes(userDefinedData)])`, and `SelfBackendVerifier` hands
48706
+ // back `userContextData.slice(128)` — the raw hex tail, undecoded and
48707
+ // unpadded. So `'session-xyz'` returns as `'73657373696f6e2d78797a'`.
48708
+ // Both forms are exposed: the hex is what an identity comparison should
48709
+ // use, and the decoded string is what everything else wants.
48710
+ userDefinedDataHex: result.userData?.userDefinedData,
48711
+ userDefinedData: decodeUserDefinedData(result.userData?.userDefinedData)
48685
48712
  };
48686
48713
  } catch (err) {
48687
48714
  return { ok: false, reason: err instanceof Error ? err.message : String(err) };
@@ -48695,6 +48722,291 @@ function buildMockResult(request) {
48695
48722
  };
48696
48723
  }
48697
48724
 
48725
+ // src/receiver.ts
48726
+ var MAX_VERIFY_BODY_BYTES = 256 * 1024;
48727
+ var DEFAULT_VERIFY_PATH = "/api/verify";
48728
+ var VerifyBodyTooLargeError = class extends Error {
48729
+ constructor() {
48730
+ super(`verification request body exceeds ${MAX_VERIFY_BODY_BYTES} bytes`);
48731
+ this.name = "VerifyBodyTooLargeError";
48732
+ }
48733
+ };
48734
+ function readVerifyBody(req) {
48735
+ const declaredLength = Number(req.headers["content-length"]);
48736
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_VERIFY_BODY_BYTES) {
48737
+ req.on("error", () => void 0);
48738
+ req.resume();
48739
+ return Promise.reject(new VerifyBodyTooLargeError());
48740
+ }
48741
+ return new Promise((resolve, reject) => {
48742
+ const chunks = [];
48743
+ let bytes2 = 0;
48744
+ let settled = false;
48745
+ const fail = (err) => {
48746
+ if (settled) return;
48747
+ settled = true;
48748
+ chunks.length = 0;
48749
+ reject(err);
48750
+ };
48751
+ req.on("data", (chunk) => {
48752
+ if (settled) return;
48753
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
48754
+ bytes2 += buffer.byteLength;
48755
+ if (bytes2 > MAX_VERIFY_BODY_BYTES) {
48756
+ chunks.length = 0;
48757
+ fail(new VerifyBodyTooLargeError());
48758
+ return;
48759
+ }
48760
+ chunks.push(buffer);
48761
+ });
48762
+ req.on("end", () => {
48763
+ if (settled) return;
48764
+ settled = true;
48765
+ resolve(Buffer.concat(chunks, bytes2).toString("utf8"));
48766
+ });
48767
+ req.on("aborted", () => fail(new Error("verification request aborted")));
48768
+ req.on("error", (err) => fail(err));
48769
+ });
48770
+ }
48771
+ function json(res, statusCode, body) {
48772
+ if (res.destroyed || res.writableEnded) return;
48773
+ res.writeHead(statusCode, { "Content-Type": "application/json" });
48774
+ res.end(JSON.stringify(body));
48775
+ }
48776
+ function createProofReceiver(options) {
48777
+ const path = options.path ?? DEFAULT_VERIFY_PATH;
48778
+ const healthPath = options.healthPath === void 0 ? "/healthz" : options.healthPath;
48779
+ return (req, res) => {
48780
+ void (async () => {
48781
+ if (healthPath !== null && req.method === "GET" && req.url === healthPath) {
48782
+ res.writeHead(200, { "Content-Type": "text/plain" });
48783
+ res.end("ok");
48784
+ return;
48785
+ }
48786
+ if (req.method !== "POST" || req.url !== path) {
48787
+ res.writeHead(404, { "Content-Type": "text/plain" });
48788
+ res.end("not found");
48789
+ return;
48790
+ }
48791
+ const request = await options.request(req);
48792
+ if (!request) {
48793
+ json(res, 503, { status: "error", result: false, reason: "receiver not ready" });
48794
+ return;
48795
+ }
48796
+ try {
48797
+ const payload = JSON.parse(await readVerifyBody(req));
48798
+ const result = await verifyProof(request, payload);
48799
+ if (!result.ok) {
48800
+ options.onProofRejected?.(result.reason);
48801
+ json(res, 200, {
48802
+ status: "error",
48803
+ result: false,
48804
+ reason: options.reasonForClient?.(result.reason) ?? result.reason
48805
+ });
48806
+ return;
48807
+ }
48808
+ const verification = {
48809
+ provider: "self.xyz",
48810
+ scope: request.scope,
48811
+ attributes: result.attributes,
48812
+ proofHash: result.proofHash,
48813
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
48814
+ endpoint: request.endpoint,
48815
+ endpointType: request.endpointType,
48816
+ proofPayload: payload,
48817
+ ...result.userIdentifier ? { userIdentifier: result.userIdentifier } : {},
48818
+ ...result.nullifier ? { nullifier: result.nullifier } : {}
48819
+ };
48820
+ const context = {
48821
+ userIdentifier: result.userIdentifier,
48822
+ nullifier: result.nullifier,
48823
+ userDefinedData: result.userDefinedData,
48824
+ userDefinedDataHex: result.userDefinedDataHex,
48825
+ payload
48826
+ };
48827
+ await options.persist(verification, context);
48828
+ if (options.onStored) {
48829
+ const notify = options.onStored;
48830
+ res.once("finish", () => notify(verification, context));
48831
+ }
48832
+ json(res, 200, { status: "success", result: true });
48833
+ } catch (err) {
48834
+ if (err instanceof VerifyBodyTooLargeError) {
48835
+ json(res, 413, { status: "error", result: false, reason: err.message });
48836
+ return;
48837
+ }
48838
+ const reason = err instanceof Error ? err.message : String(err);
48839
+ options.onHandlerError?.(reason);
48840
+ json(res, 200, {
48841
+ status: "error",
48842
+ result: false,
48843
+ reason: options.reasonForClient?.(reason) ?? reason
48844
+ });
48845
+ }
48846
+ })().catch((err) => {
48847
+ const reason = err instanceof Error ? err.message : String(err);
48848
+ options.onHandlerError?.(reason);
48849
+ if (res.headersSent) {
48850
+ if (!res.writableEnded) res.end();
48851
+ return;
48852
+ }
48853
+ json(res, 500, {
48854
+ status: "error",
48855
+ result: false,
48856
+ reason: options.reasonForClient?.(reason) ?? reason
48857
+ });
48858
+ });
48859
+ };
48860
+ }
48861
+
48862
+ // src/hosted.ts
48863
+ var SELF_SESSION_ROUTE = "/self/session";
48864
+ var SELF_CHALLENGE_ROUTE = `${SELF_SESSION_ROUTE}/challenge`;
48865
+ var SELF_ATTESTATION_ROUTE = "/self/attestation";
48866
+ function sessionMintMessage(address, scope, challenge, gatewayOrigin) {
48867
+ return `cpay-self-session:v2:${gatewayOrigin}:${address.toLowerCase()}:${scope}:${challenge}`;
48868
+ }
48869
+ function attestationFetchMessage(address, scope, challenge, gatewayOrigin) {
48870
+ return `cpay-self-fetch:v2:${gatewayOrigin}:${address.toLowerCase()}:${scope}:${challenge}`;
48871
+ }
48872
+ function gatewayOriginFor(receiverUrl) {
48873
+ return new URL(receiverUrl).origin;
48874
+ }
48875
+ var REQUEST_TIMEOUT_MS = 2e4;
48876
+ var MAX_RESPONSE_BYTES = 512 * 1024;
48877
+ async function gatewayJson(url, init2, what) {
48878
+ let res;
48879
+ try {
48880
+ res = await fetch(url, { ...init2, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
48881
+ } catch (err) {
48882
+ const failure = new Error(
48883
+ `could not reach the gateway to ${what} (${url}): ${err instanceof Error ? err.message : String(err)}`
48884
+ );
48885
+ failure.transient = true;
48886
+ throw failure;
48887
+ }
48888
+ const declared = Number(res.headers.get("content-length") ?? "0");
48889
+ if (declared > MAX_RESPONSE_BYTES) {
48890
+ throw new Error(`gateway sent an oversized response when asked to ${what}`);
48891
+ }
48892
+ const text = await res.text();
48893
+ if (text.length > MAX_RESPONSE_BYTES) {
48894
+ throw new Error(`gateway sent an oversized response when asked to ${what}`);
48895
+ }
48896
+ let body = {};
48897
+ try {
48898
+ body = text ? JSON.parse(text) : {};
48899
+ } catch {
48900
+ throw new Error(`gateway returned non-JSON when asked to ${what} (HTTP ${res.status})`);
48901
+ }
48902
+ if (!res.ok) {
48903
+ const detail = typeof body.error === "string" ? body.error : `HTTP ${res.status}`;
48904
+ const failure = new Error(`gateway refused to ${what}: ${detail}`);
48905
+ if (res.status === 429) failure.transient = true;
48906
+ throw failure;
48907
+ }
48908
+ return body;
48909
+ }
48910
+ async function signedFor(origin, address, message, sign, fallbackScope) {
48911
+ const issued = await gatewayJson(
48912
+ `${origin}${SELF_CHALLENGE_ROUTE}?address=${encodeURIComponent(address)}`,
48913
+ void 0,
48914
+ "issue a challenge"
48915
+ );
48916
+ const challenge = issued.challenge;
48917
+ if (typeof challenge !== "string") throw new Error("gateway issued no challenge");
48918
+ const scope = typeof issued.scope === "string" && issued.scope ? issued.scope : fallbackScope;
48919
+ return { challenge, signature: await sign(message(challenge, scope)), scope };
48920
+ }
48921
+ async function runHostedVerification(deps) {
48922
+ const now = deps.now ?? (() => Date.now());
48923
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
48924
+ const { scope: _mintScope, ...mintAuth } = await signedFor(
48925
+ deps.origin,
48926
+ deps.address,
48927
+ (challenge, scope) => sessionMintMessage(deps.address, scope, challenge, deps.origin),
48928
+ deps.sign,
48929
+ deps.scope
48930
+ );
48931
+ const minted = await gatewayJson(
48932
+ `${deps.origin}${SELF_SESSION_ROUTE}`,
48933
+ {
48934
+ method: "POST",
48935
+ headers: { "Content-Type": "application/json" },
48936
+ body: JSON.stringify({ address: deps.address, ...mintAuth })
48937
+ },
48938
+ "mint a verification session"
48939
+ );
48940
+ await deps.onSession?.(minted);
48941
+ const deadline = now() + deps.timeoutMs;
48942
+ let verified = false;
48943
+ while (now() < deadline) {
48944
+ await sleep(deps.pollMs);
48945
+ let polled;
48946
+ try {
48947
+ polled = await gatewayJson(
48948
+ `${deps.origin}${SELF_SESSION_ROUTE}/${minted.sessionId}`,
48949
+ void 0,
48950
+ "poll the session"
48951
+ );
48952
+ } catch (err) {
48953
+ if (err.transient) continue;
48954
+ throw err;
48955
+ }
48956
+ if (polled.status === "verified") {
48957
+ verified = true;
48958
+ break;
48959
+ }
48960
+ if (polled.status === "expired") throw new Error("the verification session expired");
48961
+ }
48962
+ if (!verified) {
48963
+ const salvaged = await collectAttestation(deps).catch(() => void 0);
48964
+ if (salvaged) return salvaged;
48965
+ throw new Error(`timed out after ${deps.timeoutMs}ms waiting for the Self proof`);
48966
+ }
48967
+ return collectAttestation(deps);
48968
+ }
48969
+ async function collectAttestation(deps) {
48970
+ const { scope: agreedScope, ...fetchAuth } = await signedFor(
48971
+ deps.origin,
48972
+ deps.address,
48973
+ (challenge, scope) => attestationFetchMessage(deps.address, scope, challenge, deps.origin),
48974
+ deps.sign,
48975
+ deps.scope
48976
+ );
48977
+ const fetched = await gatewayJson(
48978
+ `${deps.origin}${SELF_ATTESTATION_ROUTE}`,
48979
+ {
48980
+ method: "POST",
48981
+ headers: { "Content-Type": "application/json" },
48982
+ body: JSON.stringify({ address: deps.address, ...fetchAuth })
48983
+ },
48984
+ "fetch the attestation"
48985
+ );
48986
+ return checkedAttestation(fetched.attestation, deps, agreedScope);
48987
+ }
48988
+ function checkedAttestation(value, deps, scope) {
48989
+ if (typeof value !== "object" || value === null) {
48990
+ throw new Error("gateway returned no attestation");
48991
+ }
48992
+ const a = value;
48993
+ for (const field of ["provider", "scope", "proofHash", "verifiedAt"]) {
48994
+ if (typeof a[field] !== "string" || a[field] === "") {
48995
+ throw new Error(`gateway returned an attestation with no ${field}`);
48996
+ }
48997
+ }
48998
+ if (typeof a.attributes !== "object" || a.attributes === null) {
48999
+ throw new Error("gateway returned an attestation with no attributes");
49000
+ }
49001
+ if (a.scope !== scope) {
49002
+ throw new Error(`gateway returned an attestation for scope "${a.scope}", not "${scope}"`);
49003
+ }
49004
+ if ((a.userIdentifier ?? "").toLowerCase() !== deps.address.toLowerCase()) {
49005
+ throw new Error("gateway returned an attestation bound to a different address");
49006
+ }
49007
+ return a;
49008
+ }
49009
+
48698
49010
  // src/qr.ts
48699
49011
  import qrcode from "qrcode-terminal";
48700
49012
  function renderQrToTerminal(link, opts = {}) {
@@ -48703,10 +49015,23 @@ function renderQrToTerminal(link, opts = {}) {
48703
49015
  });
48704
49016
  }
48705
49017
  export {
49018
+ DEFAULT_VERIFY_PATH,
49019
+ MAX_VERIFY_BODY_BYTES,
49020
+ SELF_ATTESTATION_ROUTE,
49021
+ SELF_CHALLENGE_ROUTE,
49022
+ SELF_SESSION_ROUTE,
49023
+ VerifyBodyTooLargeError,
48706
49024
  _disclosuresFor,
49025
+ attestationFetchMessage,
48707
49026
  buildMockResult,
48708
49027
  buildVerificationLink,
49028
+ createProofReceiver,
49029
+ decodeUserDefinedData,
49030
+ gatewayOriginFor,
49031
+ readVerifyBody,
48709
49032
  renderQrToTerminal,
49033
+ runHostedVerification,
49034
+ sessionMintMessage,
48710
49035
  verifyProof
48711
49036
  };
48712
49037
  /*! Bundled license information: