@passflow/node 0.1.3 → 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.
@@ -1,9 +1,13 @@
1
- import { r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.cjs";
2
- import { FastifyPluginAsync, FastifyRequest, preHandlerAsyncHookHandler } from "fastify";
1
+ import { f as Verifier, n as ProtectedResource, u as PassflowClaims } from "./evaluate-BAJUQu_Z.cjs";
2
+ import { FastifyPluginAsync, FastifyRequest, RouteHandlerMethod, preHandlerAsyncHookHandler } from "fastify";
3
3
  export type PassflowFastifyHooks = {
4
4
  authenticate: preHandlerAsyncHookHandler;
5
5
  requireACR(min: string): preHandlerAsyncHookHandler;
6
6
  requireFresh(maxAgeSeconds: number): preHandlerAsyncHookHandler;
7
+ /** Answers 403 unless the token carries every scope: what the user delegated to the client, not what the user may do. */
8
+ requireScopes(...scopes: string[]): preHandlerAsyncHookHandler;
9
+ /** Serves the RFC 9728 metadata document. Throws `PassflowUsageError` when built from a plain verifier. */
10
+ metadata: RouteHandlerMethod;
7
11
  };
8
12
  declare module 'fastify' {
9
13
  interface FastifyInstance {
@@ -18,23 +22,28 @@ declare module 'fastify' {
18
22
  * verifier on an instance. Each is a `preHandler`-shaped async function. `authenticate` always verifies the presented
19
23
  * token and replaces `request.passflow`. `requireACR` and `requireFresh` reuse claims only when this verifier produced
20
24
  * that exact object, and otherwise verify the presented token themselves, so a broad instance-level hook followed by
21
- * a narrow route-level one enforces the narrow verifier's policy. Both throw `TypeError` at construction on an invalid
22
- * level or limit.
25
+ * a narrow route-level one enforces the narrow verifier's policy. `requireScopes` does the same for scopes.
26
+ * All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource adds its own
27
+ * parameters to the challenges. Mount `metadata` on GET, HEAD and OPTIONS, because a browser client may send a preflight
28
+ * request.
23
29
  */
24
- export declare function createFastifyHooks(verifier: Verifier): PassflowFastifyHooks;
30
+ export declare function createFastifyHooks(target: Verifier | ProtectedResource): PassflowFastifyHooks;
25
31
  /**
26
32
  * Decorates the instance with `fastify.passflow` and `request.passflow`, and registers no hook, so routes opt in one
27
33
  * at a time and public routes are untouched. Register it at most once per instance: a second registration throws
28
34
  * Fastify's own `FST_ERR_DEC_ALREADY_PRESENT`. Use {@link createFastifyHooks} for every further verifier.
29
35
  */
30
36
  export declare const passflowFastify: FastifyPluginAsync<{
31
- verifier: Verifier;
37
+ verifier: Verifier | ProtectedResource;
32
38
  }>;
33
39
  /** The claims a Passflow hook put on this request. Throws `PassflowUsageError` if none ran. */
34
40
  export declare function getAuth(request: Pick<FastifyRequest, 'passflow'>): PassflowClaims;
35
- /** Names `WWW-Authenticate` in `@fastify/cors`'s `exposedHeaders`, keeping what is already there. */
41
+ /**
42
+ * Names `WWW-Authenticate` in `@fastify/cors`'s `exposedHeaders`, keeping what is already there. Takes the package's own options type
43
+ * as it is, with `exactOptionalPropertyTypes` on too.
44
+ */
36
45
  export declare function exposeChallengeHeader<T extends object>(cors: T & {
37
- exposedHeaders?: string | string[];
46
+ exposedHeaders?: string | readonly string[] | undefined;
38
47
  }): Omit<T, 'exposedHeaders'> & {
39
48
  exposedHeaders: string[];
40
49
  };
@@ -1,9 +1,13 @@
1
- import { r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.mjs";
2
- import { FastifyPluginAsync, FastifyRequest, preHandlerAsyncHookHandler } from "fastify";
1
+ import { f as Verifier, n as ProtectedResource, u as PassflowClaims } from "./evaluate-BAJUQu_Z.mjs";
2
+ import { FastifyPluginAsync, FastifyRequest, RouteHandlerMethod, preHandlerAsyncHookHandler } from "fastify";
3
3
  export type PassflowFastifyHooks = {
4
4
  authenticate: preHandlerAsyncHookHandler;
5
5
  requireACR(min: string): preHandlerAsyncHookHandler;
6
6
  requireFresh(maxAgeSeconds: number): preHandlerAsyncHookHandler;
7
+ /** Answers 403 unless the token carries every scope: what the user delegated to the client, not what the user may do. */
8
+ requireScopes(...scopes: string[]): preHandlerAsyncHookHandler;
9
+ /** Serves the RFC 9728 metadata document. Throws `PassflowUsageError` when built from a plain verifier. */
10
+ metadata: RouteHandlerMethod;
7
11
  };
8
12
  declare module 'fastify' {
9
13
  interface FastifyInstance {
@@ -18,23 +22,28 @@ declare module 'fastify' {
18
22
  * verifier on an instance. Each is a `preHandler`-shaped async function. `authenticate` always verifies the presented
19
23
  * token and replaces `request.passflow`. `requireACR` and `requireFresh` reuse claims only when this verifier produced
20
24
  * that exact object, and otherwise verify the presented token themselves, so a broad instance-level hook followed by
21
- * a narrow route-level one enforces the narrow verifier's policy. Both throw `TypeError` at construction on an invalid
22
- * level or limit.
25
+ * a narrow route-level one enforces the narrow verifier's policy. `requireScopes` does the same for scopes.
26
+ * All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource adds its own
27
+ * parameters to the challenges. Mount `metadata` on GET, HEAD and OPTIONS, because a browser client may send a preflight
28
+ * request.
23
29
  */
24
- export declare function createFastifyHooks(verifier: Verifier): PassflowFastifyHooks;
30
+ export declare function createFastifyHooks(target: Verifier | ProtectedResource): PassflowFastifyHooks;
25
31
  /**
26
32
  * Decorates the instance with `fastify.passflow` and `request.passflow`, and registers no hook, so routes opt in one
27
33
  * at a time and public routes are untouched. Register it at most once per instance: a second registration throws
28
34
  * Fastify's own `FST_ERR_DEC_ALREADY_PRESENT`. Use {@link createFastifyHooks} for every further verifier.
29
35
  */
30
36
  export declare const passflowFastify: FastifyPluginAsync<{
31
- verifier: Verifier;
37
+ verifier: Verifier | ProtectedResource;
32
38
  }>;
33
39
  /** The claims a Passflow hook put on this request. Throws `PassflowUsageError` if none ran. */
34
40
  export declare function getAuth(request: Pick<FastifyRequest, 'passflow'>): PassflowClaims;
35
- /** Names `WWW-Authenticate` in `@fastify/cors`'s `exposedHeaders`, keeping what is already there. */
41
+ /**
42
+ * Names `WWW-Authenticate` in `@fastify/cors`'s `exposedHeaders`, keeping what is already there. Takes the package's own options type
43
+ * as it is, with `exactOptionalPropertyTypes` on too.
44
+ */
36
45
  export declare function exposeChallengeHeader<T extends object>(cors: T & {
37
- exposedHeaders?: string | string[];
46
+ exposedHeaders?: string | readonly string[] | undefined;
38
47
  }): Omit<T, 'exposedHeaders'> & {
39
48
  exposedHeaders: string[];
40
49
  };
package/dist/fastify.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { a as guard, d as withChallengeHeader, n as assertVerifier, s as PassflowUsageError, t as assertRequirement } from "./evaluate-BTuol-Oa.mjs";
1
+ import { t as adapterTarget } from "./adapter-Du22h3Lk.mjs";
2
+ import { l as PassflowUsageError, p as withChallengeHeader, s as guard, t as assertRequirement } from "./evaluate-CHts4VKy.mjs";
2
3
  // src/fastify.ts
3
4
  function send(reply, rejection) {
4
5
  reply.code(rejection.status).headers(rejection.headers).send();
@@ -8,14 +9,16 @@ function send(reply, rejection) {
8
9
  * verifier on an instance. Each is a `preHandler`-shaped async function. `authenticate` always verifies the presented
9
10
  * token and replaces `request.passflow`. `requireACR` and `requireFresh` reuse claims only when this verifier produced
10
11
  * that exact object, and otherwise verify the presented token themselves, so a broad instance-level hook followed by
11
- * a narrow route-level one enforces the narrow verifier's policy. Both throw `TypeError` at construction on an invalid
12
- * level or limit.
12
+ * a narrow route-level one enforces the narrow verifier's policy. `requireScopes` does the same for scopes.
13
+ * All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource adds its own
14
+ * parameters to the challenges. Mount `metadata` on GET, HEAD and OPTIONS, because a browser client may send a preflight
15
+ * request.
13
16
  */
14
- function createFastifyHooks(verifier) {
15
- assertVerifier(verifier);
17
+ function createFastifyHooks(target) {
18
+ const { verifier, challenge, metadata } = adapterTarget(target);
16
19
  const hook = (reuse, requirement) => async (request, reply) => {
17
20
  const existing = reuse ? request.passflow ?? void 0 : void 0;
18
- const result = await guard(verifier, request.headers.authorization, existing, requirement);
21
+ const result = await guard(verifier, request.headers.authorization, existing, requirement, challenge);
19
22
  if ("reject" in result) {
20
23
  send(reply, result.reject);
21
24
  return reply;
@@ -31,7 +34,15 @@ function createFastifyHooks(verifier) {
31
34
  requireFresh: (maxAgeSeconds) => hook(true, assertRequirement({
32
35
  kind: "fresh",
33
36
  maxAgeSeconds
34
- }))
37
+ })),
38
+ requireScopes: (...scopes) => hook(true, assertRequirement({
39
+ kind: "scope",
40
+ scopes
41
+ })),
42
+ metadata: (request, reply) => {
43
+ const { status, headers, body } = metadata(request.method);
44
+ return reply.code(status).headers(headers).send(body ?? void 0);
45
+ }
35
46
  };
36
47
  }
37
48
  const plugin = async (fastify, opts) => {
@@ -53,7 +64,10 @@ function getAuth(request) {
53
64
  if (request.passflow === null || request.passflow === void 0) throw new PassflowUsageError("[passflow] getAuth called before a Passflow hook ran on this request");
54
65
  return request.passflow;
55
66
  }
56
- /** Names `WWW-Authenticate` in `@fastify/cors`'s `exposedHeaders`, keeping what is already there. */
67
+ /**
68
+ * Names `WWW-Authenticate` in `@fastify/cors`'s `exposedHeaders`, keeping what is already there. Takes the package's own options type
69
+ * as it is, with `exactOptionalPropertyTypes` on too.
70
+ */
57
71
  function exposeChallengeHeader(cors) {
58
72
  return {
59
73
  ...cors,
package/dist/hono.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluate = require("./evaluate-C20MecTf.cjs");
2
+ const require_adapter = require("./adapter-DyCsMsEq.cjs");
3
+ const require_evaluate = require("./evaluate-Yv4mWPRI.cjs");
3
4
  // src/hono.ts
4
5
  /** `c.body` rather than a thrown HTTPException, so headers `hono/cors` already set survive the rejection. */
5
6
  function send(c, { status, headers }) {
@@ -8,14 +9,16 @@ function send(c, { status, headers }) {
8
9
  /**
9
10
  * Hono middleware, for any runtime with WebCrypto and fetch. `authenticate` always verifies the presented token and
10
11
  * replaces the `passflow` variable. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier
11
- * produced that exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction
12
- * on an invalid level or limit.
12
+ * produced that exact object, and otherwise verify the presented token themselves. `requireScopes` does the
13
+ * same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource
14
+ * adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser client may send a
15
+ * preflight request.
13
16
  */
14
- function passflowHono(verifier) {
15
- require_evaluate.assertVerifier(verifier);
17
+ function passflowHono(target) {
18
+ const { verifier, challenge, metadata } = require_adapter.adapterTarget(target);
16
19
  const middleware = (reuse, requirement) => async (c, next) => {
17
20
  const existing = reuse ? c.get("passflow") : void 0;
18
- const result = await require_evaluate.guard(verifier, c.req.header("authorization"), existing, requirement);
21
+ const result = await require_evaluate.guard(verifier, c.req.header("authorization"), existing, requirement, challenge);
19
22
  if ("reject" in result) return send(c, result.reject);
20
23
  c.set("passflow", result.claims);
21
24
  await next();
@@ -29,7 +32,15 @@ function passflowHono(verifier) {
29
32
  requireFresh: (maxAgeSeconds) => middleware(true, require_evaluate.assertRequirement({
30
33
  kind: "fresh",
31
34
  maxAgeSeconds
32
- }))
35
+ })),
36
+ requireScopes: (...scopes) => middleware(true, require_evaluate.assertRequirement({
37
+ kind: "scope",
38
+ scopes
39
+ })),
40
+ metadata: (c) => {
41
+ const { status, headers, body } = metadata(c.req.method);
42
+ return body === null ? c.body(null, status, headers) : c.body(body, 200, headers);
43
+ }
33
44
  };
34
45
  }
35
46
  /** The claims a Passflow middleware put on this context. Throws `PassflowUsageError` if none ran. */
@@ -38,7 +49,10 @@ function getAuth(c) {
38
49
  if (claims === void 0 || claims === null) throw new require_evaluate.PassflowUsageError("[passflow] getAuth called before a Passflow middleware ran on this request");
39
50
  return claims;
40
51
  }
41
- /** Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. */
52
+ /**
53
+ * Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. Takes the package's own options type
54
+ * as it is, with `exactOptionalPropertyTypes` on too.
55
+ */
42
56
  function exposeChallengeHeader(cors) {
43
57
  return {
44
58
  ...cors,
package/dist/hono.d.cts CHANGED
@@ -1,24 +1,33 @@
1
- import { r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.cjs";
2
- import { Context, MiddlewareHandler } from "hono";
1
+ import { f as Verifier, n as ProtectedResource, u as PassflowClaims } from "./evaluate-BAJUQu_Z.cjs";
2
+ import { Context, Handler, MiddlewareHandler } from "hono";
3
3
  export type PassflowVariables = {
4
4
  passflow: PassflowClaims;
5
5
  };
6
6
  /**
7
7
  * Hono middleware, for any runtime with WebCrypto and fetch. `authenticate` always verifies the presented token and
8
8
  * replaces the `passflow` variable. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier
9
- * produced that exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction
10
- * on an invalid level or limit.
9
+ * produced that exact object, and otherwise verify the presented token themselves. `requireScopes` does the
10
+ * same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource
11
+ * adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser client may send a
12
+ * preflight request.
11
13
  */
12
- export declare function passflowHono(verifier: Verifier): {
14
+ export declare function passflowHono(target: Verifier | ProtectedResource): {
13
15
  authenticate: MiddlewareHandler;
14
16
  requireACR(min: string): MiddlewareHandler;
15
17
  requireFresh(maxAgeSeconds: number): MiddlewareHandler;
18
+ /** Answers 403 unless the token carries every scope: what the user delegated to the client, not what the user may do. */
19
+ requireScopes(...scopes: string[]): MiddlewareHandler;
20
+ /** Serves the RFC 9728 metadata document. Throws `PassflowUsageError` when built from a plain verifier. */
21
+ metadata: Handler;
16
22
  };
17
23
  /** The claims a Passflow middleware put on this context. Throws `PassflowUsageError` if none ran. */
18
24
  export declare function getAuth(c: Context): PassflowClaims;
19
- /** Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. */
25
+ /**
26
+ * Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. Takes the package's own options type
27
+ * as it is, with `exactOptionalPropertyTypes` on too.
28
+ */
20
29
  export declare function exposeChallengeHeader<T extends object>(cors: T & {
21
- exposeHeaders?: string[];
30
+ exposeHeaders?: readonly string[] | undefined;
22
31
  }): Omit<T, 'exposeHeaders'> & {
23
32
  exposeHeaders: string[];
24
33
  };
package/dist/hono.d.mts CHANGED
@@ -1,24 +1,33 @@
1
- import { r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.mjs";
2
- import { Context, MiddlewareHandler } from "hono";
1
+ import { f as Verifier, n as ProtectedResource, u as PassflowClaims } from "./evaluate-BAJUQu_Z.mjs";
2
+ import { Context, Handler, MiddlewareHandler } from "hono";
3
3
  export type PassflowVariables = {
4
4
  passflow: PassflowClaims;
5
5
  };
6
6
  /**
7
7
  * Hono middleware, for any runtime with WebCrypto and fetch. `authenticate` always verifies the presented token and
8
8
  * replaces the `passflow` variable. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier
9
- * produced that exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction
10
- * on an invalid level or limit.
9
+ * produced that exact object, and otherwise verify the presented token themselves. `requireScopes` does the
10
+ * same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource
11
+ * adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser client may send a
12
+ * preflight request.
11
13
  */
12
- export declare function passflowHono(verifier: Verifier): {
14
+ export declare function passflowHono(target: Verifier | ProtectedResource): {
13
15
  authenticate: MiddlewareHandler;
14
16
  requireACR(min: string): MiddlewareHandler;
15
17
  requireFresh(maxAgeSeconds: number): MiddlewareHandler;
18
+ /** Answers 403 unless the token carries every scope: what the user delegated to the client, not what the user may do. */
19
+ requireScopes(...scopes: string[]): MiddlewareHandler;
20
+ /** Serves the RFC 9728 metadata document. Throws `PassflowUsageError` when built from a plain verifier. */
21
+ metadata: Handler;
16
22
  };
17
23
  /** The claims a Passflow middleware put on this context. Throws `PassflowUsageError` if none ran. */
18
24
  export declare function getAuth(c: Context): PassflowClaims;
19
- /** Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. */
25
+ /**
26
+ * Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. Takes the package's own options type
27
+ * as it is, with `exactOptionalPropertyTypes` on too.
28
+ */
20
29
  export declare function exposeChallengeHeader<T extends object>(cors: T & {
21
- exposeHeaders?: string[];
30
+ exposeHeaders?: readonly string[] | undefined;
22
31
  }): Omit<T, 'exposeHeaders'> & {
23
32
  exposeHeaders: string[];
24
33
  };
package/dist/hono.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { a as guard, d as withChallengeHeader, n as assertVerifier, s as PassflowUsageError, t as assertRequirement } from "./evaluate-BTuol-Oa.mjs";
1
+ import { t as adapterTarget } from "./adapter-Du22h3Lk.mjs";
2
+ import { l as PassflowUsageError, p as withChallengeHeader, s as guard, t as assertRequirement } from "./evaluate-CHts4VKy.mjs";
2
3
  // src/hono.ts
3
4
  /** `c.body` rather than a thrown HTTPException, so headers `hono/cors` already set survive the rejection. */
4
5
  function send(c, { status, headers }) {
@@ -7,14 +8,16 @@ function send(c, { status, headers }) {
7
8
  /**
8
9
  * Hono middleware, for any runtime with WebCrypto and fetch. `authenticate` always verifies the presented token and
9
10
  * replaces the `passflow` variable. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier
10
- * produced that exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction
11
- * on an invalid level or limit.
11
+ * produced that exact object, and otherwise verify the presented token themselves. `requireScopes` does the
12
+ * same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource
13
+ * adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser client may send a
14
+ * preflight request.
12
15
  */
13
- function passflowHono(verifier) {
14
- assertVerifier(verifier);
16
+ function passflowHono(target) {
17
+ const { verifier, challenge, metadata } = adapterTarget(target);
15
18
  const middleware = (reuse, requirement) => async (c, next) => {
16
19
  const existing = reuse ? c.get("passflow") : void 0;
17
- const result = await guard(verifier, c.req.header("authorization"), existing, requirement);
20
+ const result = await guard(verifier, c.req.header("authorization"), existing, requirement, challenge);
18
21
  if ("reject" in result) return send(c, result.reject);
19
22
  c.set("passflow", result.claims);
20
23
  await next();
@@ -28,7 +31,15 @@ function passflowHono(verifier) {
28
31
  requireFresh: (maxAgeSeconds) => middleware(true, assertRequirement({
29
32
  kind: "fresh",
30
33
  maxAgeSeconds
31
- }))
34
+ })),
35
+ requireScopes: (...scopes) => middleware(true, assertRequirement({
36
+ kind: "scope",
37
+ scopes
38
+ })),
39
+ metadata: (c) => {
40
+ const { status, headers, body } = metadata(c.req.method);
41
+ return body === null ? c.body(null, status, headers) : c.body(body, 200, headers);
42
+ }
32
43
  };
33
44
  }
34
45
  /** The claims a Passflow middleware put on this context. Throws `PassflowUsageError` if none ran. */
@@ -37,7 +48,10 @@ function getAuth(c) {
37
48
  if (claims === void 0 || claims === null) throw new PassflowUsageError("[passflow] getAuth called before a Passflow middleware ran on this request");
38
49
  return claims;
39
50
  }
40
- /** Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. */
51
+ /**
52
+ * Names `WWW-Authenticate` in `hono/cors`'s `exposeHeaders`, keeping what is already there. Takes the package's own options type
53
+ * as it is, with `exactOptionalPropertyTypes` on too.
54
+ */
41
55
  function exposeChallengeHeader(cors) {
42
56
  return {
43
57
  ...cors,
package/dist/index.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluate = require("./evaluate-C20MecTf.cjs");
2
+ const require_evaluate = require("./evaluate-Yv4mWPRI.cjs");
3
+ const require_loopback = require("./loopback-ADMM_GlW.cjs");
3
4
  let jose = require("jose");
4
5
  // src/header.ts
5
6
  const ALLOWED_ALGORITHMS = ["RS256", "ES256"];
@@ -7,6 +8,12 @@ const UTF8 = new TextDecoder("utf-8", {
7
8
  fatal: true,
8
9
  ignoreBOM: true
9
10
  });
11
+ /** The generic JWT media type and the access token one of RFC 9068. Media type names are case-insensitive. */
12
+ const ACCEPTED_TYP = [
13
+ "jwt",
14
+ "at+jwt",
15
+ "application/at+jwt"
16
+ ];
10
17
  const BASE64URL$1 = /^[A-Za-z0-9_-]+$/;
11
18
  function decodeProtectedHeader(segment) {
12
19
  if (!BASE64URL$1.test(segment) || segment.length % 4 === 1) return;
@@ -19,7 +26,7 @@ function decodeProtectedHeader(segment) {
19
26
  }
20
27
  /**
21
28
  * Header inspection, in the order Go and the corpus pin, before any key lookup: malformed, alg, crit,
22
- * kid. It has to run before jose, which reports a standard parameter in `crit` with the same code as a
29
+ * typ, kid. It has to run before jose, which reports a standard parameter in `crit` with the same code as a
23
30
  * malformed token. Throws `PassflowAuthError` with `invalid_token` and the reason.
24
31
  */
25
32
  function inspectHeader(token) {
@@ -30,6 +37,7 @@ function inspectHeader(token) {
30
37
  if (header === void 0) throw new require_evaluate.PassflowAuthError("invalid_token", "malformed");
31
38
  if (typeof header.alg !== "string" || !ALLOWED_ALGORITHMS.includes(header.alg)) throw new require_evaluate.PassflowAuthError("invalid_token", "alg");
32
39
  if (Object.hasOwn(header, "crit")) throw new require_evaluate.PassflowAuthError("invalid_token", "crit");
40
+ if (Object.hasOwn(header, "typ") && !(typeof header.typ === "string" && ACCEPTED_TYP.includes(header.typ.toLowerCase()))) throw new require_evaluate.PassflowAuthError("invalid_token", "typ");
33
41
  if (typeof header.kid !== "string" || header.kid === "") throw new require_evaluate.PassflowAuthError("invalid_token", "kid_missing");
34
42
  }
35
43
  // src/jwks.ts
@@ -401,21 +409,6 @@ function requireAudiences(audience) {
401
409
  if (!Array.isArray(audiences) || audiences.length === 0 || !audiences.every(isNonEmptyString)) throw new TypeError("[passflow] audience must name one or more non-empty audiences");
402
410
  return [...audiences];
403
411
  }
404
- /** The host of an `http://` URL as written, without userinfo or port. A URL spelled any other way has none. */
405
- const WRITTEN_HOST = /^http:\/\/(?:[^/?#\\\s]*@)?(\[[^\]]*\]|[^/?#:@\\%\s]*)(?::\d*)?(?:[/?#]|$)/i;
406
- const LOOPBACK_IPV4 = /^127(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
407
- /**
408
- * Loopback by the host as written, the rule Go applies. WHATWG normalization would turn `127.1`, `2130706433`
409
- * and `0x7f.1` into `127.0.0.1`, so a config that starts here would fail to start a Go API. An IPv6 literal
410
- * takes the normalized form, which gives each address one spelling. A name that merely contains "localhost"
411
- * is not loopback.
412
- */
413
- function isLoopbackHost(raw, url) {
414
- const host = WRITTEN_HOST.exec(raw)?.[1]?.toLowerCase();
415
- if (host === void 0) return false;
416
- if (host.startsWith("[")) return url.hostname === "[::1]";
417
- return host === "localhost" || host.endsWith(".localhost") || LOOPBACK_IPV4.test(host);
418
- }
419
412
  /** The key set is the root of trust. The error names the rule, never the URL. */
420
413
  function requireJwksUrl(config, issuer) {
421
414
  const raw = config.jwksUrl ?? `${issuer.replace(/\/+$/, "")}/.well-known/jwks.json`;
@@ -427,7 +420,7 @@ function requireJwksUrl(config, issuer) {
427
420
  throw new TypeError("[passflow] jwksUrl must be a valid URL");
428
421
  }
429
422
  if (url.protocol === "https:") return raw;
430
- if (url.protocol === "http:" && (config.allowInsecureJwksUrl === true || isLoopbackHost(raw, url))) return raw;
423
+ if (url.protocol === "http:" && (config.allowInsecureJwksUrl === true || require_loopback.isLoopbackHost(raw, url))) return raw;
431
424
  throw new TypeError("[passflow] jwksUrl must use https unless the host is loopback or allowInsecureJwksUrl is set");
432
425
  }
433
426
  function requireTokenTypes(tokenTypes) {
@@ -537,6 +530,78 @@ function createVerifier(config) {
537
530
  };
538
531
  return verifier;
539
532
  }
533
+ // src/resource.ts
534
+ const METADATA_WELL_KNOWN = "/.well-known/oauth-protected-resource";
535
+ const MAX_RESOURCE_BYTES = 2048;
536
+ /**
537
+ * Splits a resource into its origin, path and query. It admits no userinfo and no fragment, and nothing that needs
538
+ * escaping in a quoted challenge parameter.
539
+ */
540
+ const RESOURCE = /^([Hh][Tt][Tt][Pp][Ss]?:\/\/(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)(?::[0-9]{1,5})?)(\/(?:[A-Za-z0-9._~:/@!$&'()*+,;=-]|%[0-9A-Fa-f]{2})*)?(\?(?:[A-Za-z0-9._~:/?@!$&'()*+,;=-]|%[0-9A-Fa-f]{2})*)?$/;
541
+ /** The error names the rule, never the URL. The pattern admits ASCII only, so length is bytes. */
542
+ function splitResource(resource) {
543
+ const parts = typeof resource === "string" && resource.length <= MAX_RESOURCE_BYTES ? RESOURCE.exec(resource) : null;
544
+ if (typeof resource !== "string" || parts === null) throw new TypeError("[passflow] resource must be an absolute http or https URL of at most 2048 bytes, without userinfo or a fragment");
545
+ let url;
546
+ try {
547
+ url = new URL(resource);
548
+ } catch {
549
+ throw new TypeError("[passflow] resource must be a valid URL");
550
+ }
551
+ if (url.protocol !== "https:" && !require_loopback.isLoopbackHost(resource, url)) throw new TypeError("[passflow] resource must use https unless the host is loopback");
552
+ return {
553
+ resource,
554
+ origin: parts[1] ?? "",
555
+ path: parts[2] ?? "",
556
+ query: parts[3] ?? ""
557
+ };
558
+ }
559
+ function requireScopeList(scopes) {
560
+ if (scopes === void 0) return [];
561
+ if (!Array.isArray(scopes)) throw new TypeError("[passflow] scopes must be an array");
562
+ const checked = scopes.length === 0 ? [] : require_evaluate.assertScopes(scopes);
563
+ if (checked.includes("offline_access")) throw new TypeError("[passflow] scopes must not hold offline_access");
564
+ return checked;
565
+ }
566
+ /**
567
+ * Builds an OAuth protected resource, such as an MCP server: a verifier whose only audience is the resource, the
568
+ * RFC 9728 metadata that tells a client where to get a token, and the challenge parameters that name that metadata.
569
+ * Pass it to an adapter in place of a verifier. Touches no network. Throws `TypeError` on an invalid configuration.
570
+ */
571
+ function createProtectedResource(config) {
572
+ if (typeof config !== "object" || config === null) throw new TypeError("[passflow] config must be an object");
573
+ const { resource: rawResource, scopes: rawScopes, name, ...verifierConfig } = config;
574
+ const { audience } = verifierConfig;
575
+ if (audience !== void 0 && !(Array.isArray(audience) && audience.length === 0)) throw new TypeError("[passflow] audience must not be set: the audience is the resource");
576
+ const { resource, origin, path, query } = splitResource(rawResource);
577
+ const scopes = requireScopeList(rawScopes);
578
+ if (name !== void 0 && typeof name !== "string") throw new TypeError("[passflow] name must be a string");
579
+ const verifier = createVerifier({
580
+ ...verifierConfig,
581
+ audience: resource
582
+ });
583
+ const metadataPath = path === "/" ? METADATA_WELL_KNOWN : `${METADATA_WELL_KNOWN}${path}`;
584
+ const issuer = config.issuer;
585
+ return {
586
+ verifier,
587
+ metadataPath,
588
+ metadata: () => ({
589
+ resource,
590
+ authorization_servers: [issuer],
591
+ ...scopes.length > 0 ? { scopes_supported: [...scopes] } : {},
592
+ bearer_methods_supported: ["header"],
593
+ ...name ? { resource_name: name } : {}
594
+ }),
595
+ requireScopes: (...required) => ({
596
+ kind: "scope",
597
+ scopes: require_evaluate.assertScopes(required)
598
+ }),
599
+ challenge: {
600
+ resourceMetadata: `${origin}${metadataPath}${query}`,
601
+ ...scopes.length > 0 ? { scope: scopes.join(" ") } : {}
602
+ }
603
+ };
604
+ }
540
605
  exports.AAL1 = require_evaluate.AAL1;
541
606
  exports.AAL2 = require_evaluate.AAL2;
542
607
  exports.AAL3 = require_evaluate.AAL3;
@@ -549,6 +614,8 @@ exports.acrLevel = require_evaluate.acrLevel;
549
614
  exports.acrSatisfies = require_evaluate.acrSatisfies;
550
615
  exports.assertMaxAge = require_evaluate.assertMaxAge;
551
616
  exports.authenticate = require_evaluate.authenticate;
617
+ exports.authenticateRequest = require_evaluate.authenticateRequest;
618
+ exports.createProtectedResource = createProtectedResource;
552
619
  exports.createVerifier = createVerifier;
553
620
  exports.evaluate = require_evaluate.evaluate;
554
621
  exports.extractBearer = require_evaluate.extractBearer;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as verifiedBy, i as rolesOf, n as TenantMembership, r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.cjs";
1
+ import { a as ResourceChallenge, c as authenticateRequest, d as TenantMembership, f as Verifier, i as Requirement, l as evaluate, m as verifiedBy, n as ProtectedResource, o as ResourceMetadata, p as rolesOf, r as Rejection, s as authenticate, t as Decision, u as PassflowClaims } from "./evaluate-BAJUQu_Z.cjs";
2
2
  export declare const ACR_NONE = "0";
3
3
  export declare const AAL1 = "1";
4
4
  export declare const AAL2 = "2";
@@ -44,7 +44,7 @@ export declare const CHALLENGE_HEADER = "WWW-Authenticate";
44
44
  export declare const CORS_EXPOSED_HEADERS: readonly string[];
45
45
  type PassflowAuthErrorCode = 'missing_token' | 'invalid_token' | 'jwks_unavailable';
46
46
  /** Why a token was refused. Only `invalid_token` carries one. */
47
- type InvalidTokenReason = 'expired' | 'not_yet_valid' | 'exp_missing' | 'issuer' | 'audience' | 'type' | 'signature' | 'alg' | 'kid_missing' | 'key_unknown' | 'crit' | 'malformed';
47
+ type InvalidTokenReason = 'expired' | 'not_yet_valid' | 'exp_missing' | 'issuer' | 'audience' | 'type' | 'signature' | 'alg' | 'kid_missing' | 'key_unknown' | 'crit' | 'typ' | 'malformed';
48
48
  /**
49
49
  * An authentication failure. The message is fixed per code and carries nothing from the token, the
50
50
  * request or the JWKS URL. A jose error is never attached as `cause`: jose's claim errors keep the
@@ -69,45 +69,17 @@ export declare class PassflowUsageError extends Error {
69
69
  * and CJS builds are both loaded, where `instanceof` alone would say no.
70
70
  */
71
71
  export declare function isPassflowAuthError(e: unknown): e is PassflowAuthError;
72
- type Requirement = {
73
- kind: 'acr';
74
- min: string;
75
- } | {
76
- kind: 'fresh';
77
- maxAgeSeconds: number;
78
- };
79
- type Decision = {
80
- kind: 'allow';
81
- } | {
82
- kind: 'reject';
83
- status: 401 | 500 | 503;
84
- headers: Record<string, string>;
85
- };
86
- /** A rejected `Decision`: a `ResponseInit` as it stands (`new Response(null, rejection)`). */
87
- type Rejection = Extract<Decision, {
88
- kind: 'reject';
89
- }>;
90
- /**
91
- * Decides one requirement against claims. No claims means the middleware was composed wrongly, so the answer
92
- * is a 500 with no challenge: never a step-up, which the SDK would try to satisfy, and never a 401, because a
93
- * wiring bug must not be reported as a bad token. Throws `TypeError` on an invalid requirement.
94
- */
95
- export declare function evaluate(claims: PassflowClaims | undefined, requirement: Requirement): Decision;
96
- /**
97
- * Authenticates a request. `existing` claims are reused only when `verifier` produced that exact object;
98
- * otherwise the presented header is verified with `verifier`, so a token outside this verifier's trust policy
99
- * is rejected as not valid here, never as insufficient. Never rejects: a failure is a `{ reject }` value.
100
- */
101
- export declare function authenticate(verifier: Verifier, authorization: string | undefined | null, existing?: PassflowClaims): Promise<{
102
- claims: PassflowClaims;
103
- } | {
104
- reject: Rejection;
105
- }>;
106
72
  type VerifierConfig = {
107
- /** Required, exact match against `iss`. */
108
- issuer: string;
109
- /** Required: the Passflow application IDs that may call this API. A token must name at least one. */
110
- audience: string | string[];
73
+ /**
74
+ * Required, exact match against `iss`. The type takes `undefined` so that a value read from the environment
75
+ * passes the type check; `createVerifier` throws a `TypeError` when it is missing or empty.
76
+ */
77
+ issuer: string | undefined;
78
+ /**
79
+ * Required: the Passflow application IDs that may call this API. A token must name at least one. `undefined`
80
+ * passes the type check, as for `issuer`, and `createVerifier` throws a `TypeError` for it.
81
+ */
82
+ audience: string | string[] | undefined;
111
83
  /** Default: `{issuer}/.well-known/jwks.json`, Passflow's fixed path. OIDC discovery is not fetched. */
112
84
  jwksUrl?: string;
113
85
  /** Permits `http://` on a non-loopback host, for private networks. Default false. */
@@ -142,4 +114,25 @@ type VerifierConfig = {
142
114
  * built per request would defeat it.
143
115
  */
144
116
  export declare function createVerifier(config: VerifierConfig): Verifier;
145
- export { type Decision, type PassflowAuthErrorCode, type PassflowClaims, type Rejection, type Requirement, type TenantMembership, type Verifier, type VerifierConfig, rolesOf, verifiedBy };
117
+ type ProtectedResourceConfig = Omit<VerifierConfig, 'audience'> & {
118
+ /**
119
+ * Required: the exact URL clients name as the resource, and the audience a token must carry. It must use https
120
+ * unless the host is loopback, with no userinfo and no fragment. `undefined` passes the type check, as for
121
+ * `issuer`, and `createProtectedResource` throws a `TypeError` for it.
122
+ */
123
+ resource: string | undefined;
124
+ /**
125
+ * The scopes a client needs to start: the 401 challenge and `scopes_supported` list them. `offline_access` is
126
+ * not a scope of a resource and throws.
127
+ */
128
+ scopes?: string[];
129
+ /** Served as `resource_name`. */
130
+ name?: string;
131
+ };
132
+ /**
133
+ * Builds an OAuth protected resource, such as an MCP server: a verifier whose only audience is the resource, the
134
+ * RFC 9728 metadata that tells a client where to get a token, and the challenge parameters that name that metadata.
135
+ * Pass it to an adapter in place of a verifier. Touches no network. Throws `TypeError` on an invalid configuration.
136
+ */
137
+ export declare function createProtectedResource(config: ProtectedResourceConfig): ProtectedResource;
138
+ export { type Decision, type PassflowAuthErrorCode, type PassflowClaims, type ProtectedResource, type ProtectedResourceConfig, type Rejection, type Requirement, type ResourceChallenge, type ResourceMetadata, type TenantMembership, type Verifier, type VerifierConfig, authenticate, authenticateRequest, evaluate, rolesOf, verifiedBy };