{"_id":"@arendajaelu/smart-id-node-client","_rev":"11-69b9f63fd9287973d548917d40ddb0b1","name":"@arendajaelu/smart-id-node-client","dist-tags":{"latest":"0.1.0"},"versions":{"0.0.8":{"name":"@arendajaelu/smart-id-node-client","version":"0.0.8","keywords":["smart-id","authentication","signature","estonia","lithuania","latvia","nodejs","typescript"],"author":{"name":"Joosep Wong"},"license":"MIT","_id":"@arendajaelu/smart-id-node-client@0.0.8","maintainers":[{"name":"arendajaelu","email":"arendajaelu@gmail.com"}],"homepage":"https://github.com/arendajaelu/smart-id-node-client#readme","bugs":{"url":"https://github.com/arendajaelu/smart-id-node-client/issues"},"dist":{"shasum":"fae4e0e14daa8934fe7d7667e5225f7b4118bfaf","tarball":"https://registry.npmjs.org/@arendajaelu/smart-id-node-client/-/smart-id-node-client-0.0.8.tgz","fileCount":32,"integrity":"sha512-SUhDZYL4v7V8gXw+9RHOh1kCTenWFR7hda55B3CCzukB/G6jvse32pJq9L+ahtVHD1TVz7Xct2DWwykni5c8gw==","signatures":[{"sig":"MEYCIQD+I98mHbKc1Ij3K6iwdFrnKo/nUlGnULmQPO5SMDp29AIhAPYA46nvS5d/gRfrUldi1PFE2MMRHfVW8oA1zHh9NxeV","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":117869},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":"^18.14.0 || ^20.0.0 || ^21.0.0 || ^22.0.0 || >=24.0.0"},"exports":{".":"./dist/index.js"},"gitHead":"7eb474b67c12b19c8bdbb18fd65f63516fd3f668","scripts":{"lint":"eslint . --ext .ts","test":"jest","build":"tsc -p tsconfig.build.json","format":"prettier --write .","prepare":"npm run build","test:int":"jest --testPathPattern=int"},"_npmUser":{"name":"arendajaelu","actor":{"name":"arendajaelu","type":"user","email":"arendajaelu@gmail.com"},"email":"arendajaelu@gmail.com"},"repository":{"url":"git+https://github.com/arendajaelu/smart-id-node-client.git","type":"git"},"_npmVersion":"10.9.2","description":"Node.js library for interacting with the SK Solution Smart-ID RP V3 API (Estonia, Latvia, Lithuania) for authentication and signing.","directories":{},"_nodeVersion":"22.17.0","dependencies":{"axios":"^1.10.0","pkijs":"^3.2.5","asn1js":"^3.0.6","node-forge":"^1.3.1"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","dotenv":"^16.3.1","eslint":"^9.29.0","ts-jest":"^29.4.0","prettier":"^3.6.1","typescript":"^5.8.3","@types/jest":"^30.0.0","@types/node-forge":"^1.3.11"},"_npmOperationalInternal":{"tmp":"tmp/smart-id-node-client_0.0.8_1751466511093_0.27173120483221536","host":"s3://npm-registry-packages-npm-production"}},"0.1.0":{"name":"@arendajaelu/smart-id-node-client","version":"0.1.0","description":"Node.js library for interacting with the SK Solution Smart-ID RP V3 API (Estonia, Latvia, Lithuania) for authentication and signing.","main":"dist/index.js","types":"dist/index.d.ts","exports":{".":"./dist/index.js"},"scripts":{"build":"tsc -p tsconfig.build.json","lint":"eslint . --ext .ts","format":"prettier --write .","test":"jest","test:int":"jest --testPathPattern=int","prepare":"npm run build"},"keywords":["smart-id","smartid","mobile-id","eid","eidas","estonia","latvia","lithuania","authentication","sk-id-solutions","rp-api-v3","signature","nodejs","typescript"],"author":{"name":"Joosep Wong"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/arendajaelu/smart-id-node-client.git"},"bugs":{"url":"https://github.com/arendajaelu/smart-id-node-client/issues"},"homepage":"https://github.com/arendajaelu/smart-id-node-client#readme","engines":{"node":">=20"},"publishConfig":{"access":"public"},"dependencies":{"asn1js":"^3.0.6","axios":"^1.10.0","node-forge":"^1.3.1","pkijs":"^3.2.5"},"devDependencies":{"@types/jest":"^30.0.0","@types/node-forge":"^1.3.11","dotenv":"^16.3.1","eslint":"^9.29.0","jest":"^29.7.0","prettier":"^3.6.1","ts-jest":"^29.4.0","typescript":"^5.8.3"},"_id":"@arendajaelu/smart-id-node-client@0.1.0","gitHead":"8e47d73533a20e8b67836995be01ef639bebaa18","_nodeVersion":"22.17.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-sSimGYZL4RkSgJzBMLen8chTS9uhpodAHvLzJ20LgzAjICo7WKBOVJh/OmdG+yyccId7jw5YLT9sPesbPwjxtg==","shasum":"af3c03fed2ce939a88e3b1de652916d24c69c0c9","tarball":"https://registry.npmjs.org/@arendajaelu/smart-id-node-client/-/smart-id-node-client-0.1.0.tgz","fileCount":34,"unpackedSize":122672,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDzYjETWaVt/oQev6CsFHB+7IUPtWCEyp31tieXuVxW3wIgUpsRhAQ4BoWUa+tP3Bo3CkkBRVHOoV/UeOC5Ls17XuY="}]},"_npmUser":{"name":"arendajaelu","email":"arendajaelu@gmail.com"},"directories":{},"maintainers":[{"name":"arendajaelu","email":"arendajaelu@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/smart-id-node-client_0.1.0_1785310797465_0.5349549873943427"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-02T14:28:31.000Z","modified":"2026-07-29T07:39:57.780Z","0.0.1":"2025-07-01T11:55:54.888Z","0.0.2":"2025-07-01T12:58:40.353Z","0.0.3":"2025-07-01T14:31:39.697Z","0.0.4":"2025-07-01T17:48:19.039Z","0.0.5":"2025-07-01T18:01:59.058Z","0.0.6":"2025-07-01T18:39:10.886Z","0.0.7":"2025-07-02T09:59:36.592Z","0.0.8":"2025-07-02T14:28:31.263Z","0.1.0":"2026-07-29T07:39:57.611Z"},"bugs":{"url":"https://github.com/arendajaelu/smart-id-node-client/issues"},"author":{"name":"Joosep Wong"},"license":"MIT","homepage":"https://github.com/arendajaelu/smart-id-node-client#readme","keywords":["smart-id","smartid","mobile-id","eid","eidas","estonia","latvia","lithuania","authentication","sk-id-solutions","rp-api-v3","signature","nodejs","typescript"],"repository":{"type":"git","url":"git+https://github.com/arendajaelu/smart-id-node-client.git"},"description":"Node.js library for interacting with the SK Solution Smart-ID RP V3 API (Estonia, Latvia, Lithuania) for authentication and signing.","maintainers":[{"name":"arendajaelu","email":"arendajaelu@gmail.com"}],"readme":"# Smart-ID Nodejs client\n\n<div>\n  <p align=\"center\">\n    <img src=\"https://joosep.org/projects/smart-id-node-client/smart-id-node-client-banner.png\" width=\"800\"> \n  </p>\n</div>\n\nThis library provides a modern, developer-friendly integration with the official **Smart-ID REST API v3** from **SK ID Solutions**, supporting strong, secure electronic identity authentication and digital signing for users in **Estonia**, **Latvia**, and **Lithuania**.\n\nIt is built entirely in **TypeScript**, leverages well-established cryptographic libraries, and offers a clean, modular design following the builder pattern, giving developers full control over request construction, security validation, and interaction flows.\n\nThe library abstracts much of the low-level complexity of working with Smart-ID, while strictly following the official specifications and providing the tools necessary to build both **cross-device** (e.g., browser to mobile) and **same-device** (e.g., mobile app) authentication flows.\n\nThis DEMO was developed with **NestJS** and integrates with [DEMO:https://smartid.joosep.org](https://smartid.joosep.org) Smart-ID system.\n\n## Table of Contents\n\n- [Overview](#overview)\n  - [Features](#features)\n  - [Supported Authentication Flows](#main-authentication-flows)\n  - [Tutorials](#tutorials)\n- [Installation](#installation)\n  - [Before You Start](#before-you-start)\n- [Example Usage](#example-usage)\n- [Authentication Request Builder](#authentication-request-builder)\n  - [Methods](#authenticationrequestbuilder-methods)\n- [Authentication Request Client](#authentication-request-client)\n  - [DeviceLink Authentication](#devicelink-authentication)\n  - [Notification Authentication](#notification-authentication)\n  - [Session Handling](#session-handling)\n  - [DeviceLink Utilities](#devicelink-utilities)\n  - [Client Configuration](#client-configuration)\n  - [Security Notes](#notes-on-security--integration-scope)\n- [Callback URL Validator](#callback-url-validator)\n  - [Usage](#sample-usage)\n  - [Methods](#callbackurlvalidator-methods)\n- [Authentication Response Validator](#authentication-response-validator)\n  - [Usage](#example-usage-1)\n  - [Methods](#authenticationresponsevalidator-methods)\n  - [Integration Notes](#notes)\n- [Authentication Identity](#authentication-identity)\n  - [Identity Getters](#identity-property-getters)\n  - [Certificate Methods](#certificate-methods)\n- [Security Considerations](#security)\n- [Disclaimer](#disclaimer)\n- [References](#references)\n- [Credits](#credits)\n- [License](#license)\n\n\n\n## Overview\n\n### Features\n\n- Supports Smart-ID v3 (June 2025)\n- Strongly typed request builders (Device Link & Notification Authentication)\n- Full Authentication Response validation with certificate trust checks\n- Smart-ID Scheme Identification (End-Entity Certificate) enforcement\n- Signature reconstruction and verification logic\n- Supports VC Type: numeric4 Notification flow\n- Session Secret Digest and User Challenge Verifier validation\n- Clean, extendable, minimal dependencies (crypto, node-forge, pkijs)\n\nThis library implements the main Smart-ID RP API flows, based on version 3 of the protocol.\n\n### Main authentication flows\n![Smart-ID Authentication Flow](https://sk-eid.github.io/smart-id-documentation/rp-api/_images/flow-628705beb37e0bc366fd3907da5db31eaaa5b3c0.svg)\n\n#### Cross-device use cases\nUse case: The RP session is on a separate device from the mobile phone where the Smart-ID app is installed.\n\nFor example, the user is using a PC browser to access an RP website or a tablet to access an RP application.\n\n#### Same-device use cases\nUse case: The RP frontend (whether an RP app or website accessed by a mobile browser) resides on the same mobile device as the Smart-ID app.\n\nThe end user is using a mobile app or RP detects that the user is on a mobile browser so it can be assumed that the user intends to use the Smart-ID app on a same device.\n\nStrongly prefer the BASE/v3/*/device-link/anonymous endpoints for same-device use cases unless the user’s document-number has already been established for the current session. These endpoints provide a superior user experience as no user identifier entry is required while the device-links with callbacks provide the best security protections.\n\nHowever, a fallback option should also be provided to switch to the cross-device use cases.\n\n## Tutorials: \nTutorials: [DEMO and Tutorials](https://smartid.joosep.org)\nReference: [OpenAPI specification](https://sk-eid.github.io/smart-id-documentation/rp-api/api_specification.html)\n\n## How This Library Works\n\nThis library follows a straightforward flow:\n\n1. Use the `AuthenticationRequestBuilder` to construct the appropriate request payload.\n2. Send the request using one of the five available `SmartIdAuthClient` methods based on your use case:\n\n  - [`getAuthenticateAnonymousDeviceLink(requestPayload)`](#authenticatedevicelinkanonymous)  \n    Recommended for **same-device** scenarios (Web2App / App2App) where the user's document number is not yet known.\n\n  - [`getAuthenticateDeviceLinkByEtsi(idCode, requestPayload)`](#authenticatedevicelinkbyetsi)  \n    For **cross-device** or same-device use when the user's identity code is available.\n\n  - [`getAuthenticateDeviceLinkByDocument(documentNumber, requestPayload)`](#authenticatedevicelinkbydocument)  \n    When the user's document number is already known.\n\n  - [`startAuthenticateNotificationByEtsi(idCode, requestPayload)`](#authenticatenotificationbyetsi)  \n    Notification-based authentication with identity code.\n\n  - [`startAuthenticateNotificationByDocument(documentNumber, requestPayload)`](#authenticatenotificationbydocument)  \n    Notification-based authentication with document number.\n\n3. In **Web2App** or **App2App** scenarios, you can optionally use the `CallbackUrlValidator` to verify callback parameters.\n4. Once the session completes, use the `AuthenticationResponseValidator` to verify the final Smart-ID response.\n\nUsers are free to implement additional validation logic or fully replace the built-in validation process if desired.\n\n## Installation\n\n```\nnpm install @arendajaelu/smart-id-node-client\n```\n\n### Before You Start\n\nThis library is intended for developers who are already familiar with the Smart-ID system and its technical workflows.\n\nIf you are new to Smart-ID or have not yet set up your developer environment, please start by reading the official Smart-ID Demo Documentation provided by SK ID Solutions:\n\n👉 [https://sk-eid.github.io/smart-id-documentation/demo.html](https://sk-eid.github.io/smart-id-documentation/demo.html)\n\nThe official documentation explains the Smart-ID concept, registration process, and how to obtain demo credentials required for development and testing.\n\nOnly proceed with integrating this library after you have successfully registered for demo access and understood the basic Smart-ID API structure.\n\n## The example usage\n\n```ts\nimport { SmartIdAuthClient, AuthenticationRequestBuilder } from 'smart-id-node-client';\n\nconst client = new SmartIdAuthClient()\n  .setApiEndpoint('https://sid.demo.sk.ee/smart-id-rp/v3');\n\nconst builder = new AuthenticationRequestBuilder()\n  .withInitialCallbackUrl('https://example.com/callback')\n  .withCertificateLevel('QUALIFIED');\n\nconst requestPayload = builder.build();\n\nconst session = await client.getAuthenticateAnonymousDeviceLink(requestPayload);\nconsole.log(session);\n```\n\n## Authentication Request Builder\nThe AuthenticationRequestBuilder class provides a developer-friendly, configurable way to construct valid Smart-ID DeviceLink Authentication or Notification Authentication request payloads.\n\nThis builder is designed to simplify payload construction, reduce human error, and ensure that generated requests adhere to Smart-ID protocol expectations. The resulting payload can be used directly with the SmartIdAuthClient to initiate authentication sessions.\n\n- The builder auto-generates the rpChallenge and handles interaction encoding in Base64.\n- It supports generating both DeviceLink (e.g., QR, Web2App, App2App) and Notification authentication requests.\n- You retain full control over optional fields like initialCallbackUrl, capabilities, and requestProperties.\n\nNote: The library does not perform any I/O or network communication at the builder stage — it only prepares the payload. Sending the request is done separately via Authentication Request Client (SmartIdAuthClient)\n\n### AuthenticationRequestBuilder Methods\n\n| Method                                            | Return Type                                        | Description                                                              |\n| ------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------ |\n| `constructor(relyingPartyUUID, relyingPartyName)` | `AuthenticationRequestBuilder`                     | Creates a new builder instance with required RP identifiers.             |\n| `withInitialCallbackUrl(url)`                     | `this`                                             | Optional. Sets the callback URL for Web2App or App2App flows.            |\n| `withCertificateLevel(level)`                     | `this`                                             | Optional. Sets desired certificate level (`ADVANCED` or `QUALIFIED`).    |\n| `withHashAlgorithm(hashAlgorithm)`                | `this`                                             | Optional. Sets hash algorithm for signature generation.                  |\n| `withRequestProperties(props)`                    | `this`                                             | Optional. Adds request-specific properties, e.g., client IP sharing.     |\n| `withCapabilities(obj)`                           | `this`                                             | Optional. Adds custom capabilities to the request.                       |\n| `withInteractions(interaction)`                   | `this`                                             | Required. Defines the user-facing interaction shown on the Smart-ID app. |\n| `withVcType(vcType)`                              | `NotificationRequestBuilder`                       | Switches to Notification Authentication request builder.                 |\n| `build()`                                         | `DeviceLinkAuthRequest \\| NotificationAuthRequest` | Finalizes and returns the request payload for API consumption.           |\n\n\n## Authentication Request Client\nThe SmartIdAuthClient serves as the primary communication layer between your application and the Smart-ID REST API. It provides methods to initiate authentication sessions, query session status, handle device link flows (QR, Web2App, App2App), and ensure proper certificate pinning for secure communication.\n\nThis client is designed for flexibility, offering fine-grained control over Smart-ID integration while promoting secure and reliable interactions.\n\n### Key Features\n- Supports DeviceLink Authentication via anonymous, ETSI ID code, or document number.\n- Supports Notification Authentication via ETSI ID code or document number.\n- Built-in support for pinned server certificates and public key pinning.\n- Session polling with automatic handling of known Smart-ID error states.\n- Utility to generate secure, signed DeviceLink URLs with authCode.\n- Helper methods for callback parameter generation and API configuration\n\n### Example Usage\n```ts\n //Create an anonymous device link\nconst callbackParam = randomBytes(16).toString('hex');\n\nconst requestPayload = new AuthenticationRequestBuilder('00000000-0000-4000-8000-000000000000','DEMO')\n        .withInitialCallbackUrl(\n                `https://blueblackwhite.com/social/smartid?chksum=${callbackParam}`,\n        )\n        .withInteractions({\n          type: 'displayTextAndPIN',\n          displayText60: 'Authenticate with Smart-ID',\n        })\n        .build();\n\nconst { response, sessionStartTime } = await this.client\n        .setSchemeName('smart-id-demo')\n        .getAuthenticateAnonymousDeviceLink(requestPayload);\n\nconst link = this.client\n        .setSchemeName('smart-id-demo')\n        .createDeviceLinkUrl(response, requestPayload, sessionStartTime, {\n          deviceLinkType: 'Web2App',\n        });\n```\n\n### SmartIdAuthClient Methods\n#### DeviceLink Authentication\n* ETSI = ETSI Natural Person Semantics Identifier\n\n| Method                                                         | Description                                             |\n| -------------------------------------------------------------- | ------------------------------------------------------- |\n| `getAuthenticateAnonymousDeviceLink(payload)`                  | Starts anonymous DeviceLink authentication.             |\n| `getAuthenticateDeviceLinkByEtsi(idCode, payload)`             | Starts DeviceLink authentication by ETSI. |\n| `getAuthenticateDeviceLinkByDocument(documentNumber, payload)` | Starts DeviceLink authentication by document number.    |\n\n#### Notification Authentication\n| Method                                                             | Description                                              |\n| ------------------------------------------------------------------ | -------------------------------------------------------- |\n| `startAuthenticateNotificationByEtsi(idCode, payload)`             | Starts Notification Authentication by ETSI. |\n| `startAuthenticateNotificationByDocument(documentNumber, payload)` | Starts Notification Authentication by document number.   |\n\n#### Session Handling\n| Method                                      | Description                                                     |\n| ------------------------------------------- | --------------------------------------------------------------- |\n| `getSessionStatus(sessionID)`               | Retrieves the current status of an authentication session.      |\n| `pollForSessionResult(sessionID, options?)` | Polls session status until success, failure, or timeout occurs. |\n\n#### DeviceLink Utilities\n| Method                                                          | Description                                                             |\n| --------------------------------------------------------------- | ----------------------------------------------------------------------- |\n| `createDeviceLinkUrl(session, payload, sessionStartTime, opts)` | Generates a signed DeviceLink URL for QR, Web2App, or App2App flows.    |\n| `generateCallbackParam()`                                       | Generates a random callback parameter (e.g., for `initialCallbackUrl`). |\n\n#### Client Configuration\n| Method                              | Description                                                    |\n| ----------------------------------- | -------------------------------------------------------------- |\n| `setPublicSslKeys(fingerprints)`    | Configures SHA-256 public key pinning for additional security. |\n| `setApiEndpoint(hostUrl, version?)` | Overrides Smart-ID API endpoint and version.                   |\n| `setApiVersion(version)`            | Updates Smart-ID API version.                                  |\n| `setSchemeName(name)`               | Sets the scheme name used for signature payloads.              |\n| `setBrokeredRpName(name)`           | Sets the brokered RP name used in DeviceLink URL generation.   |\n\n#### Notes on Security & Integration Scope\nSupports TLS certificate pinning via pinnedCerts for robust server identity verification (preferred method).\n- Supports public key hash pinning to further mitigate Man-in-the-Middle (MITM) attacks.\n- Generates signed authCode for DeviceLink URLs, derived from the session secret, ensuring URL integrity.\n- Provides full control over API endpoint configuration for test, staging, and production environments.\n\n⚠️ Important:\nThis library does not manage CA certificates or public key pinning keys. It is the developer's responsibility to securely maintain, provision, and rotate these materials as part of their infrastructure.\n\n📦 Out-of-Scope:\nThe library does not include logic for generating the actual QR code image for DeviceLink URLs.\nGenerating a QR code is straightforward and intentionally left to the application layer, allowing developers to use any preferred method, for example:\n```ts\nimport QRCode from \"qrcode\";\n\nconst url = client.createDeviceLinkUrl(session, payload, sessionStartTime, { deviceLinkType: \"QR\" });\nQRCode.toFile(\"qrcode.png\", url);\n\n```\n## Callback Url Validator\nIn **DeviceLink** authentication flows that rely on callback URLs, such as **Web2App** and **App2App** scenarios, proper handling and verification of the callback URL is critical to ensure a secure, phishing-resistant authentication process.\n\nAccording to the [official Smart-ID documentation](https://sk-eid.github.io/smart-id-documentation/rp-api/callback_urls.html), the relying party's backend must verify that the callback parameters received from the Smart-ID app are valid, trustworthy, and have not been tampered with.\n\nThe `Callback Url Validator` class provides basic utilities to assist with this verification process. It allows developers to:\n\n- Validate the presence and format of expected callback parameters.\n- Check for parameter consistency and integrity.\n- Detect obvious manipulation attempts.\n\n### Flexible Integration\nThis validator can be used as a standalone component or seamlessly integrated into the AuthenticationResponseValidator via .withCallbackUrlValidate() to achieve a streamlined, end-to-end validation flow.\n\nThe library is designed with flexibility in mind:\n\nYou may perform callback URL validation and Smart-ID session response validation independently.\n\nYou can insert custom verification steps into either validation stage to suit your application's security requirements.\n\nNB!!!: This validator is designed to help streamline development, but developers are encouraged to review the [Secure Implementation Guide](https://sk-eid.github.io/smart-id-documentation/rp-api/secure_implementation.html) and perform additional checks tailored to their risk profile and threat model.\n## Sample Usage\n\n```ts\nimport { CallBackUrlValidator } from \"./callback-url-validator\";\nimport { CallbackValidationEntity } from \"./types\";\n\n// Example callback payload received from Smart-ID flow\nconst entity: CallbackValidationEntity = {\n    sessionSecretDigest: \"computedDigestFromFrontend\",\n    userChallengeVerifier: \"randomVerifierUsedInRequest\",\n    sessionSecret: \"Base64SessionSecretUsedInRequest\",\n    schemeName: \"smart-id\",\n    authenticationResponse: {\n        state: \"COMPLETE\",\n        result: {\n            endResult: \"OK\",\n            documentNumber: \"PNOEE-1234567890\",\n        },\n        signatureProtocol: \"ACSP_V2\",\n        signature: {\n            value: \"base64SignatureValue\",\n            userChallenge: \"expectedComputedHash\",\n        },\n        cert: {\n            value: \"base64Certificate\",\n            certificateLevel: \"QUALIFIED\",\n        },\n    },\n};\n\n// Perform validation\nconst validator = new CallBackUrlValidator(entity);\nconst result = validator.validate().getResult();\n\nif (result.hasError) {\n    console.error(\"Callback validation failed:\", result.errors);\n} else {\n    console.log(\"Callback successfully validated!\");\n}\n```\n## CallBackUrlValidator Methods\n| Method                         | Return Type              | Description                                                                 |\n|---------------------------------|--------------------------|-----------------------------------------------------------------------------|\n| `constructor(entity)`           | `CallBackUrlValidator`   | Creates a new validator with the provided `CallbackValidationEntity`.      |\n| `validate()`                    | `this`                   | Runs all validation checks (session status, secret digest, user challenge).|\n| `getResult()`                   | `AuthenticationResult`   | Returns the result object containing validation errors, if any.            |\n\n### Private Helper Methods\n\n| Method                             | Return Type  | Description                                                                  |\n|-------------------------------------|--------------|------------------------------------------------------------------------------|\n| `validateSessionStatus()`           | `void`       | Checks if the session completed successfully and required fields are present.|\n| `validateSessionSecretDigest()`     | `void`       | Verifies the session secret digest matches the expected value.               |\n| `validateUserChallengeVerifier()`   | `void`       | Confirms the user challenge verifier matches the expected challenge.         |\n| `computeSessionSecretDigest(secret)`| `string`     | Computes the expected session secret digest from the provided secret.        |\n| `base64UrlEncode(buffer)`           | `string`     | Encodes a Buffer to a URL-safe Base64 string (RFC 4648).                    |\n\n\n## Authentication Response Validator\nThe AuthenticationResponseValidator is a modular and extensible utility designed to facilitate comprehensive validation of Smart-ID authentication responses across all supported authentication flows, including Web2App, App2App, and traditional backend-initiated processes.\n\n### Key Capabilities\n- Core validation of Smart-ID authentication response structure and content\n- Certificate trust chain verification against configurable CA stores\n- Certificate validity period check\n- Smart-ID Scheme Identification (End-Entity Certificate) enforcement\n- Optional certificate policy OID validation\n- Seamless integration with CallbackUrlValidator for end-to-end validation of callback parameters in Web2App and App2App flows\n\n### Flexible, Composable Architecture\nThis library is designed with a developer-centric, building-block philosophy, empowering teams to tailor their validation logic based on project-specific security requirements:\n\n- Use .validate() for full Smart-ID response validation, including mandatory ACSP_V2 signature verification\n- Combine .withCallbackUrlValidate() for full-chain, end-to-end verification in callback-based flows\n- The certificate trust chain and signature checks are always enforced by .validate() and cannot be omitted\n\n### Example Usage\n```ts\n\n// Developer-managed location containing trusted CA certificates\n// ⚠️ IMPORTANT:\n// This library does **not** download or manage CA certificates for you.\n// You, as the implementer, must ensure the folder contains the correct, trusted CA certificates\n// provided by SK-ID or your organization's security policy.\n\nconst resourcesPath = path.resolve(__dirname, \"../certificates\");\nconst validator = new AuthenticationResponseValidator(resourcesPath);\n\n// validate() runs the full response check AND ACSP_V2 signature verification:\n// session state, end result, certificate presence, certificate trust chain, expiry,\n// certificate level, Smart-ID EKU, and the cryptographic ACSP_V2 signature.\n// The signature inputs (scheme name, interaction type, flow type) MUST be set before\n// validate(); if they are missing, validation fails and no identity is returned.\nconst result = validator\n        .withSchemeName('smart-id-demo')\n        .withInteractionTypeUsed('displayTextAndPIN')\n        .withFlowType('Web2App')\n        .withCallbackUrlValidate(callBackValidationEntity)\n        .validate(authResponse, requestPayload)\n        .getResult();\n\nif (result.hasError()) {\n  throw new Error(`Has errors ${JSON.stringify(result.getErrors())} `);\n}\n\n// An identity is returned ONLY when every check, including signature verification, passed.\nconst identity = result.getIdentity();\n\n//Optional validation: Check if the certificate includes any of the allowed policy OIDs (e.g., Qualified Certificates)\nconst allowOIDs = [\n  '1.3.6.1.4.1.4146.1.1', \n  '1.3.6.1.4.1.4146.1.2', \n  '1.3.6.1.4.1.10015.17.2',\n];\n\nconst allowPoliciesCheck = validator.checkIfHasAllowedCertificatePolicies(\n        identity.getCertificate(),\n        allowOIDs,\n);\nif (!allowPoliciesCheck) {\n  throw new Error('The allowPoliciesCheck was not verified.');\n}\n\nif (identity) {\n    console.log(`Given Name: ${identity.getGivenName()}`);\n    console.log(`Surname: ${identity.getSurName()}`);\n    console.log(`Document Number: ${identity.getDocumentNumber()}`);\n    console.log(`Country: ${identity.getCountry()}`);\n    console.log(`Identity Code: ${identity.getIdentityCode()}`);\n    console.log(`Identity Number: ${identity.getIdentityNumber()}`);\n    console.log(`Valid From: ${identity.getValidFrom()}`);\n    console.log(`Valid To: ${identity.getValidTo()}`);\n    console.log(`Date of Birth: ${identity.getDateOfBirth()}`);\n}\n\n```\n\n### AuthenticationResponseValidator Methods\n| Method                                                    | Return Type                       | Description                                                                                    |\n| --------------------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------- |\n| `constructor(resourcesPath, debug?)`                      | `AuthenticationResponseValidator` | Creates validator, loads trusted CA certificates from provided path.                           |\n| `validate(response, payload)`                             | `this`                            | Runs the full response and certificate validation **including mandatory ACSP\\_V2 signature verification** (structure, expiry, trust chain, certificate level, scheme checks, signature). Requires `withSchemeName()`, `withInteractionTypeUsed()` and `withFlowType()` to be set first; returns no identity unless the signature verifies. |\n| `withCallbackUrlValidate(entity)`                         | `this`                            | Runs [Callback URL Validator](#callback-url-validator) for Web2App/App2App.                    |\n| `checkIfHasAllowedCertificatePolicies(cert, allowedOids)` | `boolean`                         | Checks if the certificate contains at least one allowed policy OID.                            |\n| `verifySignature(response, payload)`                      | `boolean`                         | Verifies the ACSP\\_V2 signature against the reconstructed payload and certificate. Also invoked automatically by `validate()`.                    |\n| `withSchemeName(name)`                                    | `this`                            | Sets scheme name for ACSP\\_V2 payload reconstruction.                                          |\n| `withInteractionTypeUsed(value)`                          | `this`                            | Sets interaction type used for ACSP\\_V2 payload reconstruction.                                |\n| `withBrokeredRpName(name)`                                | `this`                            | Sets brokered RP name for ACSP\\_V2 payload reconstruction.                                     |\n| `withFlowType(value)`                                     | `this`                            | Sets flow type for ACSP\\_V2 payload reconstruction.                                            |\n| `buildACSPV2Payload(response, payload)`                   | `string`                          | Reconstructs the exact ACSP\\_V2 payload string required for signature check.                   |\n| `getTrustedCACertificates()`                              | `string[]`                        | Returns the list of CA certificate file paths loaded for trust validation.                     |\n| `getResult()`                                             | `AuthenticationResult`            | Returns the result containing validation errors and extracted identity.                        |\n\n### Notes\n\n- CA Trust Setup: The resourcesPath should point to a directory or file containing trusted .crt or .pem CA certificates.\n- DeviceLink Flows: For Web2App and App2App, always use withCallbackUrlValidate() before .validate() to properly handle callback URL parameters.\n- Security Reminder: This library assists with validation but cannot guarantee full security. Production deployments should perform additional checks according to the Smart-ID Secure Implementation Guide.\n\nStrongly recommend reviewing and following the [Secure Implementation Guide](https://sk-eid.github.io/smart-id-documentation/rp-api/secure_implementation.html) provided by SK-eID. The guide describes all critical validation steps in detail and provides best practices to ensure the security and reliability of your Smart-ID integration.\n\nNB!!!: This library aims to simplify the integration process, but **production systems should carefully evaluate and, if necessary, supplement the built-in verification logic** to meet their security standards.\n\n## Authentication Identity\nThe `AuthenticationIdentity` class represents the authenticated user's identity extracted from a Smart-ID certificate.  \n\nIt provides convenient getters to access core identity information such as name, country, identity number, and document details.\n\nAdditionally, the class offers methods to access the raw certificate, a properly formatted PEM version, and parsed certificate details including subject, issuer, and extensions.\n\nThis class is designed to simplify the process of handling Smart-ID authentication results by encapsulating identity and certificate parsing logic.\n## Identity Property Getters\n\n| Method                | Return Type | Description                          |\n|-----------------------|-------------|--------------------------------------|\n| `getGivenName()`      | `string`    | Returns the given name.              |\n| `getSurName()`        | `string`    | Returns the surname.                 |\n| `getIdentityCode()`   | `string`    | Returns the identity code.           |\n| `getIdentityNumber()` | `string`    | Returns the identity number.         |\n| `getCountry()`        | `string`    | Returns the country.                 |\n| `getDocumentNumber()` | `string`    | Returns the document number.         |\n| `getValidFrom()`      | `string`    | Returns certificate validity start.  |\n| `getValidTo()`        | `string`    | Returns certificate validity end.    |\n| `getDateOfBirth()`    | `string`    | Returns the date of birth.           |\n\n## Certificate Methods\n\n| Method                   | Return Type                              | Description                                      |\n|--------------------------|------------------------------------------|--------------------------------------------------|\n| `getCertificate()`       | `string`                                 | Returns the raw certificate (Base64).            |\n| `getPemCertificate()`    | `string`                                 | Returns the certificate in PEM format.           |\n| `getParsedCertificate()` | `Record<string, any> \\| undefined`      | Returns parsed subject, issuer, extensions, etc. |\n| `getRawCertificate()`    | `forge.pki.Certificate \\| undefined`    | Returns the raw forge certificate object.        |\n\n\n## Security\n\nThis library provides essential security validation mechanisms for Smart-ID authentication flows. It implements critical checks to help ensure the integrity, authenticity, and trustworthiness of Smart-ID responses, especially for **Web2App** and **App2App** scenarios.\n\n### ✅ Built-in Validations Provided by This Library\n\nThe library performs the following security validations out-of-the-box:\n\n- **Session Completion Check**\n  - Ensures the authentication session state is `\"COMPLETE\"`.\n  - Verifies the final authentication result is `\"OK\"`.\n  - Confirms that a valid certificate and signature are present.\n\n- **Certificate Validations**\n  - Parses and verifies the Smart-ID end-user certificate.\n  - Checks certificate expiry date.\n  - Validates the certificate against a trusted CA store (local `.pem` or `.crt` files).\n  - Enforces **Smart-ID Scheme Identification**, verifying correct KeyUsage and Extended Key Usage attributes.\n  - Optionally verifies allowed certificate policy OIDs via `checkIfHasAllowedCertificatePolicies`.\n\n- **Signature Verification**\n  - Reconstructs the signed payload based on Smart-ID specification.\n  - Verifies the signature using the public key extracted from the end-user's certificate.\n  - Supports strict signature checks for both **Web2App** and **App2App** flows.\n\n- **Callback URL Parameter Validation**\n  - Verifies session status and basic response completeness after the callback.\n  - Validates `sessionSecretDigest` integrity.\n  - Validates `userChallengeVerifier` against the signed user challenge value.\n\n### ⚠️ Limitations & Required Server-Side Considerations\n\nWhile this library covers key client-side verifications, the following security responsibilities remain with the relying party (your server application):\n\n- **Proper Storage and Management of Trusted CA Certificates**\n  - You must provide a valid, up-to-date CA certificate directory to ensure trust validation is meaningful.\n  - The library does not automatically update or fetch CA certificates.\n\n- **Replay Attack Protection**\n  - The library does not implement server-side mechanisms to prevent replay attacks.\n  - You must ensure that session tokens, user challenges, and session secrets are single-use and properly managed.\n\n- **Strict Parameter Validation**\n  - Any additional business-specific validations (e.g., IP whitelisting, request origin verification) are outside the scope of this library.\n\n- **Backend Security**\n  - The library assumes your server-side environment is secure.\n  - All sensitive materials (session secrets, brokered Relying Party names) must be protected by your backend.\n\n- **Compliance with Secure Implementation Guide**\n  - You are strongly advised to review and strictly follow the [Smart-ID Secure Implementation Guide](https://sk-eid.github.io/smart-id-documentation/rp-api/secure_implementation.html).\n  - This guide provides comprehensive recommendations that extend beyond what this library covers.\n\n### Important Note on Certificate Management\n\nThis library **does not maintain or manage trusted CA certificates by itself**.  \nYou must explicitly provide a valid path to your trusted CA certificates when initializing the `AuthenticationResponseValidator`.\n\nIt is your responsibility to ensure that:\n- The CA certificate files are complete, correct, and regularly updated.\n- The certificate storage location is secure and accessible by your application.\n\nFailure to provide appropriate and up-to-date CA certificates will compromise the effectiveness of trust validation.\n\n## Disclaimer\n\nThis is an **independent, third-party, open-source library** developed for convenience in integrating with the official Smart-ID API.\n\nIt is **not developed, reviewed, endorsed, or certified by SK ID Solutions AS** or any official Smart-ID authority.\n\nThe library is provided **\"as is\"**, without any warranties of any kind, either express or implied.  \nThe authors and contributors accept **no liability for any direct, indirect, incidental, or consequential damages**, including but not limited to security breaches, data loss, business interruption, or legal consequences resulting from the use of this library.\n\n️️️⚠️⚠️⚠️ Use of this library is entirely at your own risk. ️️️⚠️⚠️⚠️ \n\nIt is your responsibility to ensure that your Smart-ID integration fully complies with all applicable laws, regulations, and the official [Smart-ID Implementation Guidelines](https://sk-eid.github.io/smart-id-documentation/rp-api/).\n\nFor production use, thorough independent review and appropriate security measures are strongly recommended.\n\n## References\n\n- [SK-eID Smart-ID Documentation](https://sk-eid.github.io/smart-id-documentation/)\n- [Smart-ID API v3 Reference](https://sk-eid.github.io/smart-id-documentation/rp-api/)\n- [Secure Implementation Guide](https://github.com/SK-EID/smart-id-documentation/wiki/Secure-Implementation-Guide#threats-and-attacks)\n\n## Credits\n\nDeveloped and maintained by [Joosep Wong](https://medium.com/@joosepwong) | [Linkedin](https://www.linkedin.com/in/joosepwong/)\n\nThis library is initiated and maintained by Joosep Wong, and contributions from the community are warmly welcome.\nThe library is released under the [MIT License](./LICENSE), making it freely available for both personal and commercial use.\n\n## License\n\nThis library is released under the [MIT License](./LICENSE).\n\nCopyright (c) 2025-2026 Joosep Wong\n\nIt is free to use for both **commercial and non-commercial** purposes, without restriction beyond the standard MIT terms.\n\n**This package will never be relicensed.** It is and will remain available under the MIT License permanently.","readmeFilename":"README.md"}