@worldcoin/idkit-core 4.0.1 → 4.0.2-dev.6541a3e

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_959(arg0, arg1, arg2) {
395
+ wasm.__wasm_bindgen_func_elem_959(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_596(arg0, arg1) {
398
+ wasm.__wasm_bindgen_func_elem_596(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_1344(arg0, arg1, arg2, arg3) {
401
+ wasm.__wasm_bindgen_func_elem_1344(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_1344(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_958, __wasm_bindgen_func_elem_959);
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_595, __wasm_bindgen_func_elem_596);
1729
1791
  return addHeapObject(ret);
1730
1792
  };
1731
1793
  imports.wbg.__wbindgen_cast_cb9088102bce6b30 = function(arg0, arg1) {
@@ -1811,27 +1873,230 @@ 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) {
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);
1892
+ _activeNativeRequest = request2;
1893
+ return request2;
1894
+ }
1895
+ var NativeIDKitRequest = class {
1896
+ constructor(wasmPayload, config) {
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(responsePayload, config);
1921
+ this.resolvedResult = result;
1922
+ this.cleanup();
1923
+ resolve(result);
1924
+ };
1925
+ const handler = (event) => {
1926
+ const data = event.data;
1927
+ if (data?.type === MINIAPP_VERIFY_ACTION || data?.command === MINIAPP_VERIFY_ACTION) {
1928
+ handleIncomingPayload(data.payload ?? data);
1929
+ }
1930
+ };
1931
+ this.messageHandler = handler;
1932
+ window.addEventListener("message", handler);
1933
+ try {
1934
+ const miniKit = window.MiniKit;
1935
+ if (typeof miniKit?.subscribe === "function") {
1936
+ const miniKitHandler = (payload) => {
1937
+ handleIncomingPayload(payload?.payload ?? payload);
1938
+ };
1939
+ this.miniKitHandler = miniKitHandler;
1940
+ miniKit.subscribe(MINIAPP_VERIFY_ACTION, miniKitHandler);
1941
+ }
1942
+ } catch {
1943
+ }
1944
+ const sendPayload = {
1945
+ command: "verify",
1946
+ version: 2,
1947
+ payload: wasmPayload
1948
+ };
1949
+ const w = window;
1950
+ if (w.webkit?.messageHandlers?.minikit) {
1951
+ w.webkit.messageHandlers.minikit.postMessage(sendPayload);
1952
+ } else if (w.Android) {
1953
+ w.Android.postMessage(JSON.stringify(sendPayload));
1954
+ } else {
1955
+ this.cleanup();
1956
+ reject(new Error("No WebView bridge available"));
1957
+ }
1958
+ });
1959
+ this.resultPromise.catch(() => {
1960
+ }).finally(() => {
1961
+ this.settled = true;
1962
+ this.cleanup();
1963
+ if (_activeNativeRequest === this) {
1964
+ _activeNativeRequest = null;
1965
+ }
1966
+ });
1820
1967
  }
1821
- wasmInitPromise = (async () => {
1968
+ /**
1969
+ * Cancel this request. Removes the message listener so it cannot consume
1970
+ * a response meant for a later request, and rejects the pending promise.
1971
+ */
1972
+ cancel() {
1973
+ if (this.resolved || this.cancelled) return;
1974
+ this.cancelled = true;
1975
+ this.cleanup();
1976
+ this.rejectFn?.(new NativeVerifyError("cancelled" /* Cancelled */));
1977
+ if (_activeNativeRequest === this) {
1978
+ _activeNativeRequest = null;
1979
+ }
1980
+ }
1981
+ cleanup() {
1982
+ if (this.messageHandler) {
1983
+ window.removeEventListener("message", this.messageHandler);
1984
+ this.messageHandler = null;
1985
+ }
1986
+ if (this.miniKitHandler) {
1987
+ try {
1988
+ const miniKit = window.MiniKit;
1989
+ miniKit?.unsubscribe?.(MINIAPP_VERIFY_ACTION);
1990
+ } catch {
1991
+ }
1992
+ this.miniKitHandler = null;
1993
+ }
1994
+ }
1995
+ isPending() {
1996
+ return !this.settled && !this.cancelled;
1997
+ }
1998
+ async pollOnce() {
1999
+ if (this.resolved && this.resolvedResult) {
2000
+ return { type: "confirmed", result: this.resolvedResult };
2001
+ }
2002
+ return { type: "awaiting_confirmation" };
2003
+ }
2004
+ async pollUntilCompletion(options) {
2005
+ const timeout = options?.timeout ?? 3e5;
2006
+ let timeoutId;
2007
+ let abortHandler = null;
2008
+ let waiterTerminationCode = null;
1822
2009
  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;
2010
+ const result = await Promise.race([
2011
+ this.resultPromise,
2012
+ new Promise((_, reject) => {
2013
+ if (options?.signal) {
2014
+ abortHandler = () => {
2015
+ waiterTerminationCode = "cancelled" /* Cancelled */;
2016
+ reject(new NativeVerifyError("cancelled" /* Cancelled */));
2017
+ };
2018
+ if (options.signal.aborted) {
2019
+ abortHandler();
2020
+ return;
2021
+ }
2022
+ options.signal.addEventListener("abort", abortHandler, {
2023
+ once: true
2024
+ });
2025
+ }
2026
+ timeoutId = setTimeout(() => {
2027
+ waiterTerminationCode = "timeout" /* Timeout */;
2028
+ reject(new NativeVerifyError("timeout" /* Timeout */));
2029
+ }, timeout);
2030
+ })
2031
+ ]);
2032
+ return { success: true, result };
1829
2033
  } catch (error) {
1830
- wasmInitPromise = null;
1831
- throw new Error(`Failed to initialize IDKit WASM for server: ${error}`);
2034
+ if (error instanceof NativeVerifyError) {
2035
+ if (waiterTerminationCode === error.code && this.isPending()) {
2036
+ this.cancel();
2037
+ }
2038
+ return { success: false, error: error.code };
2039
+ }
2040
+ return { success: false, error: "generic_error" /* GenericError */ };
2041
+ } finally {
2042
+ if (timeoutId) {
2043
+ clearTimeout(timeoutId);
2044
+ }
2045
+ if (options?.signal && abortHandler) {
2046
+ options.signal.removeEventListener("abort", abortHandler);
2047
+ }
1832
2048
  }
1833
- })();
1834
- return wasmInitPromise;
2049
+ }
2050
+ };
2051
+ var NativeVerifyError = class extends Error {
2052
+ constructor(code) {
2053
+ super(code);
2054
+ this.code = code;
2055
+ }
2056
+ };
2057
+ function nativeResultToIDKitResult(payload, config) {
2058
+ const rpNonce = config.rp_context?.nonce ?? "";
2059
+ if ("responses" in payload && Array.isArray(payload.responses)) {
2060
+ return {
2061
+ protocol_version: payload.protocol_version ?? "4.0",
2062
+ nonce: payload.nonce ?? rpNonce,
2063
+ action: payload.action ?? config.action ?? "",
2064
+ action_description: payload.action_description,
2065
+ session_id: payload.session_id,
2066
+ responses: payload.responses,
2067
+ environment: payload.environment ?? config.environment ?? "production"
2068
+ };
2069
+ }
2070
+ if ("verifications" in payload) {
2071
+ return {
2072
+ protocol_version: "4.0",
2073
+ nonce: rpNonce,
2074
+ action: config.action ?? "",
2075
+ responses: payload.verifications.map((v) => ({
2076
+ identifier: v.verification_level,
2077
+ proof: [v.proof],
2078
+ nullifier: v.nullifier_hash,
2079
+ merkle_root: v.merkle_root,
2080
+ issuer_schema_id: 0,
2081
+ expires_at_min: 0
2082
+ })),
2083
+ environment: "production"
2084
+ };
2085
+ }
2086
+ return {
2087
+ protocol_version: "3.0",
2088
+ nonce: rpNonce,
2089
+ action: config.action ?? "",
2090
+ responses: [
2091
+ {
2092
+ identifier: payload.verification_level,
2093
+ proof: payload.proof,
2094
+ merkle_root: payload.merkle_root,
2095
+ nullifier: payload.nullifier_hash
2096
+ }
2097
+ ],
2098
+ environment: "production"
2099
+ };
1835
2100
  }
