@worldcoin/idkit-core 4.0.1-dev.fe98789 → 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
@@ -385,14 +391,14 @@ function hashSignal(signal) {
385
391
  wasm.__wbindgen_export4(deferred2_0, deferred2_1, 1);
386
392
  }
387
393
  }
388
- function __wasm_bindgen_func_elem_597(arg0, arg1) {
389
- wasm.__wasm_bindgen_func_elem_597(arg0, arg1);
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_960(arg0, arg1, arg2) {
392
- wasm.__wasm_bindgen_func_elem_960(arg0, arg1, addHeapObject(arg2));
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_1345(arg0, arg1, arg2, arg3) {
395
- wasm.__wasm_bindgen_func_elem_1345(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_1345(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) {
@@ -1793,10 +1855,6 @@ var idkit_wasm_default = __wbg_init;
1793
1855
  // src/lib/wasm.ts
1794
1856
  var wasmInitialized = false;
1795
1857
  var wasmInitPromise = null;
1796
- async function importNodeModule(specifier) {
1797
- const dynamicImport = Function("moduleName", "return import(moduleName)");
1798
- return dynamicImport(specifier);
1799
- }
1800
1858
  async function initIDKit() {
1801
1859
  if (wasmInitialized) {
1802
1860
  return;
@@ -1815,35 +1873,230 @@ async function initIDKit() {
1815
1873
  })();
1816
1874
  return wasmInitPromise;
1817
1875
  }
1818
- async function initIDKitServer() {
1819
- if (wasmInitialized) {
1820
- 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;
1821
1890
  }
1822
- if (wasmInitPromise) {
1823
- 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
+ });
1824
1967
  }
1825
- 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;
1826
2009
  try {
1827
- const { readFile } = await importNodeModule(
1828
- "node:fs/promises"
1829
- );
1830
- const { fileURLToPath } = await importNodeModule(
1831
- "node:url"
1832
- );
1833
- const { dirname, join } = await importNodeModule(
1834
- "node:path"
1835
- );
1836
- const modulePath = fileURLToPath(import.meta.url);
1837
- const wasmPath = join(dirname(modulePath), "idkit_wasm_bg.wasm");
1838
- const wasmBuffer = await readFile(wasmPath);
1839
- await idkit_wasm_default({ module_or_path: wasmBuffer });
1840
- 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 };
1841
2033
  } catch (error) {
1842
- wasmInitPromise = null;
1843
- 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
+ }
1844
2048
  }
1845
- })();
1846
- 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
+ };
1847
2100
  }
1848
2101
 
1849
2102
  // src/request.ts
@@ -1887,20 +2140,6 @@ var IDKitRequestImpl = class {
1887
2140
  }
1888
2141
  }
1889
2142
  };
1890
- function CredentialRequest(credential_type, options) {
1891
- return {
1892
- type: credential_type,
1893
- signal: options?.signal,
1894
- genesis_issued_at_min: options?.genesis_issued_at_min,
1895
- expires_at_min: options?.expires_at_min
1896
- };
1897
- }
1898
- function any(...nodes) {
1899
- return { any: nodes };
1900
- }
1901
- function all(...nodes) {
1902
- return { all: nodes };
1903
- }
1904
2143
  function orbLegacy(opts = {}) {
1905
2144
  return { type: "OrbLegacy", signal: opts.signal };
1906
2145
  }
