@worldcoin/idkit-core 2.1.0 → 4.0.1-dev.eebacb1

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.
Binary file
@@ -0,0 +1,54 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const __wbg_bridgeencryption_free: (a: number, b: number) => void;
5
+ export const __wbg_credentialrequestwasm_free: (a: number, b: number) => void;
6
+ export const __wbg_idkitproof_free: (a: number, b: number) => void;
7
+ export const __wbg_idkitrequest_free: (a: number, b: number) => void;
8
+ export const __wbg_idkitrequestbuilderwasm_free: (a: number, b: number) => void;
9
+ export const __wbg_rpcontextwasm_free: (a: number, b: number) => void;
10
+ export const __wbg_rpsignature_free: (a: number, b: number) => void;
11
+ export const base64Decode: (a: number, b: number, c: number) => void;
12
+ export const base64Encode: (a: number, b: number, c: number) => void;
13
+ export const bridgeencryption_decrypt: (a: number, b: number, c: number, d: number) => void;
14
+ export const bridgeencryption_encrypt: (a: number, b: number, c: number, d: number) => void;
15
+ export const bridgeencryption_keyBase64: (a: number, b: number) => void;
16
+ export const bridgeencryption_new: (a: number) => void;
17
+ export const bridgeencryption_nonceBase64: (a: number, b: number) => void;
18
+ export const credentialrequestwasm_credentialType: (a: number) => number;
19
+ export const credentialrequestwasm_getSignalBytes: (a: number, b: number) => void;
20
+ export const credentialrequestwasm_new: (a: number, b: number, c: number, d: number) => void;
21
+ export const credentialrequestwasm_toJSON: (a: number, b: number) => void;
22
+ export const credentialrequestwasm_withBytes: (a: number, b: number, c: number, d: number) => void;
23
+ export const credentialrequestwasm_withGenesisMin: (a: number, b: number, c: number, d: number, e: bigint) => void;
24
+ export const hashSignal: (a: number, b: number, c: number) => void;
25
+ export const idkitproof_new: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
26
+ export const idkitproof_toJSON: (a: number, b: number) => void;
27
+ export const idkitrequest_connectUrl: (a: number, b: number) => void;
28
+ export const idkitrequest_pollForStatus: (a: number) => number;
29
+ export const idkitrequest_requestId: (a: number, b: number) => void;
30
+ export const idkitrequestbuilderwasm_constraints: (a: number, b: number) => number;
31
+ export const idkitrequestbuilderwasm_new: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => number;
32
+ export const idkitrequestbuilderwasm_preset: (a: number, b: number) => number;
33
+ export const orbLegacy: (a: number, b: number, c: number) => void;
34
+ export const rpcontextwasm_new: (a: number, b: number, c: number, d: number, e: number, f: bigint, g: bigint, h: number, i: number) => void;
35
+ export const rpsignature_createdAt: (a: number) => bigint;
36
+ export const rpsignature_expiresAt: (a: number) => bigint;
37
+ export const rpsignature_nonce: (a: number, b: number) => void;
38
+ export const rpsignature_sig: (a: number, b: number) => void;
39
+ export const rpsignature_toJSON: (a: number, b: number) => void;
40
+ export const signRequest: (a: number, b: number, c: number, d: number, e: number, f: number, g: bigint) => void;
41
+ export const init_wasm: () => void;
42
+ export const hashSignalBytes: (a: number, b: number, c: number) => void;
43
+ export const request: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => number;
44
+ export const __wasm_bindgen_func_elem_510: (a: number, b: number) => void;
45
+ export const __wasm_bindgen_func_elem_509: (a: number, b: number) => void;
46
+ export const __wasm_bindgen_func_elem_873: (a: number, b: number, c: number) => void;
47
+ export const __wasm_bindgen_func_elem_872: (a: number, b: number) => void;
48
+ export const __wasm_bindgen_func_elem_1238: (a: number, b: number, c: number, d: number) => void;
49
+ export const __wbindgen_export: (a: number, b: number) => number;
50
+ export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
51
+ export const __wbindgen_export3: (a: number) => void;
52
+ export const __wbindgen_export4: (a: number, b: number, c: number) => void;
53
+ export const __wbindgen_add_to_stack_pointer: (a: number) => number;
54
+ export const __wbindgen_start: () => void;
package/LICENSE DELETED
@@ -1,7 +0,0 @@
1
- Copyright (c) 2022 Worldcoin Foundation
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
-
5
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,50 +0,0 @@
1
- // src/lib/hashing.ts
2
- import { Buffer } from "buffer/index.js";
3
- import { AbiParameters, Bytes, Hex, Hash } from "ox";
4
- function hashToField(input) {
5
- if (Bytes.validate(input) || Hex.validate(input)) return hashEncodedBytes(input);
6
- return hashString(input);
7
- }
8
- function packAndEncode(input) {
9
- const [types, values] = input.reduce(
10
- ([types2, values2], [type, value]) => {
11
- types2.push(type);
12
- values2.push(value);
13
- return [types2, values2];
14
- },
15
- [[], []]
16
- );
17
- return hashEncodedBytes(AbiParameters.encodePacked(types, values));
18
- }
19
- function hashString(input) {
20
- const bytesInput = Buffer.from(input);
21
- return hashEncodedBytes(bytesInput);
22
- }
23
- function hashEncodedBytes(input) {
24
- const hash = BigInt(Hash.keccak256(input, { as: "Hex" })) >> 8n;
25
- const rawDigest = hash.toString(16);
26
- return { hash, digest: `0x${rawDigest.padStart(64, "0")}` };
27
- }
28
- var solidityEncode = (types, values) => {
29
- if (types.length !== values.length) {
30
- throw new Error("Types and values arrays must have the same length.");
31
- }
32
- return { types, values };
33
- };
34
- var generateSignal = (signal) => {
35
- if (!signal || typeof signal === "string") return hashToField(signal ?? "");
36
- return packAndEncode(signal.types.map((type, index) => [type, signal.values[index]]));
37
- };
38
- var encodeAction = (action) => {
39
- if (!action) return "";
40
- if (typeof action === "string") return action;
41
- return action.types.map((type, index) => `${type}(${action.values[index]})`).join(",");
42
- };
43
-
44
- export {
45
- hashToField,
46
- packAndEncode,
47
- solidityEncode,
48
- generateSignal,
49
- encodeAction
50
- };
@@ -1,41 +0,0 @@
1
- declare const brand: unique symbol;
2
- type Brand<T, TBrand extends string> = T & {
3
- [brand]: TBrand;
4
- };
5
- type AbiEncodedValue = Brand<{
6
- types: string[];
7
- values: unknown[];
8
- }, 'AbiEncodedValue'>;
9
- /**
10
- * @deprecated in IDKit@1.0.0, use VerificationLevel instead
11
- */
12
- declare enum CredentialType {
13
- Orb = "orb",
14
- SecureDocument = "secure_document",
15
- Document = "document",
16
- Device = "device"
17
- }
18
- declare enum VerificationLevel {
19
- Orb = "orb",
20
- SecureDocument = "secure_document",
21
- Document = "document",
22
- Device = "device"
23
- }
24
- type IDKitConfig = {
25
- /** Unique identifier for the app verifying the action. This should be the app ID obtained from the Developer Portal. */
26
- app_id: `app_${string}`;
27
- /** Identifier for the action the user is performing. Should be left blank for [Sign in with Worldcoin](https://docs.world.org/id/sign-in). */
28
- action: AbiEncodedValue | string;
29
- /** The description of the specific action (shown to users in World App). Only recommended for actions created on-the-fly. */
30
- action_description?: string;
31
- /** Encodes data into a proof that must match when validating. Read more on the [On-chain section](https://docs.world.org/advanced/on-chain). */
32
- signal?: AbiEncodedValue | string;
33
- /** URL to a third-party bridge to use when connecting to the World App. Optional. */
34
- bridge_url?: string;
35
- /** The minimum required level of verification. Defaults to "orb". */
36
- verification_level?: VerificationLevel;
37
- /** Whether the app is a partner app and should allow deferred verification. Defaults to false. */
38
- partner?: boolean;
39
- };
40
-
41
- export { type AbiEncodedValue as A, CredentialType as C, type IDKitConfig as I, VerificationLevel as V };
@@ -1,41 +0,0 @@
1
- declare const brand: unique symbol;
2
- type Brand<T, TBrand extends string> = T & {
3
- [brand]: TBrand;
4
- };
5
- type AbiEncodedValue = Brand<{
6
- types: string[];
7
- values: unknown[];
8
- }, 'AbiEncodedValue'>;
9
- /**
10
- * @deprecated in IDKit@1.0.0, use VerificationLevel instead
11
- */
12
- declare enum CredentialType {
13
- Orb = "orb",
14
- SecureDocument = "secure_document",
15
- Document = "document",
16
- Device = "device"
17
- }
18
- declare enum VerificationLevel {
19
- Orb = "orb",
20
- SecureDocument = "secure_document",
21
- Document = "document",
22
- Device = "device"
23
- }
24
- type IDKitConfig = {
25
- /** Unique identifier for the app verifying the action. This should be the app ID obtained from the Developer Portal. */
26
- app_id: `app_${string}`;
27
- /** Identifier for the action the user is performing. Should be left blank for [Sign in with Worldcoin](https://docs.world.org/id/sign-in). */
28
- action: AbiEncodedValue | string;
29
- /** The description of the specific action (shown to users in World App). Only recommended for actions created on-the-fly. */
30
- action_description?: string;
31
- /** Encodes data into a proof that must match when validating. Read more on the [On-chain section](https://docs.world.org/advanced/on-chain). */
32
- signal?: AbiEncodedValue | string;
33
- /** URL to a third-party bridge to use when connecting to the World App. Optional. */
34
- bridge_url?: string;
35
- /** The minimum required level of verification. Defaults to "orb". */
36
- verification_level?: VerificationLevel;
37
- /** Whether the app is a partner app and should allow deferred verification. Defaults to false. */
38
- partner?: boolean;
39
- };
40
-
41
- export { type AbiEncodedValue as A, CredentialType as C, type IDKitConfig as I, VerificationLevel as V };
package/build/index.cjs DELETED
@@ -1,424 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- AppErrorCodes: () => AppErrorCodes,
24
- CredentialType: () => CredentialType,
25
- DEFAULT_VERIFICATION_LEVEL: () => DEFAULT_VERIFICATION_LEVEL,
26
- VerificationLevel: () => VerificationLevel,
27
- VerificationState: () => VerificationState,
28
- createWorldBridgeStore: () => createWorldBridgeStore,
29
- useWorldBridgeStore: () => useWorldBridgeStore,
30
- verification_level_to_credential_types: () => verification_level_to_credential_types
31
- });
32
- module.exports = __toCommonJS(src_exports);
33
-
34
- // src/types/bridge.ts
35
- var AppErrorCodes = /* @__PURE__ */ ((AppErrorCodes2) => {
36
- AppErrorCodes2["ConnectionFailed"] = "connection_failed";
37
- AppErrorCodes2["VerificationRejected"] = "verification_rejected";
38
- AppErrorCodes2["MaxVerificationsReached"] = "max_verifications_reached";
39
- AppErrorCodes2["CredentialUnavailable"] = "credential_unavailable";
40
- AppErrorCodes2["MalformedRequest"] = "malformed_request";
41
- AppErrorCodes2["InvalidNetwork"] = "invalid_network";
42
- AppErrorCodes2["InclusionProofFailed"] = "inclusion_proof_failed";
43
- AppErrorCodes2["InclusionProofPending"] = "inclusion_proof_pending";
44
- AppErrorCodes2["UnexpectedResponse"] = "unexpected_response";
45
- AppErrorCodes2["FailedByHostApp"] = "failed_by_host_app";
46
- AppErrorCodes2["GenericError"] = "generic_error";
47
- return AppErrorCodes2;
48
- })(AppErrorCodes || {});
49
- var VerificationState = /* @__PURE__ */ ((VerificationState2) => {
50
- VerificationState2["PreparingClient"] = "loading_widget";
51
- VerificationState2["WaitingForConnection"] = "awaiting_connection";
52
- VerificationState2["WaitingForApp"] = "awaiting_app";
53
- VerificationState2["Confirmed"] = "confirmed";
54
- VerificationState2["Failed"] = "failed";
55
- return VerificationState2;
56
- })(VerificationState || {});
57
-
58
- // src/types/config.ts
59
- var CredentialType = /* @__PURE__ */ ((CredentialType2) => {
60
- CredentialType2["Orb"] = "orb";
61
- CredentialType2["SecureDocument"] = "secure_document";
62
- CredentialType2["Document"] = "document";
63
- CredentialType2["Device"] = "device";
64
- return CredentialType2;
65
- })(CredentialType || {});
66
- var VerificationLevel = /* @__PURE__ */ ((VerificationLevel2) => {
67
- VerificationLevel2["Orb"] = "orb";
68
- VerificationLevel2["SecureDocument"] = "secure_document";
69
- VerificationLevel2["Document"] = "document";
70
- VerificationLevel2["Device"] = "device";
71
- return VerificationLevel2;
72
- })(VerificationLevel || {});
73
-
74
- // src/bridge.ts
75
- var import_zustand = require("zustand");
76
-
77
- // src/lib/validation.ts
78
- function validate_bridge_url(bridge_url, is_staging) {
79
- try {
80
- new URL(bridge_url);
81
- } catch (e) {
82
- return { valid: false, errors: ["Failed to parse Bridge URL."] };
83
- }
84
- const test_url = new URL(bridge_url);
85
- const errors = [];
86
- if (is_staging && ["localhost", "127.0.0.1"].includes(test_url.hostname)) {
87
- console.log("Using staging app_id with localhost bridge_url. Skipping validation.");
88
- return { valid: true };
89
- }
90
- if (test_url.protocol !== "https:") {
91
- errors.push("Bridge URL must use HTTPS.");
92
- }
93
- if (test_url.port) {
94
- errors.push("Bridge URL must use the default port (443).");
95
- }
96
- if (test_url.pathname !== "/") {
97
- errors.push("Bridge URL must not have a path.");
98
- }
99
- if (test_url.search) {
100
- errors.push("Bridge URL must not have query parameters.");
101
- }
102
- if (test_url.hash) {
103
- errors.push("Bridge URL must not have a fragment.");
104
- }
105
- if (!test_url.hostname.endsWith(".worldcoin.org") && !test_url.hostname.endsWith(".toolsforhumanity.com")) {
106
- console.warn(
107
- "Bridge URL should be a subdomain of worldcoin.org or toolsforhumanity.com. The user's identity wallet may refuse to connect. This is a temporary measure and may be removed in the future."
108
- );
109
- }
110
- if (errors.length) {
111
- return { valid: false, errors };
112
- }
113
- return { valid: true };
114
- }
115
-
116
- // src/lib/hashing.ts
117
- var import_buffer = require("buffer/index.js");
118
- var import_ox = require("ox");
119
- function hashToField(input) {
120
- if (import_ox.Bytes.validate(input) || import_ox.Hex.validate(input)) return hashEncodedBytes(input);
121
- return hashString(input);
122
- }
123
- function packAndEncode(input) {
124
- const [types, values] = input.reduce(
125
- ([types2, values2], [type, value]) => {
126
- types2.push(type);
127
- values2.push(value);
128
- return [types2, values2];
129
- },
130
- [[], []]
131
- );
132
- return hashEncodedBytes(import_ox.AbiParameters.encodePacked(types, values));
133
- }
134
- function hashString(input) {
135
- const bytesInput = import_buffer.Buffer.from(input);
136
- return hashEncodedBytes(bytesInput);
137
- }
138
- function hashEncodedBytes(input) {
139
- const hash = BigInt(import_ox.Hash.keccak256(input, { as: "Hex" })) >> 8n;
140
- const rawDigest = hash.toString(16);
141
- return { hash, digest: `0x${rawDigest.padStart(64, "0")}` };
142
- }
143
- var generateSignal = (signal) => {
144
- if (!signal || typeof signal === "string") return hashToField(signal ?? "");
145
- return packAndEncode(signal.types.map((type, index) => [type, signal.values[index]]));
146
- };
147
- var encodeAction = (action) => {
148
- if (!action) return "";
149
- if (typeof action === "string") return action;
150
- return action.types.map((type, index) => `${type}(${action.values[index]})`).join(",");
151
- };
152
-
153
- // src/lib/platform.ts
154
- var import_browser_or_node = require("browser-or-node");
155
- var isReactNative = () => {
156
- return typeof navigator !== "undefined" && navigator.product === "ReactNative";
157
- };
158
- var isWeb = () => {
159
- return import_browser_or_node.isBrowser;
160
- };
161
- var getGlobalObject = () => {
162
- if (typeof globalThis !== "undefined") return globalThis;
163
- if (typeof self !== "undefined") return self;
164
- if (typeof window !== "undefined") return window;
165
- throw new Error("Unable to locate global object");
166
- };
167
- var getCrypto = () => {
168
- const globalObj = getGlobalObject();
169
- if (typeof globalObj.crypto !== "undefined") {
170
- return globalObj.crypto;
171
- }
172
- throw new Error("Crypto API not available. For React Native, ensure polyfills are set up properly.");
173
- };
174
-
175
- // src/lib/utils.ts
176
- var import_buffer2 = require("buffer/index.js");
177
- var DEFAULT_VERIFICATION_LEVEL = "orb" /* Orb */;
178
- var buffer_encode = (buffer) => {
179
- return import_buffer2.Buffer.from(buffer).toString("base64");
180
- };
181
- var buffer_decode = (encoded) => {
182
- return import_buffer2.Buffer.from(encoded, "base64");
183
- };
184
- var verification_level_to_credential_types = (verification_level) => {
185
- switch (verification_level) {
186
- case "device" /* Device */:
187
- return ["orb" /* Orb */, "device" /* Device */];
188
- case "document" /* Document */:
189
- return ["document" /* Document */, "secure_document" /* SecureDocument */, "orb" /* Orb */];
190
- case "secure_document" /* SecureDocument */:
191
- return ["secure_document" /* SecureDocument */, "orb" /* Orb */];
192
- case "orb" /* Orb */:
193
- return ["orb" /* Orb */];
194
- default:
195
- throw new Error(`Unknown verification level: ${verification_level}`);
196
- }
197
- };
198
- var credential_type_to_verification_level = (credential_type) => {
199
- switch (credential_type) {
200
- case "orb" /* Orb */:
201
- return "orb" /* Orb */;
202
- case "secure_document" /* SecureDocument */:
203
- return "secure_document" /* SecureDocument */;
204
- case "document" /* Document */:
205
- return "document" /* Document */;
206
- case "device" /* Device */:
207
- return "device" /* Device */;
208
- default:
209
- throw new Error(`Unknown credential_type: ${credential_type}`);
210
- }
211
- };
212
-
213
- // src/lib/adapters/web-crypto-adapter.ts
214
- var WebCryptoAdapter = class {
215
- constructor() {
216
- this.encoder = new TextEncoder();
217
- this.decoder = new TextDecoder();
218
- }
219
- async generateKey() {
220
- return {
221
- iv: window.crypto.getRandomValues(new Uint8Array(12)),
222
- key: await window.crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"])
223
- };
224
- }
225
- async exportKey(key) {
226
- return buffer_encode(await window.crypto.subtle.exportKey("raw", key));
227
- }
228
- async encryptRequest(key, iv, request) {
229
- return {
230
- iv: buffer_encode(iv),
231
- payload: buffer_encode(
232
- await window.crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, this.encoder.encode(request))
233
- )
234
- };
235
- }
236
- async decryptResponse(key, iv, payload) {
237
- return this.decoder.decode(
238
- await window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, buffer_decode(payload))
239
- );
240
- }
241
- };
242
-
243
- // src/lib/adapters/react-native-crypto-adapter.ts
244
- var ReactNativeCryptoAdapter = class {
245
- constructor() {
246
- this.encoder = new TextEncoder();
247
- this.decoder = new TextDecoder();
248
- }
249
- async generateKey() {
250
- const crypto = getCrypto();
251
- return {
252
- iv: crypto.getRandomValues(new Uint8Array(12)),
253
- key: await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"])
254
- };
255
- }
256
- async exportKey(key) {
257
- const crypto = getCrypto();
258
- return buffer_encode(await crypto.subtle.exportKey("raw", key));
259
- }
260
- async encryptRequest(key, iv, request) {
261
- const crypto = getCrypto();
262
- return {
263
- iv: buffer_encode(iv),
264
- payload: buffer_encode(
265
- await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, this.encoder.encode(request))
266
- )
267
- };
268
- }
269
- async decryptResponse(key, iv, payload) {
270
- const crypto = getCrypto();
271
- return this.decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, buffer_decode(payload)));
272
- }
273
- };
274
-
275
- // src/lib/crypto.ts
276
- var cryptoAdapterInstance = null;
277
- var getCryptoAdapter = () => {
278
- if (cryptoAdapterInstance) {
279
- return cryptoAdapterInstance;
280
- }
281
- if (isWeb()) {
282
- cryptoAdapterInstance = new WebCryptoAdapter();
283
- return cryptoAdapterInstance;
284
- }
285
- if (isReactNative()) {
286
- cryptoAdapterInstance = new ReactNativeCryptoAdapter();
287
- return cryptoAdapterInstance;
288
- }
289
- throw new Error("Unsupported platform");
290
- };
291
- var generateKey = async () => {
292
- return getCryptoAdapter().generateKey();
293
- };
294
- var exportKey = async (key) => {
295
- return getCryptoAdapter().exportKey(key);
296
- };
297
- var encryptRequest = async (key, iv, request) => {
298
- return getCryptoAdapter().encryptRequest(key, iv, request);
299
- };
300
- var decryptResponse = async (key, iv, payload) => {
301
- return getCryptoAdapter().decryptResponse(key, iv, payload);
302
- };
303
-
304
- // src/bridge.ts
305
- var DEFAULT_BRIDGE_URL = "https://bridge.worldcoin.org";
306
- var createStoreImplementation = (set, get) => ({
307
- iv: null,
308
- key: null,
309
- result: null,
310
- errorCode: null,
311
- requestId: null,
312
- connectorURI: null,
313
- bridge_url: DEFAULT_BRIDGE_URL,
314
- verificationState: "loading_widget" /* PreparingClient */,
315
- createClient: async ({ bridge_url, app_id, verification_level, action_description, action, signal, partner }) => {
316
- const { key, iv } = await generateKey();
317
- if (bridge_url) {
318
- const validation = validate_bridge_url(bridge_url, app_id.includes("staging"));
319
- if (!validation.valid) {
320
- console.error(validation.errors.join("\n"));
321
- set({ verificationState: "failed" /* Failed */ });
322
- throw new Error("Invalid bridge_url. Please check the console for more details.");
323
- }
324
- }
325
- const res = await fetch(new URL("/request", bridge_url ?? DEFAULT_BRIDGE_URL), {
326
- method: "POST",
327
- headers: { "Content-Type": "application/json" },
328
- body: JSON.stringify(
329
- await encryptRequest(
330
- key,
331
- iv,
332
- JSON.stringify({
333
- app_id,
334
- action_description,
335
- action: encodeAction(action),
336
- signal: generateSignal(signal).digest,
337
- credential_types: verification_level_to_credential_types(
338
- verification_level ?? DEFAULT_VERIFICATION_LEVEL
339
- ),
340
- verification_level: verification_level ?? DEFAULT_VERIFICATION_LEVEL
341
- })
342
- )
343
- )
344
- });
345
- if (!res.ok) {
346
- set({ verificationState: "failed" /* Failed */ });
347
- throw new Error("Failed to create client");
348
- }
349
- const { request_id } = await res.json();
350
- set({
351
- iv,
352
- key,
353
- requestId: request_id,
354
- bridge_url: bridge_url ?? DEFAULT_BRIDGE_URL,
355
- verificationState: "awaiting_connection" /* WaitingForConnection */,
356
- connectorURI: `https://world.org/verify?t=wld&i=${request_id}&k=${encodeURIComponent(
357
- await exportKey(key)
358
- )}${bridge_url && bridge_url !== DEFAULT_BRIDGE_URL ? `&b=${encodeURIComponent(bridge_url)}` : ""}${partner ? `&partner=${encodeURIComponent(true)}` : ""}`
359
- });
360
- },
361
- pollForUpdates: async () => {
362
- const key = get().key;
363
- if (!key) throw new Error("No keypair found. Please call `createClient` first.");
364
- const res = await fetch(new URL(`/response/${get().requestId}`, get().bridge_url));
365
- if (!res.ok) {
366
- return set({
367
- errorCode: "connection_failed" /* ConnectionFailed */,
368
- verificationState: "failed" /* Failed */
369
- });
370
- }
371
- const { response, status } = await res.json();
372
- if (status != "completed" /* Completed */) {
373
- return set({
374
- verificationState: status == "retrieved" /* Retrieved */ ? "awaiting_app" /* WaitingForApp */ : "awaiting_connection" /* WaitingForConnection */
375
- });
376
- }
377
- let result = JSON.parse(
378
- await decryptResponse(key, buffer_decode(response.iv), response.payload)
379
- );
380
- if ("error_code" in result) {
381
- return set({
382
- errorCode: result.error_code,
383
- verificationState: "failed" /* Failed */
384
- });
385
- }
386
- if ("credential_type" in result) {
387
- result = {
388
- verification_level: credential_type_to_verification_level(result.credential_type),
389
- ...result
390
- };
391
- }
392
- set({
393
- result,
394
- key: null,
395
- requestId: null,
396
- connectorURI: null,
397
- verificationState: "confirmed" /* Confirmed */
398
- });
399
- },
400
- reset: () => {
401
- set({
402
- iv: null,
403
- key: null,
404
- result: null,
405
- errorCode: null,
406
- requestId: null,
407
- connectorURI: null,
408
- verificationState: "loading_widget" /* PreparingClient */
409
- });
410
- }
411
- });
412
- var useWorldBridgeStore = (0, import_zustand.create)(createStoreImplementation);
413
- var createWorldBridgeStore = () => (0, import_zustand.create)(createStoreImplementation);
414
- // Annotate the CommonJS export names for ESM import in node:
415
- 0 && (module.exports = {
416
- AppErrorCodes,
417
- CredentialType,
418
- DEFAULT_VERIFICATION_LEVEL,
419
- VerificationLevel,
420
- VerificationState,
421
- createWorldBridgeStore,
422
- useWorldBridgeStore,
423
- verification_level_to_credential_types
424
- });
package/build/index.d.cts DELETED
@@ -1,37 +0,0 @@
1
- import { I as ISuccessResult, A as AppErrorCodes, V as VerificationState } from './result-BZ4QXOc2.cjs';
2
- export { a as IErrorState } from './result-BZ4QXOc2.cjs';
3
- import { I as IDKitConfig, V as VerificationLevel } from './config-fuwC_Hia.cjs';
4
- export { A as AbiEncodedValue, C as CredentialType } from './config-fuwC_Hia.cjs';
5
- import * as zustand from 'zustand';
6
-
7
- type WorldBridgeStore = {
8
- bridge_url: string;
9
- iv: Uint8Array | null;
10
- key: CryptoKey | null;
11
- requestId: string | null;
12
- connectorURI: string | null;
13
- result: ISuccessResult | null;
14
- errorCode: AppErrorCodes | null;
15
- verificationState: VerificationState;
16
- createClient: (config: IDKitConfig) => Promise<void>;
17
- pollForUpdates: () => Promise<void>;
18
- reset: () => void;
19
- };
20
- /**
21
- * Single instance of the store
22
- */
23
- declare const useWorldBridgeStore: zustand.UseBoundStore<zustand.StoreApi<WorldBridgeStore>>;
24
- /**
25
- * Factory function to create a new instance of the store
26
- */
27
- declare const createWorldBridgeStore: () => zustand.UseBoundStore<zustand.StoreApi<WorldBridgeStore>>;
28
-
29
- declare const DEFAULT_VERIFICATION_LEVEL = VerificationLevel.Orb;
30
- /**
31
- * @dev use to convert verification level to accepted credential types for proof request
32
- * @param verification_level
33
- * @returns
34
- */
35
- declare const verification_level_to_credential_types: (verification_level: VerificationLevel) => string[];
36
-
37
- export { AppErrorCodes, DEFAULT_VERIFICATION_LEVEL, IDKitConfig, ISuccessResult, VerificationLevel, VerificationState, type WorldBridgeStore, createWorldBridgeStore, useWorldBridgeStore, verification_level_to_credential_types };