@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.
- package/README.md +51 -3
- package/dist/adapter-Du22h3Lk.mjs +57 -0
- package/dist/adapter-DyCsMsEq.cjs +62 -0
- package/dist/evaluate-BAJUQu_Z.d.cts +141 -0
- package/dist/evaluate-BAJUQu_Z.d.mts +141 -0
- package/dist/{evaluate-D0c1hjYp.mjs → evaluate-CHts4VKy.mjs} +55 -18
- package/dist/{evaluate-DCpDLi4x.cjs → evaluate-Yv4mWPRI.cjs} +60 -17
- package/dist/express.cjs +18 -7
- package/dist/express.d.cts +10 -4
- package/dist/express.d.mts +10 -4
- package/dist/express.mjs +18 -7
- package/dist/fastify.cjs +18 -7
- package/dist/fastify.d.cts +12 -6
- package/dist/fastify.d.mts +12 -6
- package/dist/fastify.mjs +18 -7
- package/dist/hono.cjs +18 -7
- package/dist/hono.d.cts +11 -5
- package/dist/hono.d.mts +11 -5
- package/dist/hono.mjs +18 -7
- package/dist/index.cjs +82 -2
- package/dist/index.d.cts +24 -50
- package/dist/index.d.mts +24 -50
- package/dist/index.mjs +82 -3
- package/package.json +1 -1
- package/dist/claims-BHJhnzch.d.cts +0 -51
- package/dist/claims-BHJhnzch.d.mts +0 -51
package/dist/hono.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
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.
|
|
11
|
-
* on an invalid level or
|
|
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(
|
|
14
|
-
|
|
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. */
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_evaluate = require("./evaluate-
|
|
2
|
+
const require_evaluate = require("./evaluate-Yv4mWPRI.cjs");
|
|
3
3
|
const require_loopback = require("./loopback-ADMM_GlW.cjs");
|
|
4
4
|
let jose = require("jose");
|
|
5
5
|
// src/header.ts
|
|
@@ -8,6 +8,12 @@ const UTF8 = new TextDecoder("utf-8", {
|
|
|
8
8
|
fatal: true,
|
|
9
9
|
ignoreBOM: true
|
|
10
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
|
+
];
|
|
11
17
|
const BASE64URL$1 = /^[A-Za-z0-9_-]+$/;
|
|
12
18
|
function decodeProtectedHeader(segment) {
|
|
13
19
|
if (!BASE64URL$1.test(segment) || segment.length % 4 === 1) return;
|
|
@@ -20,7 +26,7 @@ function decodeProtectedHeader(segment) {
|
|
|
20
26
|
}
|
|
21
27
|
/**
|
|
22
28
|
* Header inspection, in the order Go and the corpus pin, before any key lookup: malformed, alg, crit,
|
|
23
|
-
* 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
|
|
24
30
|
* malformed token. Throws `PassflowAuthError` with `invalid_token` and the reason.
|
|
25
31
|
*/
|
|
26
32
|
function inspectHeader(token) {
|
|
@@ -31,6 +37,7 @@ function inspectHeader(token) {
|
|
|
31
37
|
if (header === void 0) throw new require_evaluate.PassflowAuthError("invalid_token", "malformed");
|
|
32
38
|
if (typeof header.alg !== "string" || !ALLOWED_ALGORITHMS.includes(header.alg)) throw new require_evaluate.PassflowAuthError("invalid_token", "alg");
|
|
33
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");
|
|
34
41
|
if (typeof header.kid !== "string" || header.kid === "") throw new require_evaluate.PassflowAuthError("invalid_token", "kid_missing");
|
|
35
42
|
}
|
|
36
43
|
// src/jwks.ts
|
|
@@ -523,6 +530,78 @@ function createVerifier(config) {
|
|
|
523
530
|
};
|
|
524
531
|
return verifier;
|
|
525
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
|
+
}
|
|
526
605
|
exports.AAL1 = require_evaluate.AAL1;
|
|
527
606
|
exports.AAL2 = require_evaluate.AAL2;
|
|
528
607
|
exports.AAL3 = require_evaluate.AAL3;
|
|
@@ -536,6 +615,7 @@ exports.acrSatisfies = require_evaluate.acrSatisfies;
|
|
|
536
615
|
exports.assertMaxAge = require_evaluate.assertMaxAge;
|
|
537
616
|
exports.authenticate = require_evaluate.authenticate;
|
|
538
617
|
exports.authenticateRequest = require_evaluate.authenticateRequest;
|
|
618
|
+
exports.createProtectedResource = createProtectedResource;
|
|
539
619
|
exports.createVerifier = createVerifier;
|
|
540
620
|
exports.evaluate = require_evaluate.evaluate;
|
|
541
621
|
exports.extractBearer = require_evaluate.extractBearer;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
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,53 +69,6 @@ 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
|
-
/**
|
|
107
|
-
* Authenticates a web `Request`, for a fetch-style server or a framework route handler with no adapter here.
|
|
108
|
-
* Verifies the `Authorization` header with `verifier`, then applies `requirement` if there is one. A rejection
|
|
109
|
-
* comes back as a ready `Response`: empty body, the challenge when there is one, and `Cache-Control: no-store`.
|
|
110
|
-
*
|
|
111
|
-
* Throws `TypeError` before it reads a header when the verifier or the request is missing, or the requirement
|
|
112
|
-
* is invalid: those are programming errors, not a bad token.
|
|
113
|
-
*/
|
|
114
|
-
export declare function authenticateRequest(verifier: Verifier, request: Request, requirement?: Requirement): Promise<{
|
|
115
|
-
claims: PassflowClaims;
|
|
116
|
-
} | {
|
|
117
|
-
response: Response;
|
|
118
|
-
}>;
|
|
119
72
|
type VerifierConfig = {
|
|
120
73
|
/**
|
|
121
74
|
* Required, exact match against `iss`. The type takes `undefined` so that a value read from the environment
|
|
@@ -161,4 +114,25 @@ type VerifierConfig = {
|
|
|
161
114
|
* built per request would defeat it.
|
|
162
115
|
*/
|
|
163
116
|
export declare function createVerifier(config: VerifierConfig): Verifier;
|
|
164
|
-
|
|
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 };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
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.mjs";
|
|
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,53 +69,6 @@ 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
|
-
/**
|
|
107
|
-
* Authenticates a web `Request`, for a fetch-style server or a framework route handler with no adapter here.
|
|
108
|
-
* Verifies the `Authorization` header with `verifier`, then applies `requirement` if there is one. A rejection
|
|
109
|
-
* comes back as a ready `Response`: empty body, the challenge when there is one, and `Cache-Control: no-store`.
|
|
110
|
-
*
|
|
111
|
-
* Throws `TypeError` before it reads a header when the verifier or the request is missing, or the requirement
|
|
112
|
-
* is invalid: those are programming errors, not a bad token.
|
|
113
|
-
*/
|
|
114
|
-
export declare function authenticateRequest(verifier: Verifier, request: Request, requirement?: Requirement): Promise<{
|
|
115
|
-
claims: PassflowClaims;
|
|
116
|
-
} | {
|
|
117
|
-
response: Response;
|
|
118
|
-
}>;
|
|
119
72
|
type VerifierConfig = {
|
|
120
73
|
/**
|
|
121
74
|
* Required, exact match against `iss`. The type takes `undefined` so that a value read from the environment
|
|
@@ -161,4 +114,25 @@ type VerifierConfig = {
|
|
|
161
114
|
* built per request would defeat it.
|
|
162
115
|
*/
|
|
163
116
|
export declare function createVerifier(config: VerifierConfig): Verifier;
|
|
164
|
-
|
|
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as AAL3, E as acrSatisfies, S as AAL2, T as acrLevel, _ as verifiedBy, a as authenticateRequest, b as extractBearer, c as PassflowAuthError, d as CHALLENGE_HEADER, f as CORS_EXPOSED_HEADERS, g as rolesOf, h as recordProvenance, i as authenticate, l as PassflowUsageError, m as extractClaims, n as assertScopes, o as evaluate, u as isPassflowAuthError, v as assertMaxAge, w as ACR_NONE, x as AAL1, y as formatChallenge } from "./evaluate-CHts4VKy.mjs";
|
|
2
2
|
import { t as isLoopbackHost } from "./loopback-CDiL_KzV.mjs";
|
|
3
3
|
import { base64url, createLocalJWKSet, errors, importJWK, jwtVerify } from "jose";
|
|
4
4
|
// src/header.ts
|
|
@@ -7,6 +7,12 @@ const UTF8 = new TextDecoder("utf-8", {
|
|
|
7
7
|
fatal: true,
|
|
8
8
|
ignoreBOM: true
|
|
9
9
|
});
|
|
10
|
+
/** The generic JWT media type and the access token one of RFC 9068. Media type names are case-insensitive. */
|
|
11
|
+
const ACCEPTED_TYP = [
|
|
12
|
+
"jwt",
|
|
13
|
+
"at+jwt",
|
|
14
|
+
"application/at+jwt"
|
|
15
|
+
];
|
|
10
16
|
const BASE64URL$1 = /^[A-Za-z0-9_-]+$/;
|
|
11
17
|
function decodeProtectedHeader(segment) {
|
|
12
18
|
if (!BASE64URL$1.test(segment) || segment.length % 4 === 1) return;
|
|
@@ -19,7 +25,7 @@ function decodeProtectedHeader(segment) {
|
|
|
19
25
|
}
|
|
20
26
|
/**
|
|
21
27
|
* 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
|
|
28
|
+
* typ, kid. It has to run before jose, which reports a standard parameter in `crit` with the same code as a
|
|
23
29
|
* malformed token. Throws `PassflowAuthError` with `invalid_token` and the reason.
|
|
24
30
|
*/
|
|
25
31
|
function inspectHeader(token) {
|
|
@@ -30,6 +36,7 @@ function inspectHeader(token) {
|
|
|
30
36
|
if (header === void 0) throw new PassflowAuthError("invalid_token", "malformed");
|
|
31
37
|
if (typeof header.alg !== "string" || !ALLOWED_ALGORITHMS.includes(header.alg)) throw new PassflowAuthError("invalid_token", "alg");
|
|
32
38
|
if (Object.hasOwn(header, "crit")) throw new PassflowAuthError("invalid_token", "crit");
|
|
39
|
+
if (Object.hasOwn(header, "typ") && !(typeof header.typ === "string" && ACCEPTED_TYP.includes(header.typ.toLowerCase()))) throw new PassflowAuthError("invalid_token", "typ");
|
|
33
40
|
if (typeof header.kid !== "string" || header.kid === "") throw new PassflowAuthError("invalid_token", "kid_missing");
|
|
34
41
|
}
|
|
35
42
|
// src/jwks.ts
|
|
@@ -522,4 +529,76 @@ function createVerifier(config) {
|
|
|
522
529
|
};
|
|
523
530
|
return verifier;
|
|
524
531
|
}
|
|
525
|
-
|
|
532
|
+
// src/resource.ts
|
|
533
|
+
const METADATA_WELL_KNOWN = "/.well-known/oauth-protected-resource";
|
|
534
|
+
const MAX_RESOURCE_BYTES = 2048;
|
|
535
|
+
/**
|
|
536
|
+
* Splits a resource into its origin, path and query. It admits no userinfo and no fragment, and nothing that needs
|
|
537
|
+
* escaping in a quoted challenge parameter.
|
|
538
|
+
*/
|
|
539
|
+
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})*)?$/;
|
|
540
|
+
/** The error names the rule, never the URL. The pattern admits ASCII only, so length is bytes. */
|
|
541
|
+
function splitResource(resource) {
|
|
542
|
+
const parts = typeof resource === "string" && resource.length <= MAX_RESOURCE_BYTES ? RESOURCE.exec(resource) : null;
|
|
543
|
+
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");
|
|
544
|
+
let url;
|
|
545
|
+
try {
|
|
546
|
+
url = new URL(resource);
|
|
547
|
+
} catch {
|
|
548
|
+
throw new TypeError("[passflow] resource must be a valid URL");
|
|
549
|
+
}
|
|
550
|
+
if (url.protocol !== "https:" && !isLoopbackHost(resource, url)) throw new TypeError("[passflow] resource must use https unless the host is loopback");
|
|
551
|
+
return {
|
|
552
|
+
resource,
|
|
553
|
+
origin: parts[1] ?? "",
|
|
554
|
+
path: parts[2] ?? "",
|
|
555
|
+
query: parts[3] ?? ""
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function requireScopeList(scopes) {
|
|
559
|
+
if (scopes === void 0) return [];
|
|
560
|
+
if (!Array.isArray(scopes)) throw new TypeError("[passflow] scopes must be an array");
|
|
561
|
+
const checked = scopes.length === 0 ? [] : assertScopes(scopes);
|
|
562
|
+
if (checked.includes("offline_access")) throw new TypeError("[passflow] scopes must not hold offline_access");
|
|
563
|
+
return checked;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Builds an OAuth protected resource, such as an MCP server: a verifier whose only audience is the resource, the
|
|
567
|
+
* RFC 9728 metadata that tells a client where to get a token, and the challenge parameters that name that metadata.
|
|
568
|
+
* Pass it to an adapter in place of a verifier. Touches no network. Throws `TypeError` on an invalid configuration.
|
|
569
|
+
*/
|
|
570
|
+
function createProtectedResource(config) {
|
|
571
|
+
if (typeof config !== "object" || config === null) throw new TypeError("[passflow] config must be an object");
|
|
572
|
+
const { resource: rawResource, scopes: rawScopes, name, ...verifierConfig } = config;
|
|
573
|
+
const { audience } = verifierConfig;
|
|
574
|
+
if (audience !== void 0 && !(Array.isArray(audience) && audience.length === 0)) throw new TypeError("[passflow] audience must not be set: the audience is the resource");
|
|
575
|
+
const { resource, origin, path, query } = splitResource(rawResource);
|
|
576
|
+
const scopes = requireScopeList(rawScopes);
|
|
577
|
+
if (name !== void 0 && typeof name !== "string") throw new TypeError("[passflow] name must be a string");
|
|
578
|
+
const verifier = createVerifier({
|
|
579
|
+
...verifierConfig,
|
|
580
|
+
audience: resource
|
|
581
|
+
});
|
|
582
|
+
const metadataPath = path === "/" ? METADATA_WELL_KNOWN : `${METADATA_WELL_KNOWN}${path}`;
|
|
583
|
+
const issuer = config.issuer;
|
|
584
|
+
return {
|
|
585
|
+
verifier,
|
|
586
|
+
metadataPath,
|
|
587
|
+
metadata: () => ({
|
|
588
|
+
resource,
|
|
589
|
+
authorization_servers: [issuer],
|
|
590
|
+
...scopes.length > 0 ? { scopes_supported: [...scopes] } : {},
|
|
591
|
+
bearer_methods_supported: ["header"],
|
|
592
|
+
...name ? { resource_name: name } : {}
|
|
593
|
+
}),
|
|
594
|
+
requireScopes: (...required) => ({
|
|
595
|
+
kind: "scope",
|
|
596
|
+
scopes: assertScopes(required)
|
|
597
|
+
}),
|
|
598
|
+
challenge: {
|
|
599
|
+
resourceMetadata: `${origin}${metadataPath}${query}`,
|
|
600
|
+
...scopes.length > 0 ? { scope: scopes.join(" ") } : {}
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
export { AAL1, AAL2, AAL3, ACR_NONE, CHALLENGE_HEADER, CORS_EXPOSED_HEADERS, PassflowAuthError, PassflowUsageError, acrLevel, acrSatisfies, assertMaxAge, authenticate, authenticateRequest, createProtectedResource, createVerifier, evaluate, extractBearer, formatChallenge, isPassflowAuthError, rolesOf, verifiedBy };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@passflow/node",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Passflow for Node.js: token verification, ACR floors, auth_time freshness and RFC 9470 step-up challenges for resource servers, with Express, Fastify and Hono adapters, and a server-side sign-in session core for framework adapters.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/usepassflow/go/tree/main/examples/resource-server",
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
/** The `passflow_tm` wire shape, camelCased. `tenantRoles` is decoded for raw access; `rolesOf` does not read it. */
|
|
2
|
-
type TenantMembership = {
|
|
3
|
-
tenantId: string;
|
|
4
|
-
tenantName?: string;
|
|
5
|
-
tenantRoles?: string[];
|
|
6
|
-
rootGroupId?: string;
|
|
7
|
-
groups?: Record<string, string[]>;
|
|
8
|
-
groupNames?: Record<string, string>;
|
|
9
|
-
};
|
|
10
|
-
type PassflowClaims = {
|
|
11
|
-
sub: string;
|
|
12
|
-
iss: string;
|
|
13
|
-
aud: string[];
|
|
14
|
-
exp: number;
|
|
15
|
-
iat?: number;
|
|
16
|
-
/** Whole Unix seconds. Absent when the claim is absent, not a number or beyond ±2^53. */
|
|
17
|
-
authTime?: number;
|
|
18
|
-
/** `'0'` when the claim is absent or not a string. */
|
|
19
|
-
acr: string;
|
|
20
|
-
amr: string[];
|
|
21
|
-
scopes: string[];
|
|
22
|
-
sid?: string;
|
|
23
|
-
type: string;
|
|
24
|
-
tenants: Record<string, TenantMembership>;
|
|
25
|
-
/** The verifier's clock at verification, in Unix seconds. `requireFresh` measures from it. */
|
|
26
|
-
verifiedAt: number;
|
|
27
|
-
raw: Record<string, unknown>;
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* The structural part of a verifier. Declared here, with `verifiedBy`, so that provenance needs nothing
|
|
31
|
-
* from the verifier module.
|
|
32
|
-
*/
|
|
33
|
-
interface Verifier {
|
|
34
|
-
verify(token: string): Promise<PassflowClaims>;
|
|
35
|
-
refresh(): Promise<void>;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* True only for the exact object `verifier.verify` returned. A spread or clone loses provenance, which
|
|
39
|
-
* costs one more verification and never a bypass. So does any wrapper or decorator object that delegates
|
|
40
|
-
* to `verifier.verify`: it is a different identity, and this verifier's adapter re-verifies claims it
|
|
41
|
-
* returns. Two verifiers built from the same configuration are different identities too.
|
|
42
|
-
*/
|
|
43
|
-
declare function verifiedBy(claims: PassflowClaims, verifier: Verifier): boolean;
|
|
44
|
-
/**
|
|
45
|
-
* The roles a user holds in a tenant: `groups[rootGroupId]`, the rule the server's `CalcTenantRoles` and
|
|
46
|
-
* `@passflow/core`'s `parseMembership` apply. A missing tenant, root group or map gives an empty list.
|
|
47
|
-
* So does an empty `rootGroupId`, unlike the server: no role is granted from a group keyed by "".
|
|
48
|
-
* `tenantRoles` is a copy the server derives from the same root group, and is not consulted.
|
|
49
|
-
*/
|
|
50
|
-
declare function rolesOf(claims: PassflowClaims, tenantId: string): string[];
|
|
51
|
-
export { verifiedBy as a, rolesOf as i, TenantMembership as n, Verifier as r, PassflowClaims as t };
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
/** The `passflow_tm` wire shape, camelCased. `tenantRoles` is decoded for raw access; `rolesOf` does not read it. */
|
|
2
|
-
type TenantMembership = {
|
|
3
|
-
tenantId: string;
|
|
4
|
-
tenantName?: string;
|
|
5
|
-
tenantRoles?: string[];
|
|
6
|
-
rootGroupId?: string;
|
|
7
|
-
groups?: Record<string, string[]>;
|
|
8
|
-
groupNames?: Record<string, string>;
|
|
9
|
-
};
|
|
10
|
-
type PassflowClaims = {
|
|
11
|
-
sub: string;
|
|
12
|
-
iss: string;
|
|
13
|
-
aud: string[];
|
|
14
|
-
exp: number;
|
|
15
|
-
iat?: number;
|
|
16
|
-
/** Whole Unix seconds. Absent when the claim is absent, not a number or beyond ±2^53. */
|
|
17
|
-
authTime?: number;
|
|
18
|
-
/** `'0'` when the claim is absent or not a string. */
|
|
19
|
-
acr: string;
|
|
20
|
-
amr: string[];
|
|
21
|
-
scopes: string[];
|
|
22
|
-
sid?: string;
|
|
23
|
-
type: string;
|
|
24
|
-
tenants: Record<string, TenantMembership>;
|
|
25
|
-
/** The verifier's clock at verification, in Unix seconds. `requireFresh` measures from it. */
|
|
26
|
-
verifiedAt: number;
|
|
27
|
-
raw: Record<string, unknown>;
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* The structural part of a verifier. Declared here, with `verifiedBy`, so that provenance needs nothing
|
|
31
|
-
* from the verifier module.
|
|
32
|
-
*/
|
|
33
|
-
interface Verifier {
|
|
34
|
-
verify(token: string): Promise<PassflowClaims>;
|
|
35
|
-
refresh(): Promise<void>;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* True only for the exact object `verifier.verify` returned. A spread or clone loses provenance, which
|
|
39
|
-
* costs one more verification and never a bypass. So does any wrapper or decorator object that delegates
|
|
40
|
-
* to `verifier.verify`: it is a different identity, and this verifier's adapter re-verifies claims it
|
|
41
|
-
* returns. Two verifiers built from the same configuration are different identities too.
|
|
42
|
-
*/
|
|
43
|
-
declare function verifiedBy(claims: PassflowClaims, verifier: Verifier): boolean;
|
|
44
|
-
/**
|
|
45
|
-
* The roles a user holds in a tenant: `groups[rootGroupId]`, the rule the server's `CalcTenantRoles` and
|
|
46
|
-
* `@passflow/core`'s `parseMembership` apply. A missing tenant, root group or map gives an empty list.
|
|
47
|
-
* So does an empty `rootGroupId`, unlike the server: no role is granted from a group keyed by "".
|
|
48
|
-
* `tenantRoles` is a copy the server derives from the same root group, and is not consulted.
|
|
49
|
-
*/
|
|
50
|
-
declare function rolesOf(claims: PassflowClaims, tenantId: string): string[];
|
|
51
|
-
export { verifiedBy as a, rolesOf as i, TenantMembership as n, Verifier as r, PassflowClaims as t };
|