@sukujs/crypto 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +339 -2
- package/dist/index.cjs +605 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +240 -0
- package/dist/index.d.mts +240 -0
- package/dist/index.mjs +580 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +56 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/errors.ts","../src/duration.ts","../src/encoding.ts","../src/hash.ts","../src/jwt.ts","../src/random.ts","../src/password.ts","../src/seal.ts","../src/signer.ts","../src/index.ts"],"sourcesContent":["export type CryptoErrorCode =\n | 'malformed'\n | 'invalid_signature'\n | 'expired'\n | 'not_active'\n | 'invalid_claim'\n | 'algorithm_mismatch'\n | 'weak_key'\n | 'invalid_key'\n | 'invalid_input';\n\n/** Every failure in this package. Branch on `code`; do not show `message` to end users. */\nexport class CryptoError extends Error {\n override readonly name: string = 'CryptoError';\n constructor(\n readonly code: CryptoErrorCode,\n message: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n }\n}\n\n/** A token that could not be created or must not be trusted. */\nexport class JwtError extends CryptoError {\n override readonly name = 'JwtError';\n}\n","import { CryptoError } from './errors.js';\n\n/** Seconds as a number, or a string such as `30s`, `15m`, `12h`, `7d`, `2w`. */\nexport type Duration = number | `${number}${'s' | 'm' | 'h' | 'd' | 'w'}`;\n\nconst UNITS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86400, w: 604800 };\n\nexport function toSeconds(duration: Duration): number {\n if (typeof duration === 'number') {\n if (!Number.isFinite(duration) || duration < 0)\n throw new CryptoError('invalid_input', `Invalid duration: ${duration}`);\n return Math.floor(duration);\n }\n const match = /^(\\d+(?:\\.\\d+)?)([smhdw])$/.exec(duration);\n if (!match)\n throw new CryptoError(\n 'invalid_input',\n `Invalid duration \"${duration}\". Use seconds or a string like \"15m\".`,\n );\n return Math.floor(Number(match[1]) * UNITS[match[2]!]!);\n}\n","import { CryptoError } from './errors.js';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true });\n\nexport type Bytes = Uint8Array<ArrayBuffer>;\nexport type Data = string | Uint8Array;\n\nexport function toBytes(data: Data): Bytes {\n if (typeof data === 'string') return encoder.encode(data) as Bytes;\n return new Uint8Array(data) as Bytes;\n}\n\nexport function utf8(bytes: Uint8Array): string {\n try {\n return decoder.decode(bytes);\n } catch (cause) {\n throw new CryptoError('malformed', 'Bytes are not valid UTF-8.', { cause });\n }\n}\n\nexport function base64urlEncode(data: Data): string {\n const bytes = toBytes(data);\n let binary = '';\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nconst BASE64URL = /^[A-Za-z0-9_-]*$/;\n\nexport function base64urlDecode(text: string): Bytes {\n if (!BASE64URL.test(text) || text.length % 4 === 1) {\n throw new CryptoError('malformed', 'Value is not valid base64url.');\n }\n const padded = text.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((text.length + 3) % 4);\n const binary = atob(padded);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out as Bytes;\n}\n\nexport function hexEncode(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\n/**\n * Compares two values without leaking where they differ through timing. Use it for\n * secrets you compare yourself (API keys, tokens); signatures made by this package are\n * already verified in constant time.\n */\nexport function timingSafeEqual(a: Data, b: Data): boolean {\n const x = toBytes(a);\n const y = toBytes(b);\n let diff = x.length ^ y.length;\n const n = Math.max(x.length, y.length);\n for (let i = 0; i < n; i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);\n return diff === 0;\n}\n","import { type Bytes, type Data, hexEncode, toBytes } from './encoding.js';\n\nexport type HashAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** Raw digest bytes. Not for passwords: use `hashPassword`. */\nexport async function digest(algorithm: HashAlgorithm, data: Data): Promise<Bytes> {\n return new Uint8Array(await crypto.subtle.digest(algorithm, toBytes(data))) as Bytes;\n}\n\n/** Hex SHA-256, e.g. for content fingerprints and cache keys. */\nexport async function sha256(data: Data): Promise<string> {\n return hexEncode(await digest('SHA-256', data));\n}\n\nexport async function sha512(data: Data): Promise<string> {\n return hexEncode(await digest('SHA-512', data));\n}\n","import { type Duration, toSeconds } from './duration.js';\nimport { type Bytes, base64urlDecode, base64urlEncode, toBytes, utf8 } from './encoding.js';\nimport { JwtError } from './errors.js';\n\nexport type JwtAlgorithm =\n | 'HS256'\n | 'HS384'\n | 'HS512'\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'PS256'\n | 'PS384'\n | 'PS512'\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'EdDSA';\n\n/** A PEM string (PKCS#8 private or SPKI public), a JWK, or an imported `CryptoKey`. */\nexport type KeyInput = string | JsonWebKey | CryptoKey;\n\n/** Registered claims (RFC 7519). Your own claims sit alongside them. */\nexport interface JwtClaims {\n iss?: string;\n sub?: string;\n aud?: string | string[];\n exp?: number;\n nbf?: number;\n iat?: number;\n jti?: string;\n}\n\nexport type JwtPayload<T = Record<string, unknown>> = T & JwtClaims;\n\n/** Structural Standard Schema, so any schema library can validate payloads. */\ninterface PayloadSchema<T> {\n readonly '~standard': {\n readonly validate: (\n value: unknown,\n ) =>\n | { value: T; issues?: undefined }\n | { issues: readonly { message: string }[] }\n | Promise<{ value: T; issues?: undefined } | { issues: readonly { message: string }[] }>;\n };\n}\n\ninterface CommonOptions<T> {\n /** Lifetime of signed tokens. Default `1h`. `false` issues tokens that never expire. */\n expiresIn?: Duration | false;\n /** Set as `iss` when signing and required when verifying. */\n issuer?: string;\n /** Set as `aud` when signing and required when verifying. */\n audience?: string | string[];\n /** Seconds of clock skew tolerated for `exp`, `nbf` and `iat`. Default 0. */\n clockTolerance?: number;\n /** Validates the payload on verify; its output type becomes the payload type. */\n schema?: PayloadSchema<T>;\n /** `kid` header for signed tokens. */\n keyId?: string;\n /** Largest token accepted, in characters. Default 8192. */\n maxTokenLength?: number;\n /** Clock in milliseconds. For tests. */\n now?: () => number;\n}\n\nexport interface HmacJwtOptions<T> extends CommonOptions<T> {\n algorithm?: 'HS256' | 'HS384' | 'HS512';\n /** At least as long as the hash output: 32, 48 or 64 bytes for HS256, HS384, HS512. */\n secret: string | Uint8Array;\n /** Older secrets still accepted when verifying, for rotation. Never used to sign. */\n previousSecrets?: (string | Uint8Array)[];\n}\n\nexport interface KeyPairJwtOptions<T> extends CommonOptions<T> {\n algorithm: Exclude<JwtAlgorithm, 'HS256' | 'HS384' | 'HS512'>;\n /** Needed to sign. Omit on services that only verify. */\n privateKey?: KeyInput;\n /** Needed to verify. */\n publicKey?: KeyInput;\n /** Older public keys still accepted when verifying, for rotation. */\n previousPublicKeys?: KeyInput[];\n}\n\nexport type JwtOptions<T> = HmacJwtOptions<T> | KeyPairJwtOptions<T>;\n\nexport interface SignOptions {\n expiresIn?: Duration | false;\n /** Token is rejected until this much time has passed. */\n notBefore?: Duration;\n subject?: string;\n jwtId?: string;\n}\n\nexport interface Jwt<T> {\n readonly algorithm: JwtAlgorithm;\n /** Signs a payload. Adds `iat`, `exp`, and the configured `iss` and `aud`. */\n sign(payload: T & JwtClaims, options?: SignOptions): Promise<string>;\n /**\n * Verifies the signature and claims and returns the payload. Throws `JwtError` otherwise;\n * a token that fails must be treated as absent.\n */\n verify(token: string): Promise<JwtPayload<T>>;\n}\n\ninterface AlgorithmSpec {\n import: object;\n sign: object;\n /** Bytes of hash output, which is also the minimum HMAC key length. */\n size: number;\n}\n\nfunction spec(algorithm: JwtAlgorithm): AlgorithmSpec {\n const bits = algorithm.slice(2);\n const hash = `SHA-${bits}`;\n const size = Number(bits) / 8;\n switch (algorithm.slice(0, 2)) {\n case 'HS':\n return { import: { name: 'HMAC', hash }, sign: { name: 'HMAC' }, size };\n case 'RS':\n return {\n import: { name: 'RSASSA-PKCS1-v1_5', hash },\n sign: { name: 'RSASSA-PKCS1-v1_5' },\n size,\n };\n case 'PS':\n return {\n import: { name: 'RSA-PSS', hash },\n sign: { name: 'RSA-PSS', saltLength: size },\n size,\n };\n case 'ES': {\n const namedCurve = bits === '512' ? 'P-521' : `P-${bits}`;\n return { import: { name: 'ECDSA', namedCurve }, sign: { name: 'ECDSA', hash }, size };\n }\n default:\n return { import: { name: 'Ed25519' }, sign: { name: 'Ed25519' }, size: 0 };\n }\n}\n\nconst ALGORITHMS: readonly string[] = [\n 'HS256',\n 'HS384',\n 'HS512',\n 'RS256',\n 'RS384',\n 'RS512',\n 'PS256',\n 'PS384',\n 'PS512',\n 'ES256',\n 'ES384',\n 'ES512',\n 'EdDSA',\n];\n\nfunction pemBody(pem: string, label: string): Bytes | undefined {\n const match = new RegExp(`-----BEGIN ${label}-----([\\\\s\\\\S]+?)-----END ${label}-----`).exec(pem);\n if (!match) return undefined;\n const binary = atob(match[1]!.replace(/\\s+/g, ''));\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out as Bytes;\n}\n\nasync function importKey(\n input: KeyInput,\n algorithm: JwtAlgorithm,\n usage: 'sign' | 'verify',\n): Promise<CryptoKey> {\n const params = spec(algorithm).import as AlgorithmIdentifier;\n try {\n if (typeof input === 'string') {\n const label = usage === 'sign' ? 'PRIVATE KEY' : 'PUBLIC KEY';\n const der = pemBody(input, label);\n if (!der) {\n throw new JwtError(\n 'invalid_key',\n `Expected a PEM \"${label}\" block (${usage === 'sign' ? 'PKCS#8' : 'SPKI'}). ` +\n 'Convert legacy \"RSA PRIVATE KEY\" / \"EC PRIVATE KEY\" files with: openssl pkcs8 -topk8 -nocrypt.',\n );\n }\n return await crypto.subtle.importKey(\n usage === 'sign' ? 'pkcs8' : 'spki',\n der,\n params,\n false,\n [usage],\n );\n }\n if (typeof CryptoKey !== 'undefined' && input instanceof CryptoKey) {\n if (!input.usages.includes(usage))\n throw new JwtError('invalid_key', `CryptoKey does not allow \"${usage}\".`);\n return input;\n }\n return await crypto.subtle.importKey('jwk', input as JsonWebKey, params, false, [usage]);\n } catch (cause) {\n if (cause instanceof JwtError) throw cause;\n throw new JwtError('invalid_key', `Could not import the ${usage} key for ${algorithm}.`, {\n cause,\n });\n }\n}\n\nfunction importSecret(secret: string | Uint8Array, algorithm: JwtAlgorithm): Promise<CryptoKey> {\n const bytes = toBytes(secret);\n const { size, import: params } = spec(algorithm);\n if (bytes.byteLength < size) {\n throw new JwtError(\n 'weak_key',\n `${algorithm} needs a secret of at least ${size} bytes; got ${bytes.byteLength}. Generate one with randomToken(${size}).`,\n );\n }\n return crypto.subtle.importKey('raw', bytes, params as AlgorithmIdentifier, false, [\n 'sign',\n 'verify',\n ]);\n}\n\nfunction parseJson(segment: string, what: string): Record<string, unknown> {\n let value: unknown;\n try {\n value = JSON.parse(utf8(base64urlDecode(segment)));\n } catch (cause) {\n throw new JwtError('malformed', `Token ${what} is not valid.`, { cause });\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new JwtError('malformed', `Token ${what} is not an object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction numeric(claims: Record<string, unknown>, name: string): number | undefined {\n const v = claims[name];\n if (v === undefined) return undefined;\n if (typeof v !== 'number' || !Number.isFinite(v))\n throw new JwtError('invalid_claim', `Claim \"${name}\" must be a number.`);\n return v;\n}\n\n/**\n * Creates a signer and verifier bound to one algorithm and one set of keys.\n *\n * The algorithm is fixed here and never taken from a token, which rules out `alg: none` and\n * key-confusion attacks. Verification checks the signature, `exp`, `nbf`, `iat`, and the\n * configured issuer and audience.\n *\n * ```ts\n * const jwt = createJwt<{ role: string }>({ secret: env.JWT_SECRET, issuer: 'api', expiresIn: '15m' });\n * const token = await jwt.sign({ sub: user.id, role: 'admin' });\n * const payload = await jwt.verify(token);\n * ```\n */\nexport function createJwt<T = Record<string, unknown>>(options: JwtOptions<T>): Jwt<T> {\n const algorithm: JwtAlgorithm = options.algorithm ?? 'HS256';\n if (!ALGORITHMS.includes(algorithm))\n throw new JwtError('algorithm_mismatch', `Unsupported algorithm \"${algorithm}\".`);\n const hmac = algorithm.startsWith('HS');\n const params = spec(algorithm).sign as AlgorithmIdentifier;\n const tolerance = options.clockTolerance ?? 0;\n const maxLength = options.maxTokenLength ?? 8192;\n const now = () => Math.floor((options.now?.() ?? Date.now()) / 1000);\n const defaultExpiry = options.expiresIn === undefined ? '1h' : options.expiresIn;\n\n let signKey: Promise<CryptoKey> | undefined;\n let verifyKeys: Promise<CryptoKey[]> | undefined;\n\n const getSignKey = (): Promise<CryptoKey> => {\n if (signKey) return signKey;\n if (hmac) {\n if (!('secret' in options) || options.secret === undefined)\n throw new JwtError('invalid_key', `${algorithm} needs a secret.`);\n signKey = importSecret(options.secret, algorithm);\n } else {\n const key = (options as KeyPairJwtOptions<T>).privateKey;\n if (!key) throw new JwtError('invalid_key', `Signing with ${algorithm} needs a privateKey.`);\n signKey = importKey(key, algorithm, 'sign');\n }\n return signKey;\n };\n\n const getVerifyKeys = (): Promise<CryptoKey[]> => {\n if (verifyKeys) return verifyKeys;\n if (hmac) {\n const o = options as HmacJwtOptions<T>;\n if (o.secret === undefined) throw new JwtError('invalid_key', `${algorithm} needs a secret.`);\n verifyKeys = Promise.all(\n [o.secret, ...(o.previousSecrets ?? [])].map((s) => importSecret(s, algorithm)),\n );\n } else {\n const o = options as KeyPairJwtOptions<T>;\n if (!o.publicKey)\n throw new JwtError('invalid_key', `Verifying ${algorithm} needs a publicKey.`);\n verifyKeys = Promise.all(\n [o.publicKey, ...(o.previousPublicKeys ?? [])].map((k) =>\n importKey(k, algorithm, 'verify'),\n ),\n );\n }\n return verifyKeys;\n };\n\n async function sign(payload: T & JwtClaims, signOptions: SignOptions = {}): Promise<string> {\n if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {\n throw new JwtError('invalid_input', 'JWT payload must be a plain object.');\n }\n const issuedAt = now();\n const claims: Record<string, unknown> = { ...payload, iat: issuedAt };\n const expiry = signOptions.expiresIn === undefined ? defaultExpiry : signOptions.expiresIn;\n if (expiry !== false) claims.exp = issuedAt + toSeconds(expiry);\n if (signOptions.notBefore !== undefined)\n claims.nbf = issuedAt + toSeconds(signOptions.notBefore);\n if (options.issuer !== undefined) claims.iss = options.issuer;\n if (options.audience !== undefined) claims.aud = options.audience;\n if (signOptions.subject !== undefined) claims.sub = signOptions.subject;\n if (signOptions.jwtId !== undefined) claims.jti = signOptions.jwtId;\n\n const header: Record<string, string> = { alg: algorithm, typ: 'JWT' };\n if (options.keyId !== undefined) header.kid = options.keyId;\n const signingInput = `${base64urlEncode(JSON.stringify(header))}.${base64urlEncode(JSON.stringify(claims))}`;\n const signature = await crypto.subtle.sign(params, await getSignKey(), toBytes(signingInput));\n return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;\n }\n\n async function verify(token: string): Promise<JwtPayload<T>> {\n if (typeof token !== 'string' || token.length === 0)\n throw new JwtError('malformed', 'Token is missing.');\n if (token.length > maxLength) throw new JwtError('malformed', 'Token is too long.');\n const parts = token.split('.');\n if (parts.length !== 3) throw new JwtError('malformed', 'Token must have three parts.');\n const [headerPart, payloadPart, signaturePart] = parts as [string, string, string];\n\n const header = parseJson(headerPart, 'header');\n // The algorithm comes from configuration. A token naming any other one, including\n // \"none\", is rejected before any key is touched.\n if (header.alg !== algorithm) {\n throw new JwtError('algorithm_mismatch', `Token algorithm is not ${algorithm}.`);\n }\n if (header.crit !== undefined)\n throw new JwtError('malformed', 'Token uses unsupported critical headers.');\n if (header.typ !== undefined && String(header.typ).toUpperCase() !== 'JWT') {\n throw new JwtError('malformed', 'Token type is not JWT.');\n }\n\n const signature = base64urlDecode(signaturePart);\n const data = toBytes(`${headerPart}.${payloadPart}`);\n let valid = false;\n for (const key of await getVerifyKeys()) {\n if (await crypto.subtle.verify(params, key, signature, data)) {\n valid = true;\n break;\n }\n }\n if (!valid) throw new JwtError('invalid_signature', 'Token signature is not valid.');\n\n const claims = parseJson(payloadPart, 'payload');\n const at = now();\n const exp = numeric(claims, 'exp');\n const nbf = numeric(claims, 'nbf');\n const iat = numeric(claims, 'iat');\n if (exp === undefined) {\n if (defaultExpiry !== false) throw new JwtError('invalid_claim', 'Token has no expiry.');\n } else if (at >= exp + tolerance) {\n throw new JwtError('expired', 'Token has expired.');\n }\n if (nbf !== undefined && at < nbf - tolerance)\n throw new JwtError('not_active', 'Token is not active yet.');\n if (iat !== undefined && iat > at + tolerance)\n throw new JwtError('invalid_claim', 'Token was issued in the future.');\n if (options.issuer !== undefined && claims.iss !== options.issuer) {\n throw new JwtError('invalid_claim', 'Token issuer does not match.');\n }\n if (options.audience !== undefined) {\n const expected = Array.isArray(options.audience) ? options.audience : [options.audience];\n const actual = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!actual.some((a) => typeof a === 'string' && expected.includes(a))) {\n throw new JwtError('invalid_claim', 'Token audience does not match.');\n }\n }\n\n if (options.schema) {\n const result = await options.schema['~standard'].validate(claims);\n if (result.issues) {\n throw new JwtError(\n 'invalid_claim',\n `Token payload is not valid: ${result.issues.map((i) => i.message).join('; ')}`,\n );\n }\n return { ...claims, ...(result.value as object) } as JwtPayload<T>;\n }\n return claims as JwtPayload<T>;\n }\n\n return { algorithm, sign, verify };\n}\n\n/**\n * Reads a token's header and payload **without verifying anything**. The result is\n * attacker-controlled. Use only to pick a key or to log; never to make a decision.\n */\nexport function decodeJwtUnverified(token: string): {\n header: Record<string, unknown>;\n payload: Record<string, unknown>;\n} {\n const parts = typeof token === 'string' ? token.split('.') : [];\n if (parts.length !== 3) throw new JwtError('malformed', 'Token must have three parts.');\n return { header: parseJson(parts[0]!, 'header'), payload: parseJson(parts[1]!, 'payload') };\n}\n\n/** Extracts the token from an `Authorization: Bearer <token>` header value. */\nexport function bearerToken(header: string | null | undefined): string | undefined {\n if (!header) return undefined;\n const match = /^Bearer +([A-Za-z0-9._~+/-]+=*)$/i.exec(header.trim());\n return match?.[1];\n}\n","import { type Bytes, base64urlEncode, hexEncode } from './encoding.js';\nimport { CryptoError } from './errors.js';\n\n/** Cryptographically secure random bytes. */\nexport function randomBytes(length: number): Bytes {\n if (!Number.isInteger(length) || length < 0 || length > 65536) {\n throw new CryptoError('invalid_input', 'Length must be an integer between 0 and 65536.');\n }\n return crypto.getRandomValues(new Uint8Array(length)) as Bytes;\n}\n\n/** A URL-safe random token. 32 bytes (256 bits) by default: session ids, reset tokens, API keys. */\nexport function randomToken(bytes = 32): string {\n return base64urlEncode(randomBytes(bytes));\n}\n\nexport function randomHex(bytes = 16): string {\n return hexEncode(randomBytes(bytes));\n}\n\nexport function randomUUID(): string {\n return crypto.randomUUID();\n}\n\n/** A uniformly distributed integer in `[min, max)`, without modulo bias. */\nexport function randomInt(min: number, max: number): number {\n const range = max - min;\n if (\n !Number.isSafeInteger(min) ||\n !Number.isSafeInteger(max) ||\n range <= 0 ||\n range > 0xffffffff\n ) {\n throw new CryptoError(\n 'invalid_input',\n 'randomInt needs integers with 0 < max - min <= 2^32 - 1.',\n );\n }\n const limit = Math.floor(0x100000000 / range) * range;\n const buffer = new Uint32Array(1);\n for (;;) {\n crypto.getRandomValues(buffer);\n if (buffer[0]! < limit) return min + (buffer[0]! % range);\n }\n}\n","import { base64urlDecode, base64urlEncode, toBytes } from './encoding.js';\nimport { CryptoError } from './errors.js';\nimport { randomBytes } from './random.js';\n\n/** OWASP's 2023 minimum for PBKDF2-HMAC-SHA256. */\nexport const DEFAULT_PASSWORD_ITERATIONS = 600_000;\nconst MAX_ITERATIONS = 10_000_000;\nconst PREFIX = '$pbkdf2-sha256$';\n\nexport interface PasswordOptions {\n /** Work factor. Default 600,000. Raise it over time; `needsRehash` tells you which hashes lag. */\n iterations?: number;\n}\n\nasync function derive(\n password: string,\n salt: Uint8Array,\n iterations: number,\n length: number,\n): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n 'raw',\n toBytes(password.normalize('NFKC')),\n 'PBKDF2',\n false,\n ['deriveBits'],\n );\n const bits = await crypto.subtle.deriveBits(\n { name: 'PBKDF2', hash: 'SHA-256', salt: toBytes(salt), iterations },\n key,\n length * 8,\n );\n return new Uint8Array(bits);\n}\n\n/**\n * Hashes a password for storage, with a random salt, as\n * `$pbkdf2-sha256$i=<iterations>$<salt>$<hash>`.\n *\n * PBKDF2 is used because it is the password KDF every Web Crypto runtime provides. If you\n * can take a native dependency, Argon2id is the stronger choice.\n */\nexport async function hashPassword(\n password: string,\n options: PasswordOptions = {},\n): Promise<string> {\n const iterations = options.iterations ?? DEFAULT_PASSWORD_ITERATIONS;\n if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_ITERATIONS) {\n throw new CryptoError('invalid_input', 'Invalid iteration count.');\n }\n if (typeof password !== 'string' || password.length === 0)\n throw new CryptoError('invalid_input', 'Password is empty.');\n const salt = randomBytes(16);\n const hash = await derive(password, salt, iterations, 32);\n return `${PREFIX}i=${iterations}$${base64urlEncode(salt)}$${base64urlEncode(hash)}`;\n}\n\nfunction parse(\n stored: string,\n): { iterations: number; salt: Uint8Array; hash: Uint8Array } | undefined {\n if (typeof stored !== 'string' || !stored.startsWith(PREFIX)) return undefined;\n const [params, salt, hash, ...rest] = stored.slice(PREFIX.length).split('$');\n const match = /^i=(\\d{1,8})$/.exec(params ?? '');\n if (!match || !salt || !hash || rest.length) return undefined;\n const iterations = Number(match[1]);\n if (iterations < 1 || iterations > MAX_ITERATIONS) return undefined;\n try {\n return { iterations, salt: base64urlDecode(salt), hash: base64urlDecode(hash) };\n } catch {\n return undefined;\n }\n}\n\n/** `true` only if the password matches. Malformed stored values are `false`, never an error. */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const parsed = parse(stored);\n if (!parsed || typeof password !== 'string') return false;\n const actual = await derive(password, parsed.salt, parsed.iterations, parsed.hash.length);\n let diff = actual.length ^ parsed.hash.length;\n for (let i = 0; i < actual.length; i++) diff |= actual[i]! ^ (parsed.hash[i] ?? 0);\n return diff === 0;\n}\n\n/** Whether a stored hash uses fewer iterations than you now want. Rehash after a successful login. */\nexport function needsRehash(stored: string, options: PasswordOptions = {}): boolean {\n const parsed = parse(stored);\n return !parsed || parsed.iterations < (options.iterations ?? DEFAULT_PASSWORD_ITERATIONS);\n}\n","import { type Duration, toSeconds } from './duration.js';\nimport { base64urlDecode, base64urlEncode, toBytes, utf8 } from './encoding.js';\nimport { CryptoError } from './errors.js';\nimport { randomBytes } from './random.js';\n\nexport interface SealerOptions {\n /** Binds sealed values to a use, so a value sealed as `session` cannot be opened as `reset`. */\n purpose?: string;\n /** Older secrets still accepted when unsealing, for rotation. */\n previousSecrets?: (string | Uint8Array)[];\n /** Clock in milliseconds. For tests. */\n now?: () => number;\n}\n\nexport interface Sealer {\n /** Encrypts any JSON value into a URL-safe string. `ttl` makes it expire. */\n seal(value: unknown, options?: { ttl?: Duration }): Promise<string>;\n /** The original value, or `undefined` if it was tampered with, expired, or sealed with another key. */\n unseal<T = unknown>(sealed: string): Promise<T | undefined>;\n}\n\nconst VERSION = 'v1';\n\n/**\n * Authenticated encryption (AES-256-GCM) for values the client holds but must not read or\n * change: encrypted cookies, OAuth state, password-reset payloads.\n */\nexport function createSealer(secret: string | Uint8Array, options: SealerOptions = {}): Sealer {\n const purpose = toBytes(options.purpose ?? 'suku.seal');\n const now = () => options.now?.() ?? Date.now();\n\n const load = async (s: string | Uint8Array): Promise<CryptoKey> => {\n const bytes = toBytes(s);\n if (bytes.byteLength < 32) {\n throw new CryptoError(\n 'weak_key',\n `Sealing secret must be at least 32 bytes; got ${bytes.byteLength}.`,\n );\n }\n const material = await crypto.subtle.importKey('raw', bytes, 'HKDF', false, ['deriveKey']);\n return crypto.subtle.deriveKey(\n { name: 'HKDF', hash: 'SHA-256', salt: toBytes('suku.seal.v1'), info: purpose },\n material,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt'],\n );\n };\n let keys: Promise<CryptoKey[]> | undefined;\n const getKeys = () =>\n (keys ??= Promise.all([secret, ...(options.previousSecrets ?? [])].map(load)));\n\n return {\n async seal(value, sealOptions = {}) {\n const envelope: { d: unknown; e?: number } = { d: value };\n if (sealOptions.ttl !== undefined) envelope.e = now() + toSeconds(sealOptions.ttl) * 1000;\n const json = JSON.stringify(envelope);\n if (json === undefined)\n throw new CryptoError('invalid_input', 'Value cannot be serialised to JSON.');\n const iv = randomBytes(12);\n const ciphertext = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv, additionalData: purpose },\n (await getKeys())[0]!,\n toBytes(json),\n );\n return `${VERSION}.${base64urlEncode(iv)}.${base64urlEncode(new Uint8Array(ciphertext))}`;\n },\n\n async unseal<T>(sealed: string) {\n if (typeof sealed !== 'string') return undefined;\n const parts = sealed.split('.');\n if (parts.length !== 3 || parts[0] !== VERSION) return undefined;\n let iv: Uint8Array<ArrayBuffer>;\n let ciphertext: Uint8Array<ArrayBuffer>;\n try {\n iv = base64urlDecode(parts[1]!);\n ciphertext = base64urlDecode(parts[2]!);\n } catch {\n return undefined;\n }\n if (iv.byteLength !== 12) return undefined;\n for (const key of await getKeys()) {\n try {\n const plain = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv, additionalData: purpose },\n key,\n ciphertext,\n );\n const envelope = JSON.parse(utf8(new Uint8Array(plain))) as { d: T; e?: number };\n if (envelope.e !== undefined && now() >= envelope.e) return undefined;\n return envelope.d;\n } catch {\n // Wrong key or tampered data: try the next key.\n }\n }\n return undefined;\n },\n };\n}\n","import { base64urlDecode, base64urlEncode, type Data, toBytes } from './encoding.js';\nimport { CryptoError } from './errors.js';\nimport type { HashAlgorithm } from './hash.js';\n\nexport interface SignerOptions {\n hash?: HashAlgorithm;\n /** Older secrets still accepted when verifying, for rotation. */\n previousSecrets?: (string | Uint8Array)[];\n}\n\nexport interface Signer {\n /** HMAC of the data, base64url. */\n sign(data: Data): Promise<string>;\n /** Constant-time check. `false` for anything malformed. */\n verify(data: Data, signature: string): Promise<boolean>;\n /** `value.signature`, for cookies and links whose content may be read but not changed. */\n pack(value: string): Promise<string>;\n /** The original value, or `undefined` if the signature does not match. */\n unpack(packed: string): Promise<string | undefined>;\n}\n\n/**\n * HMAC signing for values that must not be tampered with: cookies, webhook payloads,\n * unsubscribe links. The value stays readable; use `createSealer` to hide it.\n */\nexport function createSigner(secret: string | Uint8Array, options: SignerOptions = {}): Signer {\n const hash = options.hash ?? 'SHA-256';\n const load = (s: string | Uint8Array) => {\n const bytes = toBytes(s);\n if (bytes.byteLength < 32) {\n throw new CryptoError(\n 'weak_key',\n `Signing secret must be at least 32 bytes; got ${bytes.byteLength}.`,\n );\n }\n return crypto.subtle.importKey('raw', bytes, { name: 'HMAC', hash }, false, ['sign', 'verify']);\n };\n let keys: Promise<CryptoKey[]> | undefined;\n const getKeys = () =>\n (keys ??= Promise.all([secret, ...(options.previousSecrets ?? [])].map(load)));\n\n const sign = async (data: Data) =>\n base64urlEncode(\n new Uint8Array(await crypto.subtle.sign('HMAC', (await getKeys())[0]!, toBytes(data))),\n );\n\n const verify = async (data: Data, signature: string) => {\n let sig: Uint8Array<ArrayBuffer>;\n try {\n sig = base64urlDecode(signature);\n } catch {\n return false;\n }\n for (const key of await getKeys()) {\n if (await crypto.subtle.verify('HMAC', key, sig, toBytes(data))) return true;\n }\n return false;\n };\n\n return {\n sign,\n verify,\n pack: async (value) => `${value}.${await sign(value)}`,\n unpack: async (packed) => {\n const at = typeof packed === 'string' ? packed.lastIndexOf('.') : -1;\n if (at === -1) return undefined;\n const value = packed.slice(0, at);\n return (await verify(value, packed.slice(at + 1))) ? value : undefined;\n },\n };\n}\n","export { type Duration, toSeconds } from './duration.js';\nexport {\n type Bytes,\n base64urlDecode,\n base64urlEncode,\n type Data,\n hexEncode,\n timingSafeEqual,\n} from './encoding.js';\nexport { CryptoError, type CryptoErrorCode, JwtError } from './errors.js';\nexport { digest, type HashAlgorithm, sha256, sha512 } from './hash.js';\nexport {\n bearerToken,\n createJwt,\n decodeJwtUnverified,\n type HmacJwtOptions,\n type Jwt,\n type JwtAlgorithm,\n type JwtClaims,\n type JwtOptions,\n type JwtPayload,\n type KeyInput,\n type KeyPairJwtOptions,\n type SignOptions,\n} from './jwt.js';\nexport {\n DEFAULT_PASSWORD_ITERATIONS,\n hashPassword,\n needsRehash,\n type PasswordOptions,\n verifyPassword,\n} from './password.js';\nexport { randomBytes, randomHex, randomInt, randomToken, randomUUID } from './random.js';\nexport { createSealer, type Sealer, type SealerOptions } from './seal.js';\nexport { createSigner, type Signer, type SignerOptions } from './signer.js';\n\nimport { toSeconds } from './duration.js';\nimport { base64urlDecode, base64urlEncode, hexEncode, timingSafeEqual } from './encoding.js';\nimport { CryptoError, JwtError } from './errors.js';\nimport { digest, sha256, sha512 } from './hash.js';\nimport { bearerToken, createJwt, decodeJwtUnverified } from './jwt.js';\nimport { hashPassword, needsRehash, verifyPassword } from './password.js';\nimport { randomBytes, randomHex, randomInt, randomToken, randomUUID } from './random.js';\nimport { createSealer } from './seal.js';\nimport { createSigner } from './signer.js';\n\n/**\n * Everything in one object, for `import sukuCrypto from '@sukujs/crypto'`.\n * The named exports are the same functions and tree-shake better.\n */\nconst sukuCrypto = {\n createJwt,\n bearerToken,\n decodeJwtUnverified,\n hashPassword,\n verifyPassword,\n needsRehash,\n createSigner,\n createSealer,\n randomToken,\n randomBytes,\n randomHex,\n randomUUID,\n randomInt,\n sha256,\n sha512,\n digest,\n timingSafeEqual,\n base64urlEncode,\n base64urlDecode,\n hexEncode,\n toSeconds,\n CryptoError,\n JwtError,\n} as const;\n\nexport default sukuCrypto;\n"],"mappings":";;;AAYA,IAAa,cAAb,cAAiC,MAAM;CAErC,YACE,AAAS,MACT,SACA,SACA;EACA,MAAM,SAAS,OAAO;EAJb;cAFsB;CAOjC;AACF;;AAGA,IAAa,WAAb,cAA8B,YAAY;;;cACf;;AAC3B;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,QAAQ,IAAI,CAAC,QAAQ,GAAI,QAAQ,mBAAmB,CAAC,CAAE,CAAC,CAAC,IAAI,IAAI,CAAC;CAE9E,MAAM,OAAO,OAAO,SAClB,gBACE,IAAI,WAAW,MAAM,OAAO,OAAO,KAAK,SAAS,MAAM,QAAQ,EAAC,CAAE,IAAK,QAAQ,IAAI,CAAC,CAAC,CACvF;CAEF,MAAM,SAAS,OAAO,MAAY,cAAsB;EACtD,IAAI;EACJ,IAAI;GACF,MAAM,gBAAgB,SAAS;EACjC,QAAQ;GACN,OAAO;EACT;EACA,KAAK,MAAM,OAAO,MAAM,QAAQ,GAC9B,IAAI,MAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,KAAK,QAAQ,IAAI,CAAC,GAAG,OAAO;EAE1E,OAAO;CACT;CAEA,OAAO;EACL;EACA;EACA,MAAM,OAAO,UAAU,GAAG,MAAM,GAAG,MAAM,KAAK,KAAK;EACnD,QAAQ,OAAO,WAAW;GACxB,MAAM,KAAK,OAAO,WAAW,WAAW,OAAO,YAAY,GAAG,IAAI;GAClE,IAAI,OAAO,IAAI,OAAO;GACtB,MAAM,QAAQ,OAAO,MAAM,GAAG,EAAE;GAChC,OAAQ,MAAM,OAAO,OAAO,OAAO,MAAM,KAAK,CAAC,CAAC,IAAK,QAAQ;EAC/D;CACF;AACF;;;;;;;ACpBA,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/** Seconds as a number, or a string such as `30s`, `15m`, `12h`, `7d`, `2w`. */
|
|
2
|
+
type Duration = number | `${number}${'s' | 'm' | 'h' | 'd' | 'w'}`;
|
|
3
|
+
export declare function toSeconds(duration: Duration): number;
|
|
4
|
+
type Bytes = Uint8Array<ArrayBuffer>;
|
|
5
|
+
type Data = string | Uint8Array;
|
|
6
|
+
export declare function base64urlEncode(data: Data): string;
|
|
7
|
+
export declare function base64urlDecode(text: string): Bytes;
|
|
8
|
+
export declare function hexEncode(bytes: Uint8Array): string;
|
|
9
|
+
/**
|
|
10
|
+
* Compares two values without leaking where they differ through timing. Use it for
|
|
11
|
+
* secrets you compare yourself (API keys, tokens); signatures made by this package are
|
|
12
|
+
* already verified in constant time.
|
|
13
|
+
*/
|
|
14
|
+
export declare function timingSafeEqual(a: Data, b: Data): boolean;
|
|
15
|
+
type CryptoErrorCode = 'malformed' | 'invalid_signature' | 'expired' | 'not_active' | 'invalid_claim' | 'algorithm_mismatch' | 'weak_key' | 'invalid_key' | 'invalid_input';
|
|
16
|
+
/** Every failure in this package. Branch on `code`; do not show `message` to end users. */
|
|
17
|
+
export declare class CryptoError extends Error {
|
|
18
|
+
readonly code: CryptoErrorCode;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
constructor(code: CryptoErrorCode, message: string, options?: {
|
|
21
|
+
cause?: unknown;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** A token that could not be created or must not be trusted. */
|
|
25
|
+
export declare class JwtError extends CryptoError {
|
|
26
|
+
readonly name = "JwtError";
|
|
27
|
+
}
|
|
28
|
+
type HashAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512';
|
|
29
|
+
/** Raw digest bytes. Not for passwords: use `hashPassword`. */
|
|
30
|
+
export declare function digest(algorithm: HashAlgorithm, data: Data): Promise<Bytes>;
|
|
31
|
+
/** Hex SHA-256, e.g. for content fingerprints and cache keys. */
|
|
32
|
+
export declare function sha256(data: Data): Promise<string>;
|
|
33
|
+
export declare function sha512(data: Data): Promise<string>;
|
|
34
|
+
type JwtAlgorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'ES512' | 'EdDSA';
|
|
35
|
+
/** A PEM string (PKCS#8 private or SPKI public), a JWK, or an imported `CryptoKey`. */
|
|
36
|
+
type KeyInput = string | JsonWebKey | CryptoKey;
|
|
37
|
+
/** Registered claims (RFC 7519). Your own claims sit alongside them. */
|
|
38
|
+
interface JwtClaims {
|
|
39
|
+
iss?: string;
|
|
40
|
+
sub?: string;
|
|
41
|
+
aud?: string | string[];
|
|
42
|
+
exp?: number;
|
|
43
|
+
nbf?: number;
|
|
44
|
+
iat?: number;
|
|
45
|
+
jti?: string;
|
|
46
|
+
}
|
|
47
|
+
type JwtPayload<T = Record<string, unknown>> = T & JwtClaims;
|
|
48
|
+
/** Structural Standard Schema, so any schema library can validate payloads. */
|
|
49
|
+
interface PayloadSchema<T> {
|
|
50
|
+
readonly '~standard': {
|
|
51
|
+
readonly validate: (value: unknown) => {
|
|
52
|
+
value: T;
|
|
53
|
+
issues?: undefined;
|
|
54
|
+
} | {
|
|
55
|
+
issues: readonly {
|
|
56
|
+
message: string;
|
|
57
|
+
}[];
|
|
58
|
+
} | Promise<{
|
|
59
|
+
value: T;
|
|
60
|
+
issues?: undefined;
|
|
61
|
+
} | {
|
|
62
|
+
issues: readonly {
|
|
63
|
+
message: string;
|
|
64
|
+
}[];
|
|
65
|
+
}>;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
interface CommonOptions<T> {
|
|
69
|
+
/** Lifetime of signed tokens. Default `1h`. `false` issues tokens that never expire. */
|
|
70
|
+
expiresIn?: Duration | false;
|
|
71
|
+
/** Set as `iss` when signing and required when verifying. */
|
|
72
|
+
issuer?: string;
|
|
73
|
+
/** Set as `aud` when signing and required when verifying. */
|
|
74
|
+
audience?: string | string[];
|
|
75
|
+
/** Seconds of clock skew tolerated for `exp`, `nbf` and `iat`. Default 0. */
|
|
76
|
+
clockTolerance?: number;
|
|
77
|
+
/** Validates the payload on verify; its output type becomes the payload type. */
|
|
78
|
+
schema?: PayloadSchema<T>;
|
|
79
|
+
/** `kid` header for signed tokens. */
|
|
80
|
+
keyId?: string;
|
|
81
|
+
/** Largest token accepted, in characters. Default 8192. */
|
|
82
|
+
maxTokenLength?: number;
|
|
83
|
+
/** Clock in milliseconds. For tests. */
|
|
84
|
+
now?: () => number;
|
|
85
|
+
}
|
|
86
|
+
interface HmacJwtOptions<T> extends CommonOptions<T> {
|
|
87
|
+
algorithm?: 'HS256' | 'HS384' | 'HS512';
|
|
88
|
+
/** At least as long as the hash output: 32, 48 or 64 bytes for HS256, HS384, HS512. */
|
|
89
|
+
secret: string | Uint8Array;
|
|
90
|
+
/** Older secrets still accepted when verifying, for rotation. Never used to sign. */
|
|
91
|
+
previousSecrets?: (string | Uint8Array)[];
|
|
92
|
+
}
|
|
93
|
+
interface KeyPairJwtOptions<T> extends CommonOptions<T> {
|
|
94
|
+
algorithm: Exclude<JwtAlgorithm, 'HS256' | 'HS384' | 'HS512'>;
|
|
95
|
+
/** Needed to sign. Omit on services that only verify. */
|
|
96
|
+
privateKey?: KeyInput;
|
|
97
|
+
/** Needed to verify. */
|
|
98
|
+
publicKey?: KeyInput;
|
|
99
|
+
/** Older public keys still accepted when verifying, for rotation. */
|
|
100
|
+
previousPublicKeys?: KeyInput[];
|
|
101
|
+
}
|
|
102
|
+
type JwtOptions<T> = HmacJwtOptions<T> | KeyPairJwtOptions<T>;
|
|
103
|
+
interface SignOptions {
|
|
104
|
+
expiresIn?: Duration | false;
|
|
105
|
+
/** Token is rejected until this much time has passed. */
|
|
106
|
+
notBefore?: Duration;
|
|
107
|
+
subject?: string;
|
|
108
|
+
jwtId?: string;
|
|
109
|
+
}
|
|
110
|
+
interface Jwt<T> {
|
|
111
|
+
readonly algorithm: JwtAlgorithm;
|
|
112
|
+
/** Signs a payload. Adds `iat`, `exp`, and the configured `iss` and `aud`. */
|
|
113
|
+
sign(payload: T & JwtClaims, options?: SignOptions): Promise<string>;
|
|
114
|
+
/**
|
|
115
|
+
* Verifies the signature and claims and returns the payload. Throws `JwtError` otherwise;
|
|
116
|
+
* a token that fails must be treated as absent.
|
|
117
|
+
*/
|
|
118
|
+
verify(token: string): Promise<JwtPayload<T>>;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Creates a signer and verifier bound to one algorithm and one set of keys.
|
|
122
|
+
*
|
|
123
|
+
* The algorithm is fixed here and never taken from a token, which rules out `alg: none` and
|
|
124
|
+
* key-confusion attacks. Verification checks the signature, `exp`, `nbf`, `iat`, and the
|
|
125
|
+
* configured issuer and audience.
|
|
126
|
+
*
|
|
127
|
+
* ```ts
|
|
128
|
+
* const jwt = createJwt<{ role: string }>({ secret: env.JWT_SECRET, issuer: 'api', expiresIn: '15m' });
|
|
129
|
+
* const token = await jwt.sign({ sub: user.id, role: 'admin' });
|
|
130
|
+
* const payload = await jwt.verify(token);
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
export declare function createJwt<T = Record<string, unknown>>(options: JwtOptions<T>): Jwt<T>;
|
|
134
|
+
/**
|
|
135
|
+
* Reads a token's header and payload **without verifying anything**. The result is
|
|
136
|
+
* attacker-controlled. Use only to pick a key or to log; never to make a decision.
|
|
137
|
+
*/
|
|
138
|
+
export declare function decodeJwtUnverified(token: string): {
|
|
139
|
+
header: Record<string, unknown>;
|
|
140
|
+
payload: Record<string, unknown>;
|
|
141
|
+
};
|
|
142
|
+
/** Extracts the token from an `Authorization: Bearer <token>` header value. */
|
|
143
|
+
export declare function bearerToken(header: string | null | undefined): string | undefined;
|
|
144
|
+
/** OWASP's 2023 minimum for PBKDF2-HMAC-SHA256. */
|
|
145
|
+
export declare const DEFAULT_PASSWORD_ITERATIONS = 600000;
|
|
146
|
+
interface PasswordOptions {
|
|
147
|
+
/** Work factor. Default 600,000. Raise it over time; `needsRehash` tells you which hashes lag. */
|
|
148
|
+
iterations?: number;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Hashes a password for storage, with a random salt, as
|
|
152
|
+
* `$pbkdf2-sha256$i=<iterations>$<salt>$<hash>`.
|
|
153
|
+
*
|
|
154
|
+
* PBKDF2 is used because it is the password KDF every Web Crypto runtime provides. If you
|
|
155
|
+
* can take a native dependency, Argon2id is the stronger choice.
|
|
156
|
+
*/
|
|
157
|
+
export declare function hashPassword(password: string, options?: PasswordOptions): Promise<string>;
|
|
158
|
+
/** `true` only if the password matches. Malformed stored values are `false`, never an error. */
|
|
159
|
+
export declare function verifyPassword(password: string, stored: string): Promise<boolean>;
|
|
160
|
+
/** Whether a stored hash uses fewer iterations than you now want. Rehash after a successful login. */
|
|
161
|
+
export declare function needsRehash(stored: string, options?: PasswordOptions): boolean;
|
|
162
|
+
/** Cryptographically secure random bytes. */
|
|
163
|
+
export declare function randomBytes(length: number): Bytes;
|
|
164
|
+
/** A URL-safe random token. 32 bytes (256 bits) by default: session ids, reset tokens, API keys. */
|
|
165
|
+
export declare function randomToken(bytes?: number): string;
|
|
166
|
+
export declare function randomHex(bytes?: number): string;
|
|
167
|
+
export declare function randomUUID(): string;
|
|
168
|
+
/** A uniformly distributed integer in `[min, max)`, without modulo bias. */
|
|
169
|
+
export declare function randomInt(min: number, max: number): number;
|
|
170
|
+
interface SealerOptions {
|
|
171
|
+
/** Binds sealed values to a use, so a value sealed as `session` cannot be opened as `reset`. */
|
|
172
|
+
purpose?: string;
|
|
173
|
+
/** Older secrets still accepted when unsealing, for rotation. */
|
|
174
|
+
previousSecrets?: (string | Uint8Array)[];
|
|
175
|
+
/** Clock in milliseconds. For tests. */
|
|
176
|
+
now?: () => number;
|
|
177
|
+
}
|
|
178
|
+
interface Sealer {
|
|
179
|
+
/** Encrypts any JSON value into a URL-safe string. `ttl` makes it expire. */
|
|
180
|
+
seal(value: unknown, options?: {
|
|
181
|
+
ttl?: Duration;
|
|
182
|
+
}): Promise<string>;
|
|
183
|
+
/** The original value, or `undefined` if it was tampered with, expired, or sealed with another key. */
|
|
184
|
+
unseal<T = unknown>(sealed: string): Promise<T | undefined>;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Authenticated encryption (AES-256-GCM) for values the client holds but must not read or
|
|
188
|
+
* change: encrypted cookies, OAuth state, password-reset payloads.
|
|
189
|
+
*/
|
|
190
|
+
export declare function createSealer(secret: string | Uint8Array, options?: SealerOptions): Sealer;
|
|
191
|
+
interface SignerOptions {
|
|
192
|
+
hash?: HashAlgorithm;
|
|
193
|
+
/** Older secrets still accepted when verifying, for rotation. */
|
|
194
|
+
previousSecrets?: (string | Uint8Array)[];
|
|
195
|
+
}
|
|
196
|
+
interface Signer {
|
|
197
|
+
/** HMAC of the data, base64url. */
|
|
198
|
+
sign(data: Data): Promise<string>;
|
|
199
|
+
/** Constant-time check. `false` for anything malformed. */
|
|
200
|
+
verify(data: Data, signature: string): Promise<boolean>;
|
|
201
|
+
/** `value.signature`, for cookies and links whose content may be read but not changed. */
|
|
202
|
+
pack(value: string): Promise<string>;
|
|
203
|
+
/** The original value, or `undefined` if the signature does not match. */
|
|
204
|
+
unpack(packed: string): Promise<string | undefined>;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* HMAC signing for values that must not be tampered with: cookies, webhook payloads,
|
|
208
|
+
* unsubscribe links. The value stays readable; use `createSealer` to hide it.
|
|
209
|
+
*/
|
|
210
|
+
export declare function createSigner(secret: string | Uint8Array, options?: SignerOptions): Signer;
|
|
211
|
+
/**
|
|
212
|
+
* Everything in one object, for `import sukuCrypto from '@sukujs/crypto'`.
|
|
213
|
+
* The named exports are the same functions and tree-shake better.
|
|
214
|
+
*/
|
|
215
|
+
declare const sukuCrypto: {
|
|
216
|
+
readonly createJwt: typeof createJwt;
|
|
217
|
+
readonly bearerToken: typeof bearerToken;
|
|
218
|
+
readonly decodeJwtUnverified: typeof decodeJwtUnverified;
|
|
219
|
+
readonly hashPassword: typeof hashPassword;
|
|
220
|
+
readonly verifyPassword: typeof verifyPassword;
|
|
221
|
+
readonly needsRehash: typeof needsRehash;
|
|
222
|
+
readonly createSigner: typeof createSigner;
|
|
223
|
+
readonly createSealer: typeof createSealer;
|
|
224
|
+
readonly randomToken: typeof randomToken;
|
|
225
|
+
readonly randomBytes: typeof randomBytes;
|
|
226
|
+
readonly randomHex: typeof randomHex;
|
|
227
|
+
readonly randomUUID: typeof randomUUID;
|
|
228
|
+
readonly randomInt: typeof randomInt;
|
|
229
|
+
readonly sha256: typeof sha256;
|
|
230
|
+
readonly sha512: typeof sha512;
|
|
231
|
+
readonly digest: typeof digest;
|
|
232
|
+
readonly timingSafeEqual: typeof timingSafeEqual;
|
|
233
|
+
readonly base64urlEncode: typeof base64urlEncode;
|
|
234
|
+
readonly base64urlDecode: typeof base64urlDecode;
|
|
235
|
+
readonly hexEncode: typeof hexEncode;
|
|
236
|
+
readonly toSeconds: typeof toSeconds;
|
|
237
|
+
readonly CryptoError: typeof CryptoError;
|
|
238
|
+
readonly JwtError: typeof JwtError;
|
|
239
|
+
};
|
|
240
|
+
export { type Bytes, type CryptoErrorCode, type Data, type Duration, type HashAlgorithm, type HmacJwtOptions, type Jwt, type JwtAlgorithm, type JwtClaims, type JwtOptions, type JwtPayload, type KeyInput, type KeyPairJwtOptions, type PasswordOptions, type Sealer, type SealerOptions, type SignOptions, type Signer, type SignerOptions, sukuCrypto as default };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/** Seconds as a number, or a string such as `30s`, `15m`, `12h`, `7d`, `2w`. */
|
|
2
|
+
type Duration = number | `${number}${'s' | 'm' | 'h' | 'd' | 'w'}`;
|
|
3
|
+
export declare function toSeconds(duration: Duration): number;
|
|
4
|
+
type Bytes = Uint8Array<ArrayBuffer>;
|
|
5
|
+
type Data = string | Uint8Array;
|
|
6
|
+
export declare function base64urlEncode(data: Data): string;
|
|
7
|
+
export declare function base64urlDecode(text: string): Bytes;
|
|
8
|
+
export declare function hexEncode(bytes: Uint8Array): string;
|
|
9
|
+
/**
|
|
10
|
+
* Compares two values without leaking where they differ through timing. Use it for
|
|
11
|
+
* secrets you compare yourself (API keys, tokens); signatures made by this package are
|
|
12
|
+
* already verified in constant time.
|
|
13
|
+
*/
|
|
14
|
+
export declare function timingSafeEqual(a: Data, b: Data): boolean;
|
|
15
|
+
type CryptoErrorCode = 'malformed' | 'invalid_signature' | 'expired' | 'not_active' | 'invalid_claim' | 'algorithm_mismatch' | 'weak_key' | 'invalid_key' | 'invalid_input';
|
|
16
|
+
/** Every failure in this package. Branch on `code`; do not show `message` to end users. */
|
|
17
|
+
export declare class CryptoError extends Error {
|
|
18
|
+
readonly code: CryptoErrorCode;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
constructor(code: CryptoErrorCode, message: string, options?: {
|
|
21
|
+
cause?: unknown;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** A token that could not be created or must not be trusted. */
|
|
25
|
+
export declare class JwtError extends CryptoError {
|
|
26
|
+
readonly name = "JwtError";
|
|
27
|
+
}
|
|
28
|
+
type HashAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512';
|
|
29
|
+
/** Raw digest bytes. Not for passwords: use `hashPassword`. */
|
|
30
|
+
export declare function digest(algorithm: HashAlgorithm, data: Data): Promise<Bytes>;
|
|
31
|
+
/** Hex SHA-256, e.g. for content fingerprints and cache keys. */
|
|
32
|
+
export declare function sha256(data: Data): Promise<string>;
|
|
33
|
+
export declare function sha512(data: Data): Promise<string>;
|
|
34
|
+
type JwtAlgorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'ES512' | 'EdDSA';
|
|
35
|
+
/** A PEM string (PKCS#8 private or SPKI public), a JWK, or an imported `CryptoKey`. */
|
|
36
|
+
type KeyInput = string | JsonWebKey | CryptoKey;
|
|
37
|
+
/** Registered claims (RFC 7519). Your own claims sit alongside them. */
|
|
38
|
+
interface JwtClaims {
|
|
39
|
+
iss?: string;
|
|
40
|
+
sub?: string;
|
|
41
|
+
aud?: string | string[];
|
|
42
|
+
exp?: number;
|
|
43
|
+
nbf?: number;
|
|
44
|
+
iat?: number;
|
|
45
|
+
jti?: string;
|
|
46
|
+
}
|
|
47
|
+
type JwtPayload<T = Record<string, unknown>> = T & JwtClaims;
|
|
48
|
+
/** Structural Standard Schema, so any schema library can validate payloads. */
|
|
49
|
+
interface PayloadSchema<T> {
|
|
50
|
+
readonly '~standard': {
|
|
51
|
+
readonly validate: (value: unknown) => {
|
|
52
|
+
value: T;
|
|
53
|
+
issues?: undefined;
|
|
54
|
+
} | {
|
|
55
|
+
issues: readonly {
|
|
56
|
+
message: string;
|
|
57
|
+
}[];
|
|
58
|
+
} | Promise<{
|
|
59
|
+
value: T;
|
|
60
|
+
issues?: undefined;
|
|
61
|
+
} | {
|
|
62
|
+
issues: readonly {
|
|
63
|
+
message: string;
|
|
64
|
+
}[];
|
|
65
|
+
}>;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
interface CommonOptions<T> {
|
|
69
|
+
/** Lifetime of signed tokens. Default `1h`. `false` issues tokens that never expire. */
|
|
70
|
+
expiresIn?: Duration | false;
|
|
71
|
+
/** Set as `iss` when signing and required when verifying. */
|
|
72
|
+
issuer?: string;
|
|
73
|
+
/** Set as `aud` when signing and required when verifying. */
|
|
74
|
+
audience?: string | string[];
|
|
75
|
+
/** Seconds of clock skew tolerated for `exp`, `nbf` and `iat`. Default 0. */
|
|
76
|
+
clockTolerance?: number;
|
|
77
|
+
/** Validates the payload on verify; its output type becomes the payload type. */
|
|
78
|
+
schema?: PayloadSchema<T>;
|
|
79
|
+
/** `kid` header for signed tokens. */
|
|
80
|
+
keyId?: string;
|
|
81
|
+
/** Largest token accepted, in characters. Default 8192. */
|
|
82
|
+
maxTokenLength?: number;
|
|
83
|
+
/** Clock in milliseconds. For tests. */
|
|
84
|
+
now?: () => number;
|
|
85
|
+
}
|
|
86
|
+
interface HmacJwtOptions<T> extends CommonOptions<T> {
|
|
87
|
+
algorithm?: 'HS256' | 'HS384' | 'HS512';
|
|
88
|
+
/** At least as long as the hash output: 32, 48 or 64 bytes for HS256, HS384, HS512. */
|
|
89
|
+
secret: string | Uint8Array;
|
|
90
|
+
/** Older secrets still accepted when verifying, for rotation. Never used to sign. */
|
|
91
|
+
previousSecrets?: (string | Uint8Array)[];
|
|
92
|
+
}
|
|
93
|
+
interface KeyPairJwtOptions<T> extends CommonOptions<T> {
|
|
94
|
+
algorithm: Exclude<JwtAlgorithm, 'HS256' | 'HS384' | 'HS512'>;
|
|
95
|
+
/** Needed to sign. Omit on services that only verify. */
|
|
96
|
+
privateKey?: KeyInput;
|
|
97
|
+
/** Needed to verify. */
|
|
98
|
+
publicKey?: KeyInput;
|
|
99
|
+
/** Older public keys still accepted when verifying, for rotation. */
|
|
100
|
+
previousPublicKeys?: KeyInput[];
|
|
101
|
+
}
|
|
102
|
+
type JwtOptions<T> = HmacJwtOptions<T> | KeyPairJwtOptions<T>;
|
|
103
|
+
interface SignOptions {
|
|
104
|
+
expiresIn?: Duration | false;
|
|
105
|
+
/** Token is rejected until this much time has passed. */
|
|
106
|
+
notBefore?: Duration;
|
|
107
|
+
subject?: string;
|
|
108
|
+
jwtId?: string;
|
|
109
|
+
}
|
|
110
|
+
interface Jwt<T> {
|
|
111
|
+
readonly algorithm: JwtAlgorithm;
|
|
112
|
+
/** Signs a payload. Adds `iat`, `exp`, and the configured `iss` and `aud`. */
|
|
113
|
+
sign(payload: T & JwtClaims, options?: SignOptions): Promise<string>;
|
|
114
|
+
/**
|
|
115
|
+
* Verifies the signature and claims and returns the payload. Throws `JwtError` otherwise;
|
|
116
|
+
* a token that fails must be treated as absent.
|
|
117
|
+
*/
|
|
118
|
+
verify(token: string): Promise<JwtPayload<T>>;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Creates a signer and verifier bound to one algorithm and one set of keys.
|
|
122
|
+
*
|
|
123
|
+
* The algorithm is fixed here and never taken from a token, which rules out `alg: none` and
|
|
124
|
+
* key-confusion attacks. Verification checks the signature, `exp`, `nbf`, `iat`, and the
|
|
125
|
+
* configured issuer and audience.
|
|
126
|
+
*
|
|
127
|
+
* ```ts
|
|
128
|
+
* const jwt = createJwt<{ role: string }>({ secret: env.JWT_SECRET, issuer: 'api', expiresIn: '15m' });
|
|
129
|
+
* const token = await jwt.sign({ sub: user.id, role: 'admin' });
|
|
130
|
+
* const payload = await jwt.verify(token);
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
export declare function createJwt<T = Record<string, unknown>>(options: JwtOptions<T>): Jwt<T>;
|
|
134
|
+
/**
|
|
135
|
+
* Reads a token's header and payload **without verifying anything**. The result is
|
|
136
|
+
* attacker-controlled. Use only to pick a key or to log; never to make a decision.
|
|
137
|
+
*/
|
|
138
|
+
export declare function decodeJwtUnverified(token: string): {
|
|
139
|
+
header: Record<string, unknown>;
|
|
140
|
+
payload: Record<string, unknown>;
|
|
141
|
+
};
|
|
142
|
+
/** Extracts the token from an `Authorization: Bearer <token>` header value. */
|
|
143
|
+
export declare function bearerToken(header: string | null | undefined): string | undefined;
|
|
144
|
+
/** OWASP's 2023 minimum for PBKDF2-HMAC-SHA256. */
|
|
145
|
+
export declare const DEFAULT_PASSWORD_ITERATIONS = 600000;
|
|
146
|
+
interface PasswordOptions {
|
|
147
|
+
/** Work factor. Default 600,000. Raise it over time; `needsRehash` tells you which hashes lag. */
|
|
148
|
+
iterations?: number;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Hashes a password for storage, with a random salt, as
|
|
152
|
+
* `$pbkdf2-sha256$i=<iterations>$<salt>$<hash>`.
|
|
153
|
+
*
|
|
154
|
+
* PBKDF2 is used because it is the password KDF every Web Crypto runtime provides. If you
|
|
155
|
+
* can take a native dependency, Argon2id is the stronger choice.
|
|
156
|
+
*/
|
|
157
|
+
export declare function hashPassword(password: string, options?: PasswordOptions): Promise<string>;
|
|
158
|
+
/** `true` only if the password matches. Malformed stored values are `false`, never an error. */
|
|
159
|
+
export declare function verifyPassword(password: string, stored: string): Promise<boolean>;
|
|
160
|
+
/** Whether a stored hash uses fewer iterations than you now want. Rehash after a successful login. */
|
|
161
|
+
export declare function needsRehash(stored: string, options?: PasswordOptions): boolean;
|
|
162
|
+
/** Cryptographically secure random bytes. */
|
|
163
|
+
export declare function randomBytes(length: number): Bytes;
|
|
164
|
+
/** A URL-safe random token. 32 bytes (256 bits) by default: session ids, reset tokens, API keys. */
|
|
165
|
+
export declare function randomToken(bytes?: number): string;
|
|
166
|
+
export declare function randomHex(bytes?: number): string;
|
|
167
|
+
export declare function randomUUID(): string;
|
|
168
|
+
/** A uniformly distributed integer in `[min, max)`, without modulo bias. */
|
|
169
|
+
export declare function randomInt(min: number, max: number): number;
|
|
170
|
+
interface SealerOptions {
|
|
171
|
+
/** Binds sealed values to a use, so a value sealed as `session` cannot be opened as `reset`. */
|
|
172
|
+
purpose?: string;
|
|
173
|
+
/** Older secrets still accepted when unsealing, for rotation. */
|
|
174
|
+
previousSecrets?: (string | Uint8Array)[];
|
|
175
|
+
/** Clock in milliseconds. For tests. */
|
|
176
|
+
now?: () => number;
|
|
177
|
+
}
|
|
178
|
+
interface Sealer {
|
|
179
|
+
/** Encrypts any JSON value into a URL-safe string. `ttl` makes it expire. */
|
|
180
|
+
seal(value: unknown, options?: {
|
|
181
|
+
ttl?: Duration;
|
|
182
|
+
}): Promise<string>;
|
|
183
|
+
/** The original value, or `undefined` if it was tampered with, expired, or sealed with another key. */
|
|
184
|
+
unseal<T = unknown>(sealed: string): Promise<T | undefined>;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Authenticated encryption (AES-256-GCM) for values the client holds but must not read or
|
|
188
|
+
* change: encrypted cookies, OAuth state, password-reset payloads.
|
|
189
|
+
*/
|
|
190
|
+
export declare function createSealer(secret: string | Uint8Array, options?: SealerOptions): Sealer;
|
|
191
|
+
interface SignerOptions {
|
|
192
|
+
hash?: HashAlgorithm;
|
|
193
|
+
/** Older secrets still accepted when verifying, for rotation. */
|
|
194
|
+
previousSecrets?: (string | Uint8Array)[];
|
|
195
|
+
}
|
|
196
|
+
interface Signer {
|
|
197
|
+
/** HMAC of the data, base64url. */
|
|
198
|
+
sign(data: Data): Promise<string>;
|
|
199
|
+
/** Constant-time check. `false` for anything malformed. */
|
|
200
|
+
verify(data: Data, signature: string): Promise<boolean>;
|
|
201
|
+
/** `value.signature`, for cookies and links whose content may be read but not changed. */
|
|
202
|
+
pack(value: string): Promise<string>;
|
|
203
|
+
/** The original value, or `undefined` if the signature does not match. */
|
|
204
|
+
unpack(packed: string): Promise<string | undefined>;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* HMAC signing for values that must not be tampered with: cookies, webhook payloads,
|
|
208
|
+
* unsubscribe links. The value stays readable; use `createSealer` to hide it.
|
|
209
|
+
*/
|
|
210
|
+
export declare function createSigner(secret: string | Uint8Array, options?: SignerOptions): Signer;
|
|
211
|
+
/**
|
|
212
|
+
* Everything in one object, for `import sukuCrypto from '@sukujs/crypto'`.
|
|
213
|
+
* The named exports are the same functions and tree-shake better.
|
|
214
|
+
*/
|
|
215
|
+
declare const sukuCrypto: {
|
|
216
|
+
readonly createJwt: typeof createJwt;
|
|
217
|
+
readonly bearerToken: typeof bearerToken;
|
|
218
|
+
readonly decodeJwtUnverified: typeof decodeJwtUnverified;
|
|
219
|
+
readonly hashPassword: typeof hashPassword;
|
|
220
|
+
readonly verifyPassword: typeof verifyPassword;
|
|
221
|
+
readonly needsRehash: typeof needsRehash;
|
|
222
|
+
readonly createSigner: typeof createSigner;
|
|
223
|
+
readonly createSealer: typeof createSealer;
|
|
224
|
+
readonly randomToken: typeof randomToken;
|
|
225
|
+
readonly randomBytes: typeof randomBytes;
|
|
226
|
+
readonly randomHex: typeof randomHex;
|
|
227
|
+
readonly randomUUID: typeof randomUUID;
|
|
228
|
+
readonly randomInt: typeof randomInt;
|
|
229
|
+
readonly sha256: typeof sha256;
|
|
230
|
+
readonly sha512: typeof sha512;
|
|
231
|
+
readonly digest: typeof digest;
|
|
232
|
+
readonly timingSafeEqual: typeof timingSafeEqual;
|
|
233
|
+
readonly base64urlEncode: typeof base64urlEncode;
|
|
234
|
+
readonly base64urlDecode: typeof base64urlDecode;
|
|
235
|
+
readonly hexEncode: typeof hexEncode;
|
|
236
|
+
readonly toSeconds: typeof toSeconds;
|
|
237
|
+
readonly CryptoError: typeof CryptoError;
|
|
238
|
+
readonly JwtError: typeof JwtError;
|
|
239
|
+
};
|
|
240
|
+
export { type Bytes, type CryptoErrorCode, type Data, type Duration, type HashAlgorithm, type HmacJwtOptions, type Jwt, type JwtAlgorithm, type JwtClaims, type JwtOptions, type JwtPayload, type KeyInput, type KeyPairJwtOptions, type PasswordOptions, type Sealer, type SealerOptions, type SignOptions, type Signer, type SignerOptions, sukuCrypto as default };
|