@softistx/alxia-clavix 0.3.2 → 0.4.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/dist/index.js CHANGED
@@ -571,13 +571,169 @@ function clavix(options) {
571
571
  };
572
572
  return self;
573
573
  }
574
+ // src/resource/viewer.ts
575
+ import { errorFormat, problem, problemOf } from "@softistx/alxia";
576
+ var NAMES = {
577
+ 401: "unauthorized",
578
+ 403: "forbidden",
579
+ 503: "unavailable"
580
+ };
581
+ function refuse(ctx, options, refusal, extra = {}, challenge) {
582
+ const headers = { "cache-control": "no-store" };
583
+ if (challenge !== undefined)
584
+ headers["www-authenticate"] = challenge;
585
+ if (options.body !== undefined) {
586
+ return ctx.reply(refusal.status, options.body(refusal), { headers });
587
+ }
588
+ if (errorFormat(ctx) === "problem") {
589
+ return problem(problemOf(ctx, {
590
+ status: refusal.status,
591
+ detail: refusal.reason,
592
+ reason: refusal.reason,
593
+ ...extra
594
+ }), { headers });
595
+ }
596
+ return ctx.reply(refusal.status, { error: NAMES[refusal.status], reason: refusal.reason, ...extra }, { headers });
597
+ }
598
+ function reshape(ctx, result, body) {
599
+ const replied = result;
600
+ if (replied === null || typeof replied !== "object")
601
+ return result;
602
+ const { status } = replied;
603
+ if (status !== 401 && status !== 503)
604
+ return result;
605
+ const headers = new Headers(replied.headers);
606
+ if (!(headers.get("content-type") ?? "").includes("problem+json")) {
607
+ return result;
608
+ }
609
+ headers.delete("content-type");
610
+ const reason = replied.body?.reason;
611
+ return ctx.reply(status, body({
612
+ status,
613
+ reason: typeof reason === "string" ? reason : "unauthorized"
614
+ }), { headers });
615
+ }
616
+ function viewerMiddleware(options, guard) {
617
+ const scope = options.scope ?? "";
618
+ const carries = options.carries ?? (() => true);
619
+ const body = options.body;
620
+ const run = guard;
621
+ const middleware = async (context, next) => {
622
+ const ctx = context;
623
+ const { request } = ctx;
624
+ if (!carries(request) || !request.headers.has("authorization")) {
625
+ return next({ viewer: null });
626
+ }
627
+ const guarded = body === undefined ? ctx : Object.create(ctx, {
628
+ reply: {
629
+ value: (status, replied, init) => {
630
+ if (status !== 401 && status !== 503) {
631
+ return ctx.reply(status, replied, init);
632
+ }
633
+ const reason = replied?.reason;
634
+ return ctx.reply(status, body({ status, reason: reason ?? "unauthorized" }), init);
635
+ }
636
+ }
637
+ });
638
+ let proceeded = false;
639
+ let entered = false;
640
+ try {
641
+ const result = await run(guarded, async ({ user }) => {
642
+ entered = true;
643
+ if (scope && !user.scopes.includes(scope)) {
644
+ const scheme = /^dpop\s/i.test(request.headers.get("authorization") ?? "") ? "DPoP" : "Bearer";
645
+ return refuse(ctx, options, { status: 403, reason: "insufficient_scope" }, { scope }, `${scheme} error="insufficient_scope", scope="${scope}"`);
646
+ }
647
+ const viewer = await options.viewerOf(user);
648
+ if (viewer === null) {
649
+ return refuse(ctx, options, { status: 401, reason: "inactive" });
650
+ }
651
+ proceeded = true;
652
+ return next({ viewer });
653
+ });
654
+ if (body !== undefined && !entered)
655
+ return reshape(ctx, result, body);
656
+ return result;
657
+ } catch (error) {
658
+ if (proceeded)
659
+ throw error;
660
+ options.onError?.(error);
661
+ return refuse(ctx, options, { status: 503, reason: "unavailable" });
662
+ }
663
+ };
664
+ return middleware;
665
+ }
666
+
667
+ // src/resource/resource.ts
668
+ var credentials = /^(Bearer|DPoP)\s+(\S+)$/i;
669
+ var tenantOf = (issuer) => new URL(issuer).hostname.split(".")[0] ?? "";
670
+ function clavixResource(options) {
671
+ const { issuer, audience, origin, replay } = options;
672
+ if (options.scope !== undefined && !/^[\x21\x23-\x5B\x5D-\x7E]*$/.test(options.scope)) {
673
+ throw new TypeError("clavixResource: scope is one token, without spaces or quotes");
674
+ }
675
+ const tenant = options.tenant ?? tenantOf(issuer);
676
+ const verifier = clavix({
677
+ issuers: { [issuer]: tenant },
678
+ audience,
679
+ warm: [issuer],
680
+ dpop: {
681
+ origin,
682
+ replay,
683
+ ...options.nonce === undefined ? {} : { nonce: options.nonce }
684
+ }
685
+ });
686
+ const scope = options.scope ?? "";
687
+ const proofOptions = resolveDpop({
688
+ origin,
689
+ replay,
690
+ ...options.nonce === undefined ? {} : { nonce: options.nonce }
691
+ });
692
+ const guard = verifier.bearer();
693
+ const schema = principalSchema(verifier.tenantOf)["~standard"];
694
+ return {
695
+ viewer: viewerMiddleware(options, guard),
696
+ ready: verifier.ready,
697
+ async streamViewer(request) {
698
+ const found = credentials.exec(request.headers.get("authorization") ?? "");
699
+ const token = found?.[2];
700
+ if (token === undefined)
701
+ return null;
702
+ const verified = await verifier.verify(token);
703
+ if (!verified.ok)
704
+ return null;
705
+ const jkt = boundKey(verified.claims);
706
+ const viaDpop = found?.[1]?.toLowerCase() === "dpop";
707
+ if (jkt === null || viaDpop !== (jkt !== undefined))
708
+ return null;
709
+ if (jkt !== undefined) {
710
+ const proof = await verifyProof({
711
+ proof: request.headers.get("dpop"),
712
+ method: request.method,
713
+ path: new URL(request.url).pathname,
714
+ accessToken: token,
715
+ jkt
716
+ }, proofOptions);
717
+ if (!proof.ok)
718
+ return null;
719
+ }
720
+ const checked = await schema.validate(verified.claims);
721
+ if (checked.issues !== undefined)
722
+ return null;
723
+ const principal = checked.value;
724
+ if (scope && !principal.scopes.includes(scope))
725
+ return null;
726
+ return options.viewerOf(principal);
727
+ }
728
+ };
729
+ }
574
730
  // src/scope.ts
