@passflow/node 0.2.0 → 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.
@@ -122,6 +122,10 @@ function isStringArray(value) {
122
122
  function stringsOf(value) {
123
123
  return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
124
124
  }
125
+ function scopesOf(payload) {
126
+ if (!Object.hasOwn(payload, "scope")) return stringsOf(payload.scopes);
127
+ return typeof payload.scope === "string" ? payload.scope.split(" ").filter((scope) => scope !== "") : [];
128
+ }
125
129
  /** A wrong JSON type means the membership cannot be read. `null` reads as absent, as Go's decoder does. */
126
130
  function decodeMembership(value) {
127
131
  if (!isPlainObject(value)) return;
@@ -169,7 +173,7 @@ function decodeTenants(value) {
169
173
  }
170
174
  /** Fail-closed claim extraction from a payload whose signature and registered claims already passed. */
171
175
  function extractClaims(payload, verifiedAt) {
172
- const { sub, iss, aud, exp, iat, auth_time: authTime, acr, amr, scopes, sid, type, passflow_tm: tenants } = payload;
176
+ const { sub, iss, aud, exp, iat, auth_time: authTime, acr, amr, client_id: clientId, sid, type, passflow_tm: tenants } = payload;
173
177
  const claims = {
174
178
  sub: typeof sub === "string" ? sub : "",
175
179
  iss: typeof iss === "string" ? iss : "",
@@ -177,7 +181,7 @@ function extractClaims(payload, verifiedAt) {
177
181
  exp,
178
182
  acr: typeof acr === "string" ? acr : "0",
179
183
  amr: stringsOf(amr),
180
- scopes: stringsOf(scopes),
184
+ scopes: scopesOf(payload),
181
185
  type: typeof type === "string" ? type : "",
182
186
  tenants: decodeTenants(tenants),
183
187
  verifiedAt,
@@ -185,6 +189,7 @@ function extractClaims(payload, verifiedAt) {
185
189
  };
186
190
  if (isExactSeconds(iat)) claims.iat = iat;
187
191
  if (isExactSeconds(authTime)) claims.authTime = Math.trunc(authTime);
192
+ if (typeof clientId === "string") claims.clientId = clientId;
188
193
  if (typeof sid === "string") claims.sid = sid;
189
194
  return claims;
190
195
  }
@@ -271,17 +276,38 @@ const reject = (status, wwwAuthenticate) => ({
271
276
  [CACHE_CONTROL]: NO_STORE
272
277
  }
273
278
  });
279
+ /** Parameter order is fixed: error, scope, resource_metadata. Absent ones are omitted. */
280
+ function formatBearer(error, scope, challenge) {
281
+ const parameters = [];
282
+ if (error !== void 0) parameters.push(`error="${error}"`);
283
+ if (scope !== void 0) parameters.push(`scope="${scope}"`);
284
+ if (challenge !== void 0) parameters.push(`resource_metadata="${challenge.resourceMetadata}"`);
285
+ return parameters.length === 0 ? "Bearer" : `Bearer ${parameters.join(", ")}`;
286
+ }
287
+ function rejectStepUp(stepUp, challenge) {
288
+ return reject(401, challenge === void 0 ? stepUp : `${stepUp}, resource_metadata="${challenge.resourceMetadata}"`);
289
+ }
274
290
  /**
275
291
  * Authentication failures never carry the step-up error: the browser SDK acts only on the step-up challenge,
276
292
  * and every other response, a plain 401 or a 503 included, reaches the caller's code unchanged.
277
293
  */
278
- function rejectAuthentication(code) {
294
+ function rejectAuthentication(code, challenge) {
279
295
  switch (code) {
280
- case "missing_token": return reject(401, "Bearer");
281
- case "invalid_token": return reject(401, "Bearer error=\"invalid_token\"");
296
+ case "missing_token": return reject(401, formatBearer(void 0, challenge?.scope, challenge));
297
+ case "invalid_token": return reject(401, formatBearer("invalid_token", challenge?.scope, challenge));
282
298
  case "jwks_unavailable": return reject(503);
283
299
  }
284
300
  }
301
+ /** The scope-token of RFC 6749, section 3.3. */
302
+ const SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
303
+ /** Internal: one or more scope tokens, or a `TypeError`. The result is a copy. */
304
+ function assertScopes(scopes) {
305
+ if (!Array.isArray(scopes) || scopes.length === 0) throw new TypeError("[passflow] scopes must name one or more scopes");
306
+ return Array.from(scopes, (scope) => {
307
+ if (typeof scope !== "string" || !SCOPE_TOKEN.test(scope)) throw new TypeError("[passflow] scopes must hold RFC 6749 scope tokens");
308
+ return scope;
309
+ });
310
+ }
285
311
  /**
286
312
  * Validates a requirement and returns it with the effective freshness limit. Throws `TypeError`: this is a
287
313
  * programming error that should stop the process at route registration, not become a `Decision`.
@@ -298,8 +324,12 @@ function assertRequirement(requirement) {
298
324
  kind: "fresh",
299
325
  maxAgeSeconds: assertMaxAge(requirement.maxAgeSeconds)
300
326
  };
327
+ if (requirement.kind === "scope") return {
328
+ kind: "scope",
329
+ scopes: assertScopes(requirement.scopes)
330
+ };
301
331
  }
302
- throw new TypeError("[passflow] a requirement is { kind: \"acr\", min } or { kind: \"fresh\", maxAgeSeconds }");
332
+ throw new TypeError("[passflow] a requirement is { kind: \"acr\", min }, { kind: \"fresh\", maxAgeSeconds } or { kind: \"scope\", scopes }");
303
333
  }
304
334
  function isFresh(claims, maxAgeSeconds) {
305
335
  const { authTime, verifiedAt } = claims;
@@ -309,36 +339,43 @@ function isFresh(claims, maxAgeSeconds) {
309
339
  /**
310
340
  * Decides one requirement against claims. No claims means the middleware was composed wrongly, so the answer
311
341
  * is a 500 with no challenge: never a step-up, which the SDK would try to satisfy, and never a 401, because a
312
- * wiring bug must not be reported as a bad token. Throws `TypeError` on an invalid requirement.
342
+ * wiring bug must not be reported as a bad token. Throws `TypeError` on an invalid requirement. With `challenge`, a
343
+ * rejection names the resource metadata.
313
344
  */
314
- function evaluate(claims, requirement) {
345
+ function evaluate(claims, requirement, challenge) {
315
346
  const checked = assertRequirement(requirement);
316
347
  if (claims === void 0 || claims === null) return reject(500);
317
- if (checked.kind === "acr") return acrSatisfies(claims.acr, checked.min) ? { kind: "allow" } : reject(401, formatChallenge({ acrValues: checked.min }));
318
- return isFresh(claims, checked.maxAgeSeconds) ? { kind: "allow" } : reject(401, formatChallenge({ maxAge: checked.maxAgeSeconds }));
348
+ if (checked.kind === "acr") return acrSatisfies(claims.acr, checked.min) ? { kind: "allow" } : rejectStepUp(formatChallenge({ acrValues: checked.min }), challenge);
349
+ if (checked.kind === "scope") {
350
+ const { scopes } = checked;
351
+ const granted = claims.scopes;
352
+ return Array.isArray(granted) && scopes.every((scope) => granted.includes(scope)) ? { kind: "allow" } : reject(403, formatBearer("insufficient_scope", scopes.join(" "), challenge));
353
+ }
354
+ return isFresh(claims, checked.maxAgeSeconds) ? { kind: "allow" } : rejectStepUp(formatChallenge({ maxAge: checked.maxAgeSeconds }), challenge);
319
355
  }
320
356
  /**
321
357
  * Authenticates a request. `existing` claims are reused only when `verifier` produced that exact object;
322
358
  * otherwise the presented header is verified with `verifier`, so a token outside this verifier's trust policy
323
- * is rejected as not valid here, never as insufficient. Never rejects: a failure is a `{ reject }` value.
359
+ * is rejected as not valid here, never as insufficient. Never rejects: a failure is a `{ reject }` value. With
360
+ * `challenge`, a 401 carries the resource's scope and metadata URL.
324
361
  */
325
- async function authenticate(verifier, authorization, existing) {
362
+ async function authenticate(verifier, authorization, existing, challenge) {
326
363
  if (existing !== void 0 && existing !== null && verifiedBy(existing, verifier)) return { claims: existing };
327
364
  const token = extractBearer(authorization);
328
- if (token === void 0) return { reject: rejectAuthentication("missing_token") };
365
+ if (token === void 0) return { reject: rejectAuthentication("missing_token", challenge) };
329
366
  try {
330
367
  return { claims: await verifier.verify(token) };
331
368
  } catch (error) {
332
- return { reject: isPassflowAuthError(error) ? rejectAuthentication(error.code) : reject(500) };
369
+ return { reject: isPassflowAuthError(error) ? rejectAuthentication(error.code, challenge) : reject(500) };
333
370
  }
334
371
  }
335
372
  /**
336
373
  * Internal: one adapter step. Authenticates, then applies the requirement if there is one.
337
374
  */
338
- async function guard(verifier, authorization, existing, requirement) {
339
- const result = await authenticate(verifier, authorization, existing);
375
+ async function guard(verifier, authorization, existing, requirement, challenge) {
376
+ const result = await authenticate(verifier, authorization, existing, challenge);
340
377
  if ("reject" in result || requirement === void 0) return result;
341
- const decision = evaluate(result.claims, requirement);
378
+ const decision = evaluate(result.claims, requirement, challenge);
342
379
  return decision.kind === "reject" ? { reject: decision } : result;
343
380
  }
344
381
  /**
@@ -439,6 +476,12 @@ Object.defineProperty(exports, "assertRequirement", {
439
476
  return assertRequirement;
440
477
  }
441
478
  });
479
+ Object.defineProperty(exports, "assertScopes", {
480
+ enumerable: true,
481
+ get: function() {
482
+ return assertScopes;
483
+ }
484
+ });
442
485
  Object.defineProperty(exports, "assertVerifier", {
443
486
  enumerable: true,
444
487
  get: function() {
package/dist/express.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluate = require("./evaluate-DCpDLi4x.cjs");
2
+ const require_adapter = require("./adapter-DyCsMsEq.cjs");
3
+ const require_evaluate = require("./evaluate-Yv4mWPRI.cjs");
3
4
  // src/express.ts
4
5
  /** Written directly and never through `next(err)`: a custom error handler would drop `WWW-Authenticate`. */
5
6
  function send(res, rejection) {
@@ -8,13 +9,15 @@ function send(res, rejection) {
8
9
  /**
9
10
  * Express 4 and 5 middleware. `authenticate` always verifies the presented token and replaces any claims on the
10
11
  * request. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier produced that
11
- * exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction on
12
- * an invalid level or limit.
12
+ * exact object, and otherwise verify the presented token themselves. `requireScopes`
13
+ * does the same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A
14
+ * protected resource adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser
15
+ * client may send a preflight request.
13
16
  */
14
- function passflowExpress(verifier) {
15
- require_evaluate.assertVerifier(verifier);
17
+ function passflowExpress(target) {
18
+ const { verifier, challenge, metadata } = require_adapter.adapterTarget(target);
16
19
  const middleware = (reuse, requirement) => (req, res, next) => {
17
- require_evaluate.guard(verifier, req.headers.authorization, reuse ? req.passflow : void 0, requirement).then((result) => {
20
+ require_evaluate.guard(verifier, req.headers.authorization, reuse ? req.passflow : void 0, requirement, challenge).then((result) => {
18
21
  if ("reject" in result) {
19
22
  send(res, result.reject);
20
23
  return;
@@ -32,7 +35,15 @@ function passflowExpress(verifier) {
32
35
  requireFresh: (maxAgeSeconds) => middleware(true, require_evaluate.assertRequirement({
33
36
  kind: "fresh",
34
37
  maxAgeSeconds
35
- }))
38
+ })),
39
+ requireScopes: (...scopes) => middleware(true, require_evaluate.assertRequirement({
40
+ kind: "scope",
41
+ scopes
42
+ })),
43
+ metadata: (req, res) => {
44
+ const { status, headers, body } = metadata(req.method);
45
+ res.status(status).set(headers).end(body ?? void 0);
46
+ }
36
47
  };
37
48
  }
38
49
  /** The claims a Passflow middleware put on this request. Throws `PassflowUsageError` if none ran. */
@@ -1,4 +1,4 @@
1
- import { r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.cjs";
1
+ import { f as Verifier, n as ProtectedResource, u as PassflowClaims } from "./evaluate-BAJUQu_Z.cjs";
2
2
  import { Request, RequestHandler } from "express";
3
3
  declare global {
4
4
  namespace Express {
@@ -11,13 +11,19 @@ declare global {
11
11
  /**
12
12
  * Express 4 and 5 middleware. `authenticate` always verifies the presented token and replaces any claims on the
13
13
  * request. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier produced that
14
- * exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction on
15
- * an invalid level or limit.
14
+ * exact object, and otherwise verify the presented token themselves. `requireScopes`
15
+ * does the same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A
16
+ * protected resource adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser
17
+ * client may send a preflight request.
16
18
  */
17
- export declare function passflowExpress(verifier: Verifier): {
19
+ export declare function passflowExpress(target: Verifier | ProtectedResource): {
18
20
  authenticate: RequestHandler;
19
21
  requireACR(min: string): RequestHandler;
20
22
  requireFresh(maxAgeSeconds: number): RequestHandler;
23
+ /** Answers 403 unless the token carries every scope: what the user delegated to the client, not what the user may do. */
24
+ requireScopes(...scopes: string[]): RequestHandler;
25
+ /** Serves the RFC 9728 metadata document. Throws `PassflowUsageError` when built from a plain verifier. */
26
+ metadata: RequestHandler;
21
27
  };
22
28
  /** The claims a Passflow middleware put on this request. Throws `PassflowUsageError` if none ran. */
23
29
  export declare function getAuth(req: Pick<Request, 'passflow'>): PassflowClaims;
@@ -1,4 +1,4 @@
1
- import { r as Verifier, t as PassflowClaims } from "./claims-BHJhnzch.mjs";
1
+ import { f as Verifier, n as ProtectedResource, u as PassflowClaims } from "./evaluate-BAJUQu_Z.mjs";
2
2
  import { Request, RequestHandler } from "express";
3
3
  declare global {
4
4
  namespace Express {
@@ -11,13 +11,19 @@ declare global {
11
11
  /**
12
12
  * Express 4 and 5 middleware. `authenticate` always verifies the presented token and replaces any claims on the
13
13
  * request. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier produced that
14
- * exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction on
15
- * an invalid level or limit.
14
+ * exact object, and otherwise verify the presented token themselves. `requireScopes`
15
+ * does the same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A
16
+ * protected resource adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser
17
+ * client may send a preflight request.
16
18
  */
17
- export declare function passflowExpress(verifier: Verifier): {
19
+ export declare function passflowExpress(target: Verifier | ProtectedResource): {
18
20
  authenticate: RequestHandler;
19
21
  requireACR(min: string): RequestHandler;
20
22
  requireFresh(maxAgeSeconds: number): RequestHandler;
23
+ /** Answers 403 unless the token carries every scope: what the user delegated to the client, not what the user may do. */
24
+ requireScopes(...scopes: string[]): RequestHandler;
25
+ /** Serves the RFC 9728 metadata document. Throws `PassflowUsageError` when built from a plain verifier. */
26
+ metadata: RequestHandler;
21
27
  };
22
28
  /** The claims a Passflow middleware put on this request. Throws `PassflowUsageError` if none ran. */
23
29
  export declare function getAuth(req: Pick<Request, 'passflow'>): PassflowClaims;
package/dist/express.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { c as PassflowUsageError, f as withChallengeHeader, n as assertVerifier, o as guard, t as assertRequirement } from "./evaluate-D0c1hjYp.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/express.ts
3
4
  /** Written directly and never through `next(err)`: a custom error handler would drop `WWW-Authenticate`. */
4
5
  function send(res, rejection) {
@@ -7,13 +8,15 @@ function send(res, rejection) {
7
8
  /**
8
9
  * Express 4 and 5 middleware. `authenticate` always verifies the presented token and replaces any claims on the
9
10
  * request. `requireACR` and `requireFresh` work alone: they reuse claims only when this verifier produced that
10
- * exact object, and otherwise verify the presented token themselves. Both throw `TypeError` at construction on
11
- * an invalid level or limit.
11
+ * exact object, and otherwise verify the presented token themselves. `requireScopes`
12
+ * does the same for scopes. All three throw `TypeError` at construction on an invalid level, limit or scope. A
13
+ * protected resource adds its own parameters to the challenges. Mount `metadata` with `app.all`, because a browser
14
+ * client may send a preflight request.
12
15
  */
13
- function passflowExpress(verifier) {
14
- assertVerifier(verifier);
16
+ function passflowExpress(target) {
17
+ const { verifier, challenge, metadata } = adapterTarget(target);
15
18
  const middleware = (reuse, requirement) => (req, res, next) => {
16
- guard(verifier, req.headers.authorization, reuse ? req.passflow : void 0, requirement).then((result) => {
19
+ guard(verifier, req.headers.authorization, reuse ? req.passflow : void 0, requirement, challenge).then((result) => {
17
20
  if ("reject" in result) {
18
21
  send(res, result.reject);
19
22
  return;
@@ -31,7 +34,15 @@ function passflowExpress(verifier) {
31
34
  requireFresh: (maxAgeSeconds) => middleware(true, assertRequirement({
32
35
  kind: "fresh",
33
36
  maxAgeSeconds
34
- }))
37
+ })),
38
+ requireScopes: (...scopes) => middleware(true, assertRequirement({
39
+ kind: "scope",
40
+ scopes
41
+ })),
42
+ metadata: (req, res) => {
43
+ const { status, headers, body } = metadata(req.method);
44
+ res.status(status).set(headers).end(body ?? void 0);
45
+ }
35
46
  };
36
47
  }
37
48
  /** The claims a Passflow middleware put on this request. Throws `PassflowUsageError` if none ran. */
package/dist/fastify.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluate = require("./evaluate-DCpDLi4x.cjs");
2
+ const require_adapter = require("./adapter-DyCsMsEq.cjs");
3
+ const require_evaluate = require("./evaluate-Yv4mWPRI.cjs");
3
4
  // src/fastify.ts
4
5
  function send(reply, rejection) {
5
6
  reply.code(rejection.status).headers(rejection.headers).send();
@@ -9,14 +10,16 @@ function send(reply, rejection) {
9
10
  * verifier on an instance. Each is a `preHandler`-shaped async function. `authenticate` always verifies the presented
10
11
  * token and replaces `request.passflow`. `requireACR` and `requireFresh` reuse claims only when this verifier produced
11
12
  * that exact object, and otherwise verify the presented token themselves, so a broad instance-level hook followed by
12
- * a narrow route-level one enforces the narrow verifier's policy. Both throw `TypeError` at construction on an invalid
13
- * level or limit.
13
+ * a narrow route-level one enforces the narrow verifier's policy. `requireScopes` does the same for scopes.
14
+ * All three throw `TypeError` at construction on an invalid level, limit or scope. A protected resource adds its own
15
+ * parameters to the challenges. Mount `metadata` on GET, HEAD and OPTIONS, because a browser client may send a preflight
16
+ * request.
14
17
  */
15
- function createFastifyHooks(verifier) {
16
- require_evaluate.assertVerifier(verifier);
18
+ function createFastifyHooks(target) {
19
+ const { verifier, challenge, metadata } = require_adapter.adapterTarget(target);
17
20
  const hook = (reuse, requirement) => async (request, reply) => {
18
21
  const existing = reuse ? request.passflow ?? void 0 : void 0;
19
- const result = await require_evaluate.guard(verifier, request.headers.authorization, existing, requirement);
22
+ const result = await require_evaluate.guard(verifier, request.headers.authorization, existing, requirement, challenge);
20
23
  if ("reject" in result) {
21
24
  send(reply, result.reject);
22
25
  return reply;
@@ -32,7 +35,15 @@ function createFastifyHooks(verifier) {
32
35
  requireFresh: (maxAgeSeconds) => hook(true, require_evaluate.assertRequirement({
33
36
  kind: "fresh",
34
37
  maxAgeSeconds
35
- }))
38
+ })),
39
+ requireScopes: (...scopes) => hook(true, require_evaluate.assertRequirement({
40
+ kind: "scope",
41
+ scopes
42
+ })),
43
+ metadata: (request, reply) => {
44
+ const { status, headers, body } = metadata(request.method);
45
+ return reply.code(status).headers(headers).send(body ?? void 0);
46
+ }
36
47
  };
37
48
  }
38
49
  const plugin = async (fastify, opts) => {
@@ -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,17 +22,19 @@ 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;
@@ -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,17 +22,19 @@ 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;
package/dist/fastify.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { c as PassflowUsageError, f as withChallengeHeader, n as assertVerifier, o as guard, t as assertRequirement } from "./evaluate-D0c1hjYp.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) => {
package/dist/hono.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_evaluate = require("./evaluate-DCpDLi4x.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. */
package/dist/hono.d.cts CHANGED
@@ -1,18 +1,24 @@
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;
package/dist/hono.d.mts CHANGED
@@ -1,18 +1,24 @@
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;