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

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,3 +1,9 @@
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
8
  var __export = (target, all2) => {
3
9
  for (var name in all2)
@@ -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
394
  function __wasm_bindgen_func_elem_960(arg0, arg1, arg2) {
389
395
  wasm.__wasm_bindgen_func_elem_960(arg0, arg1, addHeapObject(arg2));
390
396
  }
391
397
  function __wasm_bindgen_func_elem_597(arg0, arg1) {
392
398
  wasm.__wasm_bindgen_func_elem_597(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_1345(arg0, arg1, arg2, arg3) {
401
+ wasm.__wasm_bindgen_func_elem_1345(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_1345(a, state0.b, arg02, arg12);
1503
1565
  } finally {
1504
1566
  state0.a = a;
1505
1567
  }
@@ -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
@@ -1898,9 +2163,52 @@ function secureDocumentLegacy(opts = {}) {
1898
2163
  function documentLegacy(opts = {}) {
1899
2164
  return { type: "DocumentLegacy", signal: opts.signal };
1900
2165
  }
2166
+ function createWasmBuilderFromConfig(config) {
2167
+ if (!config.rp_context) {
2168
+ throw new Error("rp_context is required for WASM bridge transport");
2169
+ }
2170
+ const rpContext = new idkit_wasm_exports.RpContextWasm(
2171
+ config.rp_context.rp_id,
2172
+ config.rp_context.nonce,
2173
+ BigInt(config.rp_context.created_at),
2174
+ BigInt(config.rp_context.expires_at),
2175
+ config.rp_context.signature
2176
+ );
2177
+ if (config.type === "request") {
2178
+ return idkit_wasm_exports.request(
2179
+ config.app_id,
2180
+ String(config.action ?? ""),
2181
+ rpContext,
2182
+ config.action_description ?? null,
2183
+ config.bridge_url ?? null,
2184
+ config.allow_legacy_proofs ?? false,
2185
+ config.override_connect_base_url ?? null,
2186
+ config.environment ?? null
2187
+ );
2188
+ }
2189
+ if (config.type === "proveSession") {
2190
+ return idkit_wasm_exports.proveSession(
2191
+ config.session_id,
2192
+ config.app_id,
2193
+ rpContext,
2194
+ config.action_description ?? null,
2195
+ config.bridge_url ?? null,
2196
+ config.override_connect_base_url ?? null,
2197
+ config.environment ?? null
2198
+ );
2199
+ }
2200
+ return idkit_wasm_exports.createSession(
2201
+ config.app_id,
2202
+ rpContext,
2203
+ config.action_description ?? null,
2204
+ config.bridge_url ?? null,
2205
+ config.override_connect_base_url ?? null,
2206
+ config.environment ?? null
2207
+ );
2208
+ }
1901
2209
  var IDKitBuilder2 = class {
1902
- constructor(wasmBuilder) {
1903
- this.wasmBuilder = wasmBuilder;
2210
+ constructor(config) {
2211
+ this.config = config;
1904
2212
  }
1905
2213
  /**
1906
2214
  * Creates an IDKit request with the given constraints
@@ -1910,36 +2218,45 @@ var IDKitBuilder2 = class {
1910
2218
  *
1911
2219
  * @example
1912
2220
  * ```typescript
1913
- * const builder = await IDKit.request({ app_id, action, rp_context });
1914
- * const request = await builder.constraints(any(CredentialRequest('orb'), CredentialRequest('face')));
2221
+ * const request = await IDKit.request({ app_id, action, rp_context, allow_legacy_proofs: false })
2222
+ * .constraints(any(CredentialRequest('orb'), CredentialRequest('face')));
1915
2223
  * ```
1916
2224
  */
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
- // }
2225
+ async constraints(constraints) {
2226
+ await initIDKit();
2227
+ const wasmBuilder = createWasmBuilderFromConfig(this.config);
2228
+ if (isInWorldApp()) {
2229
+ const payload = wasmBuilder.nativePayload(constraints);
2230
+ return createNativeRequest(payload, this.config);
2231
+ }
2232
+ const wasmRequest = await wasmBuilder.constraints(
2233
+ constraints
2234
+ );
2235
+ return new IDKitRequestImpl(wasmRequest);
2236
+ }
1925
2237
  /**
1926
2238
  * Creates an IDKit request from a preset (works for all request types)
1927
2239
  *
1928
2240
  * Presets provide a simplified way to create requests with predefined
1929
2241
  * credential configurations.
1930
2242
  *
1931
- * @param preset - A preset object from orbLegacy()
2243
+ * @param preset - A preset object from orbLegacy(), secureDocumentLegacy(), or documentLegacy()
1932
2244
  * @returns A new IDKitRequest instance
1933
2245
  *
1934
2246
  * @example
1935
2247
  * ```typescript
1936
- * const builder = await IDKit.request({ app_id, action, rp_context });
1937
- * const request = await builder.preset(orbLegacy({ signal: 'user-123' }));
2248
+ * const request = await IDKit.request({ app_id, action, rp_context, allow_legacy_proofs: true })
2249
+ * .preset(orbLegacy({ signal: 'user-123' }));
1938
2250
  * ```
1939
2251
  */
1940
2252
  async preset(preset) {
1941
2253
  await initIDKit();
1942
- const wasmRequest = await this.wasmBuilder.preset(
2254
+ const wasmBuilder = createWasmBuilderFromConfig(this.config);
2255
+ if (isInWorldApp()) {
2256
+ const payload = wasmBuilder.nativePayloadFromPreset(preset);
2257
+ return createNativeRequest(payload, this.config);
2258
+ }
2259
+ const wasmRequest = await wasmBuilder.preset(
1943
2260
  preset
1944
2261
  );
1945
2262
  return new IDKitRequestImpl(wasmRequest);
@@ -1953,55 +2270,45 @@ function createRequest(config) {
1953
2270
  throw new Error("action is required");
1954
2271
  }
1955
2272
  if (!config.rp_context) {
1956
- throw new Error("rp_context is required");
2273
+ throw new Error(
2274
+ "rp_context is required. Generate it on your backend using signRequest()."
2275
+ );
1957
2276
  }
1958
2277
  if (typeof config.allow_legacy_proofs !== "boolean") {
1959
2278
  throw new Error(
1960
2279
  "allow_legacy_proofs is required. Set to true to accept v3 proofs during migration, or false to only accept v4 proofs."
1961
2280
  );
1962
2281
  }
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);
2282
+ return new IDKitBuilder2({
2283
+ type: "request",
2284
+ app_id: config.app_id,
2285
+ action: String(config.action),
2286
+ rp_context: config.rp_context,
2287
+ action_description: config.action_description,
2288
+ bridge_url: config.bridge_url,
2289
+ allow_legacy_proofs: config.allow_legacy_proofs,
2290
+ override_connect_base_url: config.override_connect_base_url,
2291
+ environment: config.environment
2292
+ });
1981
2293
  }
1982
2294
  function createSession2(config) {
1983
2295
  if (!config.app_id) {
1984
2296
  throw new Error("app_id is required");
1985
2297
  }
1986
2298
  if (!config.rp_context) {
1987
- throw new Error("rp_context is required");
2299
+ throw new Error(
2300
+ "rp_context is required. Generate it on your backend using signRequest()."
2301
+ );
1988
2302
  }
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);
2303
+ return new IDKitBuilder2({
2304
+ type: "session",
2305
+ app_id: config.app_id,
2306
+ rp_context: config.rp_context,
2307
+ action_description: config.action_description,
2308
+ bridge_url: config.bridge_url,
2309
+ override_connect_base_url: config.override_connect_base_url,
2310
+ environment: config.environment
2311
+ });
2005
2312
  }
2006
2313
  function proveSession2(sessionId, config) {
2007
2314
  if (!sessionId) {
@@ -2011,31 +2318,22 @@ function proveSession2(sessionId, config) {
2011
2318
  throw new Error("app_id is required");
2012
2319
  }
2013
2320
  if (!config.rp_context) {
2014
- throw new Error("rp_context is required");
2321
+ throw new Error(
2322
+ "rp_context is required. Generate it on your backend using signRequest()."
2323
+ );
2015
2324
  }
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);
2325
+ return new IDKitBuilder2({
2326
+ type: "proveSession",
2327
+ session_id: sessionId,
2328
+ app_id: config.app_id,
2329
+ rp_context: config.rp_context,
2330
+ action_description: config.action_description,
2331
+ bridge_url: config.bridge_url,
2332
+ override_connect_base_url: config.override_connect_base_url,
2333
+ environment: config.environment
2334
+ });
2033
2335
  }
2034
2336
  var IDKit = {
2035
- /** Initialize WASM for browser environments */
2036
- init: initIDKit,
2037
- /** Initialize WASM for Node.js/server environments */
2038
- initServer: initIDKitServer,
2039
2337
  /** Create a new verification request */
2040
2338
  request: createRequest,
2041
2339
  /** Create a new session (no action, no existing session_id) */
@@ -2078,21 +2376,71 @@ var isServerEnvironment = () => {
2078
2376
  }
2079
2377
  return false;
2080
2378
  };
2379
+ function hashToField(input) {
2380
+ const hash = BigInt("0x" + bytesToHex(keccak_256(input))) >> 8n;
2381
+ return hexToBytes(hash.toString(16).padStart(64, "0"));
2382
+ }
2383
+ function hashSignal2(signal) {
2384
+ let input;
2385
+ if (signal instanceof Uint8Array) {
2386
+ input = signal;
2387
+ } else if (signal.startsWith("0x") && isValidHex(signal.slice(2))) {
2388
+ input = hexToBytes(signal.slice(2));
2389
+ } else {
2390
+ input = new TextEncoder().encode(signal);
2391
+ }
2392
+ return "0x" + bytesToHex(hashToField(input));
2393
+ }
2394
+ function isValidHex(s) {
2395
+ if (s.length === 0) return false;
2396
+ if (s.length % 2 !== 0) return false;
2397
+ return /^[0-9a-fA-F]+$/.test(s);
2398
+ }
2081
2399
 
2082
- // src/lib/rp-signature.ts
2083
- function signRequest2(action, signingKeyHex, ttlSeconds) {
2400
+ // src/lib/signing.ts
2401
+ etc.hmacSha256Sync = (key, ...msgs) => hmac(sha256, key, etc.concatBytes(...msgs));
2402
+ var DEFAULT_TTL_SEC = 300;
2403
+ function computeRpSignatureMessage(nonceBytes, createdAt, expiresAt) {
2404
+ const message = new Uint8Array(48);
2405
+ message.set(nonceBytes, 0);
2406
+ const view = new DataView(message.buffer);
2407
+ view.setBigUint64(32, BigInt(createdAt), false);
2408
+ view.setBigUint64(40, BigInt(expiresAt), false);
2409
+ return message;
2410
+ }
2411
+ function signRequest2(_action, signingKeyHex, ttl = DEFAULT_TTL_SEC) {
2084
2412
  if (!isServerEnvironment()) {
2085
2413
  throw new Error(
2086
2414
  "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
2415
  );
2088
2416
  }
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);
2417
+ const keyHex = signingKeyHex.startsWith("0x") ? signingKeyHex.slice(2) : signingKeyHex;
2418
+ if (!/^[0-9a-fA-F]+$/.test(keyHex)) {
2419
+ throw new Error("Invalid signing key: contains non-hex characters");
2420
+ }
2421
+ if (keyHex.length !== 64) {
2422
+ throw new Error(
2423
+ `Invalid signing key: expected 32 bytes (64 hex chars), got ${keyHex.length / 2} bytes`
2424
+ );
2425
+ }
2426
+ const privKey = etc.hexToBytes(keyHex);
2427
+ const randomBytes = crypto.getRandomValues(new Uint8Array(32));
2428
+ const nonceBytes = hashToField(randomBytes);
2429
+ const createdAt = Math.floor(Date.now() / 1e3);
2430
+ const expiresAt = createdAt + ttl;
2431
+ const message = computeRpSignatureMessage(nonceBytes, createdAt, expiresAt);
2432
+ const msgHash = keccak_256(message);
2433
+ const recSig = sign(msgHash, privKey);
2434
+ const compact = recSig.toCompactRawBytes();
2435
+ const sig65 = new Uint8Array(65);
2436
+ sig65.set(compact, 0);
2437
+ sig65[64] = recSig.recovery + 27;
2438
+ return {
2439
+ sig: "0x" + bytesToHex(sig65),
2440
+ nonce: "0x" + bytesToHex(nonceBytes),
2441
+ createdAt,
2442
+ expiresAt
2443
+ };
2096
2444
  }
2097
2445
 
2098
2446
  export { CredentialRequest, IDKit, IDKitErrorCodes, all, any, documentLegacy, hashSignal2 as hashSignal, isNode, isReactNative, isWeb, orbLegacy, secureDocumentLegacy, signRequest2 as signRequest };