@serafort/core 0.1.0

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 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/utils/jwt.ts","../src/b2b/jwks.ts","../src/b2b/b2b.ts","../src/utils/retry.ts","../src/m2m/cache.ts","../src/m2m/m2m.ts","../src/client.ts"],"names":[],"mappings":";;;AAKO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvB,IAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EAEhB,WAAA,CAAY,SAAiB,IAAA,GAAO,gBAAA,EAAkB,SAAS,GAAA,EAAK,OAAA,GAA4B,EAAC,EAAG;AAClG,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAKO,IAAM,mBAAA,GAAN,cAAkC,aAAA,CAAc;AAAA,EACrD,YAAY,OAAA,GAAU,8CAAA,EAAgD,OAAO,sBAAA,EAAwB,OAAA,GAA4B,EAAC,EAAG;AACnI,IAAA,KAAA,CAAM,OAAA,EAAS,IAAA,EAAM,GAAA,EAAK,OAAO,CAAA;AACjC,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAKO,IAAM,gBAAA,GAAN,cAA+B,aAAA,CAAc;AAAA,EAClC,WAAA;AAAA,EACA,gBAAA;AAAA,EAEhB,YACE,OAAA,GAAU,uCAAA,EACV,aACA,gBAAA,EACA,OAAA,GAA4B,EAAC,EAC7B;AACA,IAAA,KAAA,CAAM,OAAA,EAAS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ort SDK errors.\n */\nexport class SerafortError extends Error {\n public readonly code: string;\n public readonly status: number;\n public readonly details: ApiErrorDetail[];\n\n constructor(message: string, code = 'SERAFORT_ERROR', status = 500, details: ApiErrorDetail[] = []) {\n super(message);\n this.name = 'SerafortError';\n this.code = code;\n this.status = status;\n this.details = details;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failed (invalid credentials, expired session, invalid JWT signature).\n */\nexport class AuthenticationError extends SerafortError {\n constructor(message = 'Authentication failed or session is invalid.', code = 'AUTHENTICATION_ERROR', details: ApiErrorDetail[] = []) {\n super(message, code, 401, details);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Multi-Factor Authentication required to complete access.\n */\nexport class MfaRequiredError extends SerafortError {\n public readonly challengeId?: string;\n public readonly supportedMethods?: string[];\n\n constructor(\n message = 'Multi-factor authentication required.',\n challengeId?: string,\n supportedMethods?: string[],\n details: ApiErrorDetail[] = []\n ) {\n super(message, 'MFA_REQUIRED', 403, details);\n this.name = 'MfaRequiredError';\n this.challengeId = challengeId;\n this.supportedMethods = supportedMethods;\n }\n}\n\n/**\n * Request payload failed validation checks.\n */\nexport class ValidationError extends SerafortError {\n constructor(message = 'Validation failed on input parameters.', details: ApiErrorDetail[] = []) {\n super(message, 'VALIDATION_ERROR', 422, details);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Rate limit exceeded (HTTP 429).\n */\nexport class RateLimitError extends SerafortError {\n public readonly retryAfterSeconds?: number;\n\n constructor(message = 'Rate limit exceeded. Please slow down requests.', retryAfterSeconds?: number, details: ApiErrorDetail[] = []) {\n super(message, 'RATE_LIMIT_EXCEEDED', 429, details);\n this.name = 'RateLimitError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\n/**\n * Requested resource or tenant does not exist.\n */\nexport class NotFoundError extends SerafortError {\n constructor(message = 'Resource not found.', code = 'NOT_FOUND', details: ApiErrorDetail[] = []) {\n super(message, code, 404, details);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Network failure, client-side timeout, or host unreachable.\n */\nexport class NetworkError extends SerafortError {\n constructor(message = 'Failed to connect to Serafort IAM service.', cause?: unknown) {\n super(message, 'NETWORK_ERROR', 0);\n this.name = 'NetworkError';\n if (cause) {\n this.cause = cause;\n }\n }\n}\n","import { AuthenticationError } from '../errors.js';\n\nexport interface DecodedJwt<T = Record<string, unknown>> {\n header: {\n alg: string;\n typ?: string;\n kid?: string;\n [key: string]: unknown;\n };\n payload: T;\n signature: Uint8Array;\n signingInput: Uint8Array;\n}\n\n/**\n * Decodes a base64url-encoded string into raw Uint8Array bytes.\n */\nexport function base64UrlToBytes(str: string): Uint8Array {\n if (typeof Buffer !== 'undefined') {\n return new Uint8Array(Buffer.from(str, 'base64url'));\n }\n\n let base64 = str.replace(/-/g, '+').replace(/_/g, '/');\n const pad = base64.length % 4;\n if (pad === 2) {\n base64 += '==';\n } else if (pad === 3) {\n base64 += '=';\n }\n\n const binaryStr = atob(base64);\n const bytes = new Uint8Array(binaryStr.length);\n for (let i = 0; i < binaryStr.length; i++) {\n bytes[i] = binaryStr.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Decodes a base64url-encoded string into a UTF-8 string.\n */\nexport function base64UrlDecode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64url').toString('utf8');\n }\n\n const bytes = base64UrlToBytes(str);\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Parses and separates the JWT into header, payload, signature, and signing input.\n */\nexport function parseJwt<T = Record<string, unknown>>(token: string): DecodedJwt<T> {\n if (!token || typeof token !== 'string') {\n throw new AuthenticationError('JWT token must be a non-empty string.');\n }\n\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new AuthenticationError('Invalid JWT format: token must contain exactly 3 dot-separated parts.');\n }\n\n const [headerB64, payloadB64, signatureB64] = parts as [string, string, string];\n\n try {\n const headerJson = base64UrlDecode(headerB64);\n const header = JSON.parse(headerJson) as DecodedJwt['header'];\n\n const payloadJson = base64UrlDecode(payloadB64);\n const payload = JSON.parse(payloadJson) as T;\n\n const signature = base64UrlToBytes(signatureB64);\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n\n return {\n header,\n payload,\n signature,\n signingInput,\n };\n } catch (err: unknown) {\n if (err instanceof AuthenticationError) throw err;\n throw new AuthenticationError(`Failed to parse JWT token: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n","import { AuthenticationError, NetworkError } from '../errors.js';\nimport { JWK, JWKS, SerafortConfig } from '../types.js';\n\nexport class JwksClient {\n private readonly jwksUrl: string;\n private readonly fetchImpl: typeof fetch;\n private cachedKeys: Map<string, CryptoKey> = new Map();\n private lastFetchedAt = 0;\n private readonly cacheTtlMs: number;\n\n constructor(config: SerafortConfig, cacheTtlMs = 3600_000) {\n const baseUrl = (config.endpoint || config.baseUrl || 'https://api.serafort.com').replace(/\\/+$/, '');\n this.jwksUrl = `${baseUrl}/.well-known/jwks.json`;\n this.fetchImpl = config.fetch || globalThis.fetch.bind(globalThis);\n this.cacheTtlMs = cacheTtlMs;\n }\n\n /**\n * Retrieves the CryptoKey matching the key ID (kid) from cache, or fetches from the JWKS endpoint.\n */\n public async getVerificationKey(kid?: string, alg = 'RS256'): Promise<CryptoKey> {\n const now = Date.now();\n const isCacheExpired = now - this.lastFetchedAt > this.cacheTtlMs;\n\n if (this.cachedKeys.size > 0 && !isCacheExpired) {\n if (kid && this.cachedKeys.has(kid)) {\n return this.cachedKeys.get(kid)!;\n }\n // If no kid specified but we have exactly 1 key cached, return it\n if (!kid && this.cachedKeys.size === 1) {\n return Array.from(this.cachedKeys.values())[0]!;\n }\n }\n\n // Refresh keys from JWKS endpoint\n await this.refreshJwks();\n\n if (kid && this.cachedKeys.has(kid)) {\n return this.cachedKeys.get(kid)!;\n }\n\n if (!kid && this.cachedKeys.size > 0) {\n return Array.from(this.cachedKeys.values())[0]!;\n }\n\n throw new AuthenticationError(\n `No matching public key found in JWKS for kid \"${kid || 'unspecified'}\" and alg \"${alg}\".`,\n 'KEY_NOT_FOUND'\n );\n }\n\n /**\n * Refreshes public keys from the JWKS endpoint and imports them as CryptoKeys.\n */\n public async refreshJwks(): Promise<void> {\n let response: Response;\n try {\n response = await this.fetchImpl(this.jwksUrl, {\n headers: { Accept: 'application/json' },\n });\n } catch (err) {\n throw new NetworkError(`Failed to fetch JWKS from ${this.jwksUrl}`, err);\n }\n\n if (!response.ok) {\n throw new AuthenticationError(`Failed to fetch JWKS (status ${response.status})`, 'JWKS_FETCH_FAILED');\n }\n\n const jwks = (await response.json()) as JWKS;\n if (!jwks.keys || !Array.isArray(jwks.keys)) {\n throw new AuthenticationError('Invalid JWKS response format: \"keys\" array missing', 'INVALID_JWKS');\n }\n\n const newKeys = new Map<string, CryptoKey>();\n\n for (const key of jwks.keys) {\n if (!key.kid) continue;\n try {\n const cryptoKey = await this.importJwk(key);\n newKeys.set(key.kid, cryptoKey);\n } catch {\n // Skip keys with unsupported algorithms or malformed structures\n }\n }\n\n this.cachedKeys = newKeys;\n this.lastFetchedAt = Date.now();\n }\n\n /**\n * Imports a raw JWK into a Web Crypto CryptoKey.\n */\n public async importJwk(key: JWK): Promise<CryptoKey> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new AuthenticationError('Web Crypto API (crypto.subtle) is not available in this environment.');\n }\n\n const alg = key.alg || (key.kty === 'RSA' ? 'RS256' : 'ES256');\n\n let importAlgorithm: RsaHashedImportParams | EcKeyImportParams;\n\n if (alg.startsWith('RS')) {\n const hashName = alg === 'RS384' ? 'SHA-384' : alg === 'RS512' ? 'SHA-512' : 'SHA-256';\n importAlgorithm = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: hashName },\n };\n } else if (alg.startsWith('ES')) {\n const namedCurve = alg === 'ES384' ? 'P-384' : alg === 'ES512' ? 'P-521' : 'P-256';\n importAlgorithm = {\n name: 'ECDSA',\n namedCurve,\n };\n } else {\n throw new AuthenticationError(`Unsupported key algorithm: ${alg}`);\n }\n\n return subtle.importKey(\n 'jwk',\n key,\n importAlgorithm,\n false, // non-extractable\n ['verify']\n );\n }\n}\n","import { AuthenticationError } from '../errors.js';\nimport { SerafortConfig, UserContext } from '../types.js';\nimport { parseJwt } from '../utils/jwt.js';\nimport { JwksClient } from './jwks.js';\n\nexport interface TokenValidationOptions {\n /** Expected JWT issuer (iss) */\n expectedIssuer?: string;\n /** Expected JWT audience (aud) */\n expectedAudience?: string;\n /** Allowed clock tolerance in seconds (default: 60s) */\n clockToleranceSeconds?: number;\n /** If true, skips cryptographic signature verification (ONLY for offline dev/testing) */\n skipSignatureCheck?: boolean;\n}\n\nexport class B2BModule {\n public readonly config: SerafortConfig;\n private readonly jwksClient: JwksClient;\n private readonly baseUrl: string;\n\n constructor(config: SerafortConfig, jwksClient?: JwksClient) {\n this.config = config;\n this.jwksClient = jwksClient ?? new JwksClient(config);\n this.baseUrl = (config.endpoint || config.baseUrl || 'https://api.serafort.com').replace(/\\/+$/, '');\n }\n\n /**\n * Validates a JWT token locally: checks signature against cached JWKS, verifies expiration,\n * issuer, and audience, and decodes claims into a strongly-typed UserContext.\n */\n public async validateToken(token: string, options: TokenValidationOptions = {}): Promise<UserContext> {\n const decoded = parseJwt<Record<string, unknown>>(token);\n const now = Math.floor(Date.now() / 1000);\n const clockTolerance = options.clockToleranceSeconds ?? 60;\n\n const payload = decoded.payload;\n\n // 1. Expiration check\n if (typeof payload['exp'] === 'number') {\n if (payload['exp'] + clockTolerance < now) {\n throw new AuthenticationError('Token has expired.', 'TOKEN_EXPIRED');\n }\n }\n\n // 2. Not before check\n if (typeof payload['nbf'] === 'number') {\n if (payload['nbf'] - clockTolerance > now) {\n throw new AuthenticationError('Token not yet valid.', 'TOKEN_NOT_YET_VALID');\n }\n }\n\n // 3. Issuer check\n const expectedIssuer = options.expectedIssuer || this.baseUrl;\n if (expectedIssuer && typeof payload['iss'] === 'string') {\n if (payload['iss'] !== expectedIssuer) {\n throw new AuthenticationError(\n `Invalid token issuer. Expected \"${expectedIssuer}\", received \"${payload['iss']}\".`,\n 'INVALID_ISSUER'\n );\n }\n }\n\n // 4. Audience check\n if (options.expectedAudience && payload['aud']) {\n const aud = Array.isArray(payload['aud']) ? payload['aud'] : [payload['aud']];\n if (!aud.includes(options.expectedAudience)) {\n throw new AuthenticationError(\n `Invalid token audience. Expected \"${options.expectedAudience}\".`,\n 'INVALID_AUDIENCE'\n );\n }\n }\n\n // 5. Cryptographic signature check (Web Crypto API)\n if (!options.skipSignatureCheck) {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new AuthenticationError('Web Crypto API (crypto.subtle) is not available to verify JWT signature.');\n }\n\n const kid = decoded.header.kid;\n const alg = decoded.header.alg || 'RS256';\n\n const cryptoKey = await this.jwksClient.getVerificationKey(kid, alg);\n\n let verifyAlgorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams;\n if (alg.startsWith('RS')) {\n verifyAlgorithm = { name: 'RSASSA-PKCS1-v1_5' };\n } else if (alg.startsWith('ES')) {\n verifyAlgorithm = { name: 'ECDSA', hash: { name: alg === 'ES384' ? 'SHA-384' : alg === 'ES512' ? 'SHA-512' : 'SHA-256' } };\n } else {\n throw new AuthenticationError(`Unsupported JWT algorithm for signature verification: ${alg}`);\n }\n\n const isValid = await subtle.verify(\n verifyAlgorithm,\n cryptoKey,\n decoded.signature as unknown as BufferSource,\n decoded.signingInput as unknown as BufferSource\n );\n\n if (!isValid) {\n throw new AuthenticationError('JWT signature verification failed.', 'INVALID_SIGNATURE');\n }\n }\n\n // 6. Map into UserContext\n return this.mapClaimsToUserContext(payload);\n }\n\n /**\n * Checks if the user context contains a specific granular permission.\n * Supports wildcard matching (e.g. \"org:*\" matches \"org:read\").\n */\n public hasPermission(userContext: UserContext, requiredPermission: string): boolean {\n if (!userContext.permissions || userContext.permissions.length === 0) {\n return false;\n }\n\n if (userContext.permissions.includes('*') || userContext.permissions.includes(requiredPermission)) {\n return true;\n }\n\n return userContext.permissions.some((perm) => {\n if (perm.endsWith(':*')) {\n const prefix = perm.slice(0, -2);\n return requiredPermission.startsWith(prefix);\n }\n return false;\n });\n }\n\n /**\n * Checks if the user context contains a specific role.\n */\n public hasRole(userContext: UserContext, requiredRole: string): boolean {\n return Array.isArray(userContext.roles) && userContext.roles.includes(requiredRole);\n }\n\n /**\n * Constructs the Enterprise SSO Login URL for a specific tenant/organization.\n */\n public getLoginUrl(tenantId: string, redirectUri: string, options: { state?: string; connection?: string } = {}): string {\n const url = new URL(`${this.baseUrl}/api/auth/sso/login`);\n url.searchParams.set('tenant_id', tenantId);\n url.searchParams.set('redirect_uri', redirectUri);\n\n if (options.state) {\n url.searchParams.set('state', options.state);\n }\n if (options.connection) {\n url.searchParams.set('connection', options.connection);\n }\n\n return url.toString();\n }\n\n /**\n * Maps un-enveloped JWT claims to standard UserContext.\n */\n private mapClaimsToUserContext(claims: Record<string, unknown>): UserContext {\n const userId = String(claims['sub'] || claims['id'] || claims['user_id'] || '');\n const tenantId = String(\n claims['tenant_id'] ||\n claims['org_id'] ||\n claims['tid'] ||\n (claims['app_metadata'] as Record<string, unknown> | undefined)?.['tenant_id'] ||\n ''\n );\n const email = claims['email'] ? String(claims['email']) : undefined;\n\n // Roles extraction\n let roles: string[] = [];\n if (Array.isArray(claims['roles'])) {\n roles = claims['roles'].map(String);\n } else if (typeof claims['role'] === 'string') {\n roles = [claims['role']];\n } else if (typeof claims['roles'] === 'string') {\n roles = claims['roles'].split(',').map((r) => r.trim());\n }\n\n // Permissions extraction\n let permissions: string[] = [];\n if (Array.isArray(claims['permissions'])) {\n permissions = claims['permissions'].map(String);\n } else if (typeof claims['scope'] === 'string') {\n permissions = claims['scope'].split(' ').map((s) => s.trim()).filter(Boolean);\n }\n\n return {\n userId,\n tenantId,\n email,\n roles,\n permissions,\n claims,\n };\n }\n}\n","import { RateLimitError, NetworkError } from '../errors.js';\nimport { RetryConfig } from '../types.js';\n\nexport interface ExecuteWithRetryOptions {\n retryConfig?: RetryConfig;\n signal?: AbortSignal;\n}\n\n/**\n * Executes an async operation with exponential backoff and jitter on retryable errors\n * (HTTP 429, 502, 503, 504, and transient network errors).\n */\nexport async function executeWithRetry<T>(\n fn: () => Promise<T>,\n options: ExecuteWithRetryOptions = {}\n): Promise<T> {\n const maxRetries = options.retryConfig?.maxRetries ?? 3;\n const initialDelay = options.retryConfig?.initialDelayMs ?? 500;\n const maxDelay = options.retryConfig?.maxDelayMs ?? 5000;\n\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (err: unknown) {\n attempt++;\n if (attempt > maxRetries) {\n throw err;\n }\n\n const isRetryable = isErrorRetryable(err);\n if (!isRetryable) {\n throw err;\n }\n\n // Check if aborted\n if (options.signal?.aborted) {\n throw new NetworkError('Request aborted by caller', options.signal.reason);\n }\n\n let delay = initialDelay * Math.pow(2, attempt - 1);\n // If error is RateLimitError and provides retryAfterSeconds, respect it if within reason\n if (err instanceof RateLimitError && err.retryAfterSeconds) {\n delay = Math.max(delay, err.retryAfterSeconds * 1000);\n }\n\n // Add jitter: +/- 20%\n const jitter = delay * (0.8 + Math.random() * 0.4);\n const cappedDelay = Math.min(jitter, maxDelay);\n\n await sleep(cappedDelay, options.signal);\n }\n }\n}\n\nfunction isErrorRetryable(err: unknown): boolean {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof NetworkError) {\n return true;\n }\n if (err instanceof Error) {\n const msg = err.message.toLowerCase();\n if (\n msg.includes('network') ||\n msg.includes('fetch failed') ||\n msg.includes('econnreset') ||\n msg.includes('econnrefused') ||\n msg.includes('etimedout')\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n return reject(new NetworkError('Request aborted while sleeping', signal.reason));\n }\n\n const timer = setTimeout(() => {\n resolve();\n }, ms);\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n reject(new NetworkError('Request aborted', signal.reason));\n },\n { once: true }\n );\n }\n });\n}\n","export interface CachedToken {\n accessToken: string;\n expiresAt: number; // Unix timestamp in seconds\n scope?: string;\n}\n\n/**\n * High-concurrency, Promise-safe in-memory cache for Machine-to-Machine (M2M) access tokens.\n * Automatically refreshes before expiration and coalesces concurrent refresh requests\n * to avoid thundering-herd problems against the IAM server.\n */\nexport class M2MTokenCache {\n private cache = new Map<string, CachedToken>();\n private inFlightRequests = new Map<string, Promise<string>>();\n\n /**\n * Refresh window buffer in seconds (default: 300s = 5 minutes).\n * A token expiring within this window will be refreshed proactively.\n */\n private readonly refreshBufferSeconds: number;\n\n constructor(refreshBufferSeconds = 300) {\n this.refreshBufferSeconds = refreshBufferSeconds;\n }\n\n /**\n * Retrieves a cached token if valid, or invokes the refresher function.\n * If a fetch is already in flight for the given cache key, coalesces into that existing promise.\n */\n public async getOrFetch(\n cacheKey: string,\n refresher: () => Promise<{ accessToken: string; expiresIn: number; scope?: string }>,\n force = false\n ): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n\n if (!force) {\n const cached = this.cache.get(cacheKey);\n if (cached && cached.expiresAt - this.refreshBufferSeconds > now) {\n return cached.accessToken;\n }\n }\n\n // Coalesce in-flight requests for the same cache key\n const existingInFlight = this.inFlightRequests.get(cacheKey);\n if (existingInFlight) {\n return existingInFlight;\n }\n\n const fetchPromise = (async () => {\n try {\n const response = await refresher();\n const expiresAt = now + response.expiresIn;\n\n this.cache.set(cacheKey, {\n accessToken: response.accessToken,\n expiresAt,\n scope: response.scope,\n });\n\n return response.accessToken;\n } finally {\n this.inFlightRequests.delete(cacheKey);\n }\n })();\n\n this.inFlightRequests.set(cacheKey, fetchPromise);\n return fetchPromise;\n }\n\n /**\n * Invalidates cached token for a specific cache key or clears all.\n */\n public invalidate(cacheKey?: string): void {\n if (cacheKey) {\n this.cache.delete(cacheKey);\n } else {\n this.cache.clear();\n }\n }\n\n /**\n * Returns current cached item metadata (for diagnostics and testing).\n */\n public get(cacheKey: string): CachedToken | undefined {\n return this.cache.get(cacheKey);\n }\n}\n","import { AuthenticationError, RateLimitError, SerafortError, NetworkError } from '../errors.js';\nimport { SerafortConfig, OAuthTokenResponse, ApiErrorEnvelope } from '../types.js';\nimport { executeWithRetry } from '../utils/retry.js';\nimport { M2MTokenCache } from './cache.js';\n\nexport class M2MModule {\n private readonly config: SerafortConfig;\n private readonly cache: M2MTokenCache;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: SerafortConfig, cache?: M2MTokenCache) {\n this.config = config;\n this.cache = cache ?? new M2MTokenCache();\n this.baseUrl = (config.endpoint || config.baseUrl || 'https://api.serafort.com').replace(/\\/+$/, '');\n this.fetchImpl = config.fetch || globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Retrieves a valid M2M access token.\n * Pulls from memory cache if valid and outside the refresh buffer.\n * If nearing expiration or missing, transparently requests a new token.\n */\n public async getAccessToken(scopes?: string[]): Promise<string> {\n const scopeStr = scopes && scopes.length > 0 ? scopes.sort().join(' ') : '';\n const cacheKey = `m2m:${this.config.clientId || 'default'}:${scopeStr}`;\n\n return this.cache.getOrFetch(cacheKey, () => this.fetchTokenNetwork(scopeStr), false);\n }\n\n /**\n * Forces a refresh of the access token, bypassing the cache.\n * Useful when an API endpoint returns 401 due to early revocation.\n */\n public async forceRefreshToken(scopes?: string[]): Promise<string> {\n const scopeStr = scopes && scopes.length > 0 ? scopes.sort().join(' ') : '';\n const cacheKey = `m2m:${this.config.clientId || 'default'}:${scopeStr}`;\n\n return this.cache.getOrFetch(cacheKey, () => this.fetchTokenNetwork(scopeStr), true);\n }\n\n /**\n * Clears the in-memory token cache.\n */\n public clearCache(): void {\n this.cache.invalidate();\n }\n\n /**\n * Performs the HTTP request to the OAuth2 token endpoint using Client Credentials grant.\n */\n private async fetchTokenNetwork(scope: string): Promise<{ accessToken: string; expiresIn: number; scope?: string }> {\n if (!this.config.clientId || !this.config.clientSecret) {\n throw new AuthenticationError('M2M authentication requires clientId and clientSecret to be configured.');\n }\n\n const tokenUrl = `${this.baseUrl}/oauth/token`;\n\n const bodyParams = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n });\n\n if (scope) {\n bodyParams.set('scope', scope);\n }\n\n return executeWithRetry(\n async () => {\n let response: Response;\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout ?? 10000);\n\n response = await this.fetchImpl(tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n },\n body: bodyParams.toString(),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n } catch (err: unknown) {\n throw new NetworkError(`Failed to connect to token endpoint at ${tokenUrl}`, err);\n }\n\n if (response.status === 429) {\n const retryAfterHeader = response.headers.get('Retry-After');\n const retryAfterSec = retryAfterHeader ? parseInt(retryAfterHeader, 10) : undefined;\n throw new RateLimitError('Rate limit exceeded on token endpoint', isNaN(retryAfterSec!) ? undefined : retryAfterSec);\n }\n\n if (!response.ok) {\n let errorPayload: ApiErrorEnvelope | undefined;\n try {\n errorPayload = (await response.json()) as ApiErrorEnvelope;\n } catch {\n // Non-JSON error body\n }\n\n const errorMessage = errorPayload?.error?.message || `OAuth token request failed with status ${response.status}`;\n const errorCode = errorPayload?.error?.code || 'TOKEN_REQUEST_FAILED';\n\n if (response.status === 401 || response.status === 400) {\n throw new AuthenticationError(errorMessage, errorCode);\n }\n\n throw new SerafortError(errorMessage, errorCode, response.status);\n }\n\n const data = (await response.json()) as OAuthTokenResponse;\n\n if (!data.access_token) {\n throw new SerafortError('OAuth token endpoint response did not contain access_token', 'INVALID_RESPONSE');\n }\n\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in || 3600,\n scope: data.scope,\n };\n },\n { retryConfig: this.config.retryPolicy }\n );\n }\n}\n","import { B2BModule } from './b2b/b2b.js';\nimport { M2MModule } from './m2m/m2m.js';\nimport { SerafortConfig } from './types.js';\n\n/**\n * Unified Serafort SDK Client.\n * Provides Machine Identity (M2M) token caching and B2B User Identity / RBAC capabilities.\n */\nexport class SerafortClient {\n public readonly config: SerafortConfig;\n public readonly m2m: M2MModule;\n public readonly b2b: B2BModule;\n\n constructor(config: SerafortConfig) {\n this.config = {\n endpoint: config.endpoint || config.baseUrl || 'https://api.serafort.com',\n ...config,\n };\n\n this.m2m = new M2MModule(this.config);\n this.b2b = new B2BModule(this.config);\n }\n\n /**\n * Helper shortcut to retrieve an M2M access token.\n */\n public async getAccessToken(scopes?: string[]): Promise<string> {\n return this.m2m.getAccessToken(scopes);\n }\n\n /**\n * Helper shortcut to validate a JWT token and decode its UserContext.\n */\n public async validateToken(token: string) {\n return this.b2b.validateToken(token);\n }\n}\n"]}
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Configuration options for initializing the Serafort SDK client.
3
+ */
4
+ interface RetryConfig {
5
+ /** Maximum number of retry attempts. Default: 3 */
6
+ maxRetries?: number;
7
+ /** Initial retry delay in milliseconds. Default: 500ms */
8
+ initialDelayMs?: number;
9
+ /** Maximum retry delay in milliseconds. Default: 5000ms */
10
+ maxDelayMs?: number;
11
+ }
12
+ interface SerafortConfig {
13
+ /** Base URL of the Serafort IAM backend (e.g. "https://auth.acme.com" or "http://localhost:3333") */
14
+ endpoint?: string;
15
+ /** Alias for endpoint */
16
+ baseUrl?: string;
17
+ /** Client identifier for Machine-to-Machine (M2M) authentication */
18
+ clientId?: string;
19
+ /** Client secret for Machine-to-Machine (M2M) authentication */
20
+ clientSecret?: string;
21
+ /** Publishable key for client-side and B2B public operations (starts with pk_live_ or pk_test_) */
22
+ publishableKey?: string;
23
+ /** Domain identifier (e.g. "auth.acme.com") */
24
+ domain?: string;
25
+ /** Request timeout in milliseconds. Default: 10,000ms */
26
+ timeout?: number;
27
+ /** Custom retry policy configuration for network resilience */
28
+ retryPolicy?: RetryConfig;
29
+ /** Custom fetch function implementation (defaults to global fetch) */
30
+ fetch?: typeof fetch;
31
+ }
32
+ /**
33
+ * Resolved user security context decoded from a verified JWT token.
34
+ */
35
+ interface UserContext {
36
+ /** The unique user identifier */
37
+ userId: string;
38
+ /** The tenant or organization identifier */
39
+ tenantId: string;
40
+ /** The primary email address of the user, if available */
41
+ email?: string;
42
+ /** Assigned roles (e.g. ["admin", "billing_manager"]) */
43
+ roles: string[];
44
+ /** Granted granular permissions (e.g. ["org:read", "billing:write"]) */
45
+ permissions: string[];
46
+ /** Raw decoded JWT payload claims */
47
+ claims: Record<string, unknown>;
48
+ }
49
+ /**
50
+ * OAuth2 token response payload from /oauth/token.
51
+ */
52
+ interface OAuthTokenResponse {
53
+ access_token: string;
54
+ token_type: string;
55
+ expires_in: number;
56
+ scope?: string;
57
+ refresh_token?: string;
58
+ }
59
+ /**
60
+ * Standard JSON Web Key (JWK) structure according to RFC 7517.
61
+ */
62
+ interface JWK {
63
+ kty: string;
64
+ kid?: string;
65
+ use?: string;
66
+ alg?: string;
67
+ n?: string;
68
+ e?: string;
69
+ crv?: string;
70
+ x?: string;
71
+ y?: string;
72
+ [key: string]: unknown;
73
+ }
74
+ /**
75
+ * Standard JSON Web Key Set (JWKS) structure according to RFC 7517.
76
+ */
77
+ interface JWKS {
78
+ keys: JWK[];
79
+ }
80
+ /**
81
+ * Standard API error detail item.
82
+ */
83
+ interface ApiErrorDetail {
84
+ field?: string;
85
+ message: string;
86
+ rule?: string;
87
+ }
88
+ /**
89
+ * Standard Serafort API response error envelope.
90
+ */
91
+ interface ApiErrorEnvelope {
92
+ status: 'error';
93
+ error: {
94
+ code: string;
95
+ message: string;
96
+ status: number;
97
+ details?: ApiErrorDetail[];
98
+ };
99
+ }
100
+
101
+ declare class JwksClient {
102
+ private readonly jwksUrl;
103
+ private readonly fetchImpl;
104
+ private cachedKeys;
105
+ private lastFetchedAt;
106
+ private readonly cacheTtlMs;
107
+ constructor(config: SerafortConfig, cacheTtlMs?: number);
108
+ /**
109
+ * Retrieves the CryptoKey matching the key ID (kid) from cache, or fetches from the JWKS endpoint.
110
+ */
111
+ getVerificationKey(kid?: string, alg?: string): Promise<CryptoKey>;
112
+ /**
113
+ * Refreshes public keys from the JWKS endpoint and imports them as CryptoKeys.
114
+ */
115
+ refreshJwks(): Promise<void>;
116
+ /**
117
+ * Imports a raw JWK into a Web Crypto CryptoKey.
118
+ */
119
+ importJwk(key: JWK): Promise<CryptoKey>;
120
+ }
121
+
122
+ interface TokenValidationOptions {
123
+ /** Expected JWT issuer (iss) */
124
+ expectedIssuer?: string;
125
+ /** Expected JWT audience (aud) */
126
+ expectedAudience?: string;
127
+ /** Allowed clock tolerance in seconds (default: 60s) */
128
+ clockToleranceSeconds?: number;
129
+ /** If true, skips cryptographic signature verification (ONLY for offline dev/testing) */
130
+ skipSignatureCheck?: boolean;
131
+ }
132
+ declare class B2BModule {
133
+ readonly config: SerafortConfig;
134
+ private readonly jwksClient;
135
+ private readonly baseUrl;
136
+ constructor(config: SerafortConfig, jwksClient?: JwksClient);
137
+ /**
138
+ * Validates a JWT token locally: checks signature against cached JWKS, verifies expiration,
139
+ * issuer, and audience, and decodes claims into a strongly-typed UserContext.
140
+ */
141
+ validateToken(token: string, options?: TokenValidationOptions): Promise<UserContext>;
142
+ /**
143
+ * Checks if the user context contains a specific granular permission.
144
+ * Supports wildcard matching (e.g. "org:*" matches "org:read").
145
+ */
146
+ hasPermission(userContext: UserContext, requiredPermission: string): boolean;
147
+ /**
148
+ * Checks if the user context contains a specific role.
149
+ */
150
+ hasRole(userContext: UserContext, requiredRole: string): boolean;
151
+ /**
152
+ * Constructs the Enterprise SSO Login URL for a specific tenant/organization.
153
+ */
154
+ getLoginUrl(tenantId: string, redirectUri: string, options?: {
155
+ state?: string;
156
+ connection?: string;
157
+ }): string;
158
+ /**
159
+ * Maps un-enveloped JWT claims to standard UserContext.
160
+ */
161
+ private mapClaimsToUserContext;
162
+ }
163
+
164
+ interface CachedToken {
165
+ accessToken: string;
166
+ expiresAt: number;
167
+ scope?: string;
168
+ }
169
+ /**
170
+ * High-concurrency, Promise-safe in-memory cache for Machine-to-Machine (M2M) access tokens.
171
+ * Automatically refreshes before expiration and coalesces concurrent refresh requests
172
+ * to avoid thundering-herd problems against the IAM server.
173
+ */
174
+ declare class M2MTokenCache {
175
+ private cache;
176
+ private inFlightRequests;
177
+ /**
178
+ * Refresh window buffer in seconds (default: 300s = 5 minutes).
179
+ * A token expiring within this window will be refreshed proactively.
180
+ */
181
+ private readonly refreshBufferSeconds;
182
+ constructor(refreshBufferSeconds?: number);
183
+ /**
184
+ * Retrieves a cached token if valid, or invokes the refresher function.
185
+ * If a fetch is already in flight for the given cache key, coalesces into that existing promise.
186
+ */
187
+ getOrFetch(cacheKey: string, refresher: () => Promise<{
188
+ accessToken: string;
189
+ expiresIn: number;
190
+ scope?: string;
191
+ }>, force?: boolean): Promise<string>;
192
+ /**
193
+ * Invalidates cached token for a specific cache key or clears all.
194
+ */
195
+ invalidate(cacheKey?: string): void;
196
+ /**
197
+ * Returns current cached item metadata (for diagnostics and testing).
198
+ */
199
+ get(cacheKey: string): CachedToken | undefined;
200
+ }
201
+
202
+ declare class M2MModule {
203
+ private readonly config;
204
+ private readonly cache;
205
+ private readonly baseUrl;
206
+ private readonly fetchImpl;
207
+ constructor(config: SerafortConfig, cache?: M2MTokenCache);
208
+ /**
209
+ * Retrieves a valid M2M access token.
210
+ * Pulls from memory cache if valid and outside the refresh buffer.
211
+ * If nearing expiration or missing, transparently requests a new token.
212
+ */
213
+ getAccessToken(scopes?: string[]): Promise<string>;
214
+ /**
215
+ * Forces a refresh of the access token, bypassing the cache.
216
+ * Useful when an API endpoint returns 401 due to early revocation.
217
+ */
218
+ forceRefreshToken(scopes?: string[]): Promise<string>;
219
+ /**
220
+ * Clears the in-memory token cache.
221
+ */
222
+ clearCache(): void;
223
+ /**
224
+ * Performs the HTTP request to the OAuth2 token endpoint using Client Credentials grant.
225
+ */
226
+ private fetchTokenNetwork;
227
+ }
228
+
229
+ /**
230
+ * Unified Serafort SDK Client.
231
+ * Provides Machine Identity (M2M) token caching and B2B User Identity / RBAC capabilities.
232
+ */
233
+ declare class SerafortClient {
234
+ readonly config: SerafortConfig;
235
+ readonly m2m: M2MModule;
236
+ readonly b2b: B2BModule;
237
+ constructor(config: SerafortConfig);
238
+ /**
239
+ * Helper shortcut to retrieve an M2M access token.
240
+ */
241
+ getAccessToken(scopes?: string[]): Promise<string>;
242
+ /**
243
+ * Helper shortcut to validate a JWT token and decode its UserContext.
244
+ */
245
+ validateToken(token: string): Promise<UserContext>;
246
+ }
247
+
248
+ /**
249
+ * Base exception class for all Serafort SDK errors.
250
+ */
251
+ declare class SerafortError extends Error {
252
+ readonly code: string;
253
+ readonly status: number;
254
+ readonly details: ApiErrorDetail[];
255
+ constructor(message: string, code?: string, status?: number, details?: ApiErrorDetail[]);
256
+ }
257
+ /**
258
+ * Authentication failed (invalid credentials, expired session, invalid JWT signature).
259
+ */
260
+ declare class AuthenticationError extends SerafortError {
261
+ constructor(message?: string, code?: string, details?: ApiErrorDetail[]);
262
+ }
263
+ /**
264
+ * Multi-Factor Authentication required to complete access.
265
+ */
266
+ declare class MfaRequiredError extends SerafortError {
267
+ readonly challengeId?: string;
268
+ readonly supportedMethods?: string[];
269
+ constructor(message?: string, challengeId?: string, supportedMethods?: string[], details?: ApiErrorDetail[]);
270
+ }
271
+ /**
272
+ * Request payload failed validation checks.
273
+ */
274
+ declare class ValidationError extends SerafortError {
275
+ constructor(message?: string, details?: ApiErrorDetail[]);
276
+ }
277
+ /**
278
+ * Rate limit exceeded (HTTP 429).
279
+ */
280
+ declare class RateLimitError extends SerafortError {
281
+ readonly retryAfterSeconds?: number;
282
+ constructor(message?: string, retryAfterSeconds?: number, details?: ApiErrorDetail[]);
283
+ }
284
+ /**
285
+ * Requested resource or tenant does not exist.
286
+ */
287
+ declare class NotFoundError extends SerafortError {
288
+ constructor(message?: string, code?: string, details?: ApiErrorDetail[]);
289
+ }
290
+ /**
291
+ * Network failure, client-side timeout, or host unreachable.
292
+ */
293
+ declare class NetworkError extends SerafortError {
294
+ constructor(message?: string, cause?: unknown);
295
+ }
296
+
297
+ interface DecodedJwt<T = Record<string, unknown>> {
298
+ header: {
299
+ alg: string;
300
+ typ?: string;
301
+ kid?: string;
302
+ [key: string]: unknown;
303
+ };
304
+ payload: T;
305
+ signature: Uint8Array;
306
+ signingInput: Uint8Array;
307
+ }
308
+ /**
309
+ * Decodes a base64url-encoded string into raw Uint8Array bytes.
310
+ */
311
+ declare function base64UrlToBytes(str: string): Uint8Array;
312
+ /**
313
+ * Decodes a base64url-encoded string into a UTF-8 string.
314
+ */
315
+ declare function base64UrlDecode(str: string): string;
316
+ /**
317
+ * Parses and separates the JWT into header, payload, signature, and signing input.
318
+ */
319
+ declare function parseJwt<T = Record<string, unknown>>(token: string): DecodedJwt<T>;
320
+
321
+ interface ExecuteWithRetryOptions {
322
+ retryConfig?: RetryConfig;
323
+ signal?: AbortSignal;
324
+ }
325
+ /**
326
+ * Executes an async operation with exponential backoff and jitter on retryable errors
327
+ * (HTTP 429, 502, 503, 504, and transient network errors).
328
+ */
329
+ declare function executeWithRetry<T>(fn: () => Promise<T>, options?: ExecuteWithRetryOptions): Promise<T>;
330
+
331
+ export { type ApiErrorDetail, type ApiErrorEnvelope, AuthenticationError, B2BModule, type JWK, type JWKS, JwksClient, M2MModule, M2MTokenCache, MfaRequiredError, NetworkError, NotFoundError, type OAuthTokenResponse, RateLimitError, type RetryConfig, SerafortClient, type SerafortConfig, SerafortError, type TokenValidationOptions, type UserContext, ValidationError, base64UrlDecode, base64UrlToBytes, executeWithRetry, parseJwt };