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