@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.
@@ -0,0 +1,437 @@
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
+ type CredentialType = "orb" | "face" | "secure_document" | "document" | "device";
10
+ /**
11
+ * A single credential request item
12
+ */
13
+ interface CredentialRequestType {
14
+ /** The type of credential being requested */
15
+ type: CredentialType;
16
+ /** Optional signal string for cryptographic binding */
17
+ signal?: string;
18
+ /** Optional minimum genesis timestamp constraint */
19
+ genesis_issued_at_min?: number;
20
+ }
21
+ /**
22
+ * Constraint node - can be a CredentialRequest or a combinator (any/all)
23
+ */
24
+ type ConstraintNode = CredentialRequestType | {
25
+ any: ConstraintNode[];
26
+ } | {
27
+ all: ConstraintNode[];
28
+ };
29
+ /**
30
+ * Relying Party context for protocol-level proof requests
31
+ *
32
+ * Required for creating a verification session. Contains RP-specific data
33
+ * needed to construct a ProofRequest. In production, this should be generated
34
+ * and signed by your backend.
35
+ */
36
+ type RpContext = {
37
+ /** The registered RP ID (e.g., "rp_123456789abcdef0") */
38
+ rp_id: string;
39
+ /** Unique nonce for this proof request */
40
+ nonce: string;
41
+ /** Unix timestamp (seconds since epoch) when created */
42
+ created_at: number;
43
+ /** Unix timestamp (seconds since epoch) when expires */
44
+ expires_at: number;
45
+ /** The RP's ECDSA signature of the nonce and created_at timestamp */
46
+ signature: string;
47
+ };
48
+ /**
49
+ * Configuration for IDKit.request()
50
+ */
51
+ type IDKitRequestConfig = {
52
+ /** Unique identifier for the app verifying the action. This should be the app ID obtained from the Developer Portal. */
53
+ app_id: `app_${string}`;
54
+ /** Identifier for the action the user is performing. Should be left blank for [Sign in with Worldcoin](https://docs.world.org/id/sign-in). */
55
+ action: AbiEncodedValue | string;
56
+ /** RP context for protocol-level proof requests (required) */
57
+ rp_context: RpContext;
58
+ /** The description of the specific action (shown to users in World App). Only recommended for actions created on-the-fly. */
59
+ action_description?: string;
60
+ /** URL to a third-party bridge to use when connecting to the World App. Optional. */
61
+ bridge_url?: string;
62
+ };
63
+
64
+ declare enum AppErrorCodes {
65
+ ConnectionFailed = "connection_failed",
66
+ VerificationRejected = "verification_rejected",
67
+ MaxVerificationsReached = "max_verifications_reached",
68
+ CredentialUnavailable = "credential_unavailable",
69
+ MalformedRequest = "malformed_request",
70
+ InvalidNetwork = "invalid_network",
71
+ InclusionProofFailed = "inclusion_proof_failed",
72
+ InclusionProofPending = "inclusion_proof_pending",
73
+ UnexpectedResponse = "unexpected_response",
74
+ FailedByHostApp = "failed_by_host_app",
75
+ GenericError = "generic_error"
76
+ }
77
+ declare enum VerificationState {
78
+ PreparingClient = "loading_widget",
79
+ WaitingForConnection = "awaiting_connection",
80
+ WaitingForApp = "awaiting_app",
81
+ Confirmed = "confirmed",
82
+ Failed = "failed"
83
+ }
84
+ declare enum ResponseStatus {
85
+ Retrieved = "retrieved",
86
+ Completed = "completed",
87
+ Initialized = "initialized"
88
+ }
89
+
90
+ interface ISuccessResult {
91
+ proof: string;
92
+ merkle_root: string;
93
+ nullifier_hash: string;
94
+ /** The credential type used to generate the proof */
95
+ verification_level: CredentialType;
96
+ }
97
+ interface IErrorState {
98
+ code: AppErrorCodes;
99
+ message?: string;
100
+ }
101
+
102
+ interface RpSignature {
103
+ sig: string;
104
+ nonce: string;
105
+ createdAt: number;
106
+ expiresAt: number;
107
+ toJSON(): { sig: string; nonce: string; createdAt: number; expiresAt: number };
108
+ }
109
+ declare class RpSignature {
110
+ private constructor();
111
+ free(): void;
112
+ [Symbol.dispose](): void;
113
+ /**
114
+ * Converts to JSON
115
+ *
116
+ * # Errors
117
+ *
118
+ * Returns an error if setting object properties fails
119
+ */
120
+ toJSON(): any;
121
+ /**
122
+ * Gets the creation timestamp
123
+ */
124
+ readonly createdAt: bigint;
125
+ /**
126
+ * Gets the expiration timestamp
127
+ */
128
+ readonly expiresAt: bigint;
129
+ /**
130
+ * Gets the signature as hex string (0x-prefixed, 65 bytes)
131
+ */
132
+ readonly sig: string;
133
+ /**
134
+ * Gets the nonce as hex string (0x-prefixed field element)
135
+ */
136
+ readonly nonce: string;
137
+ }
138
+
139
+ /**
140
+ * WASM initialization and management
141
+ */
142
+
143
+ /**
144
+ * Initializes the WASM module for browser environments
145
+ * Uses fetch-based loading (works with http/https URLs)
146
+ * This must be called before using any WASM-powered functions
147
+ * Safe to call multiple times - initialization only happens once
148
+ */
149
+ declare function initIDKit(): Promise<void>;
150
+ /**
151
+ * Initializes the WASM module for Node.js/server environments
152
+ * Uses fs-based loading since Node.js fetch doesn't support file:// URLs
153
+ * This must be called before using any WASM-powered functions
154
+ * Safe to call multiple times - initialization only happens once
155
+ */
156
+ declare function initIDKitServer(): Promise<void>;
157
+
158
+ /**
159
+ * IDKit Request
160
+ * Pure functional API for World ID verification - no dependencies
161
+ */
162
+
163
+ /** Options for pollForUpdates() */
164
+ interface WaitOptions {
165
+ /** Milliseconds between polls (default: 1000) */
166
+ pollInterval?: number;
167
+ /** Total timeout in milliseconds (default: 300000 = 5 minutes) */
168
+ timeout?: number;
169
+ /** AbortSignal for cancellation */
170
+ signal?: AbortSignal;
171
+ }
172
+ /** Status returned from pollOnce() */
173
+ interface Status {
174
+ type: "waiting_for_connection" | "awaiting_confirmation" | "confirmed" | "failed";
175
+ proof?: ISuccessResult;
176
+ error?: AppErrorCodes;
177
+ }
178
+
179
+ /**
180
+ * A World ID verification request
181
+ *
182
+ * Provides a clean, promise-based API for World ID verification flows.
183
+ * Each request represents a single verification attempt.
184
+ */
185
+ interface IDKitRequest {
186
+ /** QR code URL for World App - display this as a QR code for users to scan */
187
+ readonly connectorURI: string;
188
+ /** Unique request ID for this verification */
189
+ readonly requestId: string;
190
+ /** Poll once for current status (for manual polling) */
191
+ pollOnce(): Promise<Status>;
192
+ /** Poll continuously until completion or timeout */
193
+ pollForUpdates(options?: WaitOptions): Promise<ISuccessResult>;
194
+ }
195
+ /**
196
+ * Creates a CredentialRequest for a credential type
197
+ *
198
+ * @param credential_type - The type of credential to request (e.g., 'orb', 'face')
199
+ * @param options - Optional signal and genesis_issued_at_min
200
+ * @returns A CredentialRequest object
201
+ *
202
+ * @example
203
+ * ```typescript
204
+ * const orb = CredentialRequest('orb', { signal: 'user-123' })
205
+ * const face = CredentialRequest('face')
206
+ * ```
207
+ */
208
+ declare function CredentialRequest(credential_type: CredentialType, options?: {
209
+ signal?: string;
210
+ genesis_issued_at_min?: number;
211
+ }): CredentialRequestType;
212
+ /**
213
+ * Creates an OR constraint - at least one child must be satisfied
214
+ *
215
+ * @param nodes - Constraint nodes (CredentialRequests or nested constraints)
216
+ * @returns An "any" constraint node
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * const constraint = any(CredentialRequest('orb'), CredentialRequest('face'))
221
+ * ```
222
+ */
223
+ declare function any(...nodes: ConstraintNode[]): {
224
+ any: ConstraintNode[];
225
+ };
226
+ /**
227
+ * Creates an AND constraint - all children must be satisfied
228
+ *
229
+ * @param nodes - Constraint nodes (CredentialRequests or nested constraints)
230
+ * @returns An "all" constraint node
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * const constraint = all(CredentialRequest('orb'), any(CredentialRequest('document'), CredentialRequest('secure_document')))
235
+ * ```
236
+ */
237
+ declare function all(...nodes: ConstraintNode[]): {
238
+ all: ConstraintNode[];
239
+ };
240
+ /**
241
+ * OrbLegacy preset configuration
242
+ */
243
+ interface OrbLegacyPreset {
244
+ type: "OrbLegacy";
245
+ data: {
246
+ signal?: string;
247
+ };
248
+ }
249
+ /**
250
+ * Preset types for simplified session creation
251
+ */
252
+ type Preset = OrbLegacyPreset;
253
+ /**
254
+ * Creates an OrbLegacy preset for World ID 3.0 legacy support
255
+ *
256
+ * This preset creates a session compatible with both World ID 4.0 and 3.0 protocols.
257
+ * Use this when you need backward compatibility with older World App versions.
258
+ *
259
+ * @param opts - Optional configuration with signal
260
+ * @returns An OrbLegacy preset
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * const session = await verify({ app_id, action, rp_context })
265
+ * .preset(orbLegacy({ signal: 'user-123' }))
266
+ * ```
267
+ */
268
+ declare function orbLegacy(opts?: {
269
+ signal?: string;
270
+ }): OrbLegacyPreset;
271
+ /**
272
+ * Builder for creating IDKit requests
273
+ */
274
+ declare class IDKitRequestBuilder {
275
+ private config;
276
+ constructor(config: IDKitRequestConfig);
277
+ /**
278
+ * Creates an IDKit request with the given constraints
279
+ *
280
+ * @param constraints - Constraint tree (CredentialRequest or any/all combinators)
281
+ * @returns A new IDKitRequest instance
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * const request = await IDKit.request({ app_id, action, rp_context })
286
+ * .constraints(any(CredentialRequest('orb'), CredentialRequest('face')))
287
+ * ```
288
+ */
289
+ constraints(constraints: ConstraintNode): Promise<IDKitRequest>;
290
+ /**
291
+ * Creates an IDKit request from a preset
292
+ *
293
+ * Presets provide a simplified way to create requests with predefined
294
+ * credential configurations. The preset is converted to both World ID 4.0
295
+ * constraints and World ID 3.0 legacy fields for backward compatibility.
296
+ *
297
+ * @param preset - A preset object from orbLegacy()
298
+ * @returns A new IDKitRequest instance
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * const request = await IDKit.request({ app_id, action, rp_context })
303
+ * .preset(orbLegacy({ signal: 'user-123' }))
304
+ * ```
305
+ */
306
+ preset(preset: Preset): Promise<IDKitRequest>;
307
+ }
308
+ /**
309
+ * Creates an IDKit request builder
310
+ *
311
+ * This is the main entry point for creating World ID verification requests.
312
+ * Use the builder pattern with constraints to specify which credentials to accept.
313
+ *
314
+ * @param config - Request configuration
315
+ * @returns An IDKitRequestBuilder instance
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * import { IDKit, CredentialRequest, any } from '@worldcoin/idkit-core'
320
+ *
321
+ * // Initialize WASM (only needed once)
322
+ * await IDKit.init()
323
+ *
324
+ * // Create request items
325
+ * const orb = CredentialRequest('orb', { signal: 'user-123' })
326
+ * const face = CredentialRequest('face')
327
+ *
328
+ * // Create a verification request with constraints
329
+ * const request = await IDKit.request({
330
+ * app_id: 'app_staging_xxxxx',
331
+ * action: 'my-action',
332
+ * rp_context: {
333
+ * rp_id: 'rp_123456789abcdef0',
334
+ * nonce: 'unique-nonce',
335
+ * created_at: Math.floor(Date.now() / 1000),
336
+ * expires_at: Math.floor(Date.now() / 1000) + 3600,
337
+ * signature: 'ecdsa-signature-from-backend',
338
+ * },
339
+ * }).constraints(any(orb, face))
340
+ *
341
+ * // Display QR code
342
+ * console.log('Scan this:', request.connectorURI)
343
+ *
344
+ * // Wait for proof
345
+ * const proof = await request.pollForUpdates()
346
+ * console.log('Success:', proof)
347
+ * ```
348
+ */
349
+ declare function createRequest(config: IDKitRequestConfig): IDKitRequestBuilder;
350
+ /**
351
+ * IDKit namespace providing the main API entry points
352
+ *
353
+ * @example
354
+ * ```typescript
355
+ * import { IDKit, CredentialRequest, any } from '@worldcoin/idkit-core'
356
+ *
357
+ * // Initialize (only needed once)
358
+ * await IDKit.init()
359
+ *
360
+ * // Create a request
361
+ * const request = await IDKit.request({
362
+ * app_id: 'app_staging_xxxxx',
363
+ * action: 'my-action',
364
+ * rp_context: { ... },
365
+ * }).constraints(any(CredentialRequest('orb'), CredentialRequest('face')))
366
+ *
367
+ * // Display QR and wait for proof
368
+ * console.log(request.connectorURI)
369
+ * const proof = await request.pollForUpdates()
370
+ * ```
371
+ */
372
+ declare const IDKit: {
373
+ /** Initialize WASM for browser environments */
374
+ init: typeof initIDKit;
375
+ /** Initialize WASM for Node.js/server environments */
376
+ initServer: typeof initIDKitServer;
377
+ /** Create a new verification request */
378
+ request: typeof createRequest;
379
+ /** Create a CredentialRequest for a credential type */
380
+ CredentialRequest: typeof CredentialRequest;
381
+ /** Create an OR constraint - at least one child must be satisfied */
382
+ any: typeof any;
383
+ /** Create an AND constraint - all children must be satisfied */
384
+ all: typeof all;
385
+ /** Create an OrbLegacy preset for World ID 3.0 legacy support */
386
+ orbLegacy: typeof orbLegacy;
387
+ };
388
+
389
+ /**
390
+ * Platform detection utilities
391
+ *
392
+ * These functions help detect the runtime environment (React Native, Web, Node.js)
393
+ * to enable platform-specific behavior or warnings.
394
+ */
395
+ /**
396
+ * Checks if the code is running in React Native environment
397
+ * @returns true if running in React Native, false otherwise
398
+ */
399
+ declare const isReactNative: () => boolean;
400
+ /**
401
+ * Checks if the code is running in a web browser environment
402
+ * @returns true if running in a browser, false otherwise
403
+ */
404
+ declare const isWeb: () => boolean;
405
+ /**
406
+ * Checks if the code is running in Node.js environment
407
+ * @returns true if running in Node.js, false otherwise
408
+ */
409
+ declare const isNode: () => boolean;
410
+
411
+ /**
412
+ * Signs an RP request for World ID proof verification
413
+ *
414
+ * **Backend-only**: This function should ONLY be used in Node.js/server environments.
415
+ * Never use this in browser/client-side code as it requires access to your signing key.
416
+ *
417
+ * This function generates a cryptographic signature that authenticates your proof request.
418
+ * The returned signature, nonce, and timestamps should be passed as `rp_context` to the client.
419
+ *
420
+ * @param action - The action tied to the proof request
421
+ * @param signingKeyHex - The ECDSA private key as hex (0x-prefixed or not, 32 bytes)
422
+ * @param ttlSeconds - Optional time-to-live in seconds (defaults to 300 = 5 minutes)
423
+ * @returns RpSignature object with sig, nonce, createdAt, expiresAt to use as rp_context
424
+ * @throws Error if called in non-Node.js environment or if parameters are invalid
425
+ *
426
+ * @example
427
+ * ```typescript
428
+ * import { signRequest } from '@worldcoin/idkit-core'
429
+ *
430
+ * const signingKey = process.env.RP_SIGNING_KEY // Load from secure env var
431
+ * const signature = signRequest('my-action', signingKey)
432
+ * console.log(signature.sig, signature.nonce, signature.createdAt, signature.expiresAt)
433
+ * ```
434
+ */
435
+ declare function signRequest(action: string, signingKeyHex: string, ttlSeconds?: number): RpSignature;
436
+
437
+ export { type AbiEncodedValue, AppErrorCodes, type ConstraintNode, CredentialRequest, type CredentialRequestType, type CredentialType, IDKit, type IDKitRequest, type IDKitRequestConfig, type IErrorState, type ISuccessResult, type OrbLegacyPreset, type Preset, ResponseStatus, type RpContext, RpSignature, type Status, VerificationState, type WaitOptions, all, any, isNode, isReactNative, isWeb, orbLegacy, signRequest };