@worldcoin/idkit-core 2.1.0 → 4.0.0-dev.777cdbe

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/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 };
package/build/index.d.ts DELETED
@@ -1,37 +0,0 @@
1
- import { I as ISuccessResult, A as AppErrorCodes, V as VerificationState } from './result-CqgtArQe.js';
2
- export { a as IErrorState } from './result-CqgtArQe.js';
3
- import { I as IDKitConfig, V as VerificationLevel } from './config-fuwC_Hia.js';
4
- export { A as AbiEncodedValue, C as CredentialType } from './config-fuwC_Hia.js';
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 };
package/build/index.js DELETED
@@ -1,358 +0,0 @@
1
- import {
2
- encodeAction,
3
- generateSignal
4
- } from "./chunk-HZ2SQA5V.js";
5
-
6
- // src/types/bridge.ts
7
- var AppErrorCodes = /* @__PURE__ */ ((AppErrorCodes2) => {
8
- AppErrorCodes2["ConnectionFailed"] = "connection_failed";
9
- AppErrorCodes2["VerificationRejected"] = "verification_rejected";
10
- AppErrorCodes2["MaxVerificationsReached"] = "max_verifications_reached";
11
- AppErrorCodes2["CredentialUnavailable"] = "credential_unavailable";
12
- AppErrorCodes2["MalformedRequest"] = "malformed_request";
13
- AppErrorCodes2["InvalidNetwork"] = "invalid_network";
14
- AppErrorCodes2["InclusionProofFailed"] = "inclusion_proof_failed";
15
- AppErrorCodes2["InclusionProofPending"] = "inclusion_proof_pending";
16
- AppErrorCodes2["UnexpectedResponse"] = "unexpected_response";
17
- AppErrorCodes2["FailedByHostApp"] = "failed_by_host_app";
18
- AppErrorCodes2["GenericError"] = "generic_error";
19
- return AppErrorCodes2;
20
- })(AppErrorCodes || {});
21
- var VerificationState = /* @__PURE__ */ ((VerificationState2) => {
22
- VerificationState2["PreparingClient"] = "loading_widget";
23
- VerificationState2["WaitingForConnection"] = "awaiting_connection";
24
- VerificationState2["WaitingForApp"] = "awaiting_app";
25
- VerificationState2["Confirmed"] = "confirmed";
26
- VerificationState2["Failed"] = "failed";
27
- return VerificationState2;
28
- })(VerificationState || {});
29
-
30
- // src/types/config.ts
31
- var CredentialType = /* @__PURE__ */ ((CredentialType2) => {
32
- CredentialType2["Orb"] = "orb";
33
- CredentialType2["SecureDocument"] = "secure_document";
34
- CredentialType2["Document"] = "document";
35
- CredentialType2["Device"] = "device";
36
- return CredentialType2;
37
- })(CredentialType || {});
38
- var VerificationLevel = /* @__PURE__ */ ((VerificationLevel2) => {
39
- VerificationLevel2["Orb"] = "orb";
40
- VerificationLevel2["SecureDocument"] = "secure_document";
41
- VerificationLevel2["Document"] = "document";
42
- VerificationLevel2["Device"] = "device";
43
- return VerificationLevel2;
44
- })(VerificationLevel || {});
45
-
46
- // src/bridge.ts
47
- import { create } from "zustand";
48
-
49
- // src/lib/validation.ts
50
- function validate_bridge_url(bridge_url, is_staging) {
51
- try {
52
- new URL(bridge_url);
53
- } catch (e) {
54
- return { valid: false, errors: ["Failed to parse Bridge URL."] };
55
- }
56
- const test_url = new URL(bridge_url);
57
- const errors = [];
58
- if (is_staging && ["localhost", "127.0.0.1"].includes(test_url.hostname)) {
59
- console.log("Using staging app_id with localhost bridge_url. Skipping validation.");
60
- return { valid: true };
61
- }
62
- if (test_url.protocol !== "https:") {
63
- errors.push("Bridge URL must use HTTPS.");
64
- }
65
- if (test_url.port) {
66
- errors.push("Bridge URL must use the default port (443).");
67
- }
68
- if (test_url.pathname !== "/") {
69
- errors.push("Bridge URL must not have a path.");
70
- }
71
- if (test_url.search) {
72
- errors.push("Bridge URL must not have query parameters.");
73
- }
74
- if (test_url.hash) {
75
- errors.push("Bridge URL must not have a fragment.");
76
- }
77
- if (!test_url.hostname.endsWith(".worldcoin.org") && !test_url.hostname.endsWith(".toolsforhumanity.com")) {
78
- console.warn(
79
- "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."
80
- );
81
- }
82
- if (errors.length) {
83
- return { valid: false, errors };
84
- }
85
- return { valid: true };
86
- }
87
-
88
- // src/lib/platform.ts
89
- import { isBrowser, isNode as isNodeBoolean } from "browser-or-node";
90
- var isReactNative = () => {
91
- return typeof navigator !== "undefined" && navigator.product === "ReactNative";
92
- };
93
- var isWeb = () => {
94
- return isBrowser;
95
- };
96
- var getGlobalObject = () => {
97
- if (typeof globalThis !== "undefined") return globalThis;
98
- if (typeof self !== "undefined") return self;
99
- if (typeof window !== "undefined") return window;
100
- throw new Error("Unable to locate global object");
101
- };
102
- var getCrypto = () => {
103
- const globalObj = getGlobalObject();
104
- if (typeof globalObj.crypto !== "undefined") {
105
- return globalObj.crypto;
106
- }
107
- throw new Error("Crypto API not available. For React Native, ensure polyfills are set up properly.");
108
- };
109
-
110
- // src/lib/utils.ts
111
- import { Buffer } from "buffer/index.js";
112
- var DEFAULT_VERIFICATION_LEVEL = "orb" /* Orb */;
113
- var buffer_encode = (buffer) => {
114
- return Buffer.from(buffer).toString("base64");
115
- };
116
- var buffer_decode = (encoded) => {
117
- return Buffer.from(encoded, "base64");
118
- };
119
- var verification_level_to_credential_types = (verification_level) => {
120
- switch (verification_level) {
121
- case "device" /* Device */:
122
- return ["orb" /* Orb */, "device" /* Device */];
123
- case "document" /* Document */:
124
- return ["document" /* Document */, "secure_document" /* SecureDocument */, "orb" /* Orb */];
125
- case "secure_document" /* SecureDocument */:
126
- return ["secure_document" /* SecureDocument */, "orb" /* Orb */];
127
- case "orb" /* Orb */:
128
- return ["orb" /* Orb */];
129
- default:
130
- throw new Error(`Unknown verification level: ${verification_level}`);
131
- }
132
- };
133
- var credential_type_to_verification_level = (credential_type) => {
134
- switch (credential_type) {
135
- case "orb" /* Orb */:
136
- return "orb" /* Orb */;
137
- case "secure_document" /* SecureDocument */:
138
- return "secure_document" /* SecureDocument */;
139
- case "document" /* Document */:
140
- return "document" /* Document */;
141
- case "device" /* Device */:
142
- return "device" /* Device */;
143
- default:
144
- throw new Error(`Unknown credential_type: ${credential_type}`);
145
- }
146
- };
147
-
148
- // src/lib/adapters/web-crypto-adapter.ts
149
- var WebCryptoAdapter = class {
150
- constructor() {
151
- this.encoder = new TextEncoder();
152
- this.decoder = new TextDecoder();
153
- }
154
- async generateKey() {
155
- return {
156
- iv: window.crypto.getRandomValues(new Uint8Array(12)),
157
- key: await window.crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"])
158
- };
159
- }
160
- async exportKey(key) {
161
- return buffer_encode(await window.crypto.subtle.exportKey("raw", key));
162
- }
163
- async encryptRequest(key, iv, request) {
164
- return {
165
- iv: buffer_encode(iv),
166
- payload: buffer_encode(
167
- await window.crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, this.encoder.encode(request))
168
- )
169
- };
170
- }
171
- async decryptResponse(key, iv, payload) {
172
- return this.decoder.decode(
173
- await window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, buffer_decode(payload))
174
- );
175
- }
176
- };
177
-
178
- // src/lib/adapters/react-native-crypto-adapter.ts
179
- var ReactNativeCryptoAdapter = class {
180
- constructor() {
181
- this.encoder = new TextEncoder();
182
- this.decoder = new TextDecoder();
183
- }
184
- async generateKey() {
185
- const crypto = getCrypto();
186
- return {
187
- iv: crypto.getRandomValues(new Uint8Array(12)),
188
- key: await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"])
189
- };
190
- }
191
- async exportKey(key) {
192
- const crypto = getCrypto();
193
- return buffer_encode(await crypto.subtle.exportKey("raw", key));
194
- }
195
- async encryptRequest(key, iv, request) {
196
- const crypto = getCrypto();
197
- return {
198
- iv: buffer_encode(iv),
199
- payload: buffer_encode(
200
- await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, this.encoder.encode(request))
201
- )
202
- };
203
- }
204
- async decryptResponse(key, iv, payload) {
205
- const crypto = getCrypto();
206
- return this.decoder.decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, buffer_decode(payload)));
207
- }
208
- };
209
-
210
- // src/lib/crypto.ts
211
- var cryptoAdapterInstance = null;
212
- var getCryptoAdapter = () => {
213
- if (cryptoAdapterInstance) {
214
- return cryptoAdapterInstance;
215
- }
216
- if (isWeb()) {
217
- cryptoAdapterInstance = new WebCryptoAdapter();
218
- return cryptoAdapterInstance;
219
- }
220
- if (isReactNative()) {
221
- cryptoAdapterInstance = new ReactNativeCryptoAdapter();
222
- return cryptoAdapterInstance;
223
- }
224
- throw new Error("Unsupported platform");
225
- };
226
- var generateKey = async () => {
227
- return getCryptoAdapter().generateKey();
228
- };
229
- var exportKey = async (key) => {
230
- return getCryptoAdapter().exportKey(key);
231
- };
232
- var encryptRequest = async (key, iv, request) => {
233
- return getCryptoAdapter().encryptRequest(key, iv, request);
234
- };
235
- var decryptResponse = async (key, iv, payload) => {
236
- return getCryptoAdapter().decryptResponse(key, iv, payload);
237
- };
238
-
239
- // src/bridge.ts
240
- var DEFAULT_BRIDGE_URL = "https://bridge.worldcoin.org";
241
- var createStoreImplementation = (set, get) => ({
242
- iv: null,
243
- key: null,
244
- result: null,
245
- errorCode: null,
246
- requestId: null,
247
- connectorURI: null,
248
- bridge_url: DEFAULT_BRIDGE_URL,
249
- verificationState: "loading_widget" /* PreparingClient */,
250
- createClient: async ({ bridge_url, app_id, verification_level, action_description, action, signal, partner }) => {
251
- const { key, iv } = await generateKey();
252
- if (bridge_url) {
253
- const validation = validate_bridge_url(bridge_url, app_id.includes("staging"));
254
- if (!validation.valid) {
255
- console.error(validation.errors.join("\n"));
256
- set({ verificationState: "failed" /* Failed */ });
257
- throw new Error("Invalid bridge_url. Please check the console for more details.");
258
- }
259
- }
260
- const res = await fetch(new URL("/request", bridge_url ?? DEFAULT_BRIDGE_URL), {
261
- method: "POST",
262
- headers: { "Content-Type": "application/json" },
263
- body: JSON.stringify(
264
- await encryptRequest(
265
- key,
266
- iv,
267
- JSON.stringify({
268
- app_id,
269
- action_description,
270
- action: encodeAction(action),
271
- signal: generateSignal(signal).digest,
272
- credential_types: verification_level_to_credential_types(
273
- verification_level ?? DEFAULT_VERIFICATION_LEVEL
274
- ),
275
- verification_level: verification_level ?? DEFAULT_VERIFICATION_LEVEL
276
- })
277
- )
278
- )
279
- });
280
- if (!res.ok) {
281
- set({ verificationState: "failed" /* Failed */ });
282
- throw new Error("Failed to create client");
283
- }
284
- const { request_id } = await res.json();
285
- set({
286
- iv,
287
- key,
288
- requestId: request_id,
289
- bridge_url: bridge_url ?? DEFAULT_BRIDGE_URL,
290
- verificationState: "awaiting_connection" /* WaitingForConnection */,
291
- connectorURI: `https://world.org/verify?t=wld&i=${request_id}&k=${encodeURIComponent(
292
- await exportKey(key)
293
- )}${bridge_url && bridge_url !== DEFAULT_BRIDGE_URL ? `&b=${encodeURIComponent(bridge_url)}` : ""}${partner ? `&partner=${encodeURIComponent(true)}` : ""}`
294
- });
295
- },
296
- pollForUpdates: async () => {
297
- const key = get().key;
298
- if (!key) throw new Error("No keypair found. Please call `createClient` first.");
299
- const res = await fetch(new URL(`/response/${get().requestId}`, get().bridge_url));
300
- if (!res.ok) {
301
- return set({
302
- errorCode: "connection_failed" /* ConnectionFailed */,
303
- verificationState: "failed" /* Failed */
304
- });
305
- }
306
- const { response, status } = await res.json();
307
- if (status != "completed" /* Completed */) {
308
- return set({
309
- verificationState: status == "retrieved" /* Retrieved */ ? "awaiting_app" /* WaitingForApp */ : "awaiting_connection" /* WaitingForConnection */
310
- });
311
- }
312
- let result = JSON.parse(
313
- await decryptResponse(key, buffer_decode(response.iv), response.payload)
314
- );
315
- if ("error_code" in result) {
316
- return set({
317
- errorCode: result.error_code,
318
- verificationState: "failed" /* Failed */
319
- });
320
- }
321
- if ("credential_type" in result) {
322
- result = {
323
- verification_level: credential_type_to_verification_level(result.credential_type),
324
- ...result
325
- };
326
- }
327
- set({
328
- result,
329
- key: null,
330
- requestId: null,
331
- connectorURI: null,
332
- verificationState: "confirmed" /* Confirmed */
333
- });
334
- },
335
- reset: () => {
336
- set({
337
- iv: null,
338
- key: null,
339
- result: null,
340
- errorCode: null,
341
- requestId: null,
342
- connectorURI: null,
343
- verificationState: "loading_widget" /* PreparingClient */
344
- });
345
- }
346
- });
347
- var useWorldBridgeStore = create(createStoreImplementation);
348
- var createWorldBridgeStore = () => create(createStoreImplementation);
349
- export {
350
- AppErrorCodes,
351
- CredentialType,
352
- DEFAULT_VERIFICATION_LEVEL,
353
- VerificationLevel,
354
- VerificationState,
355
- createWorldBridgeStore,
356
- useWorldBridgeStore,
357
- verification_level_to_credential_types
358
- };
@@ -1,71 +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/lib/backend.ts
21
- var backend_exports = {};
22
- __export(backend_exports, {
23
- verifyCloudProof: () => verifyCloudProof
24
- });
25
- module.exports = __toCommonJS(backend_exports);
26
-
27
- // src/lib/hashing.ts
28
- var import_buffer = require("buffer/index.js");
29
- var import_ox = require("ox");
30
- function hashToField(input) {
31
- if (import_ox.Bytes.validate(input) || import_ox.Hex.validate(input)) return hashEncodedBytes(input);
32
- return hashString(input);
33
- }
34
- function hashString(input) {
35
- const bytesInput = import_buffer.Buffer.from(input);
36
- return hashEncodedBytes(bytesInput);
37
- }
38
- function hashEncodedBytes(input) {
39
- const hash = BigInt(import_ox.Hash.keccak256(input, { as: "Hex" })) >> 8n;
40
- const rawDigest = hash.toString(16);
41
- return { hash, digest: `0x${rawDigest.padStart(64, "0")}` };
42
- }
43
-
44
- // src/lib/backend.ts
45
- var import_browser_or_node = require("browser-or-node");
46
- async function verifyCloudProof(proof, app_id, action, signal, endpoint, headers) {
47
- if (import_browser_or_node.isBrowser) {
48
- throw new Error("verifyCloudProof can only be used in the backend.");
49
- }
50
- const response = await fetch(endpoint ?? `https://developer.worldcoin.org/api/v2/verify/${app_id}`, {
51
- method: "POST",
52
- headers: {
53
- ...headers ?? {},
54
- "Content-Type": "application/json"
55
- },
56
- body: JSON.stringify({
57
- ...proof,
58
- action,
59
- signal_hash: hashToField(signal ?? "").digest
60
- })
61
- });
62
- if (response.ok) {
63
- return { success: true };
64
- } else {
65
- return { success: false, ...await response.json() };
66
- }
67
- }
68
- // Annotate the CommonJS export names for ESM import in node:
69
- 0 && (module.exports = {
70
- verifyCloudProof
71
- });
@@ -1,12 +0,0 @@
1
- import { I as ISuccessResult } from '../result-BZ4QXOc2.cjs';
2
- import '../config-fuwC_Hia.cjs';
3
-
4
- interface IVerifyResponse {
5
- success: boolean;
6
- code?: string;
7
- detail?: string;
8
- attribute?: string | null;
9
- }
10
- declare function verifyCloudProof(proof: ISuccessResult, app_id: `app_${string}`, action: string, signal?: string, endpoint?: URL | string, headers?: Record<string, string>): Promise<IVerifyResponse>;
11
-
12
- export { type IVerifyResponse, verifyCloudProof };
@@ -1,12 +0,0 @@
1
- import { I as ISuccessResult } from '../result-CqgtArQe.js';
2
- import '../config-fuwC_Hia.js';
3
-
4
- interface IVerifyResponse {
5
- success: boolean;
6
- code?: string;
7
- detail?: string;
8
- attribute?: string | null;
9
- }
10
- declare function verifyCloudProof(proof: ISuccessResult, app_id: `app_${string}`, action: string, signal?: string, endpoint?: URL | string, headers?: Record<string, string>): Promise<IVerifyResponse>;
11
-
12
- export { type IVerifyResponse, verifyCloudProof };
@@ -1,31 +0,0 @@
1
- import {
2
- hashToField
3
- } from "../chunk-HZ2SQA5V.js";
4
-
5
- // src/lib/backend.ts
6
- import { isBrowser } from "browser-or-node";
7
- async function verifyCloudProof(proof, app_id, action, signal, endpoint, headers) {
8
- if (isBrowser) {
9
- throw new Error("verifyCloudProof can only be used in the backend.");
10
- }
11
- const response = await fetch(endpoint ?? `https://developer.worldcoin.org/api/v2/verify/${app_id}`, {
12
- method: "POST",
13
- headers: {
14
- ...headers ?? {},
15
- "Content-Type": "application/json"
16
- },
17
- body: JSON.stringify({
18
- ...proof,
19
- action,
20
- signal_hash: hashToField(signal ?? "").digest
21
- })
22
- });
23
- if (response.ok) {
24
- return { success: true };
25
- } else {
26
- return { success: false, ...await response.json() };
27
- }
28
- }
29
- export {
30
- verifyCloudProof
31
- };
@@ -1,78 +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/lib/hashing.ts
21
- var hashing_exports = {};
22
- __export(hashing_exports, {
23
- encodeAction: () => encodeAction,
24
- generateSignal: () => generateSignal,
25
- hashToField: () => hashToField,
26
- packAndEncode: () => packAndEncode,
27
- solidityEncode: () => solidityEncode
28
- });
29
- module.exports = __toCommonJS(hashing_exports);
30
- var import_buffer = require("buffer/index.js");
31
- var import_ox = require("ox");
32
- function hashToField(input) {
33
- if (import_ox.Bytes.validate(input) || import_ox.Hex.validate(input)) return hashEncodedBytes(input);
34
- return hashString(input);
35
- }
36
- function packAndEncode(input) {
37
- const [types, values] = input.reduce(
38
- ([types2, values2], [type, value]) => {
39
- types2.push(type);
40
- values2.push(value);
41
- return [types2, values2];
42
- },
43
- [[], []]
44
- );
45
- return hashEncodedBytes(import_ox.AbiParameters.encodePacked(types, values));
46
- }
47
- function hashString(input) {
48
- const bytesInput = import_buffer.Buffer.from(input);
49
- return hashEncodedBytes(bytesInput);
50
- }
51
- function hashEncodedBytes(input) {
52
- const hash = BigInt(import_ox.Hash.keccak256(input, { as: "Hex" })) >> 8n;
53
- const rawDigest = hash.toString(16);
54
- return { hash, digest: `0x${rawDigest.padStart(64, "0")}` };
55
- }
56
- var solidityEncode = (types, values) => {
57
- if (types.length !== values.length) {
58
- throw new Error("Types and values arrays must have the same length.");
59
- }
60
- return { types, values };
61
- };
62
- var generateSignal = (signal) => {
63
- if (!signal || typeof signal === "string") return hashToField(signal ?? "");
64
- return packAndEncode(signal.types.map((type, index) => [type, signal.values[index]]));
65
- };
66
- var encodeAction = (action) => {
67
- if (!action) return "";
68
- if (typeof action === "string") return action;
69
- return action.types.map((type, index) => `${type}(${action.values[index]})`).join(",");
70
- };
71
- // Annotate the CommonJS export names for ESM import in node:
72
- 0 && (module.exports = {
73
- encodeAction,
74
- generateSignal,
75
- hashToField,
76
- packAndEncode,
77
- solidityEncode
78
- });
@@ -1,21 +0,0 @@
1
- import { A as AbiEncodedValue, I as IDKitConfig } from '../config-fuwC_Hia.cjs';
2
- import { Bytes } from 'ox';
3
-
4
- interface HashFunctionOutput {
5
- hash: bigint;
6
- digest: `0x${string}`;
7
- }
8
- /**
9
- * Hashes an input using the `keccak256` hashing function used across the World ID protocol, to be used as
10
- * a ZKP input. The function will try to determine the best hashing mechanism, if the string already looks like hex-encoded
11
- * bytes (e.g. `0x0000000000000000000000000000000000000000`), it will be hashed directly.
12
- * @param input Any string, hex-like string, bytes represented as a hex string.
13
- * @returns
14
- */
15
- declare function hashToField(input: Bytes.Bytes | string): HashFunctionOutput;
16
- declare function packAndEncode(input: [string, unknown][]): HashFunctionOutput;
17
- declare const solidityEncode: (types: string[], values: unknown[]) => AbiEncodedValue;
18
- declare const generateSignal: (signal: IDKitConfig['signal']) => HashFunctionOutput;
19
- declare const encodeAction: (action: IDKitConfig['action']) => string;
20
-
21
- export { type HashFunctionOutput, encodeAction, generateSignal, hashToField, packAndEncode, solidityEncode };
@@ -1,21 +0,0 @@
1
- import { A as AbiEncodedValue, I as IDKitConfig } from '../config-fuwC_Hia.js';
2
- import { Bytes } from 'ox';
3
-
4
- interface HashFunctionOutput {
5
- hash: bigint;
6
- digest: `0x${string}`;
7
- }
8
- /**
9
- * Hashes an input using the `keccak256` hashing function used across the World ID protocol, to be used as
10
- * a ZKP input. The function will try to determine the best hashing mechanism, if the string already looks like hex-encoded
11
- * bytes (e.g. `0x0000000000000000000000000000000000000000`), it will be hashed directly.
12
- * @param input Any string, hex-like string, bytes represented as a hex string.
13
- * @returns
14
- */
15
- declare function hashToField(input: Bytes.Bytes | string): HashFunctionOutput;
16
- declare function packAndEncode(input: [string, unknown][]): HashFunctionOutput;
17
- declare const solidityEncode: (types: string[], values: unknown[]) => AbiEncodedValue;
18
- declare const generateSignal: (signal: IDKitConfig['signal']) => HashFunctionOutput;
19
- declare const encodeAction: (action: IDKitConfig['action']) => string;
20
-
21
- export { type HashFunctionOutput, encodeAction, generateSignal, hashToField, packAndEncode, solidityEncode };