@@ -1910,48 +2149,100 @@ function secureDocumentLegacy(opts = {}) {
1910
2149
  function documentLegacy(opts = {}) {
1911
2150
  return { type: "DocumentLegacy", signal: opts.signal };
1912
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
+ }
1913
2195
  var IDKitBuilder2 = class {
1914
- constructor(wasmBuilder) {
1915
- this.wasmBuilder = wasmBuilder;
2196
+ constructor(config) {
2197
+ this.config = config;
1916
2198
  }
1917
2199
  /**
1918
2200
  * Creates an IDKit request with the given constraints
1919
2201
  *
1920
- * @param constraints - Constraint tree (CredentialRequest or any/all combinators)
2202
+ * @param constraints - Constraint tree (CredentialRequest or any/all/enumerate combinators)
1921
2203
  * @returns A new IDKitRequest instance
1922
2204
  *
1923
2205
  * @example
1924
2206
  * ```typescript
1925
- * const builder = await IDKit.request({ app_id, action, rp_context });
1926
- * 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')));
1927
2209
  * ```
1928
2210
  */
1929
- //TODO: re-enable once this is supported and World ID 4.0 is rolled out live
1930
- // async constraints(constraints: ConstraintNode): Promise<IDKitRequest> {
1931
- // await initIDKit();
1932
- // const wasmRequest = (await this.wasmBuilder.constraints(
1933
- // constraints,
1934
- // )) as unknown as WasmModule.IDKitRequest;
1935
- // return new IDKitRequestImpl(wasmRequest);
1936
- // }
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
+ }
1937
2223
  /**
1938
2224
  * Creates an IDKit request from a preset (works for all request types)
1939
2225
  *
1940
2226
  * Presets provide a simplified way to create requests with predefined
1941
2227
  * credential configurations.
1942
2228
  *
1943
- * @param preset - A preset object from orbLegacy()
2229
+ * @param preset - A preset object from orbLegacy(), secureDocumentLegacy(), or documentLegacy()
1944
2230
  * @returns A new IDKitRequest instance
1945
2231
  *
1946
2232
  * @example
1947
2233
  * ```typescript
1948
- * const builder = await IDKit.request({ app_id, action, rp_context });
1949
- * 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' }));
1950
2236
  * ```
1951
2237
  */
1952
2238
  async preset(preset) {
1953
2239
  await initIDKit();
1954
- 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(
1955
2246
  preset
1956
2247
  );
1957
2248
  return new IDKitRequestImpl(wasmRequest);
@@ -1965,101 +2256,43 @@ function createRequest(config) {
1965
2256
  throw new Error("action is required");
1966
2257
  }
1967
2258
  if (!config.rp_context) {
1968
- throw new Error("rp_context is required");
2259
+ throw new Error(
2260
+ "rp_context is required. Generate it on your backend using signRequest()."
2261
+ );
1969
2262
  }
1970
2263
  if (typeof config.allow_legacy_proofs !== "boolean") {
1971
2264
  throw new Error(
1972
2265
  "allow_legacy_proofs is required. Set to true to accept v3 proofs during migration, or false to only accept v4 proofs."
1973
2266
  );
1974
2267
  }
1975
- const rpContext = new idkit_wasm_exports.RpContextWasm(
1976
- config.rp_context.rp_id,
1977
- config.rp_context.nonce,
1978
- BigInt(config.rp_context.created_at),
1979
- BigInt(config.rp_context.expires_at),
1980
- config.rp_context.signature
1981
- );
1982
- const wasmBuilder = idkit_wasm_exports.request(
1983
- config.app_id,
1984
- String(config.action),
1985
- rpContext,
1986
- config.action_description ?? null,
1987
- config.bridge_url ?? null,
1988
- config.allow_legacy_proofs,
1989
- config.override_connect_base_url ?? null,
1990
- config.environment ?? null
1991
- );
1992
- return new IDKitBuilder2(wasmBuilder);
1993
- }
1994
- function createSession2(config) {
1995
- if (!config.app_id) {
1996
- throw new Error("app_id is required");
1997
- }
1998
- if (!config.rp_context) {
1999
- throw new Error("rp_context is required");
2000
- }
2001
- const rpContext = new idkit_wasm_exports.RpContextWasm(
2002
- config.rp_context.rp_id,
2003
- config.rp_context.nonce,
2004
- BigInt(config.rp_context.created_at),
2005
- BigInt(config.rp_context.expires_at),
2006
- config.rp_context.signature
2007
- );
2008
- const wasmBuilder = idkit_wasm_exports.createSession(
2009
- config.app_id,
2010
- rpContext,
2011
- config.action_description ?? null,
2012
- config.bridge_url ?? null,
2013
- config.override_connect_base_url ?? null,
2014
- config.environment ?? null
2015
- );
2016
- return new IDKitBuilder2(wasmBuilder);
2017
- }
2018
- function proveSession2(sessionId, config) {
2019
- if (!sessionId) {
2020
- throw new Error("session_id is required");
2021
- }
2022
- if (!config.app_id) {
2023
- throw new Error("app_id is required");
2024
- }
2025
- if (!config.rp_context) {
2026
- throw new Error("rp_context is required");
2027
- }
2028
- const rpContext = new idkit_wasm_exports.RpContextWasm(
2029
- config.rp_context.rp_id,
2030
- config.rp_context.nonce,
2031
- BigInt(config.rp_context.created_at),
2032
- BigInt(config.rp_context.expires_at),
2033
- config.rp_context.signature
2034
- );
2035
- const wasmBuilder = idkit_wasm_exports.proveSession(
2036
- sessionId,
2037
- config.app_id,
2038
- rpContext,
2039
- config.action_description ?? null,
2040
- config.bridge_url ?? null,
2041
- config.override_connect_base_url ?? null,
2042
- config.environment ?? null
2043
- );
2044
- 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
+ });
2045
2279
  }
2046
2280
  var IDKit = {
2047
- /** Initialize WASM for browser environments */
2048
- init: initIDKit,
2049
- /** Initialize WASM for Node.js/server environments */
2050
- initServer: initIDKitServer,
2051
2281
  /** Create a new verification request */
2052
2282
  request: createRequest,
2053
- /** Create a new session (no action, no existing session_id) */
2054
- createSession: createSession2,
2055
- /** Prove an existing session (no action, has session_id) */
2056
- proveSession: proveSession2,
2057
- /** Create a CredentialRequest for a credential type */
2058
- CredentialRequest,
2059
- /** Create an OR constraint - at least one child must be satisfied */
2060
- any,
2061
- /** Create an AND constraint - all children must be satisfied */
2062
- 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,
2063
2296
  /** Create an OrbLegacy preset for World ID 3.0 legacy support */
2064
2297
  orbLegacy,
2065
2298
  /** Create a SecureDocumentLegacy preset for World ID 3.0 legacy support */
@@ -2090,21 +2323,71 @@ var isServerEnvironment = () => {
2090
2323
  }
2091
2324
  return false;
2092
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
+ }
2093
2346
 
2094
- // src/lib/rp-signature.ts
2095
- 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) {
2096
2359
  if (!isServerEnvironment()) {
2097
2360
  throw new Error(
2098
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."
2099
2362
  );
2100
2363
  }
2101
- const ttlBigInt = ttlSeconds !== void 0 ? BigInt(ttlSeconds) : void 0;
2102
- return idkit_wasm_exports.signRequest(action, signingKeyHex, ttlBigInt);
2103
- }
2104
-
2105
- // src/lib/hashing.ts
2106
- function hashSignal2(signal) {
2107
- 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
+ };
2108
2391
  }
2109
2392
 
2110
- 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 };