micro509 0.16.0 → 0.17.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/CHANGELOG.md +75 -1
- package/dist/internal/jose/base64url.js +40 -0
- package/dist/internal/jose/base64url.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +9 -0
- package/dist/internal/jose/strict-json.js +155 -0
- package/dist/internal/jose/strict-json.js.map +1 -0
- package/dist/jose/errors.d.ts +44 -0
- package/dist/jose/errors.js +11 -0
- package/dist/jose/errors.js.map +1 -0
- package/dist/jose/jwks.d.ts +93 -0
- package/dist/jose/jwks.js +193 -0
- package/dist/jose/jwks.js.map +1 -0
- package/dist/jose/jws.d.ts +158 -0
- package/dist/jose/jws.js +362 -0
- package/dist/jose/jws.js.map +1 -0
- package/dist/jose/jwt.d.ts +91 -0
- package/dist/jose/jwt.js +187 -0
- package/dist/jose/jwt.js.map +1 -0
- package/dist/jose/remote-jwks.d.ts +95 -0
- package/dist/jose/remote-jwks.js +298 -0
- package/dist/jose/remote-jwks.js.map +1 -0
- package/dist/jose.d.ts +7 -0
- package/dist/jose.js +5 -0
- package/dist/kdf/argon2.d.ts +78 -0
- package/dist/kdf/argon2.js +167 -0
- package/dist/kdf/argon2.js.map +1 -0
- package/dist/kdf.d.ts +2 -0
- package/dist/kdf.js +1 -0
- package/dist/ssh/ssh.d.ts +200 -0
- package/dist/ssh/ssh.js +648 -0
- package/dist/ssh/ssh.js.map +1 -0
- package/dist/ssh/wire.d.ts +3 -0
- package/dist/ssh/wire.js +105 -0
- package/dist/ssh/wire.js.map +1 -0
- package/dist/ssh.d.ts +3 -0
- package/dist/ssh.js +1 -0
- package/package.json +18 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote-jwks.js","names":["ABORTED","DEFAULTS","REDIRECT_STATUSES","LOOPBACK_HOSTS","url","resolved","value","fallback","throwMicro509Error","name","config","maxRedirects","maxTtlMs","cooldownMs","target","init","destination","from","joseFailure","message","status","headers","directives","directive","date","apparentAge","receivedAt","reportedAge","transit","requestedAt","age","maxAge","lifetime","match","expires","tooLarge","maxBytes","declared","response","successResult","reader","chunks","total","signal","done","body","offset","chunk","location","redirects","jwks","parseJwks","hop","entry","imported","fetched","carried","previous","TIMED_OUT","settings","snapshot","refresh","lastAttemptAt","controller","previousAttemptAt","timer","deadline","resolve","work","tracked","outcome","joined","settled","key","cached","current","pending","importJwkEntry","loaded","source","selected","selectJwk","selector","reloaded","request"],"sources":["../../src/jose/remote-jwks.ts"],"sourcesContent":["/**\n * Opt-in remote JWK Set resolution. A resolver is bound to one trusted JWKS URL from caller\n * configuration and keeps its own cache, so two issuers never share keys. Importing this module\n * performs no request; only a verification that reaches the resolver can.\n *\n * @module\n */\n\nimport type { JoseErrorResult, JoseResult, KeyResolutionErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JwkSelector, Jwks, RsaJwkEntry } from '#micro509/jose/jwks';\nimport { importJwkEntry, parseJwks, selectJwk } from '#micro509/jose/jwks';\nimport type { JwsKeyRequest, JwsKeyResolver } from '#micro509/jose/jws';\nimport { successResult, throwMicro509Error } from '#micro509/result/result';\n\n/** The request {@linkcode JwksTransport} must issue. */\nexport interface JwksRequestInit {\n\t/** Always `GET`. */\n\treadonly method: 'GET';\n\t/** Always `manual`: the resolver validates every redirect destination itself. */\n\treadonly redirect: 'manual';\n\t/** Always `omit`. */\n\treadonly credentials: 'omit';\n\t/** Always `no-store`: each resolver refresh must reach the issuer, bypassing the HTTP cache. */\n\treadonly cache: 'no-store';\n\t/** Configured request headers. Withheld from any origin other than the configured URL's. */\n\treadonly headers: Readonly<Record<string, string>>;\n\t/** Aborts on timeout, cancellation or when no verification still waits for the response. */\n\treadonly signal: AbortSignal;\n}\n\n/**\n * Performs one HTTP request. `fetch` satisfies this type. Supply another to route through a proxy,\n * apply egress or DNS controls, or serve fixtures; the transport sees only URLs the resolver\n * already validated.\n */\nexport type JwksTransport = (url: string, init: JwksRequestInit) => Promise<Response>;\n\n/** Redirect handling for a remote JWK Set. By default redirects are refused. */\nexport interface RemoteJwksRedirectPolicy {\n\t/** Maximum redirects followed per fetch. */\n\treadonly maxRedirects: number;\n\t/**\n\t * Approves a redirect destination. Default: same origin as the hop it came from. The scheme\n\t * rule applies first: `https`, or `http` for a loopback host.\n\t */\n\treadonly allow?: (destination: URL, from: URL) => boolean;\n}\n\n/** Configuration of {@linkcode createRemoteJwksKeyResolver}. */\nexport interface RemoteJwksConfig {\n\t/** The trusted JWKS URL. `https`, or `http` for a loopback host. Never taken from a token. */\n\treadonly url: string | URL;\n\t/** Request transport. Default: `globalThis.fetch`. */\n\treadonly transport?: JwksTransport;\n\t/** Request headers, sent only to the configured URL's origin. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/** Whole-request deadline in milliseconds, response body included. Default `5000`. */\n\treadonly timeoutMs?: number;\n\t/** Maximum response body in bytes, enforced while streaming. Default `65536`. */\n\treadonly maxResponseBytes?: number;\n\t/** Maximum keys in the set. Default `32`. */\n\treadonly maxKeys?: number;\n\t/** Redirect handling. Default: refuse every redirect. */\n\treadonly redirects?: RemoteJwksRedirectPolicy;\n\t/** Freshness applied when the response states none, in milliseconds. Default `600000`. */\n\treadonly defaultTtlMs?: number;\n\t/** Longest freshness the resolver will keep a response for, in milliseconds. Default `86400000`. */\n\treadonly maxTtlMs?: number;\n\t/**\n\t * Minimum interval between the starts of two fetches, in milliseconds. It bounds how often\n\t * unknown `kid` values, expired responses and failures can cause a request, and does not\n\t * lengthen how long a response stays fresh. Default `30000`.\n\t */\n\treadonly cooldownMs?: number;\n\t/** The clock in milliseconds since the epoch. Default `Date.now`. */\n\treadonly now?: () => number;\n}\n\n/** Codes {@linkcode createRemoteJwksKeyResolver} throws for unusable configuration. */\nexport type RemoteJwksConfigErrorCode = 'invalid_remote_jwks_config';\n\ntype FetchFailureCode = 'jwks_unavailable' | 'jwks_malformed';\n\ninterface Snapshot {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n\treadonly imported: Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>;\n}\n\ntype RefreshOutcome =\n\t| { readonly kind: 'fresh'; readonly snapshot: Snapshot }\n\t| { readonly kind: 'failed'; readonly failure: JoseErrorResult<FetchFailureCode> }\n\t| { readonly kind: 'abandoned' };\n\ninterface Refresh {\n\treadonly promise: Promise<RefreshOutcome>;\n\treadonly controller: AbortController;\n\treadonly startedAt: number;\n\treadonly previousAttemptAt: number | undefined;\n\twaiters: number;\n}\n\nconst ABORTED: unique symbol = Symbol('micro509.jose.aborted');\n\nconst DEFAULTS = {\n\ttimeoutMs: 5000,\n\tmaxResponseBytes: 65_536,\n\tmaxKeys: 32,\n\tdefaultTtlMs: 600_000,\n\tmaxTtlMs: 86_400_000,\n\tcooldownMs: 30_000,\n} as const;\n\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nfunction isPermittedUrl(url: URL): boolean {\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number, name: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved <= 0) {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', `${name} must be a positive integer`);\n\t}\n\treturn resolved;\n}\n\ninterface ResolvedConfig {\n\treadonly url: URL;\n\treadonly transport: JwksTransport;\n\treadonly headers: Readonly<Record<string, string>>;\n\treadonly timeoutMs: number;\n\treadonly maxResponseBytes: number;\n\treadonly maxKeys: number;\n\treadonly maxRedirects: number;\n\treadonly allowRedirect: (destination: URL, from: URL) => boolean;\n\treadonly defaultTtlMs: number;\n\treadonly maxTtlMs: number;\n\treadonly cooldownMs: number;\n\treadonly now: () => number;\n}\n\nfunction resolveConfig(config: RemoteJwksConfig): ResolvedConfig {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(config.url);\n\t} catch {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url is not an absolute URL');\n\t}\n\tif (!isPermittedUrl(url)) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'url must use https, or http on a loopback host',\n\t\t);\n\t}\n\tif (url.username !== '' || url.password !== '') {\n\t\treturn throwMicro509Error('invalid_remote_jwks_config', 'url must not embed credentials');\n\t}\n\tconst maxRedirects = config.redirects?.maxRedirects ?? 0;\n\tif (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) {\n\t\treturn throwMicro509Error(\n\t\t\t'invalid_remote_jwks_config',\n\t\t\t'maxRedirects must be an integer from 0 to 10',\n\t\t);\n\t}\n\tconst maxTtlMs = positiveInteger(config.maxTtlMs, DEFAULTS.maxTtlMs, 'maxTtlMs');\n\tconst cooldownMs = positiveInteger(config.cooldownMs, DEFAULTS.cooldownMs, 'cooldownMs');\n\treturn {\n\t\turl,\n\t\ttransport: config.transport ?? ((target, init) => globalThis.fetch(target, init)),\n\t\theaders: { ...config.headers },\n\t\ttimeoutMs: positiveInteger(config.timeoutMs, DEFAULTS.timeoutMs, 'timeoutMs'),\n\t\tmaxResponseBytes: positiveInteger(\n\t\t\tconfig.maxResponseBytes,\n\t\t\tDEFAULTS.maxResponseBytes,\n\t\t\t'maxResponseBytes',\n\t\t),\n\t\tmaxKeys: positiveInteger(config.maxKeys, DEFAULTS.maxKeys, 'maxKeys'),\n\t\tmaxRedirects,\n\t\tallowRedirect:\n\t\t\tconfig.redirects?.allow ?? ((destination, from) => destination.origin === from.origin),\n\t\tdefaultTtlMs: positiveInteger(config.defaultTtlMs, DEFAULTS.defaultTtlMs, 'defaultTtlMs'),\n\t\tmaxTtlMs,\n\t\tcooldownMs,\n\t\tnow: config.now ?? Date.now,\n\t};\n}\n\nfunction unavailable(message: string, status?: number): JoseErrorResult<'jwks_unavailable'> {\n\treturn joseFailure('jwks_unavailable', message, status === undefined ? undefined : { status });\n}\n\nconst NOT_A_NUMBER = Number.NaN;\n\nfunction secondsHeader(headers: Headers, name: string): number {\n\tconst value = headers.get(name);\n\treturn value !== null && /^\\d{1,10}$/.test(value) ? Number(value) * 1000 : NOT_A_NUMBER;\n}\n\n/**\n * Remaining freshness in milliseconds, never below zero and never above `maxTtlMs`.\n *\n * The lifetime is `Cache-Control: max-age`, else `Expires` less `Date`, else `defaultTtlMs`\n * (RFC 9111 §4.2.1); `no-store`, `no-cache` and unusable values give none. The response age is the\n * larger of the apparent age from `Date` and the `Age` header plus the transit delay\n * (RFC 9111 §4.2.3).\n */\nfunction freshnessMs(\n\theaders: Headers,\n\trequestedAt: number,\n\treceivedAt: number,\n\tconfig: ResolvedConfig,\n): number {\n\tconst directives = (headers.get('cache-control') ?? '')\n\t\t.split(',')\n\t\t.map((directive) => directive.trim().toLowerCase())\n\t\t.filter((directive) => directive.length > 0);\n\tif (directives.includes('no-store') || directives.includes('no-cache')) return 0;\n\tconst date = Date.parse(headers.get('date') ?? '');\n\tconst apparentAge = Number.isNaN(date) ? 0 : Math.max(0, receivedAt - date);\n\tconst reportedAge = secondsHeader(headers, 'age');\n\tconst transit = Math.max(0, receivedAt - requestedAt);\n\tconst age = Math.max(apparentAge, (Number.isNaN(reportedAge) ? 0 : reportedAge) + transit);\n\tconst maxAge = directives.find((directive) => directive.startsWith('max-age'));\n\tlet lifetime = config.defaultTtlMs;\n\tif (maxAge !== undefined) {\n\t\tconst match = /^max-age=(\"?)(\\d{1,10})\\1$/.exec(maxAge);\n\t\tlifetime = match?.[2] === undefined ? 0 : Number(match[2]) * 1000;\n\t} else if (headers.has('expires')) {\n\t\tconst expires = Date.parse(headers.get('expires') ?? '');\n\t\tlifetime = Number.isNaN(expires) ? 0 : expires - (Number.isNaN(date) ? receivedAt : date);\n\t}\n\treturn Math.min(config.maxTtlMs, Math.max(0, lifetime - age));\n}\n\ntype BodyResult = JoseResult<Uint8Array, 'jwks_unavailable' | 'jwks_malformed'>;\n\nasync function readBounded(\n\tresponse: Response,\n\tmaxBytes: number,\n\tsignal: AbortSignal,\n): Promise<BodyResult> {\n\tconst tooLarge = joseFailure('jwks_malformed', `The JWKS response exceeds ${maxBytes} bytes`);\n\tconst declared = response.headers.get('content-length');\n\tif (declared !== null && /^\\d+$/.test(declared) && Number(declared) > maxBytes) {\n\t\tawait response.body?.cancel();\n\t\treturn tooLarge;\n\t}\n\tif (response.body === null) return successResult(new Uint8Array(0));\n\tconst reader = response.body.getReader();\n\tconst release = (): void => {\n\t\treader.cancel().catch(() => undefined);\n\t};\n\tsignal.addEventListener('abort', release, { once: true });\n\ttry {\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal.aborted) return unavailable('The JWKS request was cancelled');\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\trelease();\n\t\t\t\treturn tooLarge;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t\tconst body = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbody.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn successResult(body);\n\t} finally {\n\t\tsignal.removeEventListener('abort', release);\n\t}\n}\n\ninterface Fetched {\n\treadonly jwks: Jwks;\n\treadonly expiresAt: number;\n}\n\nfunction nextHop(\n\tconfig: ResolvedConfig,\n\tfrom: URL,\n\tresponse: Response,\n\tredirects: number,\n): JoseResult<URL, 'jwks_unavailable'> {\n\tconst location = response.headers.get('location');\n\tif (redirects >= config.maxRedirects || location === null) {\n\t\treturn unavailable('The JWKS endpoint redirected', response.status);\n\t}\n\tlet destination: URL;\n\ttry {\n\t\tdestination = new URL(location, from);\n\t} catch {\n\t\treturn unavailable('The JWKS redirect target is not a URL', response.status);\n\t}\n\tif (\n\t\t!isPermittedUrl(destination) ||\n\t\tdestination.username !== '' ||\n\t\tdestination.password !== '' ||\n\t\t!config.allowRedirect(destination, from)\n\t) {\n\t\treturn unavailable('The JWKS redirect target is not permitted', response.status);\n\t}\n\treturn successResult(destination);\n}\n\nasync function readJwks(\n\tconfig: ResolvedConfig,\n\tresponse: Response,\n\trequestedAt: number,\n\tsignal: AbortSignal,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tif (response.status !== 200) {\n\t\tawait response.body?.cancel();\n\t\treturn unavailable('The JWKS endpoint did not answer 200', response.status);\n\t}\n\tconst receivedAt = config.now();\n\tconst body = await readBounded(response, config.maxResponseBytes, signal);\n\tif (!body.ok) return body;\n\tconst jwks = parseJwks(body.value, {\n\t\tmaxBytes: config.maxResponseBytes,\n\t\tmaxKeys: config.maxKeys,\n\t});\n\tif (!jwks.ok) return joseFailure('jwks_malformed', jwks.message);\n\treturn successResult({\n\t\tjwks: jwks.value,\n\t\texpiresAt: receivedAt + freshnessMs(response.headers, requestedAt, receivedAt, config),\n\t});\n}\n\nasync function fetchJwks(\n\tconfig: ResolvedConfig,\n\tsignal: AbortSignal,\n\trequestedAt: number,\n): Promise<JoseResult<Fetched, FetchFailureCode>> {\n\tlet url = config.url;\n\tfor (let redirects = 0; ; redirects++) {\n\t\tconst response = await config.transport(url.href, {\n\t\t\tmethod: 'GET',\n\t\t\tredirect: 'manual',\n\t\t\tcredentials: 'omit',\n\t\t\tcache: 'no-store',\n\t\t\theaders: url.origin === config.url.origin ? config.headers : {},\n\t\t\tsignal,\n\t\t});\n\t\tif (signal.aborted) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn unavailable('The JWKS request was cancelled');\n\t\t}\n\t\tif (response.type === 'opaqueredirect') {\n\t\t\treturn unavailable('The runtime hides redirects, so they cannot be validated');\n\t\t}\n\t\tif (!REDIRECT_STATUSES.has(response.status)) {\n\t\t\treturn await readJwks(config, response, requestedAt, signal);\n\t\t}\n\t\tawait response.body?.cancel();\n\t\tconst hop = nextHop(config, url, response, redirects);\n\t\tif (!hop.ok) return hop;\n\t\turl = hop.value;\n\t}\n}\n\nfunction entryKey(entry: RsaJwkEntry): string {\n\treturn `${entry.n}.${entry.e}`;\n}\n\nfunction carryOver(fetched: Fetched, previous: Snapshot | undefined): Snapshot {\n\tconst imported = new Map<string, Promise<JoseResult<CryptoKey, 'key_unsuitable'>>>();\n\tfor (const entry of fetched.jwks.keys) {\n\t\tconst carried = entry.kind === 'rsa' ? previous?.imported.get(entryKey(entry)) : undefined;\n\t\tif (entry.kind === 'rsa' && carried !== undefined) imported.set(entryKey(entry), carried);\n\t}\n\treturn { jwks: fetched.jwks, expiresAt: fetched.expiresAt, imported };\n}\n\nconst TIMED_OUT: unique symbol = Symbol('micro509.jose.timedOut');\n\n/**\n * Creates a key resolver that reads a JWK Set from one trusted URL.\n *\n * Behaviour, per resolver:\n *\n * - The first verification fetches the set. Later ones reuse it while fresh. Freshness is the\n * remaining lifetime from `Cache-Control: max-age`, else `Expires`, else `defaultTtlMs`, less the\n * response age (the larger of the apparent age from `Date` and `Age` plus the transit delay),\n * capped at `maxTtlMs`. `no-store`, `no-cache` and a lifetime already spent leave none: the set\n * serves the verification that fetched it and nothing after. No heuristic freshness is applied.\n * - A set that is no longer fresh is never used, whether or not a refresh succeeds. There is no\n * stale-if-error. A refresh that fails while the cached set is still fresh keeps that set until\n * it expires.\n * - Refreshes are separate from freshness: after any attempt the next one waits `cooldownMs`.\n * Within that interval a token whose `kid` is absent gets `key_not_found`, and a token that\n * needs a set that is no longer fresh gets `jwks_unavailable`. Concurrent verifications share\n * a single request, and unknown `kid` values are never cached.\n * - A refresh replaces the whole set, so a rotated-out key stops verifying as soon as the new\n * set is read. Rotation must therefore introduce a new `kid`.\n * - The whole request, response body included, is bounded by `timeoutMs` and enforced even when\n * the transport ignores the abort signal. Redirects, bytes and keys are bounded by `redirects`,\n * `maxResponseBytes` and `maxKeys`. No retry happens inside a fetch. Cancelling the last waiting\n * verification aborts the request, and a response that finishes afterwards is discarded.\n * - Request headers go only to the configured origin. `jku`, `x5u` and `jwk` headers are never\n * used.\n *\n * Throws a `ResultError` coded {@linkcode RemoteJwksConfigErrorCode} for unusable configuration.\n * Redirect destinations, and the addresses a hostname resolves to, are limited by `redirects` and\n * the transport; this module cannot see DNS answers, and browsers hide redirect targets.\n */\nexport function createRemoteJwksKeyResolver(config: RemoteJwksConfig): JwsKeyResolver {\n\tconst settings = resolveConfig(config);\n\tlet snapshot: Snapshot | undefined;\n\tlet refresh: Refresh | undefined;\n\tlet lastAttemptAt: number | undefined;\n\n\tfunction startRefresh(): Refresh {\n\t\tconst controller = new AbortController();\n\t\tconst requestedAt = settings.now();\n\t\tconst previousAttemptAt = lastAttemptAt;\n\t\tconst previous = snapshot;\n\t\tlastAttemptAt = requestedAt;\n\n\t\tasync function run(): Promise<RefreshOutcome> {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(TIMED_OUT), settings.timeoutMs);\n\t\t\t});\n\t\t\tconst work = fetchJwks(settings, controller.signal, requestedAt);\n\t\t\twork.catch(() => undefined);\n\t\t\ttry {\n\t\t\t\tconst fetched = await Promise.race([work, deadline]);\n\t\t\t\tif (fetched === TIMED_OUT) {\n\t\t\t\t\tcontroller.abort();\n\t\t\t\t\treturn { kind: 'failed', failure: unavailable('The JWKS request timed out') };\n\t\t\t\t}\n\t\t\t\tif (!fetched.ok) return { kind: 'failed', failure: fetched };\n\t\t\t\treturn { kind: 'fresh', snapshot: carryOver(fetched.value, previous) };\n\t\t\t} catch {\n\t\t\t\treturn controller.signal.aborted\n\t\t\t\t\t? { kind: 'abandoned' }\n\t\t\t\t\t: { kind: 'failed', failure: unavailable('The JWKS request failed') };\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t}\n\n\t\tconst tracked: Promise<RefreshOutcome> = run()\n\t\t\t.then((outcome): RefreshOutcome => {\n\t\t\t\tif (refresh?.promise !== tracked) return { kind: 'abandoned' };\n\t\t\t\tif (outcome.kind === 'fresh') snapshot = outcome.snapshot;\n\t\t\t\treturn outcome;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (refresh?.promise === tracked) refresh = undefined;\n\t\t\t});\n\t\treturn {\n\t\t\tpromise: tracked,\n\t\t\tcontroller,\n\t\t\tstartedAt: requestedAt,\n\t\t\tpreviousAttemptAt,\n\t\t\twaiters: 0,\n\t\t};\n\t}\n\n\tasync function awaitRefresh(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<RefreshOutcome | typeof ABORTED> {\n\t\tif (signal?.aborted === true) return ABORTED;\n\t\trefresh ??= startRefresh();\n\t\tconst joined = refresh;\n\t\tjoined.waiters++;\n\t\tif (signal === undefined) return await joined.promise;\n\t\treturn await new Promise<RefreshOutcome | typeof ABORTED>((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (): void => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tjoined.waiters--;\n\t\t\t\tif (joined.waiters === 0) {\n\t\t\t\t\tif (refresh === joined) refresh = undefined;\n\t\t\t\t\tif (lastAttemptAt === joined.startedAt) lastAttemptAt = joined.previousAttemptAt;\n\t\t\t\t\tjoined.controller.abort();\n\t\t\t\t}\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\tvoid joined.promise.then((outcome) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tfinish();\n\t\t\t\tresolve(outcome);\n\t\t\t});\n\t\t});\n\t}\n\n\tfunction refreshAllowed(): boolean {\n\t\tif (refresh !== undefined || lastAttemptAt === undefined) return true;\n\t\treturn settings.now() - lastAttemptAt >= settings.cooldownMs;\n\t}\n\n\tasync function obtain(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot | undefined, FetchFailureCode | 'aborted'>> {\n\t\tif (!refreshAllowed()) return successResult(undefined);\n\t\tconst outcome = await awaitRefresh(signal);\n\t\tif (outcome === ABORTED || outcome.kind === 'abandoned') {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tif (outcome.kind === 'failed') return outcome.failure;\n\t\treturn successResult(outcome.snapshot);\n\t}\n\n\tasync function importFrom(\n\t\tcurrent: Snapshot,\n\t\tentry: RsaJwkEntry,\n\t): Promise<JoseResult<CryptoKey, 'key_unsuitable'>> {\n\t\tconst key = entryKey(entry);\n\t\tconst cached = current.imported.get(key);\n\t\tif (cached !== undefined) return await cached;\n\t\tconst pending = importJwkEntry(entry);\n\t\tcurrent.imported.set(key, pending);\n\t\treturn await pending;\n\t}\n\n\tasync function currentSnapshot(\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<Snapshot, FetchFailureCode | 'aborted'>> {\n\t\tif (snapshot !== undefined && settings.now() < snapshot.expiresAt) {\n\t\t\treturn successResult(snapshot);\n\t\t}\n\t\tsnapshot = undefined;\n\t\tconst loaded = await obtain(signal);\n\t\tif (!loaded.ok) return loaded;\n\t\treturn loaded.value === undefined\n\t\t\t? unavailable('The JWKS endpoint is in cooldown')\n\t\t\t: successResult(loaded.value);\n\t}\n\n\tasync function select(\n\t\tcurrent: Snapshot,\n\t\tselector: JwkSelector,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<JoseResult<CryptoKey, KeyResolutionErrorCode>> {\n\t\tlet source = current;\n\t\tlet selected = selectJwk(source.jwks, selector);\n\t\tif (!selected.ok && selected.code === 'key_not_found') {\n\t\t\tconst reloaded = await obtain(signal);\n\t\t\tif (!reloaded.ok) return reloaded;\n\t\t\tif (reloaded.value !== undefined) {\n\t\t\t\tsource = reloaded.value;\n\t\t\t\tselected = selectJwk(source.jwks, selector);\n\t\t\t}\n\t\t}\n\t\tif (!selected.ok) return selected;\n\t\tconst key = await importFrom(source, selected.value);\n\t\treturn signal?.aborted === true ? joseFailure('aborted', 'Key resolution was cancelled') : key;\n\t}\n\n\treturn async (request: JwsKeyRequest) => {\n\t\tif (request.signal?.aborted === true) {\n\t\t\treturn joseFailure('aborted', 'Key resolution was cancelled');\n\t\t}\n\t\tconst current = await currentSnapshot(request.signal);\n\t\tif (!current.ok) return current;\n\t\treturn await select(\n\t\t\tcurrent.value,\n\t\t\t{ algorithm: request.algorithm, ...(request.kid === undefined ? {} : { kid: request.kid }) },\n\t\t\trequest.signal,\n\t\t);\n\t};\n}\n"],"mappings":";;;;AAuGA,MAAMA,IAAyB,OAAO,uBAAuB,GAEvDC,IAAW;CAChB,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;AACb,GAEMC,oBAAyC,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC,GAE1EC,oBAAsC,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAEvF,SAAS,eAAe,GAAmB;CAC1C,OACCC,EAAI,aAAa,YAAaA,EAAI,aAAa,WAAWD,EAAe,IAAIC,EAAI,QAAQ;AAE3F;AAEA,SAAS,gBAAgB,GAA2B,GAAkB,GAAsB;CAC3F,IAAMC,IAAWC,KAASC;CAI1B,OAHI,CAAC,OAAO,cAAcF,CAAQ,KAAKA,KAAY,IAC3CG,EAAmB,8BAA8B,GAAGC,EAAK,4BAA4B,IAEtFJ;AACR;AAiBA,SAAS,cAAc,GAA0C;CAChE,IAAID;CACJ,IAAI;EACH,IAAM,IAAI,IAAIM,EAAO,GAAG;CACzB,QAAQ;EACP,OAAOF,EAAmB,8BAA8B,4BAA4B;CACrF;CACA,IAAI,CAAC,eAAeJ,CAAG,GACtB,OAAOI,EACN,8BACA,gDACD;CAED,IA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D,IAAMyD,IAAU,MAAM,gBAAgBS,EAAQ,MAAM;EAEpD,OADKT,EAAQ,KACN,MAAM,OACZA,EAAQ,OACR;GAAE,WAAWS,EAAQ;GAAW,GAAIA,EAAQ,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,KAAKA,EAAQ,IAAI;EAAG,GAC3FA,EAAQ,MACT,IALwBT;CAMzB;AACD"}
|
package/dist/jose.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { JsonObject, JsonValue } from "./internal/jose/strict-json.js";
|
|
2
|
+
import { JoseErrorCode, JoseErrorDetails, JoseErrorResult, JoseFailure, JoseResult, JwsParseErrorCode, JwsPolicyErrorCode, JwtClaimsErrorCode, KeyResolutionErrorCode, VerifyJwsErrorCode, VerifyJwtErrorCode } from "./jose/errors.js";
|
|
3
|
+
import { DEFAULT_JOSE_LIMITS, JWS_ALGORITHMS, JoseLimits, JwsAlgorithm, JwsHeader, JwsHeaderInput, JwsKeyRequest, JwsKeyResolver, MIN_RS256_MODULUS_BITS, SignJoseErrorCode, SignJwsInput, TokenTypePolicy, Unchecked, UnverifiedJws, VerifiedJws, VerifyJwsOptions, parseCompactJws, signCompactJws, verifyCompactJws } from "./jose/jws.js";
|
|
4
|
+
import { DEFAULT_JWKS_LIMITS, JwkEntry, JwkEntryBase, JwkMetadata, JwkSelector, Jwks, JwksLimits, ParseJwksErrorCode, RsaJwkEntry, UnsupportedJwkEntry, createJwksKeyResolver, importJwkEntry, parseJwks, selectJwk } from "./jose/jwks.js";
|
|
5
|
+
import { FutureIssuedAtPolicy, JwtClaimsPolicy, MAX_CLOCK_TOLERANCE_SECONDS, RegisteredClaims, SignJwtInput, UnverifiedJwt, VerifiedJwt, VerifyJwtOptions, decodeJwtUnverified, signJwt, verifyJwt } from "./jose/jwt.js";
|
|
6
|
+
import { JwksRequestInit, JwksTransport, RemoteJwksConfig, RemoteJwksConfigErrorCode, RemoteJwksRedirectPolicy, createRemoteJwksKeyResolver } from "./jose/remote-jwks.js";
|
|
7
|
+
export { DEFAULT_JOSE_LIMITS, DEFAULT_JWKS_LIMITS, type FutureIssuedAtPolicy, JWS_ALGORITHMS, type JoseErrorCode, type JoseErrorDetails, type JoseErrorResult, type JoseFailure, type JoseLimits, type JoseResult, type JsonObject, type JsonValue, type JwkEntry, type JwkEntryBase, type JwkMetadata, type JwkSelector, type Jwks, type JwksLimits, type JwksRequestInit, type JwksTransport, type JwsAlgorithm, type JwsHeader, type JwsHeaderInput, type JwsKeyRequest, type JwsKeyResolver, type JwsParseErrorCode, type JwsPolicyErrorCode, type JwtClaimsErrorCode, type JwtClaimsPolicy, type KeyResolutionErrorCode, MAX_CLOCK_TOLERANCE_SECONDS, MIN_RS256_MODULUS_BITS, type ParseJwksErrorCode, type RegisteredClaims, type RemoteJwksConfig, type RemoteJwksConfigErrorCode, type RemoteJwksRedirectPolicy, type RsaJwkEntry, type SignJoseErrorCode, type SignJwsInput, type SignJwtInput, type TokenTypePolicy, type Unchecked, type UnsupportedJwkEntry, type UnverifiedJws, type UnverifiedJwt, type VerifiedJws, type VerifiedJwt, type VerifyJwsErrorCode, type VerifyJwsOptions, type VerifyJwtErrorCode, type VerifyJwtOptions, createJwksKeyResolver, createRemoteJwksKeyResolver, decodeJwtUnverified, importJwkEntry, parseCompactJws, parseJwks, selectJwk, signCompactJws, signJwt, verifyCompactJws, verifyJwt };
|
package/dist/jose.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { DEFAULT_JOSE_LIMITS as e, JWS_ALGORITHMS as t, MIN_RS256_MODULUS_BITS as n, parseCompactJws as r, signCompactJws as i, verifyCompactJws as a } from "./jose/jws.js";
|
|
2
|
+
import { DEFAULT_JWKS_LIMITS as o, createJwksKeyResolver as s, importJwkEntry as c, parseJwks as l, selectJwk as u } from "./jose/jwks.js";
|
|
3
|
+
import { MAX_CLOCK_TOLERANCE_SECONDS as d, decodeJwtUnverified as f, signJwt as p, verifyJwt as m } from "./jose/jwt.js";
|
|
4
|
+
import { createRemoteJwksKeyResolver as h } from "./jose/remote-jwks.js";
|
|
5
|
+
export { e as DEFAULT_JOSE_LIMITS, o as DEFAULT_JWKS_LIMITS, t as JWS_ALGORITHMS, d as MAX_CLOCK_TOLERANCE_SECONDS, n as MIN_RS256_MODULUS_BITS, s as createJwksKeyResolver, h as createRemoteJwksKeyResolver, f as decodeJwtUnverified, c as importJwkEntry, r as parseCompactJws, l as parseJwks, u as selectJwk, i as signCompactJws, p as signJwt, a as verifyCompactJws, m as verifyJwt };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Micro509Error, Result } from "../result/result.js";
|
|
2
|
+
/** Argon2id for new uses, or Argon2d for compatibility with existing formats. */
|
|
3
|
+
export type Argon2Algorithm = "argon2id" | "argon2d";
|
|
4
|
+
/** Argon2 versions used by KDBX. The native backend supports only 0x13. */
|
|
5
|
+
export type Argon2Version = 0x10 | 0x13;
|
|
6
|
+
/** Exact derivation inputs. Password encoding and format preprocessing belong to the caller. */
|
|
7
|
+
export interface Argon2Input {
|
|
8
|
+
/** Select Argon2id for new applications. */
|
|
9
|
+
readonly algorithm: Argon2Algorithm;
|
|
10
|
+
/** Exact version. No version substitution is performed. */
|
|
11
|
+
readonly version: Argon2Version;
|
|
12
|
+
/** Password or format-preprocessed input bytes. */
|
|
13
|
+
readonly password: Uint8Array;
|
|
14
|
+
/** Salt bytes. The native backend requires at least eight bytes. */
|
|
15
|
+
readonly salt: Uint8Array;
|
|
16
|
+
/** Total memory in kibibytes, at least eight times parallelism. */
|
|
17
|
+
readonly memoryKiB: number;
|
|
18
|
+
/** Number of full passes through memory. */
|
|
19
|
+
readonly passes: number;
|
|
20
|
+
/** Number of lanes. */
|
|
21
|
+
readonly parallelism: number;
|
|
22
|
+
/** Requested output length in bytes, at least four. */
|
|
23
|
+
readonly outputBytes: number;
|
|
24
|
+
/** Optional secret input, separate from the password. */
|
|
25
|
+
readonly secret?: Uint8Array;
|
|
26
|
+
/** Optional associated data included in the derivation. */
|
|
27
|
+
readonly associatedData?: Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
/** Per-invocation ceilings, checked before copying inputs or calling the backend. */
|
|
30
|
+
export interface Argon2Limits {
|
|
31
|
+
/** Memory ceiling in KiB. Default: 262144 (256 MiB). */
|
|
32
|
+
readonly maxMemoryKiB?: number;
|
|
33
|
+
/** Pass ceiling. Default: 16. */
|
|
34
|
+
readonly maxPasses?: number;
|
|
35
|
+
/** Lane ceiling. Default: 16. */
|
|
36
|
+
readonly maxParallelism?: number;
|
|
37
|
+
/** Output-byte ceiling. Default: 1024. */
|
|
38
|
+
readonly maxOutputBytes?: number;
|
|
39
|
+
/** Sum of password, salt, secret, and associated-data lengths. Default: 1048576. */
|
|
40
|
+
readonly maxInputBytes?: number;
|
|
41
|
+
}
|
|
42
|
+
/** Stable failures without password, salt, or backend exception content. */
|
|
43
|
+
export type Argon2ErrorCode = "invalid_parameters" | "limit_exceeded" | "unsupported" | "derivation_failed";
|
|
44
|
+
/** Derived bytes or a typed error. Successful output belongs to the caller. */
|
|
45
|
+
export type Argon2Result = Result<Uint8Array, Micro509Error<Argon2ErrorCode>>;
|
|
46
|
+
/**
|
|
47
|
+
* Trusted, explicitly supplied implementation for the exact requested algorithm
|
|
48
|
+
* and version. Called only after parameter and resource checks. Input arrays are
|
|
49
|
+
* private copies, wiped when the promise settles. A backend that transfers an input
|
|
50
|
+
* buffer must erase it in the receiving worker. Transfer ownership of output
|
|
51
|
+
* bytes to the caller: the wrapper copies and wipes that array before returning.
|
|
52
|
+
* Report unsupported requests explicitly, without fallback. Execution behavior
|
|
53
|
+
* and cancellation of a custom backend are its provider's responsibility.
|
|
54
|
+
*/
|
|
55
|
+
export type Argon2Backend = (input: Argon2Input) => Promise<Argon2Result>;
|
|
56
|
+
/** Resource policy and optional external implementation for {@linkcode deriveArgon2}. */
|
|
57
|
+
export interface Argon2Options {
|
|
58
|
+
/** Per-call ceilings. Applications must separately bound concurrent calls. */
|
|
59
|
+
readonly limits?: Argon2Limits;
|
|
60
|
+
/** Explicit trusted backend. Omit to use native WebCrypto version 0x13. */
|
|
61
|
+
readonly backend?: Argon2Backend;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Derives raw Argon2 bytes after validating parameters and resource ceilings.
|
|
65
|
+
*
|
|
66
|
+
* The default native WebCrypto adapter implements version 0x13. Runtime support
|
|
67
|
+
* is detected by the import/derive operations, without an extra trial derivation.
|
|
68
|
+
* Supply an explicit backend for other environments or version 0x10. There is
|
|
69
|
+
* no fallback between variants, versions, or implementations.
|
|
70
|
+
*
|
|
71
|
+
* Caller buffers are copied synchronously before the first await and never
|
|
72
|
+
* modified. Owned temporary arrays are zeroed on completion. Native key storage
|
|
73
|
+
* and runtime copies cannot be explicitly erased by JavaScript. The returned
|
|
74
|
+
* output is caller-owned. Calls cannot cancel native work once dispatched.
|
|
75
|
+
* Limits apply per call, not to concurrent invocations.
|
|
76
|
+
*/
|
|
77
|
+
export declare function deriveArgon2(input: Argon2Input, options?: Argon2Options): Promise<Argon2Result>;
|
|
78
|
+
//# sourceMappingURL=argon2.d.ts.map
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// src/kdf/argon2.ts
|
|
2
|
+
function failure(e, t) {
|
|
3
|
+
return {
|
|
4
|
+
ok: !1,
|
|
5
|
+
error: {
|
|
6
|
+
code: e,
|
|
7
|
+
message: t
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function uintInRange(e, t, n) {
|
|
12
|
+
return Number.isSafeInteger(e) && e >= t && e <= n;
|
|
13
|
+
}
|
|
14
|
+
function validate(e, t) {
|
|
15
|
+
if (e.algorithm !== "argon2id" && e.algorithm !== "argon2d") return failure("unsupported", "Unsupported Argon2 variant");
|
|
16
|
+
if (e.version !== 16 && e.version !== 19) return failure("unsupported", "Unsupported Argon2 version");
|
|
17
|
+
if (!uintInRange(e.parallelism, 1, 16777215) || !uintInRange(e.memoryKiB, 8 * e.parallelism, 4294967295) || !uintInRange(e.passes, 1, 4294967295) || !uintInRange(e.outputBytes, 4, 4294967295)) return failure("invalid_parameters", "Invalid Argon2 numeric parameters");
|
|
18
|
+
let n = [
|
|
19
|
+
e.password,
|
|
20
|
+
e.salt,
|
|
21
|
+
e.secret,
|
|
22
|
+
e.associatedData
|
|
23
|
+
];
|
|
24
|
+
if (!(e.password instanceof Uint8Array) || !(e.salt instanceof Uint8Array) || n.some((e) => e !== void 0 && !(e instanceof Uint8Array))) return failure("invalid_parameters", "Argon2 inputs must be Uint8Array values");
|
|
25
|
+
try {
|
|
26
|
+
for (let e of n) e !== void 0 && Uint8Array.prototype.values.call(e);
|
|
27
|
+
} catch {
|
|
28
|
+
return failure("invalid_parameters", "Argon2 input buffer is unavailable");
|
|
29
|
+
}
|
|
30
|
+
let r = [
|
|
31
|
+
[e.memoryKiB, t.maxMemoryKiB ?? 262144],
|
|
32
|
+
[e.passes, t.maxPasses ?? 16],
|
|
33
|
+
[e.parallelism, t.maxParallelism ?? 16],
|
|
34
|
+
[e.outputBytes, t.maxOutputBytes ?? 1024],
|
|
35
|
+
[n.reduce((e, t) => e + (t?.byteLength ?? 0), 0), t.maxInputBytes ?? 1048576]
|
|
36
|
+
];
|
|
37
|
+
if (r.some(([, e]) => !uintInRange(e, 1, 4294967295))) return failure("invalid_parameters", "Argon2 resource limits must be positive uint32 values");
|
|
38
|
+
if (r.some(([e, t]) => e > t)) return failure("limit_exceeded", "Argon2 request exceeds resource limits");
|
|
39
|
+
}
|
|
40
|
+
function snapshotInput(e) {
|
|
41
|
+
let { algorithm: t, version: n, password: r, salt: i, memoryKiB: a, passes: o, parallelism: s, outputBytes: c, secret: l, associatedData: u } = e;
|
|
42
|
+
return {
|
|
43
|
+
algorithm: t,
|
|
44
|
+
version: n,
|
|
45
|
+
password: r,
|
|
46
|
+
salt: i,
|
|
47
|
+
memoryKiB: a,
|
|
48
|
+
passes: o,
|
|
49
|
+
parallelism: s,
|
|
50
|
+
outputBytes: c,
|
|
51
|
+
...l === void 0 ? {} : { secret: l },
|
|
52
|
+
...u === void 0 ? {} : { associatedData: u }
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function copyInput(e) {
|
|
56
|
+
return {
|
|
57
|
+
algorithm: e.algorithm,
|
|
58
|
+
version: e.version,
|
|
59
|
+
memoryKiB: e.memoryKiB,
|
|
60
|
+
passes: e.passes,
|
|
61
|
+
parallelism: e.parallelism,
|
|
62
|
+
outputBytes: e.outputBytes,
|
|
63
|
+
password: new Uint8Array(e.password),
|
|
64
|
+
salt: new Uint8Array(e.salt),
|
|
65
|
+
...e.secret === void 0 ? {} : { secret: new Uint8Array(e.secret) },
|
|
66
|
+
...e.associatedData === void 0 ? {} : { associatedData: new Uint8Array(e.associatedData) }
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function eraseAccessible(e) {
|
|
70
|
+
e !== void 0 && e.byteLength > 0 && Uint8Array.prototype.fill.call(e, 0);
|
|
71
|
+
}
|
|
72
|
+
async function nativeArgon2(e) {
|
|
73
|
+
if (e.version !== 19) return failure("unsupported", "Native Argon2 supports version 0x13 only");
|
|
74
|
+
if (e.salt.byteLength < 8) return failure("unsupported", "Native Argon2 requires a salt of at least eight bytes");
|
|
75
|
+
if (e.outputBytes > 536870911) return failure("unsupported", "Requested output exceeds the native WebCrypto bit-length range");
|
|
76
|
+
if (globalThis.crypto?.subtle === void 0) return failure("unsupported", "Native WebCrypto is unavailable");
|
|
77
|
+
let t = globalThis.crypto.subtle, n;
|
|
78
|
+
switch (e.algorithm) {
|
|
79
|
+
case "argon2id":
|
|
80
|
+
n = "Argon2id";
|
|
81
|
+
break;
|
|
82
|
+
case "argon2d":
|
|
83
|
+
n = "Argon2d";
|
|
84
|
+
break;
|
|
85
|
+
default: return failure("unsupported", "Unsupported Argon2 variant");
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
let r = await Reflect.apply(t.importKey, t, [
|
|
89
|
+
"raw-secret",
|
|
90
|
+
e.password,
|
|
91
|
+
n,
|
|
92
|
+
!1,
|
|
93
|
+
["deriveBits"]
|
|
94
|
+
]);
|
|
95
|
+
if (typeof CryptoKey > "u" || !(r instanceof CryptoKey)) return failure("derivation_failed", "Native Argon2 returned an invalid key");
|
|
96
|
+
let i = {
|
|
97
|
+
name: n,
|
|
98
|
+
version: e.version,
|
|
99
|
+
memory: e.memoryKiB,
|
|
100
|
+
passes: e.passes,
|
|
101
|
+
parallelism: e.parallelism,
|
|
102
|
+
nonce: new Uint8Array(e.salt),
|
|
103
|
+
...e.secret === void 0 ? {} : { secretValue: new Uint8Array(e.secret) },
|
|
104
|
+
...e.associatedData === void 0 ? {} : { associatedData: new Uint8Array(e.associatedData) }
|
|
105
|
+
};
|
|
106
|
+
try {
|
|
107
|
+
let n = await t.deriveBits(i, r, e.outputBytes * 8);
|
|
108
|
+
return {
|
|
109
|
+
ok: !0,
|
|
110
|
+
value: new Uint8Array(n)
|
|
111
|
+
};
|
|
112
|
+
} finally {
|
|
113
|
+
i.nonce.fill(0), i.secretValue?.fill(0), i.associatedData?.fill(0);
|
|
114
|
+
}
|
|
115
|
+
} catch (e) {
|
|
116
|
+
return e instanceof Error && e.name === "NotSupportedError" ? failure("unsupported", "This runtime does not support native Argon2") : failure("derivation_failed", "Native Argon2 derivation failed");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Derives raw Argon2 bytes after validating parameters and resource ceilings.
|
|
121
|
+
*
|
|
122
|
+
* The default native WebCrypto adapter implements version 0x13. Runtime support
|
|
123
|
+
* is detected by the import/derive operations, without an extra trial derivation.
|
|
124
|
+
* Supply an explicit backend for other environments or version 0x10. There is
|
|
125
|
+
* no fallback between variants, versions, or implementations.
|
|
126
|
+
*
|
|
127
|
+
* Caller buffers are copied synchronously before the first await and never
|
|
128
|
+
* modified. Owned temporary arrays are zeroed on completion. Native key storage
|
|
129
|
+
* and runtime copies cannot be explicitly erased by JavaScript. The returned
|
|
130
|
+
* output is caller-owned. Calls cannot cancel native work once dispatched.
|
|
131
|
+
* Limits apply per call, not to concurrent invocations.
|
|
132
|
+
*/
|
|
133
|
+
async function deriveArgon2(e, t = {}) {
|
|
134
|
+
if (typeof e != "object" || !e) return failure("invalid_parameters", "Argon2 input must be an object");
|
|
135
|
+
let n;
|
|
136
|
+
try {
|
|
137
|
+
n = snapshotInput(e);
|
|
138
|
+
} catch {
|
|
139
|
+
return failure("invalid_parameters", "Argon2 input properties could not be read");
|
|
140
|
+
}
|
|
141
|
+
let r = validate(n, t.limits ?? {});
|
|
142
|
+
if (r !== void 0) return r;
|
|
143
|
+
let i = copyInput(n);
|
|
144
|
+
try {
|
|
145
|
+
let e = await (t.backend ?? nativeArgon2)(i);
|
|
146
|
+
if (!e.ok) {
|
|
147
|
+
let t = e.error.code;
|
|
148
|
+
return failure(t === "unsupported" || t === "limit_exceeded" || t === "invalid_parameters" ? t : "derivation_failed", "Argon2 backend could not derive the requested key");
|
|
149
|
+
}
|
|
150
|
+
if (!(e.value instanceof Uint8Array)) return failure("derivation_failed", "Argon2 backend returned invalid output");
|
|
151
|
+
try {
|
|
152
|
+
return e.value.byteLength === i.outputBytes ? {
|
|
153
|
+
ok: !0,
|
|
154
|
+
value: new Uint8Array(e.value)
|
|
155
|
+
} : failure("derivation_failed", "Argon2 backend returned an incorrect output length");
|
|
156
|
+
} finally {
|
|
157
|
+
eraseAccessible(e.value);
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
return failure("derivation_failed", "Argon2 backend failed");
|
|
161
|
+
} finally {
|
|
162
|
+
eraseAccessible(i.password), eraseAccessible(i.salt), eraseAccessible(i.secret), eraseAccessible(i.associatedData);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
export { deriveArgon2 };
|
|
166
|
+
|
|
167
|
+
//# sourceMappingURL=argon2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"argon2.js","names":["value","min","max","input","inputs","bytes","bounds","limits","sum","maximum","actual","secret","associatedData","subtle","name","key","params","output","error","snapshot","invalid","options","owned","result","code"],"sources":["../../src/kdf/argon2.ts"],"sourcesContent":["/**\n * Argon2 adapter and resource-policy boundary. The default backend uses native\n * WebCrypto, with no algorithm fallback or portable implementation bundled.\n *\n * @module\n */\n\nimport type { Micro509Error, Result } from '#micro509/result/result';\n\n/** Argon2id for new uses, or Argon2d for compatibility with existing formats. */\nexport type Argon2Algorithm = 'argon2id' | 'argon2d';\n\n/** Argon2 versions used by KDBX. The native backend supports only 0x13. */\nexport type Argon2Version = 0x10 | 0x13;\n\n/** Exact derivation inputs. Password encoding and format preprocessing belong to the caller. */\nexport interface Argon2Input {\n\t/** Select Argon2id for new applications. */\n\treadonly algorithm: Argon2Algorithm;\n\t/** Exact version. No version substitution is performed. */\n\treadonly version: Argon2Version;\n\t/** Password or format-preprocessed input bytes. */\n\treadonly password: Uint8Array;\n\t/** Salt bytes. The native backend requires at least eight bytes. */\n\treadonly salt: Uint8Array;\n\t/** Total memory in kibibytes, at least eight times parallelism. */\n\treadonly memoryKiB: number;\n\t/** Number of full passes through memory. */\n\treadonly passes: number;\n\t/** Number of lanes. */\n\treadonly parallelism: number;\n\t/** Requested output length in bytes, at least four. */\n\treadonly outputBytes: number;\n\t/** Optional secret input, separate from the password. */\n\treadonly secret?: Uint8Array;\n\t/** Optional associated data included in the derivation. */\n\treadonly associatedData?: Uint8Array;\n}\n\n/** Per-invocation ceilings, checked before copying inputs or calling the backend. */\nexport interface Argon2Limits {\n\t/** Memory ceiling in KiB. Default: 262144 (256 MiB). */\n\treadonly maxMemoryKiB?: number;\n\t/** Pass ceiling. Default: 16. */\n\treadonly maxPasses?: number;\n\t/** Lane ceiling. Default: 16. */\n\treadonly maxParallelism?: number;\n\t/** Output-byte ceiling. Default: 1024. */\n\treadonly maxOutputBytes?: number;\n\t/** Sum of password, salt, secret, and associated-data lengths. Default: 1048576. */\n\treadonly maxInputBytes?: number;\n}\n\n/** Stable failures without password, salt, or backend exception content. */\nexport type Argon2ErrorCode =\n\t| 'invalid_parameters'\n\t| 'limit_exceeded'\n\t| 'unsupported'\n\t| 'derivation_failed';\n\n/** Derived bytes or a typed error. Successful output belongs to the caller. */\nexport type Argon2Result = Result<Uint8Array, Micro509Error<Argon2ErrorCode>>;\n\n/**\n * Trusted, explicitly supplied implementation for the exact requested algorithm\n * and version. Called only after parameter and resource checks. Input arrays are\n * private copies, wiped when the promise settles. A backend that transfers an input\n * buffer must erase it in the receiving worker. Transfer ownership of output\n * bytes to the caller: the wrapper copies and wipes that array before returning.\n * Report unsupported requests explicitly, without fallback. Execution behavior\n * and cancellation of a custom backend are its provider's responsibility.\n */\nexport type Argon2Backend = (input: Argon2Input) => Promise<Argon2Result>;\n\n/** Resource policy and optional external implementation for {@linkcode deriveArgon2}. */\nexport interface Argon2Options {\n\t/** Per-call ceilings. Applications must separately bound concurrent calls. */\n\treadonly limits?: Argon2Limits;\n\t/** Explicit trusted backend. Omit to use native WebCrypto version 0x13. */\n\treadonly backend?: Argon2Backend;\n}\n\nfunction failure(code: Argon2ErrorCode, message: string): Argon2Result {\n\treturn { ok: false, error: { code, message } };\n}\n\nfunction uintInRange(value: number, min: number, max: number): boolean {\n\treturn Number.isSafeInteger(value) && value >= min && value <= max;\n}\n\nfunction validate(input: Argon2Input, limits: Argon2Limits): Argon2Result | undefined {\n\tif (input.algorithm !== 'argon2id' && input.algorithm !== 'argon2d') {\n\t\treturn failure('unsupported', 'Unsupported Argon2 variant');\n\t}\n\tif (input.version !== 0x10 && input.version !== 0x13) {\n\t\treturn failure('unsupported', 'Unsupported Argon2 version');\n\t}\n\t// RFC 9106 section 3.1. Memory is passed exactly, including values not\n\t// divisible by 4*p: rounding the input would change the initial hash.\n\tif (\n\t\t!uintInRange(input.parallelism, 1, 0xffffff) ||\n\t\t!uintInRange(input.memoryKiB, 8 * input.parallelism, 0xffffffff) ||\n\t\t!uintInRange(input.passes, 1, 0xffffffff) ||\n\t\t!uintInRange(input.outputBytes, 4, 0xffffffff)\n\t) {\n\t\treturn failure('invalid_parameters', 'Invalid Argon2 numeric parameters');\n\t}\n\tconst inputs = [input.password, input.salt, input.secret, input.associatedData];\n\tif (\n\t\t!(input.password instanceof Uint8Array) ||\n\t\t!(input.salt instanceof Uint8Array) ||\n\t\tinputs.some((bytes) => bytes !== undefined && !(bytes instanceof Uint8Array))\n\t) {\n\t\treturn failure('invalid_parameters', 'Argon2 inputs must be Uint8Array values');\n\t}\n\ttry {\n\t\t// A detached or out-of-bounds view reports zero length. Validate its\n\t\t// backing store before copying any of the caller's secret material.\n\t\tfor (const bytes of inputs) {\n\t\t\tif (bytes !== undefined) Uint8Array.prototype.values.call(bytes);\n\t\t}\n\t} catch {\n\t\treturn failure('invalid_parameters', 'Argon2 input buffer is unavailable');\n\t}\n\tconst bounds = [\n\t\t[input.memoryKiB, limits.maxMemoryKiB ?? 262144],\n\t\t[input.passes, limits.maxPasses ?? 16],\n\t\t[input.parallelism, limits.maxParallelism ?? 16],\n\t\t[input.outputBytes, limits.maxOutputBytes ?? 1024],\n\t\t[\n\t\t\tinputs.reduce((sum, bytes) => sum + (bytes?.byteLength ?? 0), 0),\n\t\t\tlimits.maxInputBytes ?? 1048576,\n\t\t],\n\t] as const;\n\tif (bounds.some(([, maximum]) => !uintInRange(maximum, 1, 0xffffffff))) {\n\t\treturn failure('invalid_parameters', 'Argon2 resource limits must be positive uint32 values');\n\t}\n\tif (bounds.some(([actual, maximum]) => actual > maximum)) {\n\t\treturn failure('limit_exceeded', 'Argon2 request exceeds resource limits');\n\t}\n\treturn undefined;\n}\n\nfunction snapshotInput(input: Argon2Input): Argon2Input {\n\t// Read declared properties once, including inherited and non-enumerable ones.\n\t// Byte arrays remain references until validation has enforced resource bounds.\n\tconst {\n\t\talgorithm,\n\t\tversion,\n\t\tpassword,\n\t\tsalt,\n\t\tmemoryKiB,\n\t\tpasses,\n\t\tparallelism,\n\t\toutputBytes,\n\t\tsecret,\n\t\tassociatedData,\n\t} = input;\n\treturn {\n\t\talgorithm,\n\t\tversion,\n\t\tpassword,\n\t\tsalt,\n\t\tmemoryKiB,\n\t\tpasses,\n\t\tparallelism,\n\t\toutputBytes,\n\t\t...(secret === undefined ? {} : { secret }),\n\t\t...(associatedData === undefined ? {} : { associatedData }),\n\t};\n}\n\nfunction copyInput(input: Argon2Input): Argon2Input {\n\treturn {\n\t\talgorithm: input.algorithm,\n\t\tversion: input.version,\n\t\tmemoryKiB: input.memoryKiB,\n\t\tpasses: input.passes,\n\t\tparallelism: input.parallelism,\n\t\toutputBytes: input.outputBytes,\n\t\tpassword: new Uint8Array(input.password),\n\t\tsalt: new Uint8Array(input.salt),\n\t\t...(input.secret === undefined ? {} : { secret: new Uint8Array(input.secret) }),\n\t\t...(input.associatedData === undefined\n\t\t\t? {}\n\t\t\t: { associatedData: new Uint8Array(input.associatedData) }),\n\t};\n}\n\nfunction eraseAccessible(bytes: Uint8Array | undefined): void {\n\t// Transfer detaches the sender's view. Its bytes can only be erased by the\n\t// receiving worker, and cleanup must still proceed through the other inputs.\n\tif (bytes !== undefined && bytes.byteLength > 0) Uint8Array.prototype.fill.call(bytes, 0);\n}\n\nasync function nativeArgon2(input: Argon2Input): Promise<Argon2Result> {\n\tif (input.version !== 0x13) {\n\t\treturn failure('unsupported', 'Native Argon2 supports version 0x13 only');\n\t}\n\tif (input.salt.byteLength < 8) {\n\t\treturn failure('unsupported', 'Native Argon2 requires a salt of at least eight bytes');\n\t}\n\tif (input.outputBytes > Math.floor(0xffffffff / 8)) {\n\t\treturn failure('unsupported', 'Requested output exceeds the native WebCrypto bit-length range');\n\t}\n\tif (typeof globalThis.crypto?.subtle === 'undefined') {\n\t\treturn failure('unsupported', 'Native WebCrypto is unavailable');\n\t}\n\tconst subtle = globalThis.crypto.subtle;\n\tlet name: 'Argon2id' | 'Argon2d';\n\tswitch (input.algorithm) {\n\t\tcase 'argon2id':\n\t\t\tname = 'Argon2id';\n\t\t\tbreak;\n\t\tcase 'argon2d':\n\t\t\tname = 'Argon2d';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn failure('unsupported', 'Unsupported Argon2 variant');\n\t}\n\ttry {\n\t\t// raw-secret is a runtime WebCrypto extension not present in every DOM\n\t\t// declaration. The result is narrowed rather than asserted or globally\n\t\t// augmenting consumers' SubtleCrypto definitions.\n\t\tconst key: unknown = await Reflect.apply(subtle.importKey, subtle, [\n\t\t\t'raw-secret',\n\t\t\tinput.password,\n\t\t\tname,\n\t\t\tfalse,\n\t\t\t['deriveBits'],\n\t\t]);\n\t\tif (typeof CryptoKey === 'undefined' || !(key instanceof CryptoKey)) {\n\t\t\treturn failure('derivation_failed', 'Native Argon2 returned an invalid key');\n\t\t}\n\t\tconst params = {\n\t\t\tname,\n\t\t\tversion: input.version,\n\t\t\tmemory: input.memoryKiB,\n\t\t\tpasses: input.passes,\n\t\t\tparallelism: input.parallelism,\n\t\t\tnonce: new Uint8Array(input.salt),\n\t\t\t...(input.secret === undefined ? {} : { secretValue: new Uint8Array(input.secret) }),\n\t\t\t...(input.associatedData === undefined\n\t\t\t\t? {}\n\t\t\t\t: { associatedData: new Uint8Array(input.associatedData) }),\n\t\t};\n\t\ttry {\n\t\t\tconst output = await subtle.deriveBits(params, key, input.outputBytes * 8);\n\t\t\treturn { ok: true, value: new Uint8Array(output) };\n\t\t} finally {\n\t\t\tparams.nonce.fill(0);\n\t\t\tparams.secretValue?.fill(0);\n\t\t\tparams.associatedData?.fill(0);\n\t\t}\n\t} catch (error) {\n\t\treturn error instanceof Error && error.name === 'NotSupportedError'\n\t\t\t? failure('unsupported', 'This runtime does not support native Argon2')\n\t\t\t: failure('derivation_failed', 'Native Argon2 derivation failed');\n\t}\n}\n\n/**\n * Derives raw Argon2 bytes after validating parameters and resource ceilings.\n *\n * The default native WebCrypto adapter implements version 0x13. Runtime support\n * is detected by the import/derive operations, without an extra trial derivation.\n * Supply an explicit backend for other environments or version 0x10. There is\n * no fallback between variants, versions, or implementations.\n *\n * Caller buffers are copied synchronously before the first await and never\n * modified. Owned temporary arrays are zeroed on completion. Native key storage\n * and runtime copies cannot be explicitly erased by JavaScript. The returned\n * output is caller-owned. Calls cannot cancel native work once dispatched.\n * Limits apply per call, not to concurrent invocations.\n */\nexport async function deriveArgon2(\n\tinput: Argon2Input,\n\toptions: Argon2Options = {},\n): Promise<Argon2Result> {\n\tif (input === null || typeof input !== 'object') {\n\t\treturn failure('invalid_parameters', 'Argon2 input must be an object');\n\t}\n\tlet snapshot: Argon2Input;\n\ttry {\n\t\tsnapshot = snapshotInput(input);\n\t} catch {\n\t\treturn failure('invalid_parameters', 'Argon2 input properties could not be read');\n\t}\n\tconst invalid = validate(snapshot, options.limits ?? {});\n\tif (invalid !== undefined) return invalid;\n\tconst owned = copyInput(snapshot);\n\ttry {\n\t\tconst result = await (options.backend ?? nativeArgon2)(owned);\n\t\tif (!result.ok) {\n\t\t\t// A custom provider's diagnostic may contain secrets. Return only the\n\t\t\t// recognized code and a fixed message at this public boundary.\n\t\t\tconst code = result.error.code;\n\t\t\treturn failure(\n\t\t\t\tcode === 'unsupported' || code === 'limit_exceeded' || code === 'invalid_parameters'\n\t\t\t\t\t? code\n\t\t\t\t\t: 'derivation_failed',\n\t\t\t\t'Argon2 backend could not derive the requested key',\n\t\t\t);\n\t\t}\n\t\tif (!(result.value instanceof Uint8Array)) {\n\t\t\treturn failure('derivation_failed', 'Argon2 backend returned invalid output');\n\t\t}\n\t\ttry {\n\t\t\treturn result.value.byteLength === owned.outputBytes\n\t\t\t\t? { ok: true, value: new Uint8Array(result.value) }\n\t\t\t\t: failure('derivation_failed', 'Argon2 backend returned an incorrect output length');\n\t\t} finally {\n\t\t\teraseAccessible(result.value);\n\t\t}\n\t} catch {\n\t\treturn failure('derivation_failed', 'Argon2 backend failed');\n\t} finally {\n\t\teraseAccessible(owned.password);\n\t\teraseAccessible(owned.salt);\n\t\teraseAccessible(owned.secret);\n\t\teraseAccessible(owned.associatedData);\n\t}\n}\n"],"mappings":";AAkFA,SAAS,QAAQ,GAAuB,G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qB,iCAAiC;CAClE;AACD;;;;;;;;;;;;;;;AAgBA,eAAsB,aACrB,GACA,IAAyB,CAAC,GACF;CACxB,IAAsB,OAAOf,KAAU,aAAnCA,GACH,OAAO,QAAQ,sBAAsB,gCAAgC;CAEtE,IAAIgB;CACJ,IAAI;EACH,IAAW,cAAchB,CAAK;CAC/B,QAAQ;EACP,OAAO,QAAQ,sBAAsB,2CAA2C;CACjF;CACA,IAAMiB,IAAU,SAASD,GAAUE,EAAQ,UAAU,CAAC,CAAC;CACvD,IAAID,MAAY,KAAA,GAAW,OAAOA;CAClC,IAAME,IAAQ,UAAUH,CAAQ;CAChC,IAAI;EACH,IAAMI,IAAS,OAAOF,EAAQ,WAAW,aAAA,CAAcC,CAAK;EAC5D,IAAI,CAACC,EAAO,IAAI;GAGf,IAAMC,IAAOD,EAAO,MAAM;GAC1B,OAAO,QACNC,MAAS,iBAAiBA,MAAS,oBAAoBA,MAAS,uBAC7DA,IACA,qBACH,mDACD;EACD;EACA,IAAI,EAAED,EAAO,iBAAiB,aAC7B,OAAO,QAAQ,qBAAqB,wCAAwC;EAE7E,IAAI;GACH,OAAOA,EAAO,MAAM,eAAeD,EAAM,cACtC;IAAE,IAAI;IAAM,OAAO,IAAI,WAAWC,EAAO,KAAK;GAAE,IAChD,QAAQ,qBAAqB,oDAAoD;EACrF,UAAU;GACT,gBAAgBA,EAAO,KAAK;EAC7B;CACD,QAAQ;EACP,OAAO,QAAQ,qBAAqB,uBAAuB;CAC5D,UAAU;EAIT,AAHA,gBAAgBD,EAAM,QAAQ,GAC9B,gBAAgBA,EAAM,IAAI,GAC1B,gBAAgBA,EAAM,MAAM,GAC5B,gBAAgBA,EAAM,cAAc;CACrC;AACD"}
|
package/dist/kdf.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { Argon2Algorithm, Argon2Backend, Argon2ErrorCode, Argon2Input, Argon2Limits, Argon2Options, Argon2Result, Argon2Version, deriveArgon2 } from "./kdf/argon2.js";
|
|
2
|
+
export { type Argon2Algorithm, type Argon2Backend, type Argon2ErrorCode, type Argon2Input, type Argon2Limits, type Argon2Options, type Argon2Result, type Argon2Version, deriveArgon2 };
|
package/dist/kdf.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { deriveArgon2 } from "./kdf/argon2.js";
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { ErrorResult, Micro509Error } from "../result/result.js";
|
|
2
|
+
import { EcNamedCurve, RsaHash, RsaSignatureScheme } from "../keys/keys.js";
|
|
3
|
+
import { SshErrorCode } from "./wire.js";
|
|
4
|
+
/** SSH public-key type names (RFC 4253 §6.6, RFC 5656 §6.2, RFC 8709 §4) this module reads and writes. */
|
|
5
|
+
export type SshKeyType = "ssh-rsa" | "ssh-ed25519" | "ecdsa-sha2-nistp256" | "ecdsa-sha2-nistp384" | "ecdsa-sha2-nistp521";
|
|
6
|
+
/** Algorithm family of an SSH key, discriminated by `kind`. */
|
|
7
|
+
export type SshKeyAlgorithm = {
|
|
8
|
+
/** RSA. */
|
|
9
|
+
readonly kind: "rsa";
|
|
10
|
+
/** Modulus size in bits. */
|
|
11
|
+
readonly modulusBits: number;
|
|
12
|
+
} | {
|
|
13
|
+
/** ECDSA. */
|
|
14
|
+
readonly kind: "ecdsa";
|
|
15
|
+
/** NIST curve. */
|
|
16
|
+
readonly curve: EcNamedCurve;
|
|
17
|
+
} | {
|
|
18
|
+
/** Ed25519. */
|
|
19
|
+
readonly kind: "ed25519";
|
|
20
|
+
};
|
|
21
|
+
/** Structured failure payload of the SSH key import functions. */
|
|
22
|
+
export interface SshFailure extends Micro509Error<SshErrorCode> {
|
|
23
|
+
/** Always `false` for failures. */
|
|
24
|
+
readonly ok: false;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Success-or-failure result of the SSH key import functions.
|
|
28
|
+
*
|
|
29
|
+
* `code` is `'malformed'` for structurally invalid input, `'unsupported'` for a
|
|
30
|
+
* valid construct this module does not read (encrypted keys, multi-key files,
|
|
31
|
+
* other key types, RSA below the minimum size, compressed points unless
|
|
32
|
+
* accepted), `'limit_exceeded'` for an implementation bound, and
|
|
33
|
+
* `'key_mismatch'` when the declared key types or the embedded public and
|
|
34
|
+
* private keys disagree. No message contains private key material.
|
|
35
|
+
*/
|
|
36
|
+
export type SshResult<T> = {
|
|
37
|
+
readonly ok: true;
|
|
38
|
+
readonly value: T;
|
|
39
|
+
} | ErrorResult<SshErrorCode, Record<never, never>, SshFailure>;
|
|
40
|
+
/** Policy options of the SSH key import functions. */
|
|
41
|
+
export interface SshImportOptions {
|
|
42
|
+
/**
|
|
43
|
+
* Smallest accepted RSA modulus in bits, an integer from 1 to 16384. Default: `2048`.
|
|
44
|
+
*
|
|
45
|
+
* The standards leave key strength to the relying party. RFC 8332 §5.1 calls
|
|
46
|
+
* 2048 bits prudent; OpenSSH itself accepts 1024.
|
|
47
|
+
*/
|
|
48
|
+
readonly minRsaModulusBits?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Accept SEC 1 compressed ECDSA points. Default: `false`.
|
|
51
|
+
*
|
|
52
|
+
* RFC 5656 §3.1 allows point compression; OpenSSH reads and writes only
|
|
53
|
+
* uncompressed points.
|
|
54
|
+
*/
|
|
55
|
+
readonly acceptCompressedEcPoints?: boolean;
|
|
56
|
+
/**
|
|
57
|
+
* WebCrypto parameters of an imported RSA key. Default: PKCS#1 v1.5 with
|
|
58
|
+
* SHA-256. These choose how the `CryptoKey` signs; they do not change the
|
|
59
|
+
* `ssh-rsa` key encoding.
|
|
60
|
+
*/
|
|
61
|
+
readonly rsa?: {
|
|
62
|
+
/** Signature padding scheme. */
|
|
63
|
+
readonly scheme?: RsaSignatureScheme;
|
|
64
|
+
/** Signature hash. */
|
|
65
|
+
readonly hash?: RsaHash;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Public key read from an OpenSSH public-key line. */
|
|
69
|
+
export interface ImportedSshPublicKey {
|
|
70
|
+
/** SSH key type name. */
|
|
71
|
+
readonly keyType: SshKeyType;
|
|
72
|
+
/** Algorithm family and size. */
|
|
73
|
+
readonly algorithm: SshKeyAlgorithm;
|
|
74
|
+
/** Extractable WebCrypto key with `verify` usage. */
|
|
75
|
+
readonly publicKey: CryptoKey;
|
|
76
|
+
/** The line's trailing comment; empty when absent. */
|
|
77
|
+
readonly comment: string;
|
|
78
|
+
/** `SHA256:` fingerprint of the public-key blob. */
|
|
79
|
+
readonly fingerprint: string;
|
|
80
|
+
}
|
|
81
|
+
/** Key pair read from an `openssh-key-v1` private-key file. */
|
|
82
|
+
export interface ImportedOpenSshPrivateKey extends ImportedSshPublicKey {
|
|
83
|
+
/** Extractable WebCrypto private key with `sign` usage. */
|
|
84
|
+
readonly privateKey: CryptoKey;
|
|
85
|
+
}
|
|
86
|
+
/** Options of {@linkcode exportSshPublicKey} and {@linkcode exportOpenSshPrivateKey}. */
|
|
87
|
+
export interface SshExportOptions {
|
|
88
|
+
/** Comment to attach, at most 8192 UTF-8 bytes. Must be well-formed Unicode without CR, LF or NUL. Default: empty. */
|
|
89
|
+
readonly comment?: string;
|
|
90
|
+
}
|
|
91
|
+
/** Machine-readable failure reason of the SSH key export functions. */
|
|
92
|
+
export type SshExportErrorCode = "invalid_key" | "unsupported_algorithm" | "not_extractable" | "invalid_comment";
|
|
93
|
+
/**
|
|
94
|
+
* Import an OpenSSH public-key line (`<type> <base64> [comment]`).
|
|
95
|
+
*
|
|
96
|
+
* Reads `ssh-rsa`, `ssh-ed25519`, and `ecdsa-sha2-nistp256/384/521` keys as
|
|
97
|
+
* written by `ssh-keygen` into `.pub` files. The line key type must equal the
|
|
98
|
+
* type inside the blob (RFC 4253 §6.6), an ECDSA curve identifier must equal
|
|
99
|
+
* its key type suffix (RFC 5656 §3.1), and trailing data after the blob is
|
|
100
|
+
* rejected. Fields are separated by spaces or tabs, one trailing line break
|
|
101
|
+
* is allowed, and everything after the base64 field is the comment.
|
|
102
|
+
* `authorized_keys` options and SSH certificate types are not read.
|
|
103
|
+
*
|
|
104
|
+
* Input is capped at 16 KiB and RSA moduli at 16384 bits. `input` is never
|
|
105
|
+
* modified.
|
|
106
|
+
*
|
|
107
|
+
* @param input - The line as text or UTF-8 bytes
|
|
108
|
+
* @param options - Policy options; see {@linkcode SshImportOptions}
|
|
109
|
+
* @returns The WebCrypto verification key, its comment and its SHA-256 fingerprint
|
|
110
|
+
*
|
|
111
|
+
* @see {@linkcode importSshPublicKeyOrThrow} for the throwing variant
|
|
112
|
+
* @see {@linkcode exportSshPublicKey} for the inverse operation
|
|
113
|
+
*/
|
|
114
|
+
export declare function importSshPublicKey(input: string | Uint8Array, options?: SshImportOptions): Promise<SshResult<ImportedSshPublicKey>>;
|
|
115
|
+
/**
|
|
116
|
+
* Throwing variant of {@linkcode importSshPublicKey}.
|
|
117
|
+
*
|
|
118
|
+
* @throws {ResultError} Carrying an {@linkcode SshErrorCode} as `code`
|
|
119
|
+
*/
|
|
120
|
+
export declare function importSshPublicKeyOrThrow(input: string | Uint8Array, options?: SshImportOptions): Promise<ImportedSshPublicKey>;
|
|
121
|
+
/**
|
|
122
|
+
* Import an unencrypted single-key `openssh-key-v1` private key file.
|
|
123
|
+
*
|
|
124
|
+
* Accepts the `-----BEGIN OPENSSH PRIVATE KEY-----` PEM that `ssh-keygen`
|
|
125
|
+
* writes for RSA, Ed25519 and ECDSA P-256/P-384/P-521 keys. The cipher and
|
|
126
|
+
* KDF must both be `none` with empty KDF options; any other value returns
|
|
127
|
+
* `unsupported`, as does a file holding several keys. The check integers,
|
|
128
|
+
* the `1, 2, 3, ...` padding, the block alignment, and the absence of trailing
|
|
129
|
+
* bytes are verified, and RSA integers must be canonical positive `mpint`s.
|
|
130
|
+
*
|
|
131
|
+
* The public key embedded in the file must equal the public half of the
|
|
132
|
+
* private section and its key type, or the result is `key_mismatch`. The
|
|
133
|
+
* private material is then checked cryptographically: for RSA, `p·q = n`,
|
|
134
|
+
* `d·e ≡ 1` modulo both `p-1` and `q-1`, and `iqmp·q ≡ 1 (mod p)`; for every
|
|
135
|
+
* key, a signature made with the private key must verify under the embedded
|
|
136
|
+
* public key. For Ed25519 the 32-byte suffix of the private field must equal
|
|
137
|
+
* the public key.
|
|
138
|
+
*
|
|
139
|
+
* Both keys are returned extractable. The decoded binary copy of the file is
|
|
140
|
+
* zeroed before returning. JavaScript strings, including the PEM text and the
|
|
141
|
+
* JWK members used for the import, cannot be zeroed, and `input` is never
|
|
142
|
+
* modified.
|
|
143
|
+
*
|
|
144
|
+
* @param input - The PEM file as text or UTF-8 bytes, at most 32 KiB
|
|
145
|
+
* @param options - Policy options; see {@linkcode SshImportOptions}
|
|
146
|
+
*
|
|
147
|
+
* @see {@linkcode importOpenSshPrivateKeyOrThrow} for the throwing variant
|
|
148
|
+
* @see {@linkcode exportOpenSshPrivateKey} for the inverse operation
|
|
149
|
+
*/
|
|
150
|
+
export declare function importOpenSshPrivateKey(input: string | Uint8Array, options?: SshImportOptions): Promise<SshResult<ImportedOpenSshPrivateKey>>;
|
|
151
|
+
/**
|
|
152
|
+
* Throwing variant of {@linkcode importOpenSshPrivateKey}.
|
|
153
|
+
*
|
|
154
|
+
* @throws {ResultError} Carrying an {@linkcode SshErrorCode} as `code`
|
|
155
|
+
*/
|
|
156
|
+
export declare function importOpenSshPrivateKeyOrThrow(input: string | Uint8Array, options?: SshImportOptions): Promise<ImportedOpenSshPrivateKey>;
|
|
157
|
+
/**
|
|
158
|
+
* Export a public key as an OpenSSH public-key line.
|
|
159
|
+
*
|
|
160
|
+
* Writes `<type> <base64> [comment]` with padded base64 and no trailing line
|
|
161
|
+
* break, the form `ssh-keygen` puts in `.pub` files. ECDSA points are written
|
|
162
|
+
* uncompressed. The key must be an extractable RSA, ECDSA (P-256, P-384,
|
|
163
|
+
* P-521) or Ed25519 public `CryptoKey`.
|
|
164
|
+
*
|
|
165
|
+
* @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} as `code`
|
|
166
|
+
*
|
|
167
|
+
* @see {@linkcode importSshPublicKey} for the inverse operation
|
|
168
|
+
*/
|
|
169
|
+
export declare function exportSshPublicKey(publicKey: CryptoKey, options?: SshExportOptions): Promise<string>;
|
|
170
|
+
/**
|
|
171
|
+
* Export a private key as an unencrypted `openssh-key-v1` PEM file.
|
|
172
|
+
*
|
|
173
|
+
* The file holds one key, cipher `none` and KDF `none`, with the check
|
|
174
|
+
* integers drawn from the WebCrypto random source and the public key derived
|
|
175
|
+
* from the private key. `ssh-keygen` reads it directly. Check integers are
|
|
176
|
+
* random, so compare keys, not file bytes, between two exports.
|
|
177
|
+
*
|
|
178
|
+
* The private `CryptoKey` must be extractable. The binary encoding is zeroed
|
|
179
|
+
* after the PEM text is built; the returned string and the JWK used for the
|
|
180
|
+
* export cannot be zeroed.
|
|
181
|
+
*
|
|
182
|
+
* @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} as `code`
|
|
183
|
+
*
|
|
184
|
+
* @see {@linkcode importOpenSshPrivateKey} for the inverse operation
|
|
185
|
+
*/
|
|
186
|
+
export declare function exportOpenSshPrivateKey(privateKey: CryptoKey, options?: SshExportOptions): Promise<string>;
|
|
187
|
+
/**
|
|
188
|
+
* The `SHA256:` fingerprint `ssh-keygen -l -E sha256` prints for a key.
|
|
189
|
+
*
|
|
190
|
+
* It is the SHA-256 digest of the SSH public-key blob (RFC 4253 §6.6 layout),
|
|
191
|
+
* base64-encoded without padding and prefixed with `SHA256:`. It differs from a
|
|
192
|
+
* certificate fingerprint and from a digest of the SPKI encoding. Pass a
|
|
193
|
+
* public or private `CryptoKey`, or the raw blob bytes (the decoded base64
|
|
194
|
+
* field of a public-key line). A private key must be extractable.
|
|
195
|
+
*
|
|
196
|
+
* @throws {ResultError} Carrying an {@linkcode SshExportErrorCode} when a `CryptoKey` cannot be encoded
|
|
197
|
+
*/
|
|
198
|
+
export declare function sshFingerprintSha256(key: CryptoKey | Uint8Array): Promise<string>;
|
|
199
|
+
export type { SshErrorCode };
|
|
200
|
+
//# sourceMappingURL=ssh.d.ts.map
|