1836
2101
 
1837
2102
  // src/request.ts
@@ -1875,20 +2140,6 @@ var IDKitRequestImpl = class {
1875
2140
  }
1876
2141
  }
1877
2142
  };
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
2143
  function orbLegacy(opts = {}) {
1893
2144
  return { type: "OrbLegacy", signal: opts.signal };
1894
2145
  }
@@ -1898,48 +2149,100 @@ function secureDocumentLegacy(opts = {}) {
1898
2149
  function documentLegacy(opts = {}) {
1899
2150
  return { type: "DocumentLegacy", signal: opts.signal };
1900
2151
  }
2152
+ function createWasmBuilderFromConfig(config) {
2153
+ if (!config.rp_context) {
2154
+ throw new Error("rp_context is required for WASM bridge transport");
2155
+ }
2156
+ const rpContext = new idkit_wasm_exports.RpContextWasm(
2157
+ config.rp_context.rp_id,
2158
+ config.rp_context.nonce,
2159
+ BigInt(config.rp_context.created_at),
2160
+ BigInt(config.rp_context.expires_at),
2161
+ config.rp_context.signature
2162
+ );
2163
+ if (config.type === "request") {
2164
+ return idkit_wasm_exports.request(
2165
+ config.app_id,
2166
+ String(config.action ?? ""),
2167
+ rpContext,
2168
+ config.action_description ?? null,
2169
+ config.bridge_url ?? null,
2170
+ config.allow_legacy_proofs ?? false,
2171
+ config.override_connect_base_url ?? null,
2172
+ config.environment ?? null
2173
+ );
2174
+ }
2175
+ if (config.type === "proveSession") {
2176
+ return idkit_wasm_exports.proveSession(
2177
+ config.session_id,
2178
+ config.app_id,
2179
+ rpContext,
2180
+ config.action_description ?? null,
2181
+ config.bridge_url ?? null,
2182
+ config.override_connect_base_url ?? null,
2183
+ config.environment ?? null
2184
+ );
2185
+ }
2186
+ return idkit_wasm_exports.createSession(
2187
+ config.app_id,
2188
+ rpContext,
2189
+ config.action_description ?? null,
2190
+ config.bridge_url ?? null,
2191
+ config.override_connect_base_url ?? null,
2192
+ config.environment ?? null
2193
+ );
2194
+ }
1901
2195
  var IDKitBuilder2 = class {
1902
- constructor(wasmBuilder) {
1903
- this.wasmBuilder = wasmBuilder;
2196
+ constructor(config) {
2197
+ this.config = config;
1904
2198
  }
1905
2199
  /**
1906
2200
  * Creates an IDKit request with the given constraints
1907
2201
  *
1908
- * @param constraints - Constraint tree (CredentialRequest or any/all combinators)
2202
+ * @param constraints - Constraint tree (CredentialRequest or any/all/enumerate combinators)
1909
2203
  * @returns A new IDKitRequest instance
1910
2204
  *
1911
2205
  * @example
1912
2206
  * ```typescript
1913
- * const builder = await IDKit.request({ app_id, action, rp_context });
1914
- * const request = await builder.constraints(any(CredentialRequest('orb'), CredentialRequest('face')));
2207
+ * const request = await IDKit.request({ app_id, action, rp_context, allow_legacy_proofs: false })
2208
+ * .constraints(any(CredentialRequest('orb'), CredentialRequest('face')));
1915
2209
  * ```
1916
2210
  */
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
- // }
2211
+ async constraints(constraints) {
2212
+ await initIDKit();
2213
+ const wasmBuilder = createWasmBuilderFromConfig(this.config);
2214
+ if (isInWorldApp()) {
2215
+ const payload = wasmBuilder.nativePayload(constraints);
2216
+ return createNativeRequest(payload, this.config);
2217
+ }
2218
+ const wasmRequest = await wasmBuilder.constraints(
2219
+ constraints
2220
+ );
2221
+ return new IDKitRequestImpl(wasmRequest);
2222
+ }
1925
2223
  /**
1926
2224
  * Creates an IDKit request from a preset (works for all request types)
1927
2225
  *
1928
2226
  * Presets provide a simplified way to create requests with predefined
1929
2227
  * credential configurations.
1930
2228
  *
1931
- * @param preset - A preset object from orbLegacy()
2229
+ * @param preset - A preset object from orbLegacy(), secureDocumentLegacy(), or documentLegacy()
1932
2230
  * @returns A new IDKitRequest instance
1933
2231
  *
1934
2232
  * @example
1935
2233
  * ```typescript
1936
- * const builder = await IDKit.request({ app_id, action, rp_context });
1937
- * const request = await builder.preset(orbLegacy({ signal: 'user-123' }));
2234
+ * const request = await IDKit.request({ app_id, action, rp_context, allow_legacy_proofs: true })
2235
+ * .preset(orbLegacy({ signal: 'user-123' }));
1938
2236
  * ```
1939
2237
  */
1940
2238
  async preset(preset) {
1941
2239
  await initIDKit();
1942
- const wasmRequest = await this.wasmBuilder.preset(
2240
+ const wasmBuilder = createWasmBuilderFromConfig(this.config);
2241
+ if (isInWorldApp()) {
2242
+ const payload = wasmBuilder.nativePayloadFromPreset(preset);
2243
+ return createNativeRequest(payload, this.config);
2244
+ }
2245
+ const wasmRequest = await wasmBuilder.preset(
1943
2246
  preset
1944
2247
  );
1945
2248
  return new IDKitRequestImpl(wasmRequest);
@@ -1953,101 +2256,43 @@ function createRequest(config) {
1953
2256
  throw new Error("action is required");
1954
2257
  }
1955
2258
  if (!config.rp_context) {
1956
- throw new Error("rp_context is required");
2259
+ throw new Error(
2260
+ "rp_context is required. Generate it on your backend using signRequest()."
2261
+ );
1957
2262
  }
1958
2263
  if (typeof config.allow_legacy_proofs !== "boolean") {
1959
2264
  throw new Error(
1960
2265
  "allow_legacy_proofs is required. Set to true to accept v3 proofs during migration, or false to only accept v4 proofs."
1961
2266
  );
1962
2267
  }
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);
2268
+ return new IDKitBuilder2({
2269
+ type: "request",
2270
+ app_id: config.app_id,
2271
+ action: String(config.action),
2272
+ rp_context: config.rp_context,
2273
+ action_description: config.action_description,
2274
+ bridge_url: config.bridge_url,
2275
+ allow_legacy_proofs: config.allow_legacy_proofs,
2276
+ override_connect_base_url: config.override_connect_base_url,
2277
+ environment: config.environment
2278
+ });
2033
2279
  }
2034
2280
  var IDKit = {
2035
- /** Initialize WASM for browser environments */
2036
- init: initIDKit,
2037
- /** Initialize WASM for Node.js/server environments */
2038
- initServer: initIDKitServer,
2039
2281
  /** Create a new verification request */
2040
2282
  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,
2283
+ // TODO: Re-enable when World ID 4.0 is live
2284
+ // /** Create a new session (no action, no existing session_id) */
2285
+ // createSession,
2286
+ // /** Prove an existing session (no action, has session_id) */
2287
+ // proveSession,
2288
+ // /** Create a CredentialRequest for a credential type */
2289
+ // CredentialRequest,
2290
+ // /** Create an OR constraint - at least one child must be satisfied */
2291
+ // any,
2292
+ // /** Create an AND constraint - all children must be satisfied */
2293
+ // all,
2294
+ // /** Create an enumerate constraint - all satisfiable children should be selected */
2295
+ // enumerate,
2051
2296
  /** Create an OrbLegacy preset for World ID 3.0 legacy support */
2052
2297
  orbLegacy,
2053
2298
  /** Create a SecureDocumentLegacy preset for World ID 3.0 legacy support */
@@ -2078,21 +2323,71 @@ var isServerEnvironment = () => {
2078
2323
  }
2079
2324
  return false;
2080
2325
  };
2326
+ function hashToField(input) {
2327
+ const hash = BigInt("0x" + bytesToHex(keccak_256(input))) >> 8n;
2328
+ return hexToBytes(hash.toString(16).padStart(64, "0"));
2329
+ }
2330
+ function hashSignal2(signal) {
2331
+ let input;
2332
+ if (signal instanceof Uint8Array) {
2333
+ input = signal;
2334
+ } else if (signal.startsWith("0x") && isValidHex(signal.slice(2))) {
2335
+ input = hexToBytes(signal.slice(2));
2336
+ } else {
2337
+ input = new TextEncoder().encode(signal);
2338
+ }
2339
+ return "0x" + bytesToHex(hashToField(input));
2340
+ }
2341
+ function isValidHex(s) {
2342
+ if (s.length === 0) return false;
2343
+ if (s.length % 2 !== 0) return false;
2344
+ return /^[0-9a-fA-F]+$/.test(s);
2345
+ }
2081
2346
 
2082
- // src/lib/rp-signature.ts
2083
- function signRequest2(action, signingKeyHex, ttlSeconds) {
2347
+ // src/lib/signing.ts
2348
+ etc.hmacSha256Sync = (key, ...msgs) => hmac(sha256, key, etc.concatBytes(...msgs));
2349
+ var DEFAULT_TTL_SEC = 300;
2350
+ function computeRpSignatureMessage(nonceBytes, createdAt, expiresAt) {
2351
+ const message = new Uint8Array(48);
2352
+ message.set(nonceBytes, 0);
2353
+ const view = new DataView(message.buffer);
2354
+ view.setBigUint64(32, BigInt(createdAt), false);
2355
+ view.setBigUint64(40, BigInt(expiresAt), false);
2356
+ return message;
2357
+ }
2358
+ function signRequest2(_action, signingKeyHex, ttl = DEFAULT_TTL_SEC) {
2084
2359
  if (!isServerEnvironment()) {
2085
2360
  throw new Error(
2086
2361
  "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
2362
  );
2088
2363
  }
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);
2364
+ const keyHex = signingKeyHex.startsWith("0x") ? signingKeyHex.slice(2) : signingKeyHex;
2365
+ if (!/^[0-9a-fA-F]+$/.test(keyHex)) {
2366
+ throw new Error("Invalid signing key: contains non-hex characters");
2367
+ }
2368
+ if (keyHex.length !== 64) {
2369
+ throw new Error(
2370
+ `Invalid signing key: expected 32 bytes (64 hex chars), got ${keyHex.length / 2} bytes`
2371
+ );
2372
+ }
2373
+ const privKey = etc.hexToBytes(keyHex);
2374
+ const randomBytes = crypto.getRandomValues(new Uint8Array(32));
2375
+ const nonceBytes = hashToField(randomBytes);
2376
+ const createdAt = Math.floor(Date.now() / 1e3);
2377
+ const expiresAt = createdAt + ttl;
2378
+ const message = computeRpSignatureMessage(nonceBytes, createdAt, expiresAt);
2379
+ const msgHash = keccak_256(message);
2380
+ const recSig = sign(msgHash, privKey);
2381
+ const compact = recSig.toCompactRawBytes();
2382
+ const sig65 = new Uint8Array(65);
2383
+ sig65.set(compact, 0);
2384
+ sig65[64] = recSig.recovery + 27;
2385
+ return {
2386
+ sig: "0x" + bytesToHex(sig65),
2387
+ nonce: "0x" + bytesToHex(nonceBytes),
2388
+ createdAt,
2389
+ expiresAt
2390
+ };
2096
2391
  }
2097
2392
 
2098
- export { CredentialRequest, IDKit, IDKitErrorCodes, all, any, documentLegacy, hashSignal2 as hashSignal, isNode, isReactNative, isWeb, orbLegacy, secureDocumentLegacy, signRequest2 as signRequest };
2393
+ export { IDKit, IDKitErrorCodes, documentLegacy, hashSignal2 as hashSignal, isNode, isReactNative, isWeb, orbLegacy, secureDocumentLegacy, signRequest2 as signRequest };