@worldcoin/idkit-core 2.0.2 → 4.0.1-dev.123c6a8

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