575
731
  import {
576
732
  defineMiddleware,
577
- errorFormat,
733
+ errorFormat as errorFormat2,
578
734
  markFactory,
579
- problem,
580
- problemOf
735
+ problem as problem2,
736
+ problemOf as problemOf2
581
737
  } from "@softistx/alxia";
582
738
  function requireScope(...scopes) {
583
739
  if (scopes.length === 0 || scopes.some((s) => !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(s))) {
@@ -593,8 +749,8 @@ function requireScope(...scopes) {
593
749
  if (scopes.every((s) => ctx.user.scopes.includes(s)))
594
750
  return next();
595
751
  const why = { reason: "insufficient_scope", scope };
596
- if (errorFormat(ctx) === "problem") {
597
- return problem(problemOf(ctx, {
752
+ if (errorFormat2(ctx) === "problem") {
753
+ return problem2(problemOf2(ctx, {
598
754
  status: 403,
599
755
  detail: `The access token lacks the scope: ${scope}`,
600
756
  ...why
@@ -606,10 +762,11 @@ function requireScope(...scopes) {
606
762
  markFactory(requireScope);
607
763
  export {
608
764
  clavix,
765
+ clavixResource,
609
766
  hmacDpopNonce,
610
767
  memoryDpopReplayStore,
611
768
  requireScope
612
769
  };
613
770
 
614
- //# debugId=A0E8A24ACF0832D464756E2164756E21
771
+ //# debugId=43C84EA7DE32806464756E2164756E21
615
772
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,22 +1,24 @@
1
1
  {
2
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"],
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/resource/viewer.ts", "../src/resource/resource.ts", "../src/scope.ts"],
4
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",
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, the 503 `keys_unavailable` when the issuer's keys cannot be fetched, 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
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
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
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
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
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
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",
12
+ "import type { StandardSchemaV1 } from '@softistx/alxia';\nimport {\n\ttype Bearer,\n\ttype BearerExtension,\n\tbearer,\n\ttype UnauthorizedBody,\n\ttype UnauthorizedProblem,\n\ttype UnavailableBody,\n\ttype UnavailableProblem,\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/** The body of the 503 a Clavix guard answers when the issuer's signing keys cannot be fetched. */\nexport type ClavixUnavailableBody = UnavailableBody;\n\n/** The 503 under `alxia({ errors: 'problem' })`. */\nexport type ClavixUnavailableProblem = UnavailableProblem;\n\n/** What `clavix().bearer()` makes: a middleware that gives `user`, answers the 401, or answers the 503 when the issuer's keys are unavailable. */\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 */\nexport function 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
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
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
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
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 { errorFormat, problem, problemOf } from '@softistx/alxia';\nimport type { ClavixGuard } from '../guard';\nimport type { ClavixPrincipal } from '../principal';\nimport type {\n\tClavixRefusal,\n\tClavixResourceOptions,\n\tClavixViewerMiddleware,\n} from './types';\n\ntype Next = (added: { viewer: unknown }) => Promise<unknown>;\n\n/** The minimum of alxia's middleware context this reads. */\ninterface Ctx {\n\treadonly request: Request;\n\treply(status: number, body: unknown, init?: unknown): unknown;\n}\n\nconst NAMES = {\n\t401: 'unauthorized',\n\t403: 'forbidden',\n\t503: 'unavailable',\n} as const;\n\n/** A refusal this module makes itself, in the app's error shape or alxia's. */\nfunction refuse(\n\tctx: Ctx,\n\toptions: ClavixResourceOptions<unknown>,\n\trefusal: ClavixRefusal,\n\textra: Readonly<Record<string, unknown>> = {},\n\tchallenge?: string,\n) {\n\tconst headers: Record<string, string> = { 'cache-control': 'no-store' };\n\tif (challenge !== undefined) headers['www-authenticate'] = challenge;\n\tif (options.body !== undefined) {\n\t\treturn ctx.reply(refusal.status, options.body(refusal), { headers });\n\t}\n\tif (errorFormat(ctx as never) === 'problem') {\n\t\treturn problem(\n\t\t\tproblemOf(ctx as never, {\n\t\t\t\tstatus: refusal.status,\n\t\t\t\tdetail: refusal.reason,\n\t\t\t\treason: refusal.reason,\n\t\t\t\t...extra,\n\t\t\t}),\n\t\t\t{ headers },\n\t\t);\n\t}\n\treturn ctx.reply(\n\t\trefusal.status,\n\t\t{ error: NAMES[refusal.status], reason: refusal.reason, ...extra },\n\t\t{ headers },\n\t);\n}\n\n/** The guard's own problem+json 401 or 503, in the app's error shape, headers kept. */\nfunction reshape(\n\tctx: Ctx,\n\tresult: unknown,\n\tbody: NonNullable<ClavixResourceOptions<unknown>['body']>,\n): unknown {\n\tconst replied = result as {\n\t\tstatus?: unknown;\n\t\tbody?: { reason?: unknown } | null;\n\t\theaders?: HeadersInit;\n\t} | null;\n\tif (replied === null || typeof replied !== 'object') return result;\n\tconst { status } = replied;\n\tif (status !== 401 && status !== 503) return result;\n\tconst headers = new Headers(replied.headers);\n\tif (!(headers.get('content-type') ?? '').includes('problem+json')) {\n\t\treturn result;\n\t}\n\theaders.delete('content-type');\n\tconst reason = replied.body?.reason;\n\treturn ctx.reply(\n\t\tstatus,\n\t\tbody({\n\t\t\tstatus,\n\t\t\treason: typeof reason === 'string' ? reason : 'unauthorized',\n\t\t}),\n\t\t{ headers },\n\t);\n}\n\n/** The viewer of a request: the guard judges the token and its proof, then the app maps the principal. */\nexport function viewerMiddleware<Viewer>(\n\toptions: ClavixResourceOptions<Viewer>,\n\tguard: ClavixGuard,\n): ClavixViewerMiddleware<Viewer> {\n\tconst scope = options.scope ?? '';\n\tconst carries = options.carries ?? (() => true);\n\tconst body = options.body;\n\tconst run = guard as unknown as (\n\t\tctx: Ctx,\n\t\tnext: (added: { user: ClavixPrincipal }) => Promise<unknown>,\n\t) => Promise<unknown>;\n\tconst middleware = async (context: unknown, next: Next) => {\n\t\tconst ctx = context as Ctx;\n\t\tconst { request } = ctx;\n\t\tif (!carries(request) || !request.headers.has('authorization')) {\n\t\t\treturn next({ viewer: null });\n\t\t}\n\t\t// The guard's own 401 and 503 take the app's error shape, with their\n\t\t// challenge and nonce headers; its other replies pass.\n\t\tconst guarded =\n\t\t\tbody === undefined\n\t\t\t\t? ctx\n\t\t\t\t: (Object.create(ctx, {\n\t\t\t\t\t\treply: {\n\t\t\t\t\t\t\tvalue: (status: number, replied: unknown, init?: unknown) => {\n\t\t\t\t\t\t\t\tif (status !== 401 && status !== 503) {\n\t\t\t\t\t\t\t\t\treturn ctx.reply(status, replied, init);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst reason = (replied as { reason?: string } | null)?.reason;\n\t\t\t\t\t\t\t\treturn ctx.reply(\n\t\t\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\t\t\tbody({ status, reason: reason ?? 'unauthorized' }),\n\t\t\t\t\t\t\t\t\tinit,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}) as Ctx);\n\t\tlet proceeded = false;\n\t\tlet entered = false;\n\t\ttry {\n\t\t\tconst result = await run(guarded, async ({ user }) => {\n\t\t\t\tentered = true;\n\t\t\t\tif (scope && !user.scopes.includes(scope)) {\n\t\t\t\t\t// RFC 6750 section 3.1, as `requireScope` answers it.\n\t\t\t\t\tconst scheme = /^dpop\\s/i.test(\n\t\t\t\t\t\trequest.headers.get('authorization') ?? '',\n\t\t\t\t\t)\n\t\t\t\t\t\t? 'DPoP'\n\t\t\t\t\t\t: 'Bearer';\n\t\t\t\t\treturn refuse(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\t{ status: 403, reason: 'insufficient_scope' },\n\t\t\t\t\t\t{ scope },\n\t\t\t\t\t\t`${scheme} error=\"insufficient_scope\", scope=\"${scope}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst viewer = await options.viewerOf(user);\n\t\t\t\t// An inactive account: the token is valid, so refreshing it would\n\t\t\t\t// not help: no challenge.\n\t\t\t\tif (viewer === null) {\n\t\t\t\t\treturn refuse(ctx, options, { status: 401, reason: 'inactive' });\n\t\t\t\t}\n\t\t\t\tproceeded = true;\n\t\t\t\treturn next({ viewer });\n\t\t\t});\n\t\t\t// Under `errors: 'problem'` the guard answers through `problem()`,\n\t\t\t// not `reply`: its 401 and 503 take the app's shape here.\n\t\t\tif (body !== undefined && !entered) return reshape(ctx, result, body);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\t// What runs after the guard (a route, a resolver) is never taken\n\t\t\t// for an outage.\n\t\t\tif (proceeded) throw error;\n\t\t\t// A store (the replay cache) or the viewer's read could not answer:\n\t\t\t// a 503, never an anonymous request, and never a 401 a BFF would\n\t\t\t// read as an expired session.\n\t\t\toptions.onError?.(error);\n\t\t\treturn refuse(ctx, options, { status: 503, reason: 'unavailable' });\n\t\t}\n\t};\n\treturn middleware as unknown as ClavixViewerMiddleware<Viewer>;\n}\n",
18
+ "import { clavix } from '../clavix';\nimport { resolveDpop, verifyProof } from '../dpop';\nimport { boundKey } from '../guard';\nimport { principalSchema } from '../principal';\nimport type { ClavixResource, ClavixResourceOptions } from './types';\nimport { viewerMiddleware } from './viewer';\n\nconst credentials = /^(Bearer|DPoP)\\s+(\\S+)$/i;\n\n/** The tenant of an issuer: the first label of its host. */\nconst tenantOf = (issuer: string) =>\n\tnew URL(issuer).hostname.split('.')[0] ?? '';\n\n/**\n * Clavix as the identity provider of an API, in a few lines: the verifier\n * of the tenant's issuer (warmed, DPoP proofs checked with the replay\n * store), a middleware that gives every route a `viewer`, and the viewer\n * of a stream. The app writes `viewerOf(principal)`.\n *\n * ```ts\n * const resource = clavixResource({\n * issuer: settings.issuer,\n * audience: settings.audience,\n * origin: settings.origin,\n * replay: redisDpopReplayStore(redis.client, { name: 'dpop' }),\n * viewerOf: (principal) => viewers.find(principal.subject),\n * });\n * alxia().use(resource.viewer).get('/me', ({ viewer, reply }) => reply(200, viewer));\n * ```\n */\nexport function clavixResource<Viewer>(\n\toptions: ClavixResourceOptions<Viewer>,\n): ClavixResource<Viewer> {\n\tconst { issuer, audience, origin, replay } = options;\n\tif (\n\t\toptions.scope !== undefined &&\n\t\t!/^[\\x21\\x23-\\x5B\\x5D-\\x7E]*$/.test(options.scope)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'clavixResource: scope is one token, without spaces or quotes',\n\t\t);\n\t}\n\tconst tenant = options.tenant ?? tenantOf(issuer);\n\tconst verifier = clavix({\n\t\tissuers: { [issuer]: tenant },\n\t\taudience,\n\t\twarm: [issuer],\n\t\tdpop: {\n\t\t\torigin,\n\t\t\treplay,\n\t\t\t...(options.nonce === undefined ? {} : { nonce: options.nonce }),\n\t\t},\n\t});\n\tconst scope = options.scope ?? '';\n\tconst proofOptions = resolveDpop({\n\t\torigin,\n\t\treplay,\n\t\t...(options.nonce === undefined ? {} : { nonce: options.nonce }),\n\t});\n\tconst guard = verifier.bearer();\n\tconst schema = principalSchema(verifier.tenantOf)['~standard'];\n\treturn {\n\t\tviewer: viewerMiddleware(options, guard),\n\t\tready: verifier.ready,\n\t\tasync streamViewer(request) {\n\t\t\tconst found = credentials.exec(\n\t\t\t\trequest.headers.get('authorization') ?? '',\n\t\t\t);\n\t\t\tconst token = found?.[2];\n\t\t\tif (token === undefined) return null;\n\t\t\tconst verified = await verifier.verify(token);\n\t\t\tif (!verified.ok) return null;\n\t\t\t// The key binding is checked as the guard does: a bound token needs\n\t\t\t// the DPoP scheme and a proof for this very request; an unbound one\n\t\t\t// the Bearer scheme.\n\t\t\tconst jkt = boundKey(verified.claims);\n\t\t\tconst viaDpop = found?.[1]?.toLowerCase() === 'dpop';\n\t\t\tif (jkt === null || viaDpop !== (jkt !== undefined)) return null;\n\t\t\tif (jkt !== undefined) {\n\t\t\t\tconst proof = await verifyProof(\n\t\t\t\t\t{\n\t\t\t\t\t\tproof: request.headers.get('dpop'),\n\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\tpath: new URL(request.url).pathname,\n\t\t\t\t\t\taccessToken: token,\n\t\t\t\t\t\tjkt,\n\t\t\t\t\t},\n\t\t\t\t\tproofOptions,\n\t\t\t\t);\n\t\t\t\tif (!proof.ok) return null;\n\t\t\t}\n\t\t\tconst checked = await schema.validate(verified.claims);\n\t\t\tif (checked.issues !== undefined) return null;\n\t\t\tconst principal = checked.value;\n\t\t\tif (scope && !principal.scopes.includes(scope)) return null;\n\t\t\treturn options.viewerOf(principal);\n\t\t},\n\t};\n}\n",
17
19
  "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
20
  ],
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,QAAQ;AAAA;AAAA,EAE5C,OAAO,KAAK,KAAK,GAAG,KAAK,CAAC,KAAK,KAAK,GAAG,KAAK,KAAK,GAAG,KAAK,GAAG,GAAG,KAAK,GAAG,CAAC;AAAA,EACxE,IAAI,QAAQ,SAAS;AAAA,IACpB,IAAI,QAAQ,QAAQ,QAAQ,WAAW,CAAC,KAAK,CAAC;AAAA,MAAG;AAAA,IACjD,OAAO;AAAA,MACN,KAAK,EAAE,KAAK,KAAK,GAAG,EAAE;AAAA,MACtB,QAAQ,EAAE,MAAM,SAAS,YAAY,QAAQ;AAAA,IAC9C;AAAA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WAAW;AAAA,QAAW,OAAO;AAAA,MACzC,MAAM,YAAY,QAAQ;AAAA,MAC1B,IAAI,SAAS,CAAC,UAAU,OAAO,SAAS,KAAK;AAAA,QAAG,OAAO;AAAA,MACvD,OAAO,QAAQ,SAAS,SAAS;AAAA;AAAA,EAEnC;AAAA;;ACjGD;AAAA;AAAA,iBAEC;AAAA;AAAA,aAKA;AAAA,eACA;AAAA;AAsCM,SAAS,YAAY,IAAI,QAAyC;AAAA,EACxE,IACC,OAAO,WAAW,KAClB,OAAO,KAAK,CAAC,MAAM,CAAC,8BAA8B,KAAK,CAAC,CAAC,GACxD;AAAA,IACD,MAAM,IAAI,UACT,4EACD;AAAA,EACD;AAAA,EACA,MAAM,QAAQ,OAAO,KAAK,GAAG;AAAA,EAC7B,MAAM,YAAY;AAAA,IACjB,SAAS;AAAA,MACR,oBAAoB,6CAA6C;AAAA,IAClE;AAAA,EACD;AAAA,EACA,OAAO,iBAAmE,EACzE,eAAe,YAAY,CAAC,KAAK,MAAM;AAAA,IACtC,IAAI,OAAO,MAAM,CAAC,MAAM,IAAI,KAAK,OAAO,SAAS,CAAC,CAAC;AAAA,MAAG,OAAO,KAAK;AAAA,IAClE,MAAM,MAAM,EAAE,QAAQ,sBAAsB,MAAM;AAAA,IAClD,IAAI,aAAY,GAAG,MAAM,WAAW;AAAA,MACnC,OAAO,SACN,WAAU,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;",
22
+ "debugId": "43C84EA7DE32806464756E2164756E21",
21
23
  "names": []
22
24
  }
@@ -0,0 +1,3 @@
1
+ export { clavixResource } from './resource';
2
+ export type { ClavixRefusal, ClavixResource, ClavixResourceOptions, ClavixViewerContext, ClavixViewerMiddleware, ViewerOf, } from './types';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/resource/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,YAAY,EACX,aAAa,EACb,cAAc,EACd,qBAAqB,EACrB,mBAAmB,EACnB,sBAAsB,EACtB,QAAQ,GACR,MAAM,SAAS,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { ClavixResource, ClavixResourceOptions } from './types';
2
+ /**
3
+ * Clavix as the identity provider of an API, in a few lines: the verifier
4
+ * of the tenant's issuer (warmed, DPoP proofs checked with the replay
5
+ * store), a middleware that gives every route a `viewer`, and the viewer
6
+ * of a stream. The app writes `viewerOf(principal)`.
7
+ *
8
+ * ```ts
9
+ * const resource = clavixResource({
10
+ * issuer: settings.issuer,
11
+ * audience: settings.audience,
12
+ * origin: settings.origin,
13
+ * replay: redisDpopReplayStore(redis.client, { name: 'dpop' }),
14
+ * viewerOf: (principal) => viewers.find(principal.subject),
15
+ * });
16
+ * alxia().use(resource.viewer).get('/me', ({ viewer, reply }) => reply(200, viewer));
17
+ * ```
18
+ */
19
+ export declare function clavixResource<Viewer>(options: ClavixResourceOptions<Viewer>): ClavixResource<Viewer>;
20
+ //# sourceMappingURL=resource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../../src/resource/resource.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AASrE;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,cAAc,CAAC,MAAM,EACpC,OAAO,EAAE,qBAAqB,CAAC,MAAM,CAAC,GACpC,cAAc,CAAC,MAAM,CAAC,CAkExB"}
@@ -0,0 +1,94 @@
1
+ import type { Empty, Middleware, Next, Reply } from '@softistx/alxia';
2
+ import type { DpopNonce, DpopReplayStore } from '../dpop';
3
+ import type { ClavixPrincipal } from '../principal';
4
+ /**
5
+ * Maps a verified principal to the app's own viewer, or to `null` when the
6
+ * account is inactive (disabled, erased): the request is then a 401. It
7
+ * may throw: the store it reads is down, which is a 503, never a 401.
8
+ */
9
+ export type ViewerOf<Viewer> = (principal: ClavixPrincipal) => Viewer | null | Promise<Viewer | null>;
10
+ /** Why `clavixResource()` refuses a request. */
11
+ export interface ClavixRefusal {
12
+ /** The status: 401 (no or a refused token or proof, or an inactive account), 403 (a missing scope) or 503 (the issuer or a store cannot answer). */
13
+ readonly status: 401 | 403 | 503;
14
+ /**
15
+ * The reason: the guard's (`missing`, `signature`, `dpop_proof_replay`,
16
+ * `keys_unavailable`, …), or `inactive`, `insufficient_scope`,
17
+ * `unavailable`.
18
+ */
19
+ readonly reason: string;
20
+ }
21
+ export interface ClavixResourceOptions<Viewer> {
22
+ /** The tenant's issuer: the only one allowed, and the one whose keys `ready()` waits for. `https` (`http` on localhost). */
23
+ readonly issuer: string;
24
+ /** The API's identifier at Clavix: a token's `aud` must contain it. */
25
+ readonly audience: string;
26
+ /**
27
+ * The public origin of the API (scheme and host, no path): a DPoP proof's
28
+ * `htu` must be this plus the request path. Configured, never read from a
29
+ * header.
30
+ */
31
+ readonly origin: string;
32
+ /**
33
+ * Where the proofs' `jti` are remembered, shared by every instance:
34
+ * `redisDpopReplayStore(client, { name })` from `@softistx/alxia-redis`.
35
+ * `memoryDpopReplayStore()` for a spec or one instance in development.
36
+ */
37
+ readonly replay: DpopReplayStore;
38
+ /** A server nonce for the proofs (`hmacDpopNonce`). Optional. */
39
+ readonly nonce?: DpopNonce;
40
+ /** The scope every token must carry. Left out, none is required. */
41
+ readonly scope?: string | undefined;
42
+ /**
43
+ * The tenant the issuer stands for. The first label of its host by
44
+ * default (`https://acme.clavix.example` is `acme`).
45
+ */
46
+ readonly tenant?: string;
47
+ /** The app's mapping from the verified principal to its viewer: all it writes. */
48
+ readonly viewerOf: ViewerOf<Viewer>;
49
+ /**
50
+ * Whether a request carries a viewer. A route that does not (probes,
51
+ * webhooks) goes on anonymous, its `Authorization` header unread. Every
52
+ * route by default.
53
+ */
54
+ readonly carries?: (request: Request) => boolean;
55
+ /**
56
+ * The JSON body of a refusal, in the API's own error shape. Left out,
57
+ * the guard's `{ error, reason }` is kept (and RFC 9457 problems under
58
+ * `alxia({ errors: 'problem' })`). The guard's `WWW-Authenticate` and
59
+ * `DPoP-Nonce` headers are kept either way.
60
+ */
61
+ readonly body?: (refusal: ClavixRefusal) => unknown;
62
+ /**
63
+ * Called with what a store or the viewer mapping threw, before the 503.
64
+ * Log it here; it never reaches the client.
65
+ */
66
+ readonly onError?: (error: unknown) => void;
67
+ }
68
+ /** What the middleware adds to the context of every route after it. */
69
+ export interface ClavixViewerContext<Viewer> {
70
+ /** The app's viewer, or `null` for a request without `Authorization` (or a route that carries none). */
71
+ readonly viewer: Viewer | null;
72
+ }
73
+ /**
74
+ * What `resource.viewer` makes: it reads the request's token and DPoP proof
75
+ * and gives routes a `viewer`, or answers 401, 403 or 503.
76
+ */
77
+ export type ClavixViewerMiddleware<Viewer> = Middleware<Empty, Promise<Reply<401, unknown> | Reply<403, unknown> | Reply<503, unknown> | Next<ClavixViewerContext<Viewer>>>>;
78
+ export interface ClavixResource<Viewer> {
79
+ /** The middleware: `app.use(resource.viewer)`. */
80
+ readonly viewer: ClavixViewerMiddleware<Viewer>;
81
+ /**
82
+ * The viewer of a long-lived stream (a subscription, a WebSocket
83
+ * upgrade) from its own request, checked like a route's: a token bound
84
+ * to a key (`cnf.jkt`) needs the `DPoP` scheme and a proof for that
85
+ * request (its `jti` is spent once), an unbound one the `Bearer` scheme.
86
+ * `null` for a missing, refused or out-of-scope token, or an inactive
87
+ * account. A throw of `viewerOf` (its store is down) propagates: the
88
+ * caller decides, there is no response to turn into a 503 here.
89
+ */
90
+ streamViewer(request: Request): Promise<Viewer | null>;
91
+ /** `true` once the issuer's keys are loaded: `health({ checks: { clavix: resource.ready } })`. Never throws. */
92
+ ready(): Promise<boolean>;
93
+ }
94
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/resource/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEpD;;;;GAIG;AACH,MAAM,MAAM,QAAQ,CAAC,MAAM,IAAI,CAC9B,SAAS,EAAE,eAAe,KACtB,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAE5C,gDAAgD;AAChD,MAAM,WAAW,aAAa;IAC7B,oJAAoJ;IACpJ,QAAQ,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,qBAAqB,CAAC,MAAM;IAC5C,4HAA4H;IAC5H,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,uEAAuE;IACvE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,iEAAiE;IACjE,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC;IAC3B,oEAAoE;IACpE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,kFAAkF;IAClF,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACpC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC;IACjD;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC;IACpD;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CAC5C;AAED,uEAAuE;AACvE,MAAM,WAAW,mBAAmB,CAAC,MAAM;IAC1C,wGAAwG;IACxG,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED;;;GAGG;AACH,MAAM,MAAM,sBAAsB,CAAC,MAAM,IAAI,UAAU,CACtD,KAAK,EACL,OAAO,CACJ,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,GACnB,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,GACnB,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,GACnB,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CACnC,CACD,CAAC;AAEF,MAAM,WAAW,cAAc,CAAC,MAAM;IACrC,kDAAkD;IAClD,QAAQ,CAAC,MAAM,EAAE,sBAAsB,CAAC,MAAM,CAAC,CAAC;IAChD;;;;;;;;OAQG;IACH,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACvD,gHAAgH;IAChH,KAAK,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1B"}
@@ -0,0 +1,5 @@
1
+ import type { ClavixGuard } from '../guard';
2
+ import type { ClavixResourceOptions, ClavixViewerMiddleware } from './types';
3
+ /** The viewer of a request: the guard judges the token and its proof, then the app maps the principal. */
4
+ export declare function viewerMiddleware<Viewer>(options: ClavixResourceOptions<Viewer>, guard: ClavixGuard): ClavixViewerMiddleware<Viewer>;
5
+ //# sourceMappingURL=viewer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewer.d.ts","sourceRoot":"","sources":["../../src/resource/viewer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,KAAK,EAEX,qBAAqB,EACrB,sBAAsB,EACtB,MAAM,SAAS,CAAC;AA6EjB,0GAA0G;AAC1G,wBAAgB,gBAAgB,CAAC,MAAM,EACtC,OAAO,EAAE,qBAAqB,CAAC,MAAM,CAAC,EACtC,KAAK,EAAE,WAAW,GAChB,sBAAsB,CAAC,MAAM,CAAC,CA+EhC"}
package/docs/README.md CHANGED
@@ -8,6 +8,7 @@ The [package README](../README.md) is the short version. This folder is the long
8
8
  | --- | --- |
9
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
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
+ | [Wiring an API to Clavix](guide/wiring-an-api.md) | moving an API to Clavix: `clavixEnv()`, `clavixResource({ viewerOf })`, the viewer middleware and its 401, 403 and 503 |
11
12
  | [Readiness and warm-up](guide/readiness.md) | wiring `/ready`, choosing `warm` issuers, or sizing `maxIssuers` |
12
13
  | [Security notes](guide/security.md) | exposing the API to many tenants, wildcard DNS, DPoP, step-up |
13
14
  | [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |