@worldcoin/idkit-core 4.0.1 → 4.0.2-dev.a1a85c4

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.js CHANGED
@@ -1,7 +1,13 @@
1
+ import { keccak_256 } from '@noble/hashes/sha3';
2
+ import { hexToBytes, bytesToHex } from '@noble/hashes/utils';
3
+ import { hmac } from '@noble/hashes/hmac';
4
+ import { sha256 } from '@noble/hashes/sha2';
5
+ import { etc, sign } from '@noble/secp256k1';
6
+
1
7
  var __defProp = Object.defineProperty;
2
- var __export = (target, all2) => {
3
- for (var name in all2)
4
- __defProp(target, name, { get: all2[name], enumerable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
5
11
  };
6
12
 
7
13
  // src/types/result.ts
@@ -242,6 +248,22 @@ function _assertClass(instance, klass) {
242
248
  throw new Error(`expected instance of ${klass.name}`);
243
249
  }
244
250
  }
251
+ function createSession(app_id, rp_context, action_description, bridge_url, override_connect_base_url, environment) {
252
+ const ptr0 = passStringToWasm0(app_id, wasm.__wbindgen_export, wasm.__wbindgen_export2);
253
+ const len0 = WASM_VECTOR_LEN;
254
+ _assertClass(rp_context, RpContextWasm);
255
+ var ptr1 = rp_context.__destroy_into_raw();
256
+ var ptr2 = isLikeNone(action_description) ? 0 : passStringToWasm0(action_description, wasm.__wbindgen_export, wasm.__wbindgen_export2);
257
+ var len2 = WASM_VECTOR_LEN;
258
+ var ptr3 = isLikeNone(bridge_url) ? 0 : passStringToWasm0(bridge_url, wasm.__wbindgen_export, wasm.__wbindgen_export2);
259
+ var len3 = WASM_VECTOR_LEN;
260
+ var ptr4 = isLikeNone(override_connect_base_url) ? 0 : passStringToWasm0(override_connect_base_url, wasm.__wbindgen_export, wasm.__wbindgen_export2);
261
+ var len4 = WASM_VECTOR_LEN;
262
+ var ptr5 = isLikeNone(environment) ? 0 : passStringToWasm0(environment, wasm.__wbindgen_export, wasm.__wbindgen_export2);
263
+ var len5 = WASM_VECTOR_LEN;
264
+ const ret = wasm.createSession(ptr0, len0, ptr1, ptr2, len2, ptr3, len3, ptr4, len4, ptr5, len5);
265
+ return IDKitBuilder.__wrap(ret);
266
+ }
245
267
  function request(app_id, action, rp_context, action_description, bridge_url, allow_legacy_proofs, override_connect_base_url, environment) {
246
268
  const ptr0 = passStringToWasm0(app_id, wasm.__wbindgen_export, wasm.__wbindgen_export2);
247
269
  const len0 = WASM_VECTOR_LEN;
@@ -260,9 +282,6 @@ function request(app_id, action, rp_context, action_description, bridge_url, all
260
282
  const ret = wasm.idkitbuilder_new(ptr0, len0, ptr1, len1, ptr2, ptr3, len3, ptr4, len4, allow_legacy_proofs, ptr5, len5, ptr6, len6);
261
283
  return IDKitBuilder.__wrap(ret);
262
284
  }
263
- function init_wasm() {
264
- wasm.init_wasm();
265
- }
266
285
  function base64Decode(data) {
267
286
  try {
268
287
  const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
@@ -301,22 +320,6 @@ function proveSession(session_id, app_id, rp_context, action_description, bridge
301
320
  const ret = wasm.idkitbuilder_forProveSession(ptr0, len0, ptr1, len1, ptr2, ptr3, len3, ptr4, len4, ptr5, len5, ptr6, len6);
302
321
  return IDKitBuilder.__wrap(ret);
303
322
  }
304
- function createSession(app_id, rp_context, action_description, bridge_url, override_connect_base_url, environment) {
305
- const ptr0 = passStringToWasm0(app_id, wasm.__wbindgen_export, wasm.__wbindgen_export2);
306
- const len0 = WASM_VECTOR_LEN;
307
- _assertClass(rp_context, RpContextWasm);
308
- var ptr1 = rp_context.__destroy_into_raw();
309
- var ptr2 = isLikeNone(action_description) ? 0 : passStringToWasm0(action_description, wasm.__wbindgen_export, wasm.__wbindgen_export2);
310
- var len2 = WASM_VECTOR_LEN;
311
- var ptr3 = isLikeNone(bridge_url) ? 0 : passStringToWasm0(bridge_url, wasm.__wbindgen_export, wasm.__wbindgen_export2);
312
- var len3 = WASM_VECTOR_LEN;
313
- var ptr4 = isLikeNone(override_connect_base_url) ? 0 : passStringToWasm0(override_connect_base_url, wasm.__wbindgen_export, wasm.__wbindgen_export2);
314
- var len4 = WASM_VECTOR_LEN;
315
- var ptr5 = isLikeNone(environment) ? 0 : passStringToWasm0(environment, wasm.__wbindgen_export, wasm.__wbindgen_export2);
316
- var len5 = WASM_VECTOR_LEN;
317
- const ret = wasm.createSession(ptr0, len0, ptr1, ptr2, len2, ptr3, len3, ptr4, len4, ptr5, len5);
318
- return IDKitBuilder.__wrap(ret);
319
- }
320
323
  function passArray8ToWasm0(arg, malloc) {
321
324
  const ptr = malloc(arg.length * 1, 1) >>> 0;
322
325
  getUint8ArrayMemory0().set(arg, ptr / 1);
@@ -341,6 +344,28 @@ function base64Encode(data) {
341
344
  wasm.__wbindgen_export4(deferred2_0, deferred2_1, 1);
342
345
  }
343
346
  }
347
+ function init_wasm() {
348
+ wasm.init_wasm();
349
+ }
350
+ function signRequest(action, signing_key_hex, ttl_seconds) {
351
+ try {
352
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
353
+ const ptr0 = passStringToWasm0(action, wasm.__wbindgen_export, wasm.__wbindgen_export2);
354
+ const len0 = WASM_VECTOR_LEN;
355
+ const ptr1 = passStringToWasm0(signing_key_hex, wasm.__wbindgen_export, wasm.__wbindgen_export2);
356
+ const len1 = WASM_VECTOR_LEN;
357
+ wasm.signRequest(retptr, ptr0, len0, ptr1, len1, !isLikeNone(ttl_seconds), isLikeNone(ttl_seconds) ? BigInt(0) : ttl_seconds);
358
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
359
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
360
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
361
+ if (r2) {
362
+ throw takeObject(r1);
363
+ }
364
+ return RpSignature.__wrap(r0);
365
+ } finally {
366
+ wasm.__wbindgen_add_to_stack_pointer(16);
367
+ }
368
+ }
344
369
  function hashSignal(signal) {
345
370
  let deferred2_0;
346
371
  let deferred2_1;
@@ -366,33 +391,14 @@ function hashSignal(signal) {
366
391
  wasm.__wbindgen_export4(deferred2_0, deferred2_1, 1);
367
392
  }
368
393
  }
369
- function signRequest(action, signing_key_hex, ttl_seconds) {
370
- try {
371
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
372
- const ptr0 = passStringToWasm0(action, wasm.__wbindgen_export, wasm.__wbindgen_export2);
373
- const len0 = WASM_VECTOR_LEN;
374
- const ptr1 = passStringToWasm0(signing_key_hex, wasm.__wbindgen_export, wasm.__wbindgen_export2);
375
- const len1 = WASM_VECTOR_LEN;
376
- wasm.signRequest(retptr, ptr0, len0, ptr1, len1, !isLikeNone(ttl_seconds), isLikeNone(ttl_seconds) ? BigInt(0) : ttl_seconds);
377
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
378
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
379
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
380
- if (r2) {
381
- throw takeObject(r1);
382
- }
383
- return RpSignature.__wrap(r0);
384
- } finally {
385
- wasm.__wbindgen_add_to_stack_pointer(16);
386
- }
387
- }
388
- function __wasm_bindgen_func_elem_960(arg0, arg1, arg2) {
389
- wasm.__wasm_bindgen_func_elem_960(arg0, arg1, addHeapObject(arg2));
394
+ function __wasm_bindgen_func_elem_962(arg0, arg1, arg2) {
395
+ wasm.__wasm_bindgen_func_elem_962(arg0, arg1, addHeapObject(arg2));
390
396
  }
391
- function __wasm_bindgen_func_elem_597(arg0, arg1) {
392
- wasm.__wasm_bindgen_func_elem_597(arg0, arg1);
397
+ function __wasm_bindgen_func_elem_599(arg0, arg1) {
398
+ wasm.__wasm_bindgen_func_elem_599(arg0, arg1);
393
399
  }
394
- function __wasm_bindgen_func_elem_1343(arg0, arg1, arg2, arg3) {
395
- wasm.__wasm_bindgen_func_elem_1343(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
400
+ function __wasm_bindgen_func_elem_1347(arg0, arg1, arg2, arg3) {
401
+ wasm.__wasm_bindgen_func_elem_1347(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
396
402
  }
397
403
  var __wbindgen_enum_RequestCache = ["default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached"];
398
404
  var __wbindgen_enum_RequestCredentials = ["omit", "same-origin", "include"];
@@ -769,6 +775,34 @@ var IDKitBuilder = class _IDKitBuilder {
769
775
  const ret = wasm.idkitbuilder_constraints(ptr, addHeapObject(constraints_json));
770
776
  return takeObject(ret);
771
777
  }
778
+ /**
779
+ * Builds the native payload for constraints (synchronous, no bridge connection).
780
+ *
781
+ * Used by the native transport to get the same payload format as the bridge
782
+ * without creating a network connection.
783
+ *
784
+ * # Errors
785
+ *
786
+ * Returns an error if constraints are invalid or payload construction fails.
787
+ * @param {any} constraints_json
788
+ * @returns {any}
789
+ */
790
+ nativePayload(constraints_json) {
791
+ try {
792
+ const ptr = this.__destroy_into_raw();
793
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
794
+ wasm.idkitbuilder_nativePayload(retptr, ptr, addHeapObject(constraints_json));
795
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
796
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
797
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
798
+ if (r2) {
799
+ throw takeObject(r1);
800
+ }
801
+ return takeObject(r0);
802
+ } finally {
803
+ wasm.__wbindgen_add_to_stack_pointer(16);
804
+ }
805
+ }
772
806
  /**
773
807
  * Creates a new builder for proving an existing session
774
808
  * @param {string} session_id
@@ -824,6 +858,34 @@ var IDKitBuilder = class _IDKitBuilder {
824
858
  const ret = wasm.createSession(ptr0, len0, ptr1, ptr2, len2, ptr3, len3, ptr4, len4, ptr5, len5);
825
859
  return _IDKitBuilder.__wrap(ret);
826
860
  }
861
+ /**
862
+ * Builds the native payload from a preset (synchronous, no bridge connection).
863
+ *
864
+ * Used by the native transport to get the same payload format as the bridge
865
+ * without creating a network connection.
866
+ *
867
+ * # Errors
868
+ *
869
+ * Returns an error if the preset is invalid or payload construction fails.
870
+ * @param {any} preset_json
871
+ * @returns {any}
872
+ */
873
+ nativePayloadFromPreset(preset_json) {
874
+ try {
875
+ const ptr = this.__destroy_into_raw();
876
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
877
+ wasm.idkitbuilder_nativePayloadFromPreset(retptr, ptr, addHeapObject(preset_json));
878
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
879
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
880
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
881
+ if (r2) {
882
+ throw takeObject(r1);
883
+ }
884
+ return takeObject(r0);
885
+ } finally {
886
+ wasm.__wbindgen_add_to_stack_pointer(16);
887
+ }
888
+ }
827
889
  /**
828
890
  * Creates a new builder for uniqueness requests
829
891
  * @param {string} app_id
@@ -1499,7 +1561,7 @@ function __wbg_get_imports() {
1499
1561
  const a = state0.a;
1500
1562
  state0.a = 0;
1501
1563
  try {
1502
- return __wasm_bindgen_func_elem_1343(a, state0.b, arg02, arg12);
1564
+ return __wasm_bindgen_func_elem_1347(a, state0.b, arg02, arg12);
1503
1565
  } finally {
1504
1566
  state0.a = a;
1505
1567
  }
@@ -1712,20 +1774,20 @@ function __wbg_get_imports() {
1712
1774
  const ret = getStringFromWasm0(arg0, arg1);
1713
1775
  return addHeapObject(ret);
1714
1776
  };
1715
- imports.wbg.__wbindgen_cast_4625c577ab2ec9ee = function(arg0) {
1716
- const ret = BigInt.asUintN(64, arg0);
1777
+ imports.wbg.__wbindgen_cast_2d12912bac8cf5ca = function(arg0, arg1) {
1778
+ const ret = makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_961, __wasm_bindgen_func_elem_962);
1717
1779
  return addHeapObject(ret);
1718
1780
  };
1719
- imports.wbg.__wbindgen_cast_91c43ecf1f8dafb8 = function(arg0, arg1) {
1720
- const ret = makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_596, __wasm_bindgen_func_elem_597);
1781
+ imports.wbg.__wbindgen_cast_4625c577ab2ec9ee = function(arg0) {
1782
+ const ret = BigInt.asUintN(64, arg0);
1721
1783
  return addHeapObject(ret);
1722
1784
  };
1723
1785
  imports.wbg.__wbindgen_cast_9ae0607507abb057 = function(arg0) {
1724
1786
  const ret = arg0;
1725
1787
  return addHeapObject(ret);
1726
1788
  };
1727
- imports.wbg.__wbindgen_cast_ab10518eebecf9a3 = function(arg0, arg1) {
1728
- const ret = makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_959, __wasm_bindgen_func_elem_960);
1789
+ imports.wbg.__wbindgen_cast_b8b1061c2d0ea705 = function(arg0, arg1) {
1790
+ const ret = makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_598, __wasm_bindgen_func_elem_599);
1729
1791
  return addHeapObject(ret);
1730
1792
  };
1731
1793
  imports.wbg.__wbindgen_cast_cb9088102bce6b30 = function(arg0, arg1) {
@@ -1811,27 +1873,242 @@ async function initIDKit() {
1811
1873
  })();
1812
1874
  return wasmInitPromise;
1813
1875
  }
1814
- async function initIDKitServer() {
1815
- if (wasmInitialized) {
1816
- return;
1876
+
1877
+ // src/transports/native.ts
1878
+ var MINIAPP_VERIFY_ACTION = "miniapp-verify-action";
1879
+ function isInWorldApp() {
1880
+ return typeof window !== "undefined" && Boolean(window.WorldApp);
1881
+ }
1882
+ var _requestCounter = 0;
1883
+ var _activeNativeRequest = null;
1884
+ function createNativeRequest(wasmPayload, config, signalHashes = {}) {
1885
+ if (_activeNativeRequest?.isPending()) {
1886
+ console.warn(
1887
+ "IDKit native request already in flight. Reusing active request."
1888
+ );
1889
+ return _activeNativeRequest;
1817
1890
  }
1818
- if (wasmInitPromise) {
1819
- return wasmInitPromise;
1891
+ const request2 = new NativeIDKitRequest(wasmPayload, config, signalHashes);
1892
+ _activeNativeRequest = request2;
1893
+ return request2;
1894
+ }
1895
+ var NativeIDKitRequest = class {
1896
+ constructor(wasmPayload, config, signalHashes = {}) {
1897
+ this.connectorURI = "";
1898
+ this.resolved = false;
1899
+ this.cancelled = false;
1900
+ this.settled = false;
1901
+ this.resolvedResult = null;
1902
+ this.messageHandler = null;
1903
+ this.miniKitHandler = null;
1904
+ this.rejectFn = null;
1905
+ this.requestId = crypto.randomUUID?.() ?? `native-${Date.now()}-${++_requestCounter}`;
1906
+ this.resultPromise = new Promise((resolve, reject) => {
1907
+ this.rejectFn = reject;
1908
+ const handleIncomingPayload = (responsePayload) => {
1909
+ if (this.cancelled || this.resolved || this.settled) return;
1910
+ if (responsePayload?.status === "error") {
1911
+ this.cleanup();
1912
+ reject(
1913
+ new NativeVerifyError(
1914
+ responsePayload.error_code ?? "generic_error" /* GenericError */
1915
+ )
1916
+ );
1917
+ return;
1918
+ }
1919
+ this.resolved = true;
1920
+ const result = nativeResultToIDKitResult(
1921
+ responsePayload,
1922
+ config,
1923
+ signalHashes
1924
+ );
1925
+ this.resolvedResult = result;
1926
+ this.cleanup();
1927
+ resolve(result);
1928
+ };
1929
+ const handler = (event) => {
1930
+ const data = event.data;
1931
+ if (data?.type === MINIAPP_VERIFY_ACTION || data?.command === MINIAPP_VERIFY_ACTION) {
1932
+ handleIncomingPayload(data.payload ?? data);
1933
+ }
1934
+ };
1935
+ this.messageHandler = handler;
1936
+ window.addEventListener("message", handler);
1937
+ try {
1938
+ const miniKit = window.MiniKit;
1939
+ if (typeof miniKit?.subscribe === "function") {
1940
+ const miniKitHandler = (payload) => {
1941
+ handleIncomingPayload(payload?.payload ?? payload);
1942
+ };
1943
+ this.miniKitHandler = miniKitHandler;
1944
+ miniKit.subscribe(MINIAPP_VERIFY_ACTION, miniKitHandler);
1945
+ }
1946
+ } catch {
1947
+ }
1948
+ const sendPayload = {
1949
+ command: "verify",
1950
+ version: 2,
1951
+ payload: wasmPayload
1952
+ };
1953
+ const w = window;
1954
+ if (w.webkit?.messageHandlers?.minikit) {
1955
+ w.webkit.messageHandlers.minikit.postMessage(sendPayload);
1956
+ } else if (w.Android) {
1957
+ w.Android.postMessage(JSON.stringify(sendPayload));
1958
+ } else {
1959
+ this.cleanup();
1960
+ reject(new Error("No WebView bridge available"));
1961
+ }
1962
+ });
1963
+ this.resultPromise.catch(() => {
1964
+ }).finally(() => {
1965
+ this.settled = true;
1966
+ this.cleanup();
1967
+ if (_activeNativeRequest === this) {
1968
+ _activeNativeRequest = null;
1969
+ }
1970
+ });
1820
1971
  }
1821
- wasmInitPromise = (async () => {
1972
+ /**
1973
+ * Cancel this request. Removes the message listener so it cannot consume
1974
+ * a response meant for a later request, and rejects the pending promise.
1975
+ */
1976
+ cancel() {
1977
+ if (this.resolved || this.cancelled) return;
1978
+ this.cancelled = true;
1979
+ this.cleanup();
1980
+ this.rejectFn?.(new NativeVerifyError("cancelled" /* Cancelled */));
1981
+ if (_activeNativeRequest === this) {
1982
+ _activeNativeRequest = null;
1983
+ }
1984
+ }
1985
+ cleanup() {
1986
+ if (this.messageHandler) {
1987
+ window.removeEventListener("message", this.messageHandler);
1988
+ this.messageHandler = null;
1989
+ }
1990
+ if (this.miniKitHandler) {
1991
+ try {
1992
+ const miniKit = window.MiniKit;
1993
+ miniKit?.unsubscribe?.(MINIAPP_VERIFY_ACTION);
1994
+ } catch {
1995
+ }
1996
+ this.miniKitHandler = null;
1997
+ }
1998
+ }
1999
+ isPending() {
2000
+ return !this.settled && !this.cancelled;
2001
+ }
2002
+ async pollOnce() {
2003
+ if (this.resolved && this.resolvedResult) {
2004
+ return { type: "confirmed", result: this.resolvedResult };
2005
+ }
2006
+ return { type: "awaiting_confirmation" };
2007
+ }
2008
+ async pollUntilCompletion(options) {
2009
+ const timeout = options?.timeout ?? 3e5;
2010
+ let timeoutId;
2011
+ let abortHandler = null;
2012
+ let waiterTerminationCode = null;
1822
2013
  try {
1823
- const { readFile } = await import('fs/promises');
1824
- const { fileURLToPath } = await import('url');
1825
- const wasmUrl = new URL("idkit_wasm_bg.wasm", import.meta.url);
1826
- const wasmBuffer = await readFile(fileURLToPath(wasmUrl));
1827
- await idkit_wasm_default({ module_or_path: wasmBuffer });
1828
- wasmInitialized = true;
2014
+ const result = await Promise.race([
2015
+ this.resultPromise,
2016
+ new Promise((_, reject) => {
2017
+ if (options?.signal) {
2018
+ abortHandler = () => {
2019
+ waiterTerminationCode = "cancelled" /* Cancelled */;
2020
+ reject(new NativeVerifyError("cancelled" /* Cancelled */));
2021
+ };
2022
+ if (options.signal.aborted) {
2023
+ abortHandler();
2024
+ return;
2025
+ }
2026
+ options.signal.addEventListener("abort", abortHandler, {
2027
+ once: true
2028
+ });
2029
+ }
2030
+ timeoutId = setTimeout(() => {
2031
+ waiterTerminationCode = "timeout" /* Timeout */;
2032
+ reject(new NativeVerifyError("timeout" /* Timeout */));
2033
+ }, timeout);
2034
+ })
2035
+ ]);
2036
+ return { success: true, result };
1829
2037
  } catch (error) {
1830
- wasmInitPromise = null;
1831
- throw new Error(`Failed to initialize IDKit WASM for server: ${error}`);
2038
+ if (error instanceof NativeVerifyError) {
2039
+ if (waiterTerminationCode === error.code && this.isPending()) {
2040
+ this.cancel();
2041
+ }
2042
+ return { success: false, error: error.code };
2043
+ }
2044
+ return { success: false, error: "generic_error" /* GenericError */ };
2045
+ } finally {
2046
+ if (timeoutId) {
2047
+ clearTimeout(timeoutId);
2048
+ }
2049
+ if (options?.signal && abortHandler) {
2050
+ options.signal.removeEventListener("abort", abortHandler);
2051
+ }
1832
2052
  }
1833
- })();
1834
- return wasmInitPromise;
2053
+ }
2054
+ };
2055
+ var NativeVerifyError = class extends Error {
2056
+ constructor(code) {
2057
+ super(code);
2058
+ this.code = code;
2059
+ }
2060
+ };
2061
+ function nativeResultToIDKitResult(payload, config, signalHashes) {
2062
+ const rpNonce = config.rp_context?.nonce ?? "";
2063
+ if ("responses" in payload) {
2064
+ const v4 = payload;
2065
+ return {
2066
+ protocol_version: v4.protocol_version ?? "4.0",
2067
+ nonce: v4.nonce ?? rpNonce,
2068
+ action: v4.action ?? config.action ?? "",
2069
+ action_description: v4.action_description,
2070
+ session_id: v4.session_id,
2071
+ responses: v4.responses.map((item) => ({
2072
+ ...item,
2073
+ signal_hash: signalHashes[item.identifier]
2074
+ })),
2075
+ environment: v4.environment ?? config.environment ?? "production"
2076
+ };
2077
+ }
2078
+ if ("verifications" in payload) {
2079
+ const multi = payload;
2080
+ return {
2081
+ protocol_version: "4.0",
2082
+ nonce: rpNonce,
2083
+ action: config.action ?? "",
2084
+ responses: multi.verifications.map((v) => ({
2085
+ identifier: v.verification_level,
2086
+ signal_hash: v.signal_hash ?? signalHashes[v.verification_level],
2087
+ proof: [v.proof],
2088
+ nullifier: v.nullifier_hash,
2089
+ merkle_root: v.merkle_root,
2090
+ issuer_schema_id: 0,
2091
+ expires_at_min: 0
2092
+ })),
2093
+ environment: "production"
2094
+ };
2095
+ }
2096
+ const single = payload;
2097
+ return {
2098
+ protocol_version: "3.0",
2099
+ nonce: rpNonce,
2100
+ action: config.action ?? "",
2101
+ responses: [
2102
+ {
2103
+ identifier: single.verification_level,
2104
+ signal_hash: single.signal_hash ?? signalHashes[single.verification_level],
2105
+ proof: single.proof,
2106
+ merkle_root: single.merkle_root,
2107
+ nullifier: single.nullifier_hash
2108
+ }
2109
+ ],
2110
+ environment: "production"
2111
+ };
1835
2112
  }
1836
2113
 
1837
2114
  // src/request.ts
@@ -1875,20 +2152,6 @@ var IDKitRequestImpl = class {
1875
2152
  }
1876
2153
  }
1877
2154
  };
1878
- function CredentialRequest(credential_type, options) {
1879
- return {
1880
- type: credential_type,
1881
- signal: options?.signal,
1882
- genesis_issued_at_min: options?.genesis_issued_at_min,
1883
- expires_at_min: options?.expires_at_min
1884
- };
1885
- }
1886
- function any(...nodes) {
1887
- return { any: nodes };
1888
- }
1889
- function all(...nodes) {
1890
- return { all: nodes };
1891
- }
1892
2155
  function orbLegacy(opts = {}) {
1893
2156
  return { type: "OrbLegacy", signal: opts.signal };
1894
2157
  }
@@ -1898,48 +2161,108 @@ function secureDocumentLegacy(opts = {}) {
1898
2161
  function documentLegacy(opts = {}) {
1899
2162
  return { type: "DocumentLegacy", signal: opts.signal };
1900
2163
  }
2164
+ function createWasmBuilderFromConfig(config) {
2165
+ if (!config.rp_context) {
2166
+ throw new Error("rp_context is required for WASM bridge transport");
2167
+ }
2168
+ const rpContext = new idkit_wasm_exports.RpContextWasm(
2169
+ config.rp_context.rp_id,
2170
+ config.rp_context.nonce,
2171
+ BigInt(config.rp_context.created_at),
2172
+ BigInt(config.rp_context.expires_at),
2173
+ config.rp_context.signature
2174
+ );
2175
+ if (config.type === "request") {
2176
+ return idkit_wasm_exports.request(
2177
+ config.app_id,
2178
+ String(config.action ?? ""),
2179
+ rpContext,
2180
+ config.action_description ?? null,
2181
+ config.bridge_url ?? null,
2182
+ config.allow_legacy_proofs ?? false,
2183
+ config.override_connect_base_url ?? null,
2184
+ config.environment ?? null
2185
+ );
2186
+ }
2187
+ if (config.type === "proveSession") {
2188
+ return idkit_wasm_exports.proveSession(
2189
+ config.session_id,
2190
+ config.app_id,
2191
+ rpContext,
2192
+ config.action_description ?? null,
2193
+ config.bridge_url ?? null,
2194
+ config.override_connect_base_url ?? null,
2195
+ config.environment ?? null
2196
+ );
2197
+ }
2198
+ return idkit_wasm_exports.createSession(
2199
+ config.app_id,
2200
+ rpContext,
2201
+ config.action_description ?? null,
2202
+ config.bridge_url ?? null,
2203
+ config.override_connect_base_url ?? null,
2204
+ config.environment ?? null
2205
+ );
2206
+ }
1901
2207
  var IDKitBuilder2 = class {
1902
- constructor(wasmBuilder) {
1903
- this.wasmBuilder = wasmBuilder;
2208
+ constructor(config) {
2209
+ this.config = config;
1904
2210
  }
1905
2211
  /**
1906
2212
  * Creates an IDKit request with the given constraints
1907
2213
  *
1908
- * @param constraints - Constraint tree (CredentialRequest or any/all combinators)
2214
+ * @param constraints - Constraint tree (CredentialRequest or any/all/enumerate combinators)
1909
2215
  * @returns A new IDKitRequest instance
1910
2216
  *
1911
2217
  * @example
1912
2218
  * ```typescript
1913
- * const builder = await IDKit.request({ app_id, action, rp_context });
1914
- * const request = await builder.constraints(any(CredentialRequest('orb'), CredentialRequest('face')));
2219
+ * const request = await IDKit.request({ app_id, action, rp_context, allow_legacy_proofs: false })
2220
+ * .constraints(any(CredentialRequest('orb'), CredentialRequest('face')));
1915
2221
  * ```
1916
2222
  */
1917
- //TODO: re-enable once this is supported and World ID 4.0 is rolled out live
1918
- // async constraints(constraints: ConstraintNode): Promise<IDKitRequest> {
1919
- // await initIDKit();
1920
- // const wasmRequest = (await this.wasmBuilder.constraints(
1921
- // constraints,
1922
- // )) as unknown as WasmModule.IDKitRequest;
1923
- // return new IDKitRequestImpl(wasmRequest);
1924
- // }
2223
+ async constraints(constraints) {
2224
+ await initIDKit();
2225
+ const wasmBuilder = createWasmBuilderFromConfig(this.config);
2226
+ if (isInWorldApp()) {
2227
+ const wasmResult = wasmBuilder.nativePayload(constraints);
2228
+ return createNativeRequest(
2229
+ wasmResult.payload,
2230
+ this.config,
2231
+ wasmResult.signal_hashes ?? {}
2232
+ );
2233
+ }
2234
+ const wasmRequest = await wasmBuilder.constraints(
2235
+ constraints
2236
+ );
2237
+ return new IDKitRequestImpl(wasmRequest);
2238
+ }
1925
2239
  /**
1926
2240
  * Creates an IDKit request from a preset (works for all request types)
1927
2241
  *
1928
2242
  * Presets provide a simplified way to create requests with predefined
1929
2243
  * credential configurations.
1930
2244
  *
1931
- * @param preset - A preset object from orbLegacy()
2245
+ * @param preset - A preset object from orbLegacy(), secureDocumentLegacy(), or documentLegacy()
1932
2246
  * @returns A new IDKitRequest instance
1933
2247
  *
1934
2248
  * @example
1935
2249
  * ```typescript
1936
- * const builder = await IDKit.request({ app_id, action, rp_context });
1937
- * const request = await builder.preset(orbLegacy({ signal: 'user-123' }));
2250
+ * const request = await IDKit.request({ app_id, action, rp_context, allow_legacy_proofs: true })
2251
+ * .preset(orbLegacy({ signal: 'user-123' }));
1938
2252
  * ```
1939
2253
  */
1940
2254
  async preset(preset) {
1941
2255
  await initIDKit();
1942
- const wasmRequest = await this.wasmBuilder.preset(
2256
+ const wasmBuilder = createWasmBuilderFromConfig(this.config);
2257
+ if (isInWorldApp()) {
2258
+ const wasmResult = wasmBuilder.nativePayloadFromPreset(preset);
2259
+ return createNativeRequest(
2260
+ wasmResult.payload,
2261
+ this.config,
2262
+ wasmResult.signal_hashes ?? {}
2263
+ );
2264
+ }
2265
+ const wasmRequest = await wasmBuilder.preset(
1943
2266
  preset
1944
2267
  );
1945
2268
  return new IDKitRequestImpl(wasmRequest);
@@ -1953,101 +2276,43 @@ function createRequest(config) {
1953
2276
  throw new Error("action is required");
1954
2277
  }
1955
2278
  if (!config.rp_context) {
1956
- throw new Error("rp_context is required");
2279
+ throw new Error(
2280
+ "rp_context is required. Generate it on your backend using signRequest()."
2281
+ );
1957
2282
  }
1958
2283
  if (typeof config.allow_legacy_proofs !== "boolean") {
1959
2284
  throw new Error(
1960
2285
  "allow_legacy_proofs is required. Set to true to accept v3 proofs during migration, or false to only accept v4 proofs."
1961
2286
  );
1962
2287
  }
1963
- const rpContext = new idkit_wasm_exports.RpContextWasm(
1964
- config.rp_context.rp_id,
1965
- config.rp_context.nonce,
1966
- BigInt(config.rp_context.created_at),
1967
- BigInt(config.rp_context.expires_at),
1968
- config.rp_context.signature
1969
- );
1970
- const wasmBuilder = idkit_wasm_exports.request(
1971
- config.app_id,
1972
- String(config.action),
1973
- rpContext,
1974
- config.action_description ?? null,
1975
- config.bridge_url ?? null,
1976
- config.allow_legacy_proofs,
1977
- config.override_connect_base_url ?? null,
1978
- config.environment ?? null
1979
- );
1980
- return new IDKitBuilder2(wasmBuilder);
1981
- }
1982
- function createSession2(config) {
1983
- if (!config.app_id) {
1984
- throw new Error("app_id is required");
1985
- }
1986
- if (!config.rp_context) {
1987
- throw new Error("rp_context is required");
1988
- }
1989
- const rpContext = new idkit_wasm_exports.RpContextWasm(
1990
- config.rp_context.rp_id,
1991
- config.rp_context.nonce,
1992
- BigInt(config.rp_context.created_at),
1993
- BigInt(config.rp_context.expires_at),
1994
- config.rp_context.signature
1995
- );
1996
- const wasmBuilder = idkit_wasm_exports.createSession(
1997
- config.app_id,
1998
- rpContext,
1999
- config.action_description ?? null,
2000
- config.bridge_url ?? null,
2001
- config.override_connect_base_url ?? null,
2002
- config.environment ?? null
2003
- );
2004
- return new IDKitBuilder2(wasmBuilder);
2005
- }
2006
- function proveSession2(sessionId, config) {
2007
- if (!sessionId) {
2008
- throw new Error("session_id is required");
2009
- }
2010
- if (!config.app_id) {
2011
- throw new Error("app_id is required");
2012
- }
2013
- if (!config.rp_context) {
2014
- throw new Error("rp_context is required");
2015
- }
2016
- const rpContext = new idkit_wasm_exports.RpContextWasm(
2017
- config.rp_context.rp_id,
2018
- config.rp_context.nonce,
2019
- BigInt(config.rp_context.created_at),
2020
- BigInt(config.rp_context.expires_at),
2021
- config.rp_context.signature
2022
- );
2023
- const wasmBuilder = idkit_wasm_exports.proveSession(
2024
- sessionId,
2025
- config.app_id,
2026
- rpContext,
2027
- config.action_description ?? null,
2028
- config.bridge_url ?? null,
2029
- config.override_connect_base_url ?? null,
2030
- config.environment ?? null
2031
- );
2032
- return new IDKitBuilder2(wasmBuilder);
2288
+ return new IDKitBuilder2({
2289
+ type: "request",
2290
+ app_id: config.app_id,
2291
+ action: String(config.action),
2292
+ rp_context: config.rp_context,
2293
+ action_description: config.action_description,
2294
+ bridge_url: config.bridge_url,
2295
+ allow_legacy_proofs: config.allow_legacy_proofs,
2296
+ override_connect_base_url: config.override_connect_base_url,
2297
+ environment: config.environment
2298
+ });
2033
2299
  }
2034
2300
  var IDKit = {
2035
- /** Initialize WASM for browser environments */
2036
- init: initIDKit,
2037
- /** Initialize WASM for Node.js/server environments */
2038
- initServer: initIDKitServer,
2039
2301
  /** Create a new verification request */
2040
2302
  request: createRequest,
2041
- /** Create a new session (no action, no existing session_id) */
2042
- createSession: createSession2,
2043
- /** Prove an existing session (no action, has session_id) */
2044
- proveSession: proveSession2,
2045
- /** Create a CredentialRequest for a credential type */
2046
- CredentialRequest,
2047
- /** Create an OR constraint - at least one child must be satisfied */
2048
- any,
2049
- /** Create an AND constraint - all children must be satisfied */
2050
- all,
2303
+ // TODO: Re-enable when World ID 4.0 is live
2304
+ // /** Create a new session (no action, no existing session_id) */
2305
+ // createSession,
2306
+ // /** Prove an existing session (no action, has session_id) */
2307
+ // proveSession,
2308
+ // /** Create a CredentialRequest for a credential type */
2309
+ // CredentialRequest,
2310
+ // /** Create an OR constraint - at least one child must be satisfied */
2311
+ // any,
2312
+ // /** Create an AND constraint - all children must be satisfied */
2313
+ // all,
2314
+ // /** Create an enumerate constraint - all satisfiable children should be selected */
2315
+ // enumerate,
2051
2316
  /** Create an OrbLegacy preset for World ID 3.0 legacy support */
2052
2317
  orbLegacy,
2053
2318
  /** Create a SecureDocumentLegacy preset for World ID 3.0 legacy support */
@@ -2078,21 +2343,71 @@ var isServerEnvironment = () => {
2078
2343
  }
2079
2344
  return false;
2080
2345
  };
2346
+ function hashToField(input) {
2347
+ const hash = BigInt("0x" + bytesToHex(keccak_256(input))) >> 8n;
2348
+ return hexToBytes(hash.toString(16).padStart(64, "0"));
2349
+ }
2350
+ function hashSignal2(signal) {
2351
+ let input;
2352
+ if (signal instanceof Uint8Array) {
2353
+ input = signal;
2354
+ } else if (signal.startsWith("0x") && isValidHex(signal.slice(2))) {
2355
+ input = hexToBytes(signal.slice(2));
2356
+ } else {
2357
+ input = new TextEncoder().encode(signal);
2358
+ }
2359
+ return "0x" + bytesToHex(hashToField(input));
2360
+ }
2361
+ function isValidHex(s) {
2362
+ if (s.length === 0) return false;
2363
+ if (s.length % 2 !== 0) return false;
2364
+ return /^[0-9a-fA-F]+$/.test(s);
2365
+ }
2081
2366
 
2082
- // src/lib/rp-signature.ts
2083
- function signRequest2(action, signingKeyHex, ttlSeconds) {
2367
+ // src/lib/signing.ts
2368
+ etc.hmacSha256Sync = (key, ...msgs) => hmac(sha256, key, etc.concatBytes(...msgs));
2369
+ var DEFAULT_TTL_SEC = 300;
2370
+ function computeRpSignatureMessage(nonceBytes, createdAt, expiresAt) {
2371
+ const message = new Uint8Array(48);
2372
+ message.set(nonceBytes, 0);
2373
+ const view = new DataView(message.buffer);
2374
+ view.setBigUint64(32, BigInt(createdAt), false);
2375
+ view.setBigUint64(40, BigInt(expiresAt), false);
2376
+ return message;
2377
+ }
2378
+ function signRequest2(_action, signingKeyHex, ttl = DEFAULT_TTL_SEC) {
2084
2379
  if (!isServerEnvironment()) {
2085
2380
  throw new Error(
2086
2381
  "signRequest can only be used in Node.js environments. This function requires access to signing keys and should never be called from browser/client-side code."
2087
2382
  );
2088
2383
  }
2089
- const ttlBigInt = ttlSeconds !== void 0 ? BigInt(ttlSeconds) : void 0;
2090
- return idkit_wasm_exports.signRequest(action, signingKeyHex, ttlBigInt);
2091
- }
2092
-
2093
- // src/lib/hashing.ts
2094
- function hashSignal2(signal) {
2095
- return idkit_wasm_exports.hashSignal(signal);
2384
+ const keyHex = signingKeyHex.startsWith("0x") ? signingKeyHex.slice(2) : signingKeyHex;
2385
+ if (!/^[0-9a-fA-F]+$/.test(keyHex)) {
2386
+ throw new Error("Invalid signing key: contains non-hex characters");
2387
+ }
2388
+ if (keyHex.length !== 64) {
2389
+ throw new Error(
2390
+ `Invalid signing key: expected 32 bytes (64 hex chars), got ${keyHex.length / 2} bytes`
2391
+ );
2392
+ }
2393
+ const privKey = etc.hexToBytes(keyHex);
2394
+ const randomBytes = crypto.getRandomValues(new Uint8Array(32));
2395
+ const nonceBytes = hashToField(randomBytes);
2396
+ const createdAt = Math.floor(Date.now() / 1e3);
2397
+ const expiresAt = createdAt + ttl;
2398
+ const message = computeRpSignatureMessage(nonceBytes, createdAt, expiresAt);
2399
+ const msgHash = keccak_256(message);
2400
+ const recSig = sign(msgHash, privKey);
2401
+ const compact = recSig.toCompactRawBytes();
2402
+ const sig65 = new Uint8Array(65);
2403
+ sig65.set(compact, 0);
2404
+ sig65[64] = recSig.recovery + 27;
2405
+ return {
2406
+ sig: "0x" + bytesToHex(sig65),
2407
+ nonce: "0x" + bytesToHex(nonceBytes),
2408
+ createdAt,
2409
+ expiresAt
2410
+ };
2096
2411
  }
2097
2412
 
2098
- export { CredentialRequest, IDKit, IDKitErrorCodes, all, any, documentLegacy, hashSignal2 as hashSignal, isNode, isReactNative, isWeb, orbLegacy, secureDocumentLegacy, signRequest2 as signRequest };
2413
+ export { IDKit, IDKitErrorCodes, documentLegacy, hashSignal2 as hashSignal, isNode, isReactNative, isWeb, orbLegacy, secureDocumentLegacy, signRequest2 as signRequest };