@softistx/alxia-clavix 0.0.0-stage → 0.3.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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/dist/clavix.d.ts +85 -0
  4. package/dist/clavix.d.ts.map +1 -0
  5. package/dist/dpop/htu.d.ts +11 -0
  6. package/dist/dpop/htu.d.ts.map +1 -0
  7. package/dist/dpop/index.d.ts +6 -0
  8. package/dist/dpop/index.d.ts.map +1 -0
  9. package/dist/dpop/jwk.d.ts +20 -0
  10. package/dist/dpop/jwk.d.ts.map +1 -0
  11. package/dist/dpop/nonce.d.ts +29 -0
  12. package/dist/dpop/nonce.d.ts.map +1 -0
  13. package/dist/dpop/options.d.ts +33 -0
  14. package/dist/dpop/options.d.ts.map +1 -0
  15. package/dist/dpop/proof.d.ts +32 -0
  16. package/dist/dpop/proof.d.ts.map +1 -0
  17. package/dist/dpop/replay-store.d.ts +24 -0
  18. package/dist/dpop/replay-store.d.ts.map +1 -0
  19. package/dist/guard.d.ts +19 -0
  20. package/dist/guard.d.ts.map +1 -0
  21. package/dist/index.d.ts +6 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +615 -0
  24. package/dist/index.js.map +22 -0
  25. package/dist/issuers.d.ts +19 -0
  26. package/dist/issuers.d.ts.map +1 -0
  27. package/dist/lru.d.ts +10 -0
  28. package/dist/lru.d.ts.map +1 -0
  29. package/dist/principal.d.ts +25 -0
  30. package/dist/principal.d.ts.map +1 -0
  31. package/dist/scope.d.ts +30 -0
  32. package/dist/scope.d.ts.map +1 -0
  33. package/dist/unverified-issuer.d.ts +3 -0
  34. package/dist/unverified-issuer.d.ts.map +1 -0
  35. package/docs/README.md +14 -0
  36. package/docs/guide/issuers-and-tenants.md +70 -0
  37. package/docs/guide/principal-and-scopes.md +59 -0
  38. package/docs/guide/readiness.md +31 -0
  39. package/docs/guide/security.md +128 -0
  40. package/docs/roadmap.md +38 -0
  41. package/docs/troubleshooting.md +269 -0
  42. package/package.json +52 -5
