UNPKG

@reclaimprotocol/js-sdk

Version:

Designed to request proofs from the Reclaim protocol and manage the flow of claims and witness interactions.

1,178 lines (1,172 loc) 97.6 kB
declare const SUPPORTED_TEE_ATTESTATION_VERSIONS: readonly ["v2", "v3"]; type TeeAttestationVersion = typeof SUPPORTED_TEE_ATTESTATION_VERSIONS[number]; interface TeeAttestation { proof_version: TeeAttestationVersion; tee_provider: string; tee_technology: string; nonce: string; timestamp: string; workload: { container_name: string; image_digest: string; }; verifier: { container_name: string; image_digest: string; }; attestation: { token: string; }; error?: { code: string; message: string; }; } interface Proof { identifier: string; claimData: ProviderClaimData; signatures: string[]; witnesses: WitnessData[]; extractedParameterValues: any; /** * A JSON serializable object that is returned by the provider as additional data attached to proof. * This data is not verified or validated. */ publicData?: any; taskId?: number; teeAttestation?: TeeAttestation; } declare const RECLAIM_EXTENSION_ACTIONS: { CHECK_EXTENSION: string; EXTENSION_RESPONSE: string; START_VERIFICATION: string; STATUS_UPDATE: string; }; interface ExtensionMessage { action: string; messageId: string; data?: any; extensionID?: string; } interface WitnessData { id: string; url: string; claimAttestation?: AttestorClaimAttestation; } /** * Attestation produced by an attestor running inside a Trusted Execution * Environment. Binds the attestor's signing key (and its signature over * the claim) to a hardware-backed enclave identity. * * Verified by `runAttestorTeeVerification`. */ interface AttestorClaimAttestation { /** ETH address of the attestor whose enclave produced the attestation. Matches `WitnessData.id`. */ attestor_address: string; /** Attestor signature over the claim. Must equal the corresponding entry in `Proof.signatures`. */ claim_signature: string; /** Raw attestation report. For GCP Confidential Space, a JWT (header.payload.signature). */ attestation_report: string; } interface ProviderClaimData { provider: string; parameters: string; owner: string; timestampS: number; context: string; identifier: string; epoch: number; } interface Context { contextAddress: string; contextMessage: string; reclaimSessionId: string; extractedParameters?: Record<string, string>; providerHash?: string; attestationNonce?: string; attestationNonceData?: { applicationId: string; sessionId: string; timestamp: string; attestationVersion?: TeeAttestationVersion; }; } interface Beacon { getState(epoch?: number): Promise<BeaconState>; close?(): Promise<void>; } type BeaconState = { witnesses: WitnessData[]; epoch: number; witnessesRequiredForClaim: number; nextEpochTimestampS: number; }; /** * Information of the exact provider and its version used in the verification session. * * See also: * * * `ReclaimProofRequest.getProviderVersion()` - With a ReclaimProofRequest object, you can get the provider id & exact version of provider used in verification session. */ interface ProviderVersionInfo { /** * The identifier of provider used in verifications that resulted in a proof * * See also: * * * `ReclaimProofRequest.getProviderVersion()` - With a ReclaimProofRequest object, you can get the provider id & exact version of provider used in verification session. */ providerId: string; /** * The exact version of provider used in verifications that resulted in a proof. * * This cannot be a version constaint or version expression. * * See also: * * * `ReclaimProofRequest.getProviderVersion()` - With a ReclaimProofRequest object, you can get the provider id & exact version of provider used in verification session. */ providerVersion: string; /** * List of allowed pre-release tags. * For example, if you are using AI, provide `['ai']` to allow AI patch versions of the provider. */ allowedTags: string[]; } /** * Fetches the provider configuration by the providerId and its version; and constructs the robust hash requirements needed for proof validation. * It resolves both explicitly required HTTP requests and allowed injected requests based on the provider version. * * See also: * * * `ReclaimProofRequest.getProviderHashRequirements()` - An alternative of this function to get the expected hashes for a proof request. The result can be provided in verifyProof function's `config` parameter for proof validation. * * `getProviderHashRequirementsFromSpec()` - An alternative of this function to get the expected hashes from a provider spec. The result can be provided in verifyProof function's `config` parameter for proof validation. * * @param providerId - The unique identifier of the selected provider. * @param exactProviderVersionString - The specific version string of the provider configuration to ensure deterministic validation. * @returns A promise that resolves to `ProviderHashRequirementsConfig` representing the expected hashes for proof validation. */ declare function fetchProviderHashRequirementsBy(providerId: string, exactProviderVersionString: string | null | undefined, allowedTags: string[] | null | undefined, proofs?: Proof[]): Promise<ProviderHashRequirementsConfig[]>; /** * Generates an array of `RequestSpec` objects by replacing template parameters with their corresponding values. * * If the input template includes `templateParams` (e.g., `['param1', 'param2']`), this function will * cartesian-map (or pairwise-map) the provided `templateParameters` record (e.g., `{ param1: ['v1', 'v2'], param2: ['a1', 'a2'] }`) * to generate `RequestSpec` configurations. How those configurations are shaped is controlled by * `template.templateParamsMode` (defaults to `'separate'`): * * - `'separate'`: each value pair produces its own independent `RequestSpec` — N values in, N * specs out, each expected to match its own separate proof. * - `'merge'`: all value pairs are folded into a single `RequestSpec`, whose `responseMatches`/ * `responseRedactions` arrays gain one entry per value — N values in, 1 spec out (with N * entries), expected to match one proof that bundles all N values into a single claim. * * The function ensures that: * 1. Parameters strictly specified in `template.templateParams` are found — unless NONE of them * are present at all AND the template is optional (`template.required === false`), in which * case that template is silently skipped (contributes no spec) rather than throwing. This is * the expected shape for a template describing data a user may legitimately not have at all * (e.g. zero followed artists never produces that group's witness params in any proof). * A required (default) template with missing params still throws, and a template with only * SOME of its declared params present (a partial, inconsistent match) still throws regardless * of `required` — that indicates malformed data, not legitimate absence. * 2. All specified template parameters arrays have the exact same length (pairwise mapping). * 3. String replacements are fully applied (all occurrences) to `responseMatches` (value) and `responseRedactions` (jsonPath, xPath, regex). * * @param requestSpecTemplates - The base template `RequestSpec` containing parameter placeholders. * @param templateParameters - A record mapping parameter names to arrays of strings representing the extracted values. * @returns An array of fully constructed `RequestSpec` objects with templates replaced. May contain * fewer entries than `requestSpecTemplates` when optional templates were skipped per the above. * @throws {InvalidRequestSpecError} If a required template's parameters are missing, or any template's * parameter value arrays have mismatched lengths. */ declare function generateSpecsFromRequestSpecTemplate(requestSpecTemplates: RequestSpec[], templateParameters: Record<string, string[]>): RequestSpec[]; declare function takeTemplateParametersFromProofs(proofs?: Proof[]): Record<string, string[]>; declare function takePairsWhereValueIsArray(o: Record<string, string> | undefined): Record<string, string[]>; /** * Builds and returns raw hash requirement spec that can be used with `getProviderHashRequirementsFromSpec` to computes the expected proof hashes for a provider configuration * by combining its explicitly required requests and allowed injected requests. * It resolves template parameters from provided proofs to generate the final request specifications. * * @param providerConfig - The provider configuration containing request data and allowed injected requests. * @param proofs - Optional array of proofs used to extract template parameters for resolving placeholders in injected requests. * @returns A structured configuration containing that can be used with `getProviderHashRequirementsFromSpec` to compute the hashes. */ declare function getProviderHashRequirementSpecFromProviderConfig(providerConfig: ReclaimProviderConfigWithRequestSpec, proofs?: Proof[]): ProviderHashRequirementSpec; /** * Transforms a raw provider hash requirement specification into a structured configuration for proof validation. * It computes the proof hashes for both required and allowed extra requests to correctly match uploaded proofs. * * See also: * * * `fetchProviderHashRequirementsBy()` - An alternative of this function to get the expected hashes for a provider version by providing providerId and exactProviderVersionString. The result can be provided in verifyProof function's `config` parameter for proof validation. * * `ReclaimProofRequest.getProviderHashRequirements()` - An alternative of this function to get the expected hashes for a proof request. The result can be provided in verifyProof function's `config` parameter for proof validation. * * @param spec - The raw provider specifications including required and allowed requests. * @returns A structured configuration containing computed required and allowed hashes for validation. */ declare function getProviderHashRequirementsFromSpec(spec: ProviderHashRequirementSpec): ProviderHashRequirementsConfig; /** * Computes the claim hash for a specific request specification based on its properties. * * @param request - The HTTP request specification (e.g., URL, method, sniffs). * @returns A string representing the hashed proof claim parameters. */ declare function hashRequestSpec(request: RequestSpec): HashRequirement; /** * Represents the raw specification of hash requirements provided by a provider's configuration. */ interface ProviderHashRequirementSpec { /** List of request specs that can match with HTTP requests to create a proof using Reclaim Protocol */ requests: RequestSpec[] | undefined; } /** * The structured hash requirements configuration used during proof verification and content validation. */ type ProviderHashRequirementsConfig = { /** * Array of computed hash requirements that must be satisfied by the proofs. */ hashes: HashRequirement[]; }; /** * Describes a hash requirement for a proof. */ type HashRequirement = { /** * The hash value(s) to match. An array represents multiple valid hashes for optional configurations. */ value: string | string[]; /** * Whether the hash is required to be present in the proof. * Defaults to true */ required?: boolean; /** * Whether the hash can appear multiple times in the proof. * Defaults to false */ multiple?: boolean; }; interface ReclaimProviderConfigWithRequestSpec { requestData: InterceptorRequestSpec[]; allowedInjectedRequestData: InjectedRequestSpec[]; } /** * Specific marker interface for intercepted request specifications. */ interface InterceptorRequestSpec extends RequestSpec { } /** * Specific marker interface for injected request specifications. */ interface InjectedRequestSpec extends RequestSpec { } /** * Represents the properties and validation steps for an HTTP request involved in a Reclaim proof. */ interface RequestSpec { /** The URL or generic path of the HTTP request */ url: string; /** Type or representation of the URL */ urlType: string; /** The HTTP method used for the request */ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; /** Identifies and captures the request body if enabled */ bodySniff: BodySniff; /** Required matching configurations for the HTTP response */ responseMatches: ResponseMatchSpec[]; /** Redaction rules applied to the HTTP response before passing to attestors */ responseRedactions: ResponseRedactionSpec[]; /** * Whether request matching this spec is required and always expected in list of proofs * Defaults to true. */ required?: boolean; /** * Whether request matching this spec is allowed to appear multiple times in list of proofs. * Defaults to true. */ multiple?: boolean; /** * Template parameter variables for the request spec that should be replaced with real values * during dynamic request spec construction. */ templateParams?: string[]; /** * Controls how a template with multiple values per `templateParams` entry is expanded by * `generateSpecsFromRequestSpecTemplate`. * * - `'separate'` (default): each value produces its own independent `RequestSpec` (and * therefore its own expected hash), matching N separate proofs. Use this when the same * small claim shape is expected to appear as N separate proofs (e.g. one proof per employee * record). * - `'merge'`: all values are folded into a single `RequestSpec`, with one `responseMatches`/ * `responseRedactions` entry generated per value, matching one proof/hash. Use this when a * single claim bundles many values together (e.g. one claim proving 30 playlist names at * once) — the shape that `'separate'` cannot express, since it can only ever produce many * small specs, never one combined spec. */ templateParamsMode?: 'separate' | 'merge'; } /** * Defines the configuration for identifying/sniffing the request body. */ interface BodySniff { /** Indicates whether body sniffing is enabled */ enabled: boolean; /** The template string used to match or capture the body */ template: string; } /** * Specifies a rule to match against a string in response to validate proof content. */ interface ResponseMatchSpec { /** If true, the match condition is reversed */ invert: boolean | undefined; /** If true, the match condition is optional and won't fail if absent */ isOptional: boolean | undefined; /** The matching mechanism, typically regex or simple string containment */ type: "regex" | "contains"; /** The pattern or value to look for in the response */ value: string; } /** * Specifies redaction rules for obscuring sensitive parts of the response. */ interface ResponseRedactionSpec { /** Optional hashing method applied to the redacted content (e.g., 'oprf') */ hash?: "oprf" | "oprf-mpc" | "oprf-raw" | undefined; /** JSON path for locating the value to redact */ jsonPath: string; /** RegEx applied to correctly parse and extract/redact value */ regex: string; /** XPath for XML/HTML matching configuration */ xPath: string; } /** * Result of verifying an attestor TEE attestation. */ type AttestorTeeVerificationResult = { isVerified: boolean; error?: string; /** sha256 image digest of the attestor container, on success. */ imageDigest?: string; }; /** * Validates a GCP Confidential Space attestation JWT produced by an * attestor running in a Confidential Space VM, and asserts that the * attestation binds to the given attestor address. * * The attestor (running inside the TEE) calls the Confidential Space * launcher's attestation endpoint with two nonces: * - `attestor_public_key:<eth-address>` - binds to the signing key. * - `attestor_cert_hash:<sha256-hex>` - binds to the live TLS cert. * * This function only verifies the public-key nonce. The TLS cert hash * binding is informational and not checked here. Callers that need to * pin to a specific attestor image should compare the returned * `imageDigest` against a known-good value. * * The JWT signature is verified by walking the x5c certificate chain * to a pinned GCP Confidential Space Root CA. No outbound network * calls are made. * * Node-only (uses node:crypto). Mirrors the environment restriction in * the existing `verifyTeeAttestation` helper. * * @param report - the raw JWT string (header.payload.signature). * @param expectedAttestorAddress - hex ETH address (0x-prefixed or * unprefixed) that the attestation should be bound to. */ declare function verifyAttestorTeeAttestation(report: string, expectedAttestorAddress: string): Promise<AttestorTeeVerificationResult>; /** * Configuration for verifying the attestor's TEE attestation on each * witness of the proof. */ type AttestorTeeAttestationConfig = { /** * Optional allowlist of expected attestor container image digests * (e.g. `"sha256:4906340f..."`). When provided, the attestation's * `submods.container.image_digest` must be in this list. * * Leave undefined to skip image pinning and rely solely on the JWT * chain rooting to the GCP Confidential Space Root CA + nonce * binding to the attestor address. */ expectedImageDigests?: string[]; }; /** * Content validation configuration specifying essential required hashes and optional extra proofs. * Used to explicitly validate that a generated proof matches the exact request structure expected. */ type ValidationConfigWithHash = { /** * Array of computed hashes that must be satisfied by the proofs. * * An element can be a `HashRequirement` object or a string that is equivalent to * a `{ value: '<hash>', required: true, multiple: false }` as `HashRequirement`. */ hashes: (string | HashRequirement)[]; }; /** * Content validation configuration specifying the provider id and version used in the verification session that generated the proofs. * Used to explicitly validate that a generated proof matches the exact request structure expected. * * See also: * * * `ReclaimProofRequest.getProviderVersion()` - With a ReclaimProofRequest object, you can get the provider id & exact version of provider used in verification session. */ interface ValidationConfigWithProviderInformation { /** * The identifier of provider used in verifications that resulted in a proof * * See also: * * * `ReclaimProofRequest.getProviderVersion()` - With a ReclaimProofRequest object, you can get the provider id & exact version of provider used in verification session. **/ providerId: string; /** * The exact version of provider used in verifications that resulted in a proof. * * This cannot be a version constaint or version expression. It can be undefined or left blank if proof must be validated with latest version of provider. * Patches for the next provider version are also fetched and hashes from that spec is also be used to compare the hashes from proof. * * See also: * * * `ReclaimProofRequest.getProviderVersion()` - With a ReclaimProofRequest object, you can get the provider id & exact version of provider used in verification session. **/ providerVersion?: string; /** * List of allowed pre-release tags. * For example, if you are using AI, provide `['ai']` to allow AI patch versions of the provider. */ allowedTags?: string[]; } /** * Legacy configuration to completely bypass content validation during verification. * Warning: Using this poses a risk as it avoids strictly matching proof parameters to expected hashes. */ interface ValidationConfigWithDisabledValidation { dangerouslyDisableContentValidation: true; } /** * Represents the configuration options applied when validating proof contents, allowing * strict hash checking or intentionally skipping validation if flagged. */ type ValidationConfig = ValidationConfigWithHash | ValidationConfigWithProviderInformation | ValidationConfigWithDisabledValidation; /** * Describes the comprehensive configuration required to initialize the proof verification process. * Aligns with `ValidationConfig` options for verifying signatures alongside proof contents. */ type TeeAttestationConfig = { /** * Your application secret (Ethereum private key). * Used to recompute the TEE attestation nonce and to derive the application ID * for binding the attestation to your application. */ appSecret: string; }; type VerifyAttestationConfig = { /** * TEE attestation verification configuration. * When provided, verifies the TEE attestation included in the proof. * The result will include `isTeeAttestationVerified` and `isVerified` will be false * if TEE attestation data is missing or verification fails. */ teeAttestation?: TeeAttestationConfig; /** * Attestor TEE attestation verification configuration. * When provided, verifies that every witness on every proof has a valid * `claimAttestation` from an attestor running inside a TEE (GCP * Confidential Space). * * Independent of `teeAttestation`, which verifies the verifier-app's * own TEE attestation. Both can be enabled together. * * The result will include `isAttestorTeeAttestationVerified` and * `isVerified` will be false if any witness is missing TEE attestation * data or its verification fails. */ attestorTeeAttestation?: AttestorTeeAttestationConfig; }; type PiiVerificationConfig = { hasNoPii?: true; }; type VerificationConfig = ValidationConfig & VerifyAttestationConfig & PiiVerificationConfig; declare const HASH_REQUIRED_DEFAULT = true; declare const HASH_MATCH_MULTIPLE_DEFAULT = true; declare function getHashFromProof(proof: Proof, piiConfig?: PiiVerificationConfig): string[]; declare function assertValidProofsByHash(proofs: Proof[], config: ProviderHashRequirementsConfig, piiConfig?: PiiVerificationConfig): void; declare function isHttpProviderClaimParams(claimParams: unknown): claimParams is HttpProviderClaimParams; declare function getHttpProviderClaimParamsFromProof(proof: Proof): HttpProviderClaimParams; /** * Asserts that the proof is validated by checking the content of proof with with expectations from provider config or hash based on [options] * @param proofs - The proofs to validate * @param config - The validation config * @throws {ProofNotValidatedError} When the proof is not validated */ declare function assertValidateProof(proofs: Proof[], config: VerificationConfig, piiConfig?: PiiVerificationConfig): Promise<void>; type ClaimID = ProviderClaimData['identifier']; type ClaimInfo = Pick<ProviderClaimData, 'context' | 'provider' | 'parameters'>; type CompleteClaimData = Pick<ProviderClaimData, 'owner' | 'timestampS' | 'epoch'> & ClaimInfo; interface HttpProviderClaimParams { body?: string | null; method: RequestSpec['method']; responseMatches: ResponseMatchSpec[]; responseRedactions: ResponseRedactionSpec[]; url: string; } interface HashableHttpProviderClaimParams { body: string; method: RequestSpec['method']; responseMatches: (Omit<ResponseMatchSpec, 'isOptional'>)[]; responseRedactions: ResponseRedactionSpec[]; url: string; } type SignedClaim = { claim: CompleteClaimData; signatures: Uint8Array[]; }; type CreateVerificationRequest = { providerIds: string[]; applicationSecret?: string; }; type StartSessionParams = { /** * Callback function that is invoked when the session is successfully created. * * @param proofOrProofs - A single proof object or an array of proof objects. This can be empty when proofs are sent to callback. */ onSuccess: OnSuccess; /** * Callback function that is invoked when the session fails to be created. * * @param error - The error that caused the session to fail. */ onError: OnError; /** * Configuration for proof validation. Defaults to the provider id and version used in this session. */ verificationConfig?: VerificationConfig; }; /** * Callback function that is invoked when the session is successfully created. * * @param proofOrProofs - A single proof object or an array of proof objects. This can be empty when proofs are sent to callback. */ type OnSuccess = (proofOrProofs: Proof | Proof[]) => void; /** * Callback function that is invoked when the session fails to be created. * * @param error - The error that caused the session to fail. */ type OnError = (error: Error) => void; type ProofRequestOptions = { /** * Enables troubleshooting mode and more verbose logging */ log?: boolean; /** * Accepts AI providers in the verification flow */ acceptAiProviders?: boolean; useAppClip?: boolean; device?: string; envUrl?: string; useBrowserExtension?: boolean; extensionID?: string; providerVersion?: string; /** * @deprecated Use `portalUrl` instead. */ customSharePageUrl?: string; /** * URL of the portal/share page for the verification flow. * * @default 'https://portal.reclaimprotocol.org' */ portalUrl?: string; customAppClipUrl?: string; launchOptions?: ReclaimFlowInitOptions; /** * Whether the verification client should automatically submit necessary proofs once they are generated. * If set to false, the user must manually click a button to submit. * * @since 4.7.0 * @default true */ canAutoSubmit?: boolean; /** * An identifier used to select a user's language and formatting preferences. * * Locales are expected to be canonicalized according to the "preferred value" entries in the [IANA Language Subtag Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). * For example, `he`, and `iw` are equal and both have the languageCode `he`, because `iw` is a deprecated language subtag that was replaced by the subtag `he`. * * Defaults to the browser's locale if available, otherwise English (en). * * For more info, refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#description * * @since 4.9.0 */ preferredLocale?: string; /** * Additional metadata to pass to the verification client frontend. * This can be used to customize the client UI experience, such as customizing themes or UI by passing context-specific information. * The keys and values must be strings. For most clients, this is not required and goes unused. * * This has no effect on the verification process. * * Example: `{ theme: 'dark', verify_another_way_link: 'https://exampe.org/alternative-verification?id=1234' }` * * @since 4.7.0 */ metadata?: Record<string, string>; /** * Generates a TEE attestation nonce during session initialization and expects a TEE attestation in the proof. * * @default true */ acceptTeeAttestation?: boolean; /** * Identifier of the partner organization (e.g. the SheerID orgId) this * verification session belongs to. * * When set, it is included on session initialization and on session status * updates sent by the SDK, and in the template passed to the verification * client, which forwards it on its own status updates. Used for * per-organization attribution/analytics. * * This has no effect on the verification process. */ orgId?: string; }; type ReclaimFlowInitOptions = { /** * Enables deferred deep links for the Reclaim verification flow. * * When enabled, users without the verifier app installed will receive a deferred deep link * that automatically launches the verification flow after they install the app, ensuring * a seamless continuation of the verification process. * * **Default Behavior:** Enabled by default for Android. Opt-in during rollout phase for iOS. * Will default to `true` for all apps once fully released. * See: https://blog.reclaimprotocol.org/posts/moving-beyond-google-play-instant */ canUseDeferredDeepLinksFlow?: boolean; /** * Verification mode for the flow. * * - `'portal'`: Opens the portal URL in the browser (remote browser verification). * - `'app'`: Verifier app flow via the share page. If `useAppClip` is `true`, uses App Clip on iOS. * * Can be set at call time via `triggerReclaimFlow({ verificationMode })` or `getRequestUrl({ verificationMode })`, * or at init time via `launchOptions: { verificationMode }`. * * @default 'portal' */ verificationMode?: 'app' | 'portal'; /** * The deeplink to ios mobile application. * Defaults to `reclaimverifier://org.reclaimprotocol.app`. */ iosDeepLinkBaseUrl?: string; /** * The link to ios app store page. * Defaults to Reclaim Verifier's iOS App store page * `itms-apps://apps.apple.com/in/app/reclaim-verifier/id6503247508` */ iosAppDownloadUrl?: string; }; type ReclaimFlowLaunchOptions = ReclaimFlowInitOptions & { /** * Target DOM element to embed the verification flow in an iframe. * When provided, the portal opens inside the element instead of a new tab. * Use `closeEmbeddedFlow()` to remove the iframe programmatically. * * Only applies to portal mode. */ target?: HTMLElement; }; /** * Handle returned by `triggerReclaimFlow` to control the launched flow. */ type FlowHandle = { /** Closes the flow (removes iframe, closes tab, stops polling) */ close: () => void; /** The iframe element when using embedded mode, `undefined` otherwise */ iframe?: HTMLIFrameElement; /** The tab/window reference when using new tab mode, `undefined` otherwise */ tab?: Window | null; }; /** Alias for `FlowHandle` */ type EmbeddedFlowHandle = FlowHandle; type ModalOptions = { title?: string; description?: string; extensionUrl?: string; darkTheme?: boolean; modalPopupTimer?: number; showExtensionInstallButton?: boolean; onClose?: () => void; }; type SerializableModalOptions = Omit<ModalOptions, 'onClose'>; declare enum ClaimCreationType { STANDALONE = "createClaim", ON_ME_CHAIN = "createClaimOnMechain" } declare enum DeviceType { ANDROID = "android", IOS = "ios", DESKTOP = "desktop", MOBILE = "mobile" } type InitSessionResponse = { sessionId: string; resolvedProviderVersion: string; }; interface UpdateSessionResponse { success: boolean; message?: string; } declare enum SessionStatus { SESSION_INIT = "SESSION_INIT", SESSION_STARTED = "SESSION_STARTED", USER_INIT_VERIFICATION = "USER_INIT_VERIFICATION", USER_STARTED_VERIFICATION = "USER_STARTED_VERIFICATION", PROOF_GENERATION_STARTED = "PROOF_GENERATION_STARTED", PROOF_GENERATION_SUCCESS = "PROOF_GENERATION_SUCCESS", PROOF_GENERATION_FAILED = "PROOF_GENERATION_FAILED", PROOF_SUBMITTED = "PROOF_SUBMITTED", AI_PROOF_SUBMITTED = "AI_PROOF_SUBMITTED", PROOF_SUBMISSION_FAILED = "PROOF_SUBMISSION_FAILED", ERROR_SUBMITTED = "ERROR_SUBMITTED", ERROR_SUBMISSION_FAILED = "ERROR_SUBMISSION_FAILED", PROOF_MANUAL_VERIFICATION_SUBMITED = "PROOF_MANUAL_VERIFICATION_SUBMITED", SESSION_CANCELLED = "SESSION_CANCELLED" } type ProofPropertiesJSON = { applicationId: string; providerId: string; sessionId: string; context: Context; signature: string; redirectUrl?: string; redirectUrlOptions?: TemplateData['redirectUrlOptions']; parameters: { [key: string]: string; }; /** * @deprecated use timestamp instead (maintained for compatibility) */ timeStamp?: string; timestamp?: string; appCallbackUrl?: string; cancelCallbackUrl?: TemplateData['cancelCallbackUrl']; cancelRedirectUrl?: TemplateData['cancelRedirectUrl']; cancelRedirectUrlOptions?: TemplateData['cancelRedirectUrlOptions']; claimCreationType?: ClaimCreationType; options?: ProofRequestOptions; sdkVersion: string; jsonProofResponse?: boolean; resolvedProviderVersion: string; modalOptions?: SerializableModalOptions; teeAttestation?: TeeAttestation | string; }; type HttpFormEntry = { name: string; value: string; }; type HttpRedirectionMethod = 'GET' | 'POST'; /** * Options for HTTP redirection. * * Only supported by Portal flow. * On other SDKs, this will be ignored and a GET redirection will be performed with the URL. * * @since 4.11.0 * @default "{ method: 'GET' }" */ type HttpRedirectionOptions = { /** * List of name-value pairs to be sent as the body of the form request. * When `method` is set to `POST`, `body` will be sent with 'application/x-www-form-urlencoded' content type. * When `method` is set to `GET`, `body` will be sent as query parameters. * * @default undefined */ body?: HttpFormEntry[] | null | undefined; /** * HTTP method to use for the redirection. * * POST will result in `body` being sent with 'application/x-www-form-urlencoded' content type. * GET will result in `body`, if present, being sent as query parameters. * * With `method` set to `GET` and no `body`, this will result in a simple GET redirection using `window.location.href`. * * @default 'GET' */ method?: HttpRedirectionMethod; }; type TemplateData = { sessionId: string; providerId: string; applicationId: string; signature: string; timestamp: string; callbackUrl: string; context: string; parameters: { [key: string]: string; }; redirectUrl: string; redirectUrlOptions?: HttpRedirectionOptions; cancelCallbackUrl?: string | null; cancelRedirectUrl?: string | null; cancelRedirectUrlOptions?: HttpRedirectionOptions; acceptAiProviders: boolean; sdkVersion: string; jsonProofResponse?: boolean; providerVersion?: string; resolvedProviderVersion: string; log?: boolean; canAutoSubmit?: boolean; metadata?: Record<string, string>; preferredLocale?: ProofRequestOptions['preferredLocale']; acceptTeeAttestation?: boolean; teeAttestationVersion?: TeeAttestationVersion; orgId?: string; }; type TrustedData = { context: Record<string, unknown>; extractedParameters: Record<string, string>; }; type VerifyProofResultSuccess = { isVerified: true; isTeeAttestationVerified?: boolean; isAttestorTeeAttestationVerified?: boolean; error: undefined; data: TrustedData[]; publicData: any[]; }; type VerifyProofResultFailure = { isVerified: false; isTeeAttestationVerified?: boolean; isAttestorTeeAttestationVerified?: boolean; error: Error; data: []; publicData: []; }; type VerifyProofResult = VerifyProofResultSuccess | VerifyProofResultFailure; type ProviderVersionConfig = { major?: number; minor?: number; patch?: number; prereleaseTag?: string; prereleaseNumber?: number; }; type StatusUrlResponse = { message: string; session?: { id: string; appId: string; httpProviderId: string[]; providerId: string; providerVersionString: string; sessionId: string; proofs?: Proof[]; statusV2: string; error?: { type: string; message: string; }; }; providerId?: string; }; type ProviderConfigResponse = { message: string; providers?: ReclaimProviderConfig[]; providerId?: string; providerVersionString?: string; }; interface ReclaimProviderConfig extends ReclaimProviderConfigWithRequestSpec { loginUrl: string; customInjection: string; geoLocation: string; injectionType: string; disableRequestReplay: boolean; verificationType: string; } type ProviderHashRequirementsResponse = { message?: string; hashRequirements?: ProviderHashRequirementsConfig; providerId?: string; providerVersionString?: string; }; /** * Verifies one or more Reclaim proofs by validating signatures, verifying witness information, * and performing content validation against the expected configuration. * * See also: * * * `ReclaimProofRequest.getProviderHashRequirements()` - To get the expected proof hash requirements for a proof request. * * `fetchProviderHashRequirementsBy()` - To get the expected proof hash requirements for a provider version by providing providerId and exactProviderVersionString. * * `getProviderHashRequirementsFromSpec()` - To get the expected proof hash requirements from a provider spec. * * All 3 functions above are alternatives of each other and result from these functions can be directly used as `config` parameter in this function for proof validation. * * Replay protection: this function is stateless. It verifies that a proof is cryptographically * bound to a specific `sessionId`/`applicationId` (via the `appSecret`-keyed attestation nonce * when `teeAttestation` is provided) but does not track which proofs have already been * verified. Callers must (a) verify the proof's `sessionId` matches a session they initiated * and (b) persist accepted `sessionId`s and reject duplicates. See the README's * "Replay Protection" section for details. * * @param proofOrProofs - A single proof object or an array of proof objects to be verified. * @param config - Verification configuration that specifies required hashes, allowed extra hashes, or disables content validation. Optionally includes `teeAttestation` to require TEE attestation verification. * @returns Verification result with `isVerified`, `isTeeAttestationVerified` (always boolean), extracted `data` from each proof, and optional `error` on failure. The application ID is derived from `appSecret` automatically. * * @example * ```typescript * // Fast and simple automatically fetched verification * const { isVerified, data } = await verifyProof(proof, request.getProviderVersion()); * * // With TEE attestation verification (fails if TEE data is missing or invalid) * const { isVerified, isTeeAttestationVerified, data } = await verifyProof(proof, { ...request.getProviderVersion(), teeAttestation: { appSecret: APP_SECRET } }); * * // Or, by manually providing the details: * * const { isVerified, data } = await verifyProof(proof, { * providerId: "YOUR_PROVIDER_ID", * // The exact provider version used in the session. * providerVersion: "1.0.0", * // Optionally provide tags. For example, this can be `['ai']` when you want to allow patches from ai. * allowedTags: ["ai"] * }); * * // Validate a single proof against expected hash * const { isVerified, data } = await verifyProof(proof, { hashes: ['0xAbC...'] }); * if (isVerified) { * console.log(data[0].context); * console.log(data[0].extractedParameters); * } * * // Validate multiple proofs * const { isVerified, data } = await verifyProof([proof1, proof2], { * hashes: ['0xAbC...', '0xF22..'], * }); * * // Validate multiple proofs and handle optional matches or repeated proofs * const { isVerified, data } = await verifyProof([proof1, proof2, sameAsProof2], { * hashes: [ * // A string hash is perfectly equivalent to { value: '...', required: true, multiple: true } * '0xStrict1...', * // An array 'value' means 1 proof can have any 1 matching hash from this list. * // 'multiple: true' (the default) means any proof matching this hash is allowed to appear multiple times in the list of proofs. * { value: ['0xOpt1..', '0xOpt2..'], multiple: true }, * // 'required: false' means there can be 0 proofs matching this hash. Such proofs may be optionally present. (Defaults to true). * { value: '0xE33..', required: false } * ], * }); * ``` */ declare function verifyProof(proofOrProofs: Proof | Proof[], config: VerificationConfig): Promise<VerifyProofResult>; /** * Transforms a Reclaim proof into a format suitable for on-chain verification * * @param proof - The proof object to transform * @returns Object containing claimInfo and signedClaim formatted for blockchain contracts * * @example * ```typescript * const { claimInfo, signedClaim } = transformForOnchain(proof); * // Use claimInfo and signedClaim with smart contract verification * ``` */ declare function transformForOnchain(proof: Proof): { claimInfo: any; signedClaim: any; }; declare class ReclaimProofRequest { private applicationId; private signature?; private appCallbackUrl?; private sessionId; private options?; private context; private attestationNonce?; private attestationNonceData?; private claimCreationType?; private providerId; private resolvedProviderVersion?; private parameters; private redirectUrl?; private redirectUrlOptions?; private cancelCallbackUrl?; private cancelRedirectUrl?; private cancelRedirectUrlOptions?; private intervals; private timeStamp; private sdkVersion; private jsonProofResponse; private lastFailureTime?; private templateData; private extensionID; private customSharePageUrl?; private appSharePageUrl; private customAppClipUrl?; private portalTab?; private portalIframe?; private modalOptions?; private modal?; private readonly FAILURE_TIMEOUT; private constructor(); /** * Initializes a new Reclaim proof request instance with automatic signature generation and session creation. * * @param applicationId - Your Reclaim application ID * @param appSecret - Your application secret key for signing requests * @param providerId - The ID of the provider to use for proof generation * @param options - Optional configuration options for the proof request * @returns A fully initialized proof request instance * @throws {InitError} When initialization fails due to invalid parameters or session creation errors * * @example * ```typescript * const proofRequest = await ReclaimProofRequest.init( * 'your-app-id', * 'your-app-secret', * 'provider-id', * { portalUrl: 'https://portal.reclaimprotocol.org', log: true } * ); * ``` */ static init(applicationId: string, appSecret: string, providerId: string, options?: ProofRequestOptions): Promise<ReclaimProofRequest>; /** * Initializes a new Reclaim proof request using a signature computed externally * (e.g. on a trusted backend), so `appSecret` never has to live on the client. * * The signature must be produced over `canonicalize({ providerId, timestamp })` * using the application's `appSecret` — see `generateInitSignature()` for the * exact algorithm. The same `timestamp` used at signing time must be passed here. * * TEE attestation: the attestation nonce depends on `sessionId`, which is only * known after the backend init call. To use TEE without exposing `appSecret`, * pass an async `getAttestationNonce` callback that derives the nonce on your * server using `generateAttestationNonce(appSecret, applicationId, sessionId, timestamp)`. * If `acceptTeeAttestation` is left enabled but no callback is provided, init throws. * * @param applicationId - Your Reclaim application ID * @param providerId - The ID of the provider to use for proof generation * @param sessionAuth - Pre-computed signature, the timestamp it was signed over, * and an optional async callback to compute the attestation nonce. * @param options - Optional configuration options for the proof request * * @example * ```typescript * // Backend (Node): * const timestamp = Date.now().toString(); * const signature = await generateInitSignature(APP_SECRET, providerId, timestamp); * // ...return { signature, timestamp } to the client... * * // Client: * const proofRequest = await ReclaimProofRequest.initWithSignature( * applicationId, * providerId, * { signature, timestamp }, * { acceptTeeAttestation: false } * ); * ``` */ static initWithSignature(applicationId: string, providerId: string, sessionAuth: { signature: string; timestamp: string; getAttestationNonce?: (sessionId: string) => Promise<string> | string; }, options?: ProofRequestOptions): Promise<ReclaimProofRequest>; /** * Creates a ReclaimProofRequest instance from a JSON string representation * * This method deserializes a previously exported proof request (via toJsonString) and reconstructs * the instance with all its properties. Useful for recreating requests on the frontend or across different contexts. * * @param jsonString - JSON string containing the serialized proof request data * @returns {Promise<ReclaimProofRequest>} - Reconstructed proof request instance * @throws {InvalidParamError} When JSON string is invalid or contains invalid parameters * * @example * ```typescript * const jsonString = proofRequest.toJsonString(); * const reconstructed = await ReclaimProofRequest.fromJsonString(jsonString); * // Can also be used with InApp SDK's startVerificationFromJson method * ``` */ static fromJsonString(jsonString: string): Promise<ReclaimProofRequest>; /** * Sets a custom callback URL where proofs will be submitted via HTTP `POST` * * By default, proofs are sent as HTTP POST with `Content-Type` as `application/x-www-form-urlencoded`. * Pass function argument `jsonProofResponse` as `true` to send proofs with `Content-Type` as `application/json`. * * When a custom callback URL is set, proofs are sent to the custom URL *instead* of the Reclaim backend. * Consequently, the startSession `onSuccess` callback will be invoked with an empty array (`[]`) * instead of the proof data, as the proof is not available to the SDK in this flow. * * This verification session's id will be present in `X-Reclaim-Session-Id` header of the request. * The request URL will contain query param `allowAiWitness` with value `true` when AI Witness should be allowed by handler of the request. * * Note: InApp SDKs are unaffected by this property as they do not handle proof submission. * * @param url - The URL where proofs should be submitted via HTTP `POST` * @param jsonProofResponse - Optional. Set to true to submit proofs as `application/json`. Defaults to false * @throws {InvalidParamError} When URL is invalid * * @example * ```typescript * proofRequest.setAppCallbackUrl('https://your-backend.com/callback'); * // Or with JSON format * proofRequest.setAppCallbackUrl('https://your-backend.com/callback', true); * ``` */ setAppCallbackUrl(url: string, jsonProofResponse?: boolean): void; /** * Sets a redirect URL where users will be redirected after successfully acquiring and submitting proof * * @param url - The URL where users should be redirected after successful proof generation * @param method - The redirection method that should be used for redirection. Allowed options: `GET`, and `POST`. * `POST` form redirection is only supported in Portal flow. * @param body - List of name-value pairs to be sent as the body of the form request. * `When `method` is set to `POST`, `body` will be sent with 'application/x-www-form-urlencoded' content type. * When `method` is set to `GET`, if `body` is set then `body` will be sent as query parameters. * Sending `body` on redirection is only supported in Portal flow. * * @throws {InvalidParamError} When URL is invalid * * @example * ```typescript * proofRequest.setRedirectUrl('https://your-app.com/success'); * ``` */ setRedirectUrl(url: string, method?: HttpRedirectionMethod, body?: HttpFormEntry[] | undefined): void; /** * Sets a custom callback URL where errors that abort the verification process will be submitted via HTTP POST * * Errors will be HTTP POSTed with `header 'Content-Type': 'application/json'`. * When a custom error callback URL is set, Reclaim will no longer receive errors upon submission, * and listeners on the startSession method will not be triggered. Your application must * coordinate with your backend to receive errors. * * This verification session's id will be present in `X-Reclaim-Session-Id` header of the request. * * Following is the data format which is sent as an HTTP POST request to the url with `Content-Type: application/json`: * ```json * { * "type": "string", // Name of the exception * "message": "string", * "sessionId": "string", * // context as canonicalized json string * "context": "string", * // Other fields with more details about error may be present * // [key: any]: any * } * ``` * * For more details about response format, check out [official documentation of Error Callback URL](https://docs.reclaimprotocol.org/js-sdk/preparing-request#cancel