@@ -0,0 +1,22 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/clavix.ts", "../src/dpop/jwk.ts", "../src/dpop/nonce.ts", "../src/dpop/options.ts", "../src/dpop/htu.ts", "../src/dpop/proof.ts", "../src/dpop/replay-store.ts", "../src/guard.ts", "../src/issuers.ts", "../src/lru.ts", "../src/principal.ts", "../src/unverified-issuer.ts", "../src/scope.ts"],
4
+ "sourcesContent": [
5
+ "import {\n\tcreateJwt,\n\ttype JwksJwt,\n\ttype JwksOptions,\n\ttype Verifier,\n} from '@softistx/alxia-jwt';\nimport { type DpopOptions, resolveDpop } from './dpop';\nimport { type ClavixGuard, guard } from './guard';\nimport {\n\ttype IssuerRules,\n\tlistIssuers,\n\tnormaliseDomain,\n\tresolveIssuer,\n} from './issuers';\nimport { Lru } from './lru';\nimport { principalSchema } from './principal';\nimport { unverifiedIssuer } from './unverified-issuer';\n\nexport interface ClavixOptions\n\textends Pick<\n\t\tJwksOptions,\n\t\t| 'audience'\n\t\t| 'cacheMs'\n\t\t| 'staleMs'\n\t\t| 'refetchMs'\n\t\t| 'timeoutMs'\n\t\t| 'clockTolerance'\n\t\t| 'algorithms'\n\t> {\n\t/**\n\t * The deployment's domain: an issuer `https://<tenant>.<domain>` is\n\t * allowed, with exactly one DNS label in front of it.\n\t */\n\treadonly domain?: string;\n\t/**\n\t * Issuers allowed beside the pattern (custom domains, a test issuer): a\n\t * list, or `{ issuer: tenant }` to name the tenant each one stands for.\n\t * Compared byte for byte.\n\t */\n\treadonly issuers?: readonly string[] | Readonly<Record<string, string>>;\n\t/** The API's identifier, which a token's `aud` must contain. */\n\treadonly audience: string;\n\t/**\n\t * Issuers whose keys are kept at once, once a token from them has\n\t * verified; the least recently used is dropped past it. 100 by default.\n\t * `warm` issuers are not counted.\n\t */\n\treadonly maxIssuers?: number;\n\t/**\n\t * Issuers met but not yet proven, kept in a small cache of their own: one\n\t * moves to the `maxIssuers` cache only when a token from it verifies, so\n\t * forged issuers can only push each other out. `min(maxIssuers, 16)` by\n\t * default.\n\t */\n\treadonly probation?: number;\n\t/**\n\t * Issuers whose keys `ready` waits for, each allowed by the same rules as\n\t * a token's issuer (a TypeError otherwise). They are pinned: never\n\t * evicted, and not counted against `maxIssuers`. Left out, `ready` is\n\t * always ready.\n\t */\n\treadonly warm?: readonly string[];\n\t/**\n\t * Verifies the DPoP proof of sender-constrained tokens (RFC 9449) and\n\t * accepts the `DPoP` scheme. Left out, a token bound to a key (`cnf.jkt`)\n\t * is refused outright, as a bearer or as `DPoP`.\n\t */\n\treadonly dpop?: DpopOptions;\n}\n\nexport interface ClavixVerifier extends Verifier {\n\t/**\n\t * The tenant of an issuer the options allow: the slug of a pattern issuer,\n\t * the mapped name of a listed one. `undefined` for a refused issuer, and\n\t * for a listed issuer given without a tenant.\n\t */\n\ttenantOf(issuer: string): string | undefined;\n\t/**\n\t * A readiness check for `health({ checks: { clavix: auth.ready } })`:\n\t * resolves `true` once the keys of every `warm` issuer are loaded (a set\n\t * within `cacheMs`, or stale within `staleMs`), `false` otherwise, and\n\t * never throws. With no `warm` issuer it is always `true`: keys are then\n\t * fetched on a tenant's first token, and a probe cannot wait for tenants\n\t * it does not know.\n\t */\n\tready(): Promise<boolean>;\n\t/**\n\t * A guard, as `@softistx/alxia-jwt`'s `bearer()` (same 401s and cookie mode): the\n\t * routes after it read a `ClavixPrincipal` as `user`. A token whose claims\n\t * are malformed (no `sub`, `iss` or `client_id`, a bad `scope`, `roles`,\n\t * `permissions` or `cnf`) is a 401 `malformed`, refused by the RFC 9068\n\t * profile before the principal is built; reason `claims` is only for a\n\t * listed issuer with no tenant (give `{ issuer: tenant }`).\n\t */\n\tbearer(options?: {\n\t\t/** Reads the token from this cookie when no `Authorization` header carries one. */\n\t\treadonly cookie?: string;\n\t}): ClavixGuard;\n}\n\n/** The options handed on to `createJwt`: nothing else of `options` reaches it. */\nconst PASSTHROUGH = [\n\t'audience',\n\t'cacheMs',\n\t'staleMs',\n\t'refetchMs',\n\t'timeoutMs',\n\t'clockTolerance',\n\t'algorithms',\n] as const;\n\n/** The defined `keys` of `source`, typed as such. */\nfunction pick<T extends object, K extends keyof T>(\n\tsource: T,\n\tkeys: readonly K[],\n): Pick<T, K> {\n\tconst picked: Partial<Pick<T, K>> = {};\n\tfor (const key of keys) {\n\t\tif (source[key] !== undefined) picked[key] = source[key];\n\t}\n\treturn picked as Pick<T, K>;\n}\n\n/** The rules that say which issuers a verifier trusts, from its options (a TypeError when they give none). */\nfunction issuerRules(options: ClavixOptions): IssuerRules {\n\tif (options.domain === undefined && options.issuers === undefined) {\n\t\tthrow new TypeError('clavix: give domain, issuers, or both');\n\t}\n\tif (typeof options.audience !== 'string' || options.audience === '') {\n\t\tthrow new TypeError('clavix: audience is required');\n\t}\n\tconst listed = listIssuers(options.issuers ?? []);\n\tif (options.domain === undefined && listed.size === 0) {\n\t\tthrow new TypeError('clavix: give domain, issuers, or both');\n\t}\n\treturn {\n\t\tdomain:\n\t\t\toptions.domain === undefined\n\t\t\t\t? undefined\n\t\t\t\t: normaliseDomain(options.domain),\n\t\tlisted,\n\t};\n}\n\n/** A positive integer option, or its default. */\nfunction count(name: string, value: number | undefined, fallback: number) {\n\tconst n = value ?? fallback;\n\tif (!Number.isInteger(n) || n < 1) {\n\t\tthrow new TypeError(`clavix: ${name} must be a positive integer`);\n\t}\n\treturn n;\n}\n\n/**\n * A verifier of the access tokens Clavix issues, for any tenant: a token is\n * checked with the keys of its own issuer, but only an issuer the options\n * allow is ever fetched from.\n *\n * ```ts\n * const verifier = clavix({ domain: 'clavix.example', audience: 'https://api.example' });\n * const result = await verifier.verify(token);\n * ```\n */\nexport function clavix(options: ClavixOptions): ClavixVerifier {\n\tconst rules = issuerRules(options);\n\tconst max = count('maxIssuers', options.maxIssuers, 100);\n\tconst probationSize = count(\n\t\t'probation',\n\t\toptions.probation,\n\t\tMath.min(max, 16),\n\t);\n\tconst passthrough = pick(options, PASSTHROUGH);\n\tconst create = (issuer: string): JwksJwt =>\n\t\tcreateJwt({ ...passthrough, discovery: issuer, profile: 'rfc9068' });\n\n\t// Pinned: never evicted, not counted in `max`.\n\tconst pinned = new Map<string, JwksJwt>();\n\tfor (const issuer of options.warm ?? []) {\n\t\tif (resolveIssuer(rules, issuer) === undefined) {\n\t\t\tthrow new TypeError(`clavix: warm issuer ${issuer} is not allowed`);\n\t\t}\n\t\tpinned.set(issuer, create(issuer));\n\t}\n\t// Proven issuers, then issuers met but not yet proven by a verified token.\n\tconst proven = new Lru<JwksJwt>(max);\n\tconst probation = new Lru<JwksJwt>(probationSize);\n\tconst verifierOf = (issuer: string): JwksJwt => {\n\t\tconst known = pinned.get(issuer) ?? proven.get(issuer);\n\t\tif (known !== undefined) return known;\n\t\tlet verifier = probation.get(issuer);\n\t\tif (verifier === undefined) {\n\t\t\tverifier = create(issuer);\n\t\t\tprobation.set(issuer, verifier);\n\t\t}\n\t\treturn verifier;\n\t};\n\tconst tenantOf = (issuer: string) => resolveIssuer(rules, issuer)?.tenant;\n\tconst schema = principalSchema(tenantOf);\n\tconst dpop =\n\t\toptions.dpop === undefined ? undefined : resolveDpop(options.dpop);\n\n\tconst self: ClavixVerifier = {\n\t\ttenantOf,\n\t\tready: async () =>\n\t\t\t(await Promise.all([...pinned.values()].map((v) => v.ready()))).every(\n\t\t\t\tBoolean,\n\t\t\t),\n\t\tbearer: (guardOptions) =>\n\t\t\tguard({ jwt: self, schema, dpop, cookie: guardOptions?.cookie }),\n\t\tasync verify(token) {\n\t\t\tconst issuer = unverifiedIssuer(token);\n\t\t\tif (issuer === undefined) return { ok: false, reason: 'malformed' };\n\t\t\tif (resolveIssuer(rules, issuer) === undefined) {\n\t\t\t\treturn { ok: false, reason: 'issuer' };\n\t\t\t}\n\t\t\tconst verifier = verifierOf(issuer);\n\t\t\tconst result = await verifier.verify(token);\n\t\t\t// one verified token proves the issuer: it leaves probation\n\t\t\tif (result.ok && probation.get(issuer) === verifier) {\n\t\t\t\tprobation.delete(issuer);\n\t\t\t\tproven.set(issuer, verifier);\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n\treturn self;\n}\n",
6
+ "import type { DpopAlgorithm } from './options';\n\n/** The members of a proof's header, claims and key that are read. */\nexport type Fields = Partial<\n\tRecord<\n\t\t| 'typ'\n\t\t| 'alg'\n\t\t| 'jwk'\n\t\t| 'crit'\n\t\t| 'htm'\n\t\t| 'htu'\n\t\t| 'iat'\n\t\t| 'jti'\n\t\t| 'ath'\n\t\t| 'nonce'\n\t\t| 'd'\n\t\t| 'kty'\n\t\t| 'crv'\n\t\t| 'x'\n\t\t| 'y',\n\t\tunknown\n\t>\n>;\n\nexport const encoder = new TextEncoder();\n\nexport const isObject = (value: unknown): value is Fields =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** A JWT part as an object, or `undefined`. */\nexport function decode(part: string): Fields | undefined {\n\ttry {\n\t\tconst value: unknown = JSON.parse(\n\t\t\tBuffer.from(part, 'base64url').toString('utf8'),\n\t\t);\n\t\treturn isObject(value) ? value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport interface ProofKey {\n\treadonly jwk: JsonWebKey;\n\treadonly params: EcKeyImportParams | Algorithm;\n}\n\n/**\n * The public key of a proof's header, kept to its public members, with its\n * algorithm's import parameters; `undefined` for a private key, another\n * curve, or a key that does not fit `alg`.\n */\nexport function publicKey(\n\tjwk: Fields,\n\talg: DpopAlgorithm,\n): ProofKey | undefined {\n\tif (jwk.d !== undefined) return undefined;\n\tconst text = (name: 'kty' | 'crv' | 'x' | 'y') => {\n\t\tconst value = jwk[name];\n\t\treturn typeof value === 'string' ? value : undefined;\n\t};\n\tconst [kty, crv, x, y] = [text('kty'), text('crv'), text('x'), text('y')];\n\tif (alg === 'ES256') {\n\t\tif (kty !== 'EC' || crv !== 'P-256' || !x || !y) return undefined;\n\t\treturn {\n\t\t\tjwk: { kty, crv, x, y },\n\t\t\tparams: { name: 'ECDSA', namedCurve: 'P-256' },\n\t\t};\n\t}\n\tif (kty !== 'OKP' || crv !== 'Ed25519' || !x) return undefined;\n\treturn { jwk: { kty, crv, x }, params: { name: 'Ed25519' } };\n}\n\n/** The RFC 7638 thumbprint of a public JWK made by `publicKey`. */\nexport async function jwkThumbprint(jwk: JsonWebKey): Promise<string> {\n\tconst members =\n\t\tjwk.kty === 'EC'\n\t\t\t? { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }\n\t\t\t: { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n\tconst digest = await crypto.subtle.digest(\n\t\t'SHA-256',\n\t\tencoder.encode(JSON.stringify(members)),\n\t);\n\treturn Buffer.from(digest).toString('base64url');\n}\n",
7
+ "/**\n * The server nonce of RFC 9449 section 8: `issue` makes the nonce a client\n * must put in its next proof, `accepts` tells whether a nonce is still valid.\n */\nexport interface DpopNonce {\n\tissue(): string | Promise<string>;\n\taccepts(nonce: string): boolean | Promise<boolean>;\n\t/**\n\t * A fresh nonce for a client whose accepted `nonce` is near its end\n\t * (RFC 9449 section 8.2), sent as `DPoP-Nonce` on the answer so the next\n\t * proof does not meet a `use_dpop_nonce` refusal; `undefined` while it\n\t * has time left.\n\t */\n\trenew?(nonce: string): string | Promise<string | undefined> | undefined;\n}\n\nconst encoder = new TextEncoder();\n\n/** Constant-time equality of two strings. */\nexport function timingSafeEqual(a: string, b: string): boolean {\n\tconst x = encoder.encode(a);\n\tconst y = encoder.encode(b);\n\tif (x.length !== y.length) return false;\n\tlet diff = 0;\n\tfor (let i = 0; i < x.length; i++) {\n\t\tdiff |= (x[i] as number) ^ (y[i] as number);\n\t}\n\treturn diff === 0;\n}\n\n/**\n * A stateless nonce: a time stamp signed with a key derived from `secret`\n * (HMAC-SHA-256, with a label of its own, so the same secret may serve\n * elsewhere), valid for `ttlMs` (5 minutes by default). Every instance\n * sharing `secret` accepts the nonces of the others, with nothing stored.\n * The secret needs 16 characters.\n */\nexport function hmacDpopNonce(options: {\n\treadonly secret: string;\n\treadonly ttlMs?: number;\n}): DpopNonce {\n\tconst ttlMs = options.ttlMs ?? 300_000;\n\tif (!(Number.isFinite(ttlMs) && ttlMs > 0)) {\n\t\tthrow new TypeError(\n\t\t\t'clavix: the dpop nonce ttlMs must be a finite number above 0',\n\t\t);\n\t}\n\tif (typeof options.secret !== 'string' || options.secret.length < 16) {\n\t\tthrow new TypeError('clavix: the dpop nonce secret needs 16 characters');\n\t}\n\tconst hmac = (raw: BufferSource) =>\n\t\tcrypto.subtle.importKey(\n\t\t\t'raw',\n\t\t\traw,\n\t\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\t\tfalse,\n\t\t\t['sign'],\n\t\t);\n\tconst key = (async () => {\n\t\tconst master = await hmac(encoder.encode(options.secret));\n\t\tconst derived = await crypto.subtle.sign(\n\t\t\t'HMAC',\n\t\t\tmaster,\n\t\t\tencoder.encode('@softistx/alxia-clavix dpop nonce v1'),\n\t\t);\n\t\treturn hmac(derived);\n\t})();\n\tconst mac = async (stamp: string) =>\n\t\tBuffer.from(\n\t\t\tawait crypto.subtle.sign('HMAC', await key, encoder.encode(stamp)),\n\t\t).toString('base64url');\n\tconst issue = async () => {\n\t\tconst stamp = String(Date.now());\n\t\treturn `${stamp}.${await mac(stamp)}`;\n\t};\n\treturn {\n\t\tissue,\n\t\tasync accepts(nonce) {\n\t\t\tconst [stamp, signature, ...rest] = nonce.split('.');\n\t\t\tif (stamp === undefined || signature === undefined || rest.length > 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!/^\\d{1,16}$/.test(stamp)) return false;\n\t\t\tconst age = Date.now() - Number(stamp);\n\t\t\tif (age < -1000 || age > ttlMs) return false;\n\t\t\treturn timingSafeEqual(signature, await mac(stamp));\n\t\t},\n\t\tasync renew(nonce) {\n\t\t\tconst age = Date.now() - Number(nonce.split('.')[0]);\n\t\t\treturn age > ttlMs / 2 ? await issue() : undefined;\n\t\t},\n\t};\n}\n",
8
+ "import type { DpopNonce } from './nonce';\nimport type { DpopReplayStore } from './replay-store';\n\n/** The signature algorithms a DPoP proof may use (RFC 9449 section 4.2). */\nexport type DpopAlgorithm = 'ES256' | 'EdDSA';\n\nexport interface DpopOptions {\n\t/**\n\t * The origin clients use to reach the API (`https://api.example.com`), what\n\t * a proof's `htu` must start with. Behind a proxy the request's own URL is\n\t * the internal one: this is the public one, never read from a header.\n\t */\n\treadonly origin: string;\n\t/** Where the `jti` of accepted proofs are remembered: `redisDpopReplayStore` in production, `memoryDpopReplayStore()` for tests. */\n\treadonly replay: DpopReplayStore;\n\t/** Proof algorithms accepted, `['ES256', 'EdDSA']` by default. */\n\treadonly algorithms?: readonly DpopAlgorithm[];\n\t/** How old a proof's `iat` may be, in seconds. 60 by default. */\n\treadonly maxAgeSec?: number;\n\t/** How far ahead of this server's clock an `iat` may be, in seconds. 5 by default. */\n\treadonly clockSkewSec?: number;\n\t/** Asks clients for a server nonce (RFC 9449 section 8): `hmacDpopNonce({ secret })`. Off by default. */\n\treadonly nonce?: DpopNonce;\n}\n\nexport interface ResolvedDpop {\n\treadonly origin: string;\n\treadonly replay: DpopReplayStore;\n\treadonly algorithms: readonly DpopAlgorithm[];\n\treadonly maxAgeSec: number;\n\treadonly clockSkewSec: number;\n\treadonly nonce: DpopNonce | undefined;\n}\n\n/** The options, checked, with their defaults. */\nexport function resolveDpop(options: DpopOptions): ResolvedDpop {\n\tlet origin: string;\n\ttry {\n\t\tconst url = new URL(options.origin);\n\t\tif (\n\t\t\t(url.protocol !== 'https:' && url.protocol !== 'http:') ||\n\t\t\turl.pathname !== '/' ||\n\t\t\turl.search !== '' ||\n\t\t\turl.hash !== '' ||\n\t\t\turl.username !== '' ||\n\t\t\turl.password !== ''\n\t\t) {\n\t\t\tthrow new Error('not an origin');\n\t\t}\n\t\torigin = url.origin;\n\t} catch {\n\t\tthrow new TypeError(\n\t\t\t`clavix: dpop.origin must be an origin such as \"https://api.example.com\", got ${JSON.stringify(options.origin)}`,\n\t\t);\n\t}\n\tif (typeof options.replay?.claim !== 'function') {\n\t\tthrow new TypeError('clavix: dpop.replay is required');\n\t}\n\tconst algorithms = options.algorithms ?? ['ES256', 'EdDSA'];\n\tif (\n\t\talgorithms.length === 0 ||\n\t\t!algorithms.every((a) => a === 'ES256' || a === 'EdDSA')\n\t) {\n\t\tthrow new TypeError('clavix: dpop.algorithms takes ES256, EdDSA or both');\n\t}\n\tconst maxAgeSec = options.maxAgeSec ?? 60;\n\tconst clockSkewSec = options.clockSkewSec ?? 5;\n\tif (!(Number.isFinite(maxAgeSec) && maxAgeSec > 0)) {\n\t\tthrow new TypeError(\n\t\t\t'clavix: dpop.maxAgeSec must be a finite number above 0',\n\t\t);\n\t}\n\tif (!(Number.isFinite(clockSkewSec) && clockSkewSec >= 0)) {\n\t\tthrow new TypeError(\n\t\t\t'clavix: dpop.clockSkewSec must be a finite number, 0 or more',\n\t\t);\n\t}\n\treturn {\n\t\torigin,\n\t\treplay: options.replay,\n\t\talgorithms,\n\t\tmaxAgeSec,\n\t\tclockSkewSec,\n\t\tnonce: options.nonce,\n\t};\n}\n",
9
+ "/**\n * Whether a proof's `htu` names this request: the configured public origin\n * (already normalised by `resolveDpop`) and the request's path, the query and the fragment ignored (RFC 9449\n * section 4.3). The scheme and host compare without case and without a\n * default port (`:443`, `:80`) as URL parsing normalises them; the path\n * compares exactly (a trailing slash matters; percent-escapes compare as\n * written, RFC 3986 6.2.2 normalisation is not applied, which can only refuse); a `htu` with userinfo never\n * matches.\n */\nexport function sameUrl(htu: string, origin: string, path: string): boolean {\n\ttry {\n\t\tconst claimed = new URL(htu);\n\t\tif (claimed.username !== '' || claimed.password !== '') return false;\n\t\t// never `new URL(path, origin)`: a path such as `//host/x` would replace the origin\n\t\treturn claimed.origin === origin && claimed.pathname === path;\n\t} catch {\n\t\treturn false;\n\t}\n}\n",
10
+ "import { sameUrl } from './htu';\nimport {\n\tdecode,\n\tencoder,\n\ttype Fields,\n\tisObject,\n\tjwkThumbprint,\n\ttype ProofKey,\n\tpublicKey,\n} from './jwk';\nimport { timingSafeEqual } from './nonce';\nimport type { DpopAlgorithm, ResolvedDpop } from './options';\n\n/** Why a request's DPoP check failed. */\nexport type DpopReason =\n\t| 'dpop_required'\n\t| 'dpop_unsupported'\n\t| 'dpop_unbound'\n\t| 'dpop_proof_missing'\n\t| 'dpop_proof_malformed'\n\t| 'dpop_proof_type'\n\t| 'dpop_proof_algorithm'\n\t| 'dpop_proof_key'\n\t| 'dpop_proof_signature'\n\t| 'dpop_proof_method'\n\t| 'dpop_proof_url'\n\t| 'dpop_proof_iat'\n\t| 'dpop_proof_jti'\n\t| 'dpop_proof_ath'\n\t| 'dpop_proof_thumbprint'\n\t| 'dpop_proof_replay'\n\t| 'dpop_malformed'\n\t| 'dpop_nonce';\n\nexport type ProofResult =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** A fresh nonce to send as `DPoP-Nonce`: the accepted one is near its end. */\n\t\t\treadonly nonce?: string;\n\t }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly reason: DpopReason;\n\t\t\t/** Set with `dpop_nonce`: the nonce the client must use. */\n\t\t\treadonly nonce?: string;\n\t };\n\nexport interface ProofInput {\n\t/** The `DPoP` header value. */\n\treadonly proof: string | null;\n\t/** The request's method. */\n\treadonly method: string;\n\t/** The request's path, as the client sent it. */\n\treadonly path: string;\n\t/** The access token the proof is bound to. */\n\treadonly accessToken: string;\n\t/** The token's `cnf.jkt`. */\n\treadonly jkt: string;\n}\n\nconst MAX_JTI = 256;\n/** A proof stays remembered a little past the end of its `iat` window. */\nconst REMEMBER_MARGIN_MS = 5000;\nconst fail = (reason: DpopReason): ProofResult => ({ ok: false, reason });\n\ninterface Parsed {\n\treadonly head: string;\n\treadonly body: string;\n\treadonly signature: string;\n\treadonly header: Fields;\n\treadonly claims: Fields;\n}\n\n/** The three parts of a proof, decoded, or the reason it is no JWT. */\nfunction parse(proof: string): Parsed | DpopReason {\n\tconst parts = proof.split('.');\n\tif (parts.length !== 3) return 'dpop_proof_malformed';\n\tconst [head, body, signature] = parts as [string, string, string];\n\tconst header = decode(head);\n\tconst claims = decode(body);\n\t// `crit` names extensions this server does not know: RFC 7515 4.1.11 refuses them\n\tif (header === undefined || claims === undefined || 'crit' in header) {\n\t\treturn 'dpop_proof_malformed';\n\t}\n\treturn { head, body, signature, header, claims };\n}\n\n/**\n * The proof's key, once its header is right (`typ` exactly `dpop+jwt`, an\n * accepted `alg`, a public `jwk`) and its signature verifies with it.\n */\nasync function verifySignature(\n\tparsed: Parsed,\n\talgorithms: readonly DpopAlgorithm[],\n): Promise<ProofKey | DpopReason> {\n\tconst { header } = parsed;\n\tif (header.typ !== 'dpop+jwt') return 'dpop_proof_type';\n\tconst alg = algorithms.find((a) => a === header.alg);\n\tif (alg === undefined) return 'dpop_proof_algorithm';\n\tif (!isObject(header.jwk)) return 'dpop_proof_key';\n\tconst key = publicKey(header.jwk, alg);\n\tif (key === undefined) return 'dpop_proof_key';\n\ttry {\n\t\tconst valid = await crypto.subtle.verify(\n\t\t\talg === 'ES256'\n\t\t\t\t? { name: 'ECDSA', hash: 'SHA-256' }\n\t\t\t\t: { name: 'Ed25519' },\n\t\t\tawait crypto.subtle.importKey('jwk', key.jwk, key.params, false, [\n\t\t\t\t'verify',\n\t\t\t]),\n\t\t\tBuffer.from(parsed.signature, 'base64url'),\n\t\t\tencoder.encode(`${parsed.head}.${parsed.body}`),\n\t\t);\n\t\treturn valid ? key : 'dpop_proof_signature';\n\t} catch {\n\t\treturn 'dpop_proof_signature';\n\t}\n}\n\n/** The claims that tie the proof to this request and this token. */\nasync function checkClaims(\n\tclaims: Fields,\n\tinput: ProofInput,\n\toptions: ResolvedDpop,\n\tkey: ProofKey,\n): Promise<DpopReason | { readonly jti: string }> {\n\tif (claims.htm !== input.method) return 'dpop_proof_method';\n\tif (\n\t\ttypeof claims.htu !== 'string' ||\n\t\t!sameUrl(claims.htu, options.origin, input.path)\n\t) {\n\t\treturn 'dpop_proof_url';\n\t}\n\tconst nowSec = Date.now() / 1000;\n\tconst { iat, jti } = claims;\n\tif (\n\t\ttypeof iat !== 'number' ||\n\t\t!Number.isFinite(iat) ||\n\t\tiat < nowSec - options.maxAgeSec ||\n\t\tiat > nowSec + options.clockSkewSec\n\t) {\n\t\treturn 'dpop_proof_iat';\n\t}\n\tif (typeof jti !== 'string' || jti === '' || jti.length > MAX_JTI) {\n\t\treturn 'dpop_proof_jti';\n\t}\n\tconst hash = await crypto.subtle.digest(\n\t\t'SHA-256',\n\t\tencoder.encode(input.accessToken),\n\t);\n\tif (\n\t\ttypeof claims.ath !== 'string' ||\n\t\t!timingSafeEqual(claims.ath, Buffer.from(hash).toString('base64url'))\n\t) {\n\t\treturn 'dpop_proof_ath';\n\t}\n\tif (!timingSafeEqual(await jwkThumbprint(key.jwk), input.jkt)) {\n\t\treturn 'dpop_proof_thumbprint';\n\t}\n\treturn { jti };\n}\n\n/**\n * Checks a DPoP proof against RFC 9449 section 4.3, in the cheap-to-costly\n * order, and remembers its `jti` last: a proof refused for anything else is\n * never recorded.\n */\nexport async function verifyProof(\n\tinput: ProofInput,\n\toptions: ResolvedDpop,\n): Promise<ProofResult> {\n\tif (input.proof === null || input.proof === '') {\n\t\treturn fail('dpop_proof_missing');\n\t}\n\tconst parsed = parse(input.proof);\n\tif (typeof parsed === 'string') return fail(parsed);\n\tconst key = await verifySignature(parsed, options.algorithms);\n\tif (typeof key === 'string') return fail(key);\n\tconst checked = await checkClaims(parsed.claims, input, options, key);\n\tif (typeof checked === 'string') return fail(checked);\n\tlet renewed: string | undefined;\n\tif (options.nonce !== undefined) {\n\t\tconst { nonce } = parsed.claims;\n\t\tif (typeof nonce === 'string' && (await options.nonce.accepts(nonce))) {\n\t\t\trenewed = await options.nonce.renew?.(nonce);\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: 'dpop_nonce',\n\t\t\t\tnonce: await options.nonce.issue(),\n\t\t\t};\n\t\t}\n\t}\n\tconst ttlMs =\n\t\t(options.maxAgeSec + options.clockSkewSec) * 1000 + REMEMBER_MARGIN_MS;\n\tconst first = await options.replay.claim(\n\t\t`${input.jkt}:${checked.jti}`,\n\t\tttlMs,\n\t);\n\tif (!first) return fail('dpop_proof_replay');\n\treturn renewed === undefined ? { ok: true } : { ok: true, nonce: renewed };\n}\n",
11
+ "/**\n * Remembers the `jti` of the proofs already accepted, so that a proof is\n * used once. `claim` records `key` for `ttlMs` and answers `true` the first\n * time, `false` while it is still remembered. It must be atomic across the\n * processes that serve the API (Redis `SET NX PX`), and it may throw: a store\n * that cannot answer fails the request (a 500), it never lets a proof\n * through unchecked.\n */\nexport interface DpopReplayStore {\n\tclaim(key: string, ttlMs: number): Promise<boolean>;\n}\n\n/**\n * A replay store in the memory of this process: **for tests and a single\n * instance only**. Two instances behind a load balancer each have their own\n * memory, so a proof replayed on the other one is accepted: use\n * `redisDpopReplayStore` from `@softistx/alxia-redis` there. It holds at\n * most `maxEntries` live proofs (10 000 by default) and throws past that,\n * rather than growing without bound or forgetting a proof. Once full, each\n * claim first sweeps the expired entries, which costs O(`maxEntries`).\n */\nexport function memoryDpopReplayStore(\n\toptions: { readonly maxEntries?: number } = {},\n): DpopReplayStore {\n\tconst max = options.maxEntries ?? 10_000;\n\tconst seen = new Map<string, number>();\n\treturn {\n\t\tasync claim(key, ttlMs) {\n\t\t\tconst now = Date.now();\n\t\t\tconst until = seen.get(key);\n\t\t\tif (until !== undefined && until > now) return false;\n\t\t\tif (seen.size >= max) {\n\t\t\t\tfor (const [stored, expiry] of seen) {\n\t\t\t\t\tif (expiry <= now) seen.delete(stored);\n\t\t\t\t}\n\t\t\t\tif (seen.size >= max) {\n\t\t\t\t\tthrow new Error('memoryDpopReplayStore: full (use a shared store)');\n\t\t\t\t}\n\t\t\t}\n\t\t\tseen.set(key, now + ttlMs);\n\t\t\treturn true;\n\t\t},\n\t};\n}\n",
12
+ "import type { StandardSchemaV1 } from '@softistx/alxia';\nimport {\n\ttype Bearer,\n\ttype BearerExtension,\n\tbearer,\n\ttype UnauthorizedBody,\n\ttype UnauthorizedProblem,\n\ttype Verifier,\n} from '@softistx/alxia-jwt';\nimport { type DpopReason, type ResolvedDpop, verifyProof } from './dpop';\nimport type { ClavixPrincipal } from './principal';\n\n/** The body of a Clavix 401: the reasons of `@softistx/alxia-jwt`'s, and the DPoP ones. */\nexport type ClavixUnauthorizedBody = UnauthorizedBody<DpopReason>;\n\n/** The 401 under `alxia({ errors: 'problem' })`. */\nexport type ClavixUnauthorizedProblem = UnauthorizedProblem<DpopReason>;\n\n/** What `clavix().bearer()` makes: a middleware that gives `user`, or answers the 401. */\nexport type ClavixGuard = Bearer<\n\tStandardSchemaV1<unknown, ClavixPrincipal>,\n\tDpopReason\n>;\n\nexport interface GuardOptions {\n\treadonly jwt: Verifier;\n\treadonly schema: StandardSchemaV1<unknown, ClavixPrincipal>;\n\treadonly cookie?: string | undefined;\n\treadonly dpop?: ResolvedDpop | undefined;\n}\n\n/**\n * The token's `cnf.jkt`: `undefined` for a token with no key binding,\n * `null` when `cnf` is present but not a plain object, or has a `jkt` that\n * is not a non-empty string (so the\n * guard does not depend on the verifier's profile to refuse it).\n */\nfunction boundKey(claims: {\n\treadonly cnf?: unknown;\n}): string | null | undefined {\n\tconst { cnf } = claims;\n\tif (cnf === undefined) return undefined;\n\tif (typeof cnf !== 'object' || cnf === null || Array.isArray(cnf)) {\n\t\treturn null;\n\t}\n\tif (!('jkt' in cnf)) return undefined;\n\treturn typeof cnf.jkt === 'string' && cnf.jkt !== '' ? cnf.jkt : null;\n}\n\nconst isProofReason = (reason: string): boolean =>\n\treason.startsWith('dpop_proof_');\n\n/** The DPoP half of the guard, as an extension of `@softistx/alxia-jwt`'s `bearer()`. */\nfunction dpopExtension(\n\tdpop: ResolvedDpop | undefined,\n): BearerExtension<DpopReason> {\n\tconst algs = dpop?.algorithms.join(' ') ?? '';\n\tconst scheme = (error: string, description?: string) =>\n\t\t`DPoP error=\"${error}\"${description === undefined ? '' : `, error_description=\"${description}\"`}, algs=\"${algs}\"`;\n\treturn {\n\t\tschemes: ['DPoP'],\n\t\tasync bound({ request, token, scheme: used, claims }) {\n\t\t\tconst jkt = boundKey(claims);\n\t\t\tif (jkt === null) return { reason: 'dpop_malformed' };\n\t\t\tif (used !== 'DPoP') {\n\t\t\t\t// a bound token as a bearer is a stolen token: no proof was given\n\t\t\t\treturn jkt === undefined ? undefined : { reason: 'dpop_required' };\n\t\t\t}\n\t\t\tif (dpop === undefined) return { reason: 'dpop_unsupported' };\n\t\t\tif (jkt === undefined) return { reason: 'dpop_unbound' };\n\t\t\tconst proof = await verifyProof(\n\t\t\t\t{\n\t\t\t\t\tproof: request.headers.get('dpop'),\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\tpath: new URL(request.url).pathname,\n\t\t\t\t\taccessToken: token,\n\t\t\t\t\tjkt,\n\t\t\t\t},\n\t\t\t\tdpop,\n\t\t\t);\n\t\t\tif (proof.ok) {\n\t\t\t\treturn proof.nonce === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: { headers: { 'dpop-nonce': proof.nonce } };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\treason: proof.reason,\n\t\t\t\t...(proof.nonce === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { headers: { 'dpop-nonce': proof.nonce } }),\n\t\t\t};\n\t\t},\n\t\tchallenge(reason, used) {\n\t\t\tif (dpop === undefined) return undefined;\n\t\t\tif (reason === 'missing') return `Bearer, DPoP algs=\"${algs}\"`;\n\t\t\tif (reason === 'dpop_required') {\n\t\t\t\treturn scheme(\n\t\t\t\t\t'invalid_token',\n\t\t\t\t\t'the token is bound to a key: use the DPoP scheme with a proof',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (reason === 'dpop_unbound') {\n\t\t\t\treturn scheme(\n\t\t\t\t\t'invalid_token',\n\t\t\t\t\t'the token is not bound to a key: use the Bearer scheme',\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (reason === 'dpop_nonce') return scheme('use_dpop_nonce');\n\t\t\tif (isProofReason(reason)) return scheme('invalid_dpop_proof');\n\t\t\t// a token refused under the DPoP scheme is answered in that scheme\n\t\t\tif (used === 'DPoP' && reason !== 'insufficient_user_authentication') {\n\t\t\t\treturn scheme('invalid_token');\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/** The guard of `clavix().bearer()`: `Bearer` and, with `dpop`, `DPoP` tokens. */\nexport function guard(options: GuardOptions): ClavixGuard {\n\treturn bearer({\n\t\tjwt: options.jwt,\n\t\tschema: options.schema,\n\t\t...(options.cookie === undefined ? {} : { cookie: options.cookie }),\n\t\textension: dpopExtension(options.dpop),\n\t});\n}\n",
13
+ "/** The allowed issuers of a Clavix deployment, and the tenant each one stands for. */\nexport interface IssuerRules {\n\t/** A lowercase DNS name without a dot at either end. */\n\treadonly domain: string | undefined;\n\t/** Issuer to tenant (`undefined` when the list gives none). */\n\treadonly listed: ReadonlyMap<string, string | undefined>;\n}\n\nconst LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** `domain` as a lowercase ASCII DNS name, or a `TypeError`. */\nexport function normaliseDomain(domain: string): string {\n\tconst name = domain\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/^\\./, '')\n\t\t.replace(/\\.$/, '');\n\tconst labels = name.split('.');\n\tif (\n\t\tlabels.length < 2 ||\n\t\tname.length > 253 ||\n\t\t!labels.every((label) => LABEL.test(label) && !label.startsWith('xn--'))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`clavix: domain must be an ASCII DNS name such as \"clavix.example\", got ${JSON.stringify(domain)}`,\n\t\t);\n\t}\n\treturn name;\n}\n\n/** The listed issuers as a map; an issuer must be an `https` URL, or `http` on this machine. */\nexport function listIssuers(\n\tissuers: readonly string[] | Readonly<Record<string, string>>,\n): Map<string, string | undefined> {\n\tconst map = new Map<string, string | undefined>();\n\tconst entries: [string, string | undefined][] = Array.isArray(issuers)\n\t\t? issuers.map((issuer) => [issuer, undefined])\n\t\t: Object.entries(issuers);\n\tfor (const [issuer, tenant] of entries) {\n\t\tlet url: URL;\n\t\ttry {\n\t\t\turl = new URL(issuer);\n\t\t} catch {\n\t\t\tthrow new TypeError(`clavix: issuer is not a URL: ${issuer}`);\n\t\t}\n\t\tif (\n\t\t\turl.protocol !== 'https:' &&\n\t\t\t!(url.protocol === 'http:' && LOCAL.has(url.hostname))\n\t\t) {\n\t\t\tthrow new TypeError(`clavix: issuer must be an https URL: ${issuer}`);\n\t\t}\n\t\tif (tenant === '') {\n\t\t\tthrow new TypeError(`clavix: the tenant of ${issuer} is empty`);\n\t\t}\n\t\tmap.set(issuer, tenant);\n\t}\n\treturn map;\n}\n\n/**\n * The slug of `https://<slug>.<domain>`, exactly: one DNS label in front of\n * the domain, lowercase ASCII (so no IDN, no `xn--` look-alike), and no port,\n * userinfo, path, query, fragment, trailing slash or trailing dot.\n */\nfunction slugOf(issuer: string, domain: string): string | undefined {\n\tconst prefix = 'https://';\n\tconst suffix = `.${domain}`;\n\tif (!issuer.startsWith(prefix) || !issuer.endsWith(suffix)) return undefined;\n\tconst label = issuer.slice(prefix.length, issuer.length - suffix.length);\n\treturn LABEL.test(label) && !label.startsWith('xn--') ? label : undefined;\n}\n\n/**\n * Whether `issuer` is allowed, and for which tenant: a listed issuer (byte\n * for byte) first, then the domain pattern. `undefined` when refused.\n */\nexport function resolveIssuer(\n\trules: IssuerRules,\n\tissuer: string,\n): { readonly tenant: string | undefined } | undefined {\n\tif (rules.listed.has(issuer)) return { tenant: rules.listed.get(issuer) };\n\tif (rules.domain === undefined) return undefined;\n\tconst slug = slugOf(issuer, rules.domain);\n\treturn slug === undefined ? undefined : { tenant: slug };\n}\n",
14
+ "/** A map that keeps at most `max` entries, dropping the least recently used. */\nexport class Lru<V> {\n\treadonly #entries = new Map<string, V>();\n\treadonly #max: number;\n\n\tconstructor(max: number) {\n\t\tthis.#max = max;\n\t}\n\n\tget size(): number {\n\t\treturn this.#entries.size;\n\t}\n\n\tget(key: string): V | undefined {\n\t\tconst value = this.#entries.get(key);\n\t\tif (value === undefined) return undefined;\n\t\tthis.#entries.delete(key);\n\t\tthis.#entries.set(key, value);\n\t\treturn value;\n\t}\n\n\tdelete(key: string): void {\n\t\tthis.#entries.delete(key);\n\t}\n\n\tset(key: string, value: V): void {\n\t\tthis.#entries.delete(key);\n\t\tthis.#entries.set(key, value);\n\t\tif (this.#entries.size > this.#max) {\n\t\t\tconst oldest = this.#entries.keys().next();\n\t\t\tif (!oldest.done) this.#entries.delete(oldest.value);\n\t\t}\n\t}\n}\n",
15
+ "import type { StandardSchemaV1 } from '@softistx/alxia';\nimport type { JwtClaims } from '@softistx/alxia-jwt';\n\n/** Who a verified Clavix access token stands for: what routes behind `bearer()` read as `user`. */\nexport interface ClavixPrincipal {\n\t/** The token's `sub`. */\n\treadonly subject: string;\n\t/** The tenant of the issuer: the slug of a pattern issuer, or the mapped name of a listed one. */\n\treadonly tenant: string;\n\t/** The token's `iss`. */\n\treadonly issuer: string;\n\t/** The client the token was issued to (`client_id`). */\n\treadonly clientId: string;\n\t/** The granted scopes: `scope` split on spaces, `[]` when absent. */\n\treadonly scopes: readonly string[];\n\t/** The subject's roles, `[]` when absent. */\n\treadonly roles: readonly string[];\n\t/** The verified claims, untouched (`permissions`, `cnf`, …). */\n\treadonly claims: JwtClaims;\n}\n\nconst isString = (value: unknown): value is string =>\n\ttypeof value === 'string' && value !== '';\n\n/**\n * The Standard Schema that maps verified claims to a principal. A claim an\n * RFC 9068 token must carry but does not is an issue, so a 401 `claims`.\n */\nexport function principalSchema(\n\ttenantOf: (issuer: string) => string | undefined,\n): StandardSchemaV1<unknown, ClavixPrincipal> {\n\treturn {\n\t\t'~standard': {\n\t\t\tversion: 1,\n\t\t\tvendor: '@softistx/alxia-clavix',\n\t\t\tvalidate(value) {\n\t\t\t\tconst claims = value as JwtClaims;\n\t\t\t\tconst issues: { message: string; path: string[] }[] = [];\n\t\t\t\tconst need = (name: string) =>\n\t\t\t\t\tissues.push({ message: `${name} is required`, path: [name] });\n\t\t\t\tconst { iss, sub, client_id: clientId, scope, roles } = claims;\n\t\t\t\tif (!isString(iss)) need('iss');\n\t\t\t\tif (!isString(sub)) need('sub');\n\t\t\t\tif (!isString(clientId)) need('client_id');\n\t\t\t\tif (scope !== undefined && typeof scope !== 'string') {\n\t\t\t\t\tissues.push({ message: 'scope must be a string', path: ['scope'] });\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\troles !== undefined &&\n\t\t\t\t\t!(Array.isArray(roles) && roles.every((r) => typeof r === 'string'))\n\t\t\t\t) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tmessage: 'roles must be an array of strings',\n\t\t\t\t\t\tpath: ['roles'],\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst tenant = isString(iss) ? tenantOf(iss) : undefined;\n\t\t\t\tif (isString(iss) && tenant === undefined) {\n\t\t\t\t\tissues.push({ message: 'the issuer has no tenant', path: ['iss'] });\n\t\t\t\t}\n\t\t\t\tif (issues.length > 0) return { issues };\n\t\t\t\treturn {\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\tsubject: sub as string,\n\t\t\t\t\t\ttenant: tenant as string,\n\t\t\t\t\t\tissuer: iss as string,\n\t\t\t\t\t\tclientId: clientId as string,\n\t\t\t\t\t\tscopes:\n\t\t\t\t\t\t\ttypeof scope === 'string' ? scope.split(' ').filter(Boolean) : [],\n\t\t\t\t\t\troles: roles ?? [],\n\t\t\t\t\t\tclaims,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n",
16
+ "const isObject = (value: unknown): value is Record<string, unknown> =>\n\tvalue !== null && typeof value === 'object' && !Array.isArray(value);\n\n/** The `iss` of a token's payload, read WITHOUT verifying anything: it only picks whose keys to verify with. */\nexport function unverifiedIssuer(token: string): string | undefined {\n\tconst parts = token.split('.');\n\tconst payload = parts[1];\n\tif (parts.length !== 3 || payload === undefined) return undefined;\n\tif (!/^[A-Za-z0-9_-]+$/.test(payload)) return undefined;\n\ttry {\n\t\tconst claims: unknown = JSON.parse(\n\t\t\tnew TextDecoder('utf-8', { fatal: true }).decode(\n\t\t\t\tBuffer.from(payload, 'base64url'),\n\t\t\t),\n\t\t);\n\t\treturn isObject(claims) && typeof claims['iss'] === 'string'\n\t\t\t? claims['iss']\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
17
+ "import {\n\tdefineMiddleware,\n\terrorFormat,\n\ttype Middleware,\n\tmarkFactory,\n\ttype Next,\n\ttype Problem,\n\tproblem,\n\tproblemOf,\n\ttype Reply,\n} from '@softistx/alxia';\n\n/** The body of the 403. */\nexport interface InsufficientScopeBody {\n\treadonly error: 'forbidden';\n\treadonly reason: 'insufficient_scope';\n\t/** The scopes the route needs, space-separated. */\n\treadonly scope: string;\n}\n\n/** The 403 under `alxia({ errors: 'problem' })`: `reason` and `scope` are its extensions. */\nexport type InsufficientScopeProblem = Problem<\n\t403,\n\tOmit<InsufficientScopeBody, 'error'>\n>;\n\n/**\n * What `requireScope()` makes: it reads the `user` that `bearer()` gives and\n * lets the request on, or answers the 403.\n */\nexport type RequireScope = Middleware<\n\t{ user: { readonly scopes: readonly string[] } },\n\tPromise<\n\t\tReply<403, InsufficientScopeBody | InsufficientScopeProblem> | Next<object>\n\t>\n>;\n\n/**\n * A guard after `bearer()`: the token must carry every one of `scopes`, or a\n * 403 whose `WWW-Authenticate: Bearer error=\"insufficient_scope\", scope=\"…\"`\n * names them (RFC 6750 section 3.1).\n *\n * ```ts\n * app.use(auth.bearer()).get('/invoices', requireScope('invoices:read'), ({ user, reply }) => …)\n * ```\n */\nexport function requireScope(...scopes: readonly string[]): RequireScope {\n\tif (\n\t\tscopes.length === 0 ||\n\t\tscopes.some((s) => !/^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/.test(s))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'requireScope: give scopes, each a non-empty token without spaces or quotes',\n\t\t);\n\t}\n\tconst scope = scopes.join(' ');\n\tconst challenge = {\n\t\theaders: {\n\t\t\t'www-authenticate': `Bearer error=\"insufficient_scope\", scope=\"${scope}\"`,\n\t\t},\n\t};\n\treturn defineMiddleware<{ user: { readonly scopes: readonly string[] } }>()(\n\t\tasync function requireScope(ctx, next) {\n\t\t\tif (scopes.every((s) => ctx.user.scopes.includes(s))) return next();\n\t\t\tconst why = { reason: 'insufficient_scope', scope } as const;\n\t\t\tif (errorFormat(ctx) === 'problem') {\n\t\t\t\treturn problem(\n\t\t\t\t\tproblemOf(ctx, {\n\t\t\t\t\t\tstatus: 403,\n\t\t\t\t\t\tdetail: `The access token lacks the scope: ${scope}`,\n\t\t\t\t\t\t...why,\n\t\t\t\t\t}),\n\t\t\t\t\tchallenge,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn ctx.reply(403, { error: 'forbidden', ...why }, challenge);\n\t\t},\n\t) as RequireScope;\n}\n\nmarkFactory(requireScope);\n"
18
+ ],
19
+ "mappings": ";AAAA;AAAA;AAAA;;;ACwBO,IAAM,UAAU,IAAI;AAEpB,IAAM,WAAW,CAAC,UACxB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAG7D,SAAS,MAAM,CAAC,MAAkC;AAAA,EACxD,IAAI;AAAA,IACH,MAAM,QAAiB,KAAK,MAC3B,OAAO,KAAK,MAAM,WAAW,EAAE,SAAS,MAAM,CAC/C;AAAA,IACA,OAAO,SAAS,KAAK,IAAI,QAAQ;AAAA,IAChC,MAAM;AAAA,IACP;AAAA;AAAA;AAcK,SAAS,SAAS,CACxB,KACA,KACuB;AAAA,EACvB,IAAI,IAAI,MAAM;AAAA,IAAW;AAAA,EACzB,MAAM,OAAO,CAAC,SAAoC;AAAA,IACjD,MAAM,QAAQ,IAAI;AAAA,IAClB,OAAO,OAAO,UAAU,WAAW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AAK,OAAO,SAAS,CAAC,CAAC;AAAA,MAAG,OAAO,KAAK;AAAA,IAClE,MAAM,MAAM,EAAE,QAAQ,sBAAsB,MAAM;AAAA,IAClD,IAAI,YAAY,GAAG,MAAM,WAAW;AAAA,MACnC,OAAO,QACN,UAAU,KAAK;AAAA,QACd,QAAQ;AAAA,QACR,QAAQ,qCAAqC;AAAA,WAC1C;AAAA,MACJ,CAAC,GACD,SACD;AAAA,IACD;AAAA,IACA,OAAO,IAAI,MAAM,KAAK,EAAE,OAAO,gBAAgB,IAAI,GAAG,SAAS;AAAA,GAEjE;AAAA;AAGD,YAAY,YAAY;",
20
+ "debugId": "A0E8A24ACF0832D464756E2164756E21",
21
+ "names": []
22
+ }
@@ -0,0 +1,19 @@
1
+ /** The allowed issuers of a Clavix deployment, and the tenant each one stands for. */
2
+ export interface IssuerRules {
3
+ /** A lowercase DNS name without a dot at either end. */
4
+ readonly domain: string | undefined;
5
+ /** Issuer to tenant (`undefined` when the list gives none). */
6
+ readonly listed: ReadonlyMap<string, string | undefined>;
7
+ }
8
+ /** `domain` as a lowercase ASCII DNS name, or a `TypeError`. */
9
+ export declare function normaliseDomain(domain: string): string;
10
+ /** The listed issuers as a map; an issuer must be an `https` URL, or `http` on this machine. */
11
+ export declare function listIssuers(issuers: readonly string[] | Readonly<Record<string, string>>): Map<string, string | undefined>;
12
+ /**
13
+ * Whether `issuer` is allowed, and for which tenant: a listed issuer (byte
14
+ * for byte) first, then the domain pattern. `undefined` when refused.
15
+ */
16
+ export declare function resolveIssuer(rules: IssuerRules, issuer: string): {
17
+ readonly tenant: string | undefined;
18
+ } | undefined;
19
+ //# sourceMappingURL=issuers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"issuers.d.ts","sourceRoot":"","sources":["../src/issuers.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,MAAM,WAAW,WAAW;IAC3B,wDAAwD;IACxD,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,+DAA+D;IAC/D,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;CACzD;AAKD,gEAAgE;AAChE,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAiBtD;AAED,gGAAgG;AAChG,wBAAgB,WAAW,CAC1B,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAC3D,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAwBjC;AAeD;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,MAAM,GACZ;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,GAAG,SAAS,CAKrD"}
package/dist/lru.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** A map that keeps at most `max` entries, dropping the least recently used. */
2
+ export declare class Lru<V> {
3
+ #private;
4
+ constructor(max: number);
5
+ get size(): number;
6
+ get(key: string): V | undefined;
7
+ delete(key: string): void;
8
+ set(key: string, value: V): void;
9
+ }
10
+ //# sourceMappingURL=lru.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lru.d.ts","sourceRoot":"","sources":["../src/lru.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,qBAAa,GAAG,CAAC,CAAC;;gBAIL,GAAG,EAAE,MAAM;IAIvB,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS;IAQ/B,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI;CAQhC"}
@@ -0,0 +1,25 @@
1
+ import type { StandardSchemaV1 } from '@softistx/alxia';
2
+ import type { JwtClaims } from '@softistx/alxia-jwt';
3
+ /** Who a verified Clavix access token stands for: what routes behind `bearer()` read as `user`. */
4
+ export interface ClavixPrincipal {
5
+ /** The token's `sub`. */
6
+ readonly subject: string;
7
+ /** The tenant of the issuer: the slug of a pattern issuer, or the mapped name of a listed one. */
8
+ readonly tenant: string;
9
+ /** The token's `iss`. */
10
+ readonly issuer: string;
11
+ /** The client the token was issued to (`client_id`). */
12
+ readonly clientId: string;
13
+ /** The granted scopes: `scope` split on spaces, `[]` when absent. */
14
+ readonly scopes: readonly string[];
15
+ /** The subject's roles, `[]` when absent. */
16
+ readonly roles: readonly string[];
17
+ /** The verified claims, untouched (`permissions`, `cnf`, …). */
18
+ readonly claims: JwtClaims;
19
+ }
20
+ /**
21
+ * The Standard Schema that maps verified claims to a principal. A claim an
22
+ * RFC 9068 token must carry but does not is an issue, so a 401 `claims`.
23
+ */
24
+ export declare function principalSchema(tenantOf: (issuer: string) => string | undefined): StandardSchemaV1<unknown, ClavixPrincipal>;
25
+ //# sourceMappingURL=principal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principal.d.ts","sourceRoot":"","sources":["../src/principal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,mGAAmG;AACnG,MAAM,WAAW,eAAe;IAC/B,yBAAyB;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,kGAAkG;IAClG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yBAAyB;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,wDAAwD;IACxD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,qEAAqE;IACrE,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,6CAA6C;IAC7C,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,gEAAgE;IAChE,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;CAC3B;AAKD;;;GAGG;AACH,wBAAgB,eAAe,CAC9B,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,GAC9C,gBAAgB,CAAC,OAAO,EAAE,eAAe,CAAC,CA8C5C"}
@@ -0,0 +1,30 @@
1
+ import { type Middleware, type Next, type Problem, type Reply } from '@softistx/alxia';
2
+ /** The body of the 403. */
3
+ export interface InsufficientScopeBody {
4
+ readonly error: 'forbidden';
5
+ readonly reason: 'insufficient_scope';
6
+ /** The scopes the route needs, space-separated. */
7
+ readonly scope: string;
8
+ }
9
+ /** The 403 under `alxia({ errors: 'problem' })`: `reason` and `scope` are its extensions. */
10
+ export type InsufficientScopeProblem = Problem<403, Omit<InsufficientScopeBody, 'error'>>;
11
+ /**
12
+ * What `requireScope()` makes: it reads the `user` that `bearer()` gives and
13
+ * lets the request on, or answers the 403.
14
+ */
15
+ export type RequireScope = Middleware<{
16
+ user: {
17
+ readonly scopes: readonly string[];
18
+ };
19
+ }, Promise<Reply<403, InsufficientScopeBody | InsufficientScopeProblem> | Next<object>>>;
20
+ /**
21
+ * A guard after `bearer()`: the token must carry every one of `scopes`, or a
22
+ * 403 whose `WWW-Authenticate: Bearer error="insufficient_scope", scope="…"`
23
+ * names them (RFC 6750 section 3.1).
24
+ *
25
+ * ```ts
26
+ * app.use(auth.bearer()).get('/invoices', requireScope('invoices:read'), ({ user, reply }) => …)
27
+ * ```
28
+ */
29
+ export declare function requireScope(...scopes: readonly string[]): RequireScope;
30
+ //# sourceMappingURL=scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../src/scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,UAAU,EAEf,KAAK,IAAI,EACT,KAAK,OAAO,EAGZ,KAAK,KAAK,EACV,MAAM,iBAAiB,CAAC;AAEzB,2BAA2B;AAC3B,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,oBAAoB,CAAC;IACtC,mDAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB;AAED,6FAA6F;AAC7F,MAAM,MAAM,wBAAwB,GAAG,OAAO,CAC7C,GAAG,EACH,IAAI,CAAC,qBAAqB,EAAE,OAAO,CAAC,CACpC,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,UAAU,CACpC;IAAE,IAAI,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAAA;CAAE,EAChD,OAAO,CACN,KAAK,CAAC,GAAG,EAAE,qBAAqB,GAAG,wBAAwB,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAC3E,CACD,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,GAAG,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,YAAY,CAgCvE"}
@@ -0,0 +1,3 @@
1
+ /** The `iss` of a token's payload, read WITHOUT verifying anything: it only picks whose keys to verify with. */
2
+ export declare function unverifiedIssuer(token: string): string | undefined;
3
+ //# sourceMappingURL=unverified-issuer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unverified-issuer.d.ts","sourceRoot":"","sources":["../src/unverified-issuer.ts"],"names":[],"mappings":"AAGA,gHAAgH;AAChH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAiBlE"}
package/docs/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # @softistx/alxia-clavix documentation
2
+
3
+ The [package README](../README.md) is the short version. This folder is the long one.
4
+
5
+ ## Guide
6
+
7
+ | Page | Read it when |
8
+ | --- | --- |
9
+ | [Issuers and tenants](guide/issuers-and-tenants.md) | choosing `domain` or `issuers`, mapping a custom domain to a tenant, or reading why an issuer was refused |
10
+ | [The principal and scopes](guide/principal-and-scopes.md) | reading `user` in a route, guarding a route with `requireScope`, or reading the 401 and 403 |
11
+ | [Readiness and warm-up](guide/readiness.md) | wiring `/ready`, choosing `warm` issuers, or sizing `maxIssuers` |
12
+ | [Security notes](guide/security.md) | exposing the API to many tenants, wildcard DNS, DPoP, step-up |
13
+ | [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
14
+ | [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
@@ -0,0 +1,70 @@
1
+ # Issuers and tenants
2
+
3
+ `clavix` reads the token's `iss` without verifying anything, only to decide whether that issuer is
4
+ allowed. An allowed issuer's keys are fetched (OpenID discovery) and the token is verified with them;
5
+ a refused one is `issuer`, with no network call.
6
+
7
+ ```ts
8
+ import { clavix } from '@softistx/alxia-clavix';
9
+
10
+ const auth = clavix({
11
+ domain: 'clavix.example.com',
12
+ issuers: { 'https://login.customer.example.org': 'customer' },
13
+ audience: 'https://api.example.com',
14
+ });
15
+
16
+ auth.tenantOf('https://acme.clavix.example.com'); // 'acme'
17
+ auth.tenantOf('https://login.customer.example.org'); // 'customer'
18
+ auth.tenantOf('https://evil.example.net'); // undefined
19
+ ```
20
+
21
+ ## The pattern
22
+
23
+ With `domain: 'clavix.example.com'`, an issuer is allowed when it is exactly
24
+ `https://<label>.clavix.example.com`:
25
+
26
+ - one DNS label in front of the domain, lowercase ASCII letters, digits and hyphens;
27
+ - no port, userinfo, path, query, fragment, trailing slash or trailing dot;
28
+ - `https` only.
29
+
30
+ `domain` must be dedicated to Clavix tenants: every `https://<label>.<domain>` is trusted, so no other
31
+ host may live under it (a third-party `status.` or `docs.` host, or a dangling CNAME, would become a
32
+ trusted issuer). Other hosts go in `issuers`.
33
+
34
+ The label is the tenant. `domain` is trimmed, lowercased, and a leading or trailing dot is dropped;
35
+ it must be an ASCII DNS name of two labels or more.
36
+
37
+ Refused look-alikes, each `issuer`:
38
+
39
+ | Issuer | Why |
40
+ | --- | --- |
41
+ | `https://a.b.clavix.example.com` | two labels |
42
+ | `https://clavix.example.com` | no tenant label |
43
+ | `https://acme.clavix.example.com/` | trailing slash |
44
+ | `https://acme.clavix.example.com:8443` | port |
45
+ | `https://acme.clavix.example.com.evil.net` | the domain is not the suffix |
46
+ | `https://evilclavix.example.com` | no dot before the domain |
47
+ | `https://Acme.clavix.example.com` | upper case (the issuer is compared as written; the token's `iss` is never lowercased) |
48
+ | `https://xn--acme-9ua.clavix.example.com` | punycode (IDN) label |
49
+ | `http://acme.clavix.example.com` | not https |
50
+
51
+ ## Custom domains
52
+
53
+ A tenant on its own domain is not covered by the pattern. List it in `issuers`: as an array, or as
54
+ `{ issuer: tenant }` to name the tenant it stands for. A listed issuer is compared byte for byte, so
55
+ list the exact string the token carries. Listed without a tenant (an array), it is verified but has no
56
+ tenant: `tenantOf` answers `undefined`, and `bearer()` answers 401 `claims` (the issuer has no tenant, `issues[0].path` is `['iss']`),
57
+ so use the map form for any issuer that signs in users.
58
+
59
+ `issuers` accepts `https` URLs, and `http` for `localhost`, `127.0.0.1` and `[::1]` (tests).
60
+
61
+ ## Bounding the keys kept
62
+
63
+ Each allowed issuer gets its own key cache, in one of three places:
64
+
65
+ - `warm` issuers are pinned: never evicted, not counted in `maxIssuers`;
66
+ - an issuer met for the first time waits in a probation cache (`probation`, `min(maxIssuers, 16)` by
67
+ default), where forged issuers only push each other out;
68
+ - once a token from it verifies, it moves to the `maxIssuers` cache (default 100), which keeps the most
69
+ recently used ones; the least recently used is dropped past it and fetched again on its next token. See
70
+ [Readiness and warm-up](readiness.md) and [Security notes](security.md).
@@ -0,0 +1,59 @@
1
+ # The principal and scopes
2
+
3
+ `auth.bearer()` is `@softistx/alxia-jwt`'s bearer guard with a schema: routes after it read a
4
+ `ClavixPrincipal` as `user`.
5
+
6
+ ```ts
7
+ import { alxia } from '@softistx/alxia';
8
+ import { clavix, requireScope } from '@softistx/alxia-clavix';
9
+
10
+ const auth = clavix({ domain: 'clavix.example.com', audience: 'https://api.example.com' });
11
+
12
+ alxia()
13
+ .get('/ping', ({ reply }) => reply(200, 'pong')) // open: declared before the guard
14
+ .use(auth.bearer())
15
+ .get('/me', ({ user, reply }) => reply(200, { tenant: user.tenant, roles: user.roles }))
16
+ .post('/invoices', requireScope('invoices:write'), ({ user, reply }) => reply(201, { by: user.subject }))
17
+ .listen(3000);
18
+ ```
19
+
20
+ ## `ClavixPrincipal`
21
+
22
+ | Field | From |
23
+ | --- | --- |
24
+ | `subject` | `sub` |
25
+ | `tenant` | the issuer: the slug of a pattern issuer, the mapped name of a listed one |
26
+ | `issuer` | `iss` |
27
+ | `clientId` | `client_id` |
28
+ | `scopes` | `scope` split on spaces, `[]` when absent |
29
+ | `roles` | `roles`, `[]` when absent |
30
+ | `claims` | the verified claims, untouched (`permissions`, `cnf`, …) |
31
+
32
+ A token with a missing or empty `sub`, `iss` or `client_id`, or a `scope`, `roles`, `permissions` or
33
+ `cnf` of the wrong shape, is a 401 `malformed`: the RFC 9068 profile refuses it before the principal is
34
+ built. Reason `claims` (with the `issues` listed, `iss` first) is only for an issuer that has no
35
+ tenant, one listed as an array: use `{ issuer: tenant }`. To read from a cookie
36
+ instead of the header: `auth.bearer({ cookie: 'access_token' })`.
37
+
38
+ ## `requireScope`
39
+
40
+ `requireScope('a', 'b')` needs every scope and runs after `bearer()`. Without them it answers
41
+
42
+ ```http
43
+ HTTP/1.1 403 Forbidden
44
+ www-authenticate: Bearer error="insufficient_scope", scope="a b"
45
+
46
+ {"error":"forbidden","reason":"insufficient_scope","scope":"a b"}
47
+ ```
48
+
49
+ Under `alxia({ errors: 'problem' })` it is an RFC 9457 problem with `reason` and `scope` as
50
+ extensions. Scopes are non-empty strings without spaces or quotes; give at least one.
51
+
52
+ ## 401 reasons
53
+
54
+ `missing` (no token), `malformed`, `issuer`, `audience`, `type`, `signature`, `algorithm`, `expired`,
55
+ `not_yet_valid`, `key`, `keys_unavailable`, `claims`, and with DPoP (RFC 9449): `dpop_required`,
56
+ `dpop_unsupported`, `dpop_malformed`, `dpop_unbound`, `dpop_proof_*` (the check of the proof that failed) and `dpop_nonce`.
57
+ The challenge follows the scheme: `Bearer error="invalid_token"` for a bearer token, `DPoP
58
+ error="invalid_token"`, `invalid_dpop_proof` or `use_dpop_nonce` (with `algs` and a `DPoP-Nonce`
59
+ header) for the DPoP ones. See [Troubleshooting](../troubleshooting.md).
@@ -0,0 +1,31 @@
1
+ # Readiness and warm-up
2
+
3
+ Keys are fetched from an issuer on the first token it signs. To have a probe say "not ready" until
4
+ important issuers' keys are loaded, list them in `warm` and give `auth.ready` to `health`:
5
+
6
+ ```ts
7
+ import { alxia, health } from '@softistx/alxia';
8
+ import { clavix } from '@softistx/alxia-clavix';
9
+
10
+ const auth = clavix({
11
+ domain: 'clavix.example.com',
12
+ audience: 'https://api.example.com',
13
+ warm: ['https://acme.clavix.example.com', 'https://globex.clavix.example.com'],
14
+ });
15
+
16
+ alxia().plugin(health({ checks: { clavix: auth.ready } })).listen(3000);
17
+ ```
18
+
19
+ `ready()` resolves `true` once every warm issuer's key set is loaded (fresh within `cacheMs`, or stale
20
+ within `staleMs`), `false` otherwise, and never throws. Calling it is what loads the keys, so the
21
+ probe itself warms them. With no `warm` issuer it is always `true`: a probe cannot wait for tenants it
22
+ does not know.
23
+
24
+ Every warm issuer must be allowed by the same rules as a token's issuer; `clavix` throws a `TypeError`
25
+ at startup otherwise.
26
+
27
+ ## Pinned issuers
28
+
29
+ Warm issuers are pinned: their key sets live outside the `maxIssuers` cache and the probation cache,
30
+ are never evicted, and are not counted against `maxIssuers`. Traffic from other tenants, forged
31
+ issuers included, cannot push them out. Keep `warm` to the issuers you must serve at once.
@@ -0,0 +1,128 @@
1
+ # Security notes
2
+
3
+ ## What is checked
4
+
5
+ A token is accepted only when its issuer is allowed, its signature verifies with that issuer's
6
+ published keys, and the RFC 9068 profile holds: header `typ` `at+jwt`, `aud` containing `audience`,
7
+ `exp`, `iat`, `sub`, `client_id` and `jti` present. The `iss` is read unverified, but only to pick
8
+ whose keys to verify with; an attacker cannot make a token valid by choosing it.
9
+
10
+ ## Wildcard DNS
11
+
12
+ With `domain`, any `https://<label>.<domain>` is allowed. If the domain has wildcard DNS, an attacker
13
+ can mint valid-shaped issuers (`https://r4nd0m.clavix.example.com`) in unlimited number. Each unknown
14
+ one costs a discovery fetch. Those issuers cannot evict real tenants: a new issuer waits in a small
15
+ probation cache (`probation`, `min(maxIssuers, 16)` by default) and moves to the `maxIssuers` cache only
16
+ after a token from it verifies, and `warm` issuers are pinned outside both. Forged issuers only push
17
+ each other out of probation. Each fetch is bounded by `timeoutMs` and the memory by the two caches; the
18
+ number of fetches is not, hence the mitigations below. A genuine new tenant whose first token arrives
19
+ during a flood may have to be fetched again. There is no bypass: a token from such an issuer verifies only if that host really
20
+ serves keys for it, which the attacker cannot do under your domain.
21
+
22
+ Dedicate `domain` to Clavix tenants: no other host may live under it. A third-party `status.` or
23
+ `docs.` host, or a dangling CNAME someone can claim, would be a trusted issuer. Host those names
24
+ elsewhere, or list the issuers you trust in `issuers` and leave `domain` out.
25
+
26
+ Mitigations:
27
+
28
+ - list tenants in `issuers` instead of `domain` when they are few and known;
29
+ - keep `maxIssuers` above the real tenant count, and put the tenants you cannot afford to refetch in `warm`;
30
+ - restrict the API's outbound network (egress) to the Clavix hosts;
31
+ - rate-limit unauthenticated requests upstream.
32
+
33
+ ## DPoP
34
+
35
+ A token bound to a key carries `cnf.jkt` (RFC 9449): a thief of the token cannot use it without the
36
+ private key. Turn the check on with `dpop`:
37
+
38
+ ```ts
39
+ import { connectRedis } from '@softistx/redis';
40
+ import { clavix, hmacDpopNonce } from '@softistx/alxia-clavix';
41
+ import { redisDpopReplayStore } from '@softistx/alxia-redis';
42
+
43
+ const connection = await connectRedis(Bun.env['REDIS_URL']!);
44
+
45
+ const auth = clavix({
46
+ domain: 'clavix.example.com',
47
+ audience: 'https://api.example.com',
48
+ dpop: {
49
+ origin: 'https://api.example.com', // the URL clients call, not the proxy's
50
+ replay: redisDpopReplayStore(connection.client, { name: 'dpop' }),
51
+ nonce: hmacDpopNonce({ secret: Bun.env['DPOP_NONCE_SECRET']! }), // optional, 16 characters or more
52
+ },
53
+ });
54
+ ```
55
+
56
+ `@softistx/alxia-redis` needs no peer on `@softistx/alxia-clavix`: its store is typed by shape, and the
57
+ two are kept in step by a type-level spec in clavix.
58
+
59
+ A client sends `Authorization: DPoP <token>` and a `DPoP: <proof>` header. The guard is
60
+ `@softistx/alxia-jwt`'s `bearer()` with the DPoP half plugged in through its extension point, so
61
+ the 401 bodies, the cookie mode and `alxia({ errors: 'problem' })` are the same. On every call
62
+ `auth.bearer()` checks, in this order:
63
+
64
+ 1. the token verifies as before, and carries `cnf.jkt` (else `dpop_unbound`; `dpop_unsupported` when
65
+ `dpop` is not configured at all);
66
+ 2. the proof is one JWT, header `typ` exactly `dpop+jwt` (compared case-sensitively), no `crit`
67
+ header (an extension this server cannot understand, refused as `dpop_proof_malformed`), `alg`
68
+ `ES256` or `EdDSA` (`dpop.algorithms`), and a public `jwk` (`EC` P-256 or `OKP` Ed25519, no
69
+ private member), with a valid signature by that key;
70
+ 3. `htm` is the request method, `htu` is `dpop.origin` plus the request path (query and fragment
71
+ ignored; scheme and host compared without case, `:443` and `:80` equal to none, the path exact,
72
+ userinfo refused);
73
+ 4. `iat` is at most `maxAgeSec` (60) old and at most `clockSkewSec` (5) ahead;
74
+ 5. `jti` is present (at most 256 characters), `ath` is the base64url SHA-256 of the access token,
75
+ and the JWK thumbprint (RFC 7638) of the proof key equals `cnf.jkt`;
76
+ 6. with `nonce`, the proof carries a nonce the server issued;
77
+ 7. only then the `jti` is recorded in `dpop.replay`: a refused proof is never recorded, and one
78
+ already recorded is `dpop_proof_replay`.
79
+
80
+ A token with `cnf.jkt` sent as `Bearer`, or in the cookie, is always refused (`dpop_required`), also
81
+ when `dpop` is not configured: without the proof it is a stolen token. A token without `cnf.jkt` keeps
82
+ working as `Bearer`.
83
+
84
+ ### Migrating a deployment
85
+
86
+ This is a behaviour change. Until now a token with `cnf.jkt` passed as a bearer token; now it is a 401
87
+ `dpop_required`. Before upgrading an API that receives bound tokens:
88
+
89
+ 1. add `dpop` to `clavix()` (a replay store, and the public `origin`);
90
+ 2. have the clients send `Authorization: DPoP <token>` and a proof header, instead of
91
+ `Authorization: Bearer <token>`;
92
+ 3. tokens without `cnf.jkt` need nothing: they keep working as `Bearer`.
93
+
94
+ The `WWW-Authenticate` of a request with no token also changes with `dpop`: `Bearer` becomes
95
+ `Bearer, DPoP algs="ES256 EdDSA"` (the algorithms you accept).
96
+
97
+ ### Multi-instance
98
+
99
+ The replay store must be shared. `memoryDpopReplayStore()` is for tests and one instance: with two
100
+ instances, a proof replayed on the other one is accepted. It also keeps at most `maxEntries` live
101
+ proofs (10 000 by default) and throws past that, rather than growing without bound or forgetting one.
102
+ Use `redisDpopReplayStore` from `@softistx/alxia-redis`, or a store of your own (`claim(key, ttlMs)`
103
+ answering `true` once, atomically). A store that throws makes the request fail with a 500: a proof is
104
+ never accepted unchecked. The store holds proofs under `<jkt>:<jti>`, for `maxAgeSec + clockSkewSec`
105
+ plus a 5 second margin. The access token's own `jti` is not the proof's.
106
+
107
+ ### Behind a proxy (`htu`)
108
+
109
+ `origin` is yours, never a header. Behind a proxy the request URL is the internal one, and `Host` or
110
+ `X-Forwarded-*` are what an attacker sends. The proof's `htu` is compared with the public origin you
111
+ configure and the path the API receives, so a proxy that strips a path prefix breaks `htu`
112
+ (`dpop_proof_url`). Giving a public base with a prefix is not built yet:
113
+ [softistx/alxia#993](https://github.com/softistx/alxia/issues/993).
114
+
115
+ ### Nonces
116
+
117
+ With `nonce`, a proof without a valid one is a 401 `use_dpop_nonce` carrying a fresh `DPoP-Nonce`
118
+ header: the client retries once with it in the proof. A response to an accepted proof also carries a
119
+ fresh `DPoP-Nonce` once the nonce used is past half its life (RFC 9449 section 8.2), so the next proof
120
+ does not meet a refusal. `hmacDpopNonce` is stateless (every instance with the same secret accepts the
121
+ nonces of the others), derives its HMAC key from the secret with a label of its own, and expires nonces
122
+ after `ttlMs` (5 minutes by default; a finite number above 0, else a `TypeError`). A nonce limits how long a proof can be pre-made; the `jti` check still stops
123
+ replays.
124
+
125
+ ## Step-up
126
+
127
+ `acr` and `auth_time` are readable on `user.claims`, but this package does not enforce an
128
+ authentication strength: that is the identity provider's decision (see the [roadmap](../roadmap.md)).
@@ -0,0 +1,38 @@
1
+ # Roadmap
2
+
3
+ What `@softistx/alxia-clavix` gives an app, and what is coming. This page is a
4
+ direction, not a commitment: the version something shipped in is the only
5
+ number on it.
6
+
7
+ ## Now
8
+
9
+ - **Moving to the `@softistx` scope.** The package is now `@softistx/alxia-clavix` (it was `@alxia/clavix`). Same code and API; replace the dependency and the imports ([migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md)). The old name is deprecated.
10
+
11
+ ## Next
12
+
13
+ Nothing scheduled yet.
14
+
15
+ ## Later
16
+
17
+ - **Reserved labels.** Keep names such as `www`, `status` or `docs` from being
18
+ accepted as a tenant under `domain`.
19
+
20
+ ## Not planned
21
+
22
+ - **Step-up checks (`acr`, `auth_time`) in the API.** The identity provider
23
+ decides how strongly a user signed in.
24
+
25
+ ## Shipped
26
+
27
+ ### Unreleased
28
+
29
+ - **DPoP proofs checked.** `clavix({ dpop })` accepts the `DPoP` scheme and verifies each proof
30
+ (`typ`, ES256 or EdDSA, `htm`, `htu` from the public origin, fresh `iat`, single-use `jti`, `ath`,
31
+ key thumbprint equal to `cnf.jkt`), with an optional `DPoP-Nonce` and `WWW-Authenticate: DPoP`
32
+ answers. A token with `cnf.jkt` sent as `Bearer` is now refused (behaviour change: bound-token clients move to the `DPoP` scheme). Known limit: [a proxy that strips a path prefix](https://github.com/softistx/alxia/issues/993).
33
+
34
+ ### 0.1.0
35
+
36
+ - **Verify Clavix access tokens in an API.** A multi-tenant issuer allow-list
37
+ (a domain pattern and listed issuers, with the tenant of each), the RFC 9068
38
+ profile, the principal as `user`, `requireScope`, and readiness with `warm`.