@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/README.md
CHANGED
|
@@ -54,7 +54,7 @@ app.get('/invoices', { preHandler: app.passflow.requireACR(AAL2) }, async (reque
|
|
|
54
54
|
}));
|
|
55
55
|
```
|
|
56
56
|
|
|
57
|
-
A second registration throws Fastify's own `FST_ERR_DEC_ALREADY_PRESENT`, so use `createFastifyHooks(verifier)` for every further verifier. It returns the same
|
|
57
|
+
A second registration throws Fastify's own `FST_ERR_DEC_ALREADY_PRESENT`, so use `createFastifyHooks(verifier)` for every further verifier. It returns the same hooks with no plugin and no decoration.
|
|
58
58
|
|
|
59
59
|
### Hono
|
|
60
60
|
|
|
@@ -78,7 +78,12 @@ app.get('/invoices', passflow.requireACR(AAL2), (c) => c.json({ subject: getAuth
|
|
|
78
78
|
```js
|
|
79
79
|
import { AAL2, authenticateRequest, createVerifier } from '@passflow/node';
|
|
80
80
|
|
|
81
|
-
const verifier = createVerifier({
|
|
81
|
+
const verifier = createVerifier({
|
|
82
|
+
issuer: process.env.PASSFLOW_ISSUER,
|
|
83
|
+
audience: process.env.PASSFLOW_AUDIENCE?.split(',')
|
|
84
|
+
.map((id) => id.trim())
|
|
85
|
+
.filter(Boolean),
|
|
86
|
+
});
|
|
82
87
|
|
|
83
88
|
export async function GET(request) {
|
|
84
89
|
const result = await authenticateRequest(verifier, request, { kind: 'acr', min: AAL2 });
|
|
@@ -87,6 +92,8 @@ export async function GET(request) {
|
|
|
87
92
|
}
|
|
88
93
|
```
|
|
89
94
|
|
|
95
|
+
`audience` takes a string or a list, and a string is one audience: a comma-separated `PASSFLOW_AUDIENCE` is split first, as above. A missing or empty value throws `TypeError` at startup.
|
|
96
|
+
|
|
90
97
|
The requirement is `{ kind: 'acr', min }` or `{ kind: 'fresh', maxAgeSeconds }`, or none. A missing verifier or request, or an invalid requirement, throws `TypeError` before any header is read.
|
|
91
98
|
|
|
92
99
|
### Any other framework
|
|
@@ -100,6 +107,46 @@ const result = await authenticate(verifier, request.headers.get('authorization')
|
|
|
100
107
|
if ('reject' in result) return new Response(null, result.reject);
|
|
101
108
|
```
|
|
102
109
|
|
|
110
|
+
## Protect an MCP server
|
|
111
|
+
|
|
112
|
+
`createProtectedResource` makes the API an OAuth protected resource (RFC 9728). It takes the options of `createVerifier` except `audience`, because the resource URL is the only audience. Register the same URL, with its scopes, under `oidc.resources` in Passflow. The token's `aud` carries the URL exactly as it is registered and the SDK compares it byte for byte, so `resource` must match the registered URI to the byte: `https://mcp.example.com/mcp/` with a trailing `/` is another resource, and its tokens get 401. Pass the result to an adapter in place of a verifier.
|
|
113
|
+
|
|
114
|
+
```js
|
|
115
|
+
import { createProtectedResource } from '@passflow/node';
|
|
116
|
+
import { passflowExpress } from '@passflow/node/express';
|
|
117
|
+
import express from 'express';
|
|
118
|
+
|
|
119
|
+
const resource = createProtectedResource({
|
|
120
|
+
issuer: 'https://auth.example.com',
|
|
121
|
+
resource: 'https://mcp.example.com/mcp',
|
|
122
|
+
scopes: ['mcp'], // what a client needs to start
|
|
123
|
+
name: 'Notes',
|
|
124
|
+
});
|
|
125
|
+
const passflow = passflowExpress(resource);
|
|
126
|
+
|
|
127
|
+
const app = express();
|
|
128
|
+
app.all(resource.metadataPath, passflow.metadata);
|
|
129
|
+
app.post('/mcp', passflow.requireScopes('mcp'), mcpHandler);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`requireScopes` authenticates on demand. A scope is what the user delegated to the client, not what the user may do, so check the user's own permissions in the handler. In Hono, mount `metadata` with `app.all` too. In Fastify, mount it on all three methods:
|
|
133
|
+
|
|
134
|
+
```js
|
|
135
|
+
await app.register(passflowFastify, { verifier: resource });
|
|
136
|
+
app.route({ method: ['GET', 'HEAD', 'OPTIONS'], url: resource.metadataPath, handler: app.passflow.metadata });
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
On another framework, serve `resource.metadata()` as JSON, call `authenticate(resource.verifier, authorization, undefined, resource.challenge)`, and then `evaluate(claims, resource.requireScopes('mcp'), resource.challenge)`.
|
|
140
|
+
|
|
141
|
+
| Situation | Status | `WWW-Authenticate` |
|
|
142
|
+
| ------------- | ------ | ---------------------------------------------------------------------------------------------------------- |
|
|
143
|
+
| No token | 401 | `Bearer scope="mcp", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"` |
|
|
144
|
+
| Invalid token | 401 | `Bearer error="invalid_token", scope="mcp", resource_metadata="…"` |
|
|
145
|
+
| Missing scope | 403 | `Bearer error="insufficient_scope", scope="mcp notes:write", resource_metadata="…"` |
|
|
146
|
+
| Step-up | 401 | the step-up challenge below, then `, resource_metadata="…"` |
|
|
147
|
+
|
|
148
|
+
The 403 lists every scope the route requires.
|
|
149
|
+
|
|
103
150
|
## Sign users in on the server: `@passflow/node/session`
|
|
104
151
|
|
|
105
152
|
`@passflow/node/session` is the framework-neutral core that `@passflow/nextjs` and `@passflow/tanstack-react-start` build on. Use one of those for an app; use the core directly to write an adapter for another framework. It reads web `Request`s, returns web `Response`s, and runs on any runtime with WebCrypto and `fetch`.
|
|
@@ -165,7 +212,8 @@ type PassflowClaims = {
|
|
|
165
212
|
authTime?: number; // whole Unix seconds; absent when the claim is absent, not a number or beyond ±2^53
|
|
166
213
|
acr: string; // '0' when the claim is absent or not a string
|
|
167
214
|
amr: string[];
|
|
168
|
-
scopes: string[];
|
|
215
|
+
scopes: string[]; // the scope claim, or the scopes array of a token without one
|
|
216
|
+
clientId?: string; // the client the token was issued to
|
|
169
217
|
sid?: string;
|
|
170
218
|
type: string;
|
|
171
219
|
tenants: Record<string, TenantMembership>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { l as PassflowUsageError, r as assertVerifier } from "./evaluate-CHts4VKy.mjs";
|
|
2
|
+
// src/adapter.ts
|
|
3
|
+
const METHODS = "GET, HEAD, OPTIONS";
|
|
4
|
+
/** Internal: the adapters fail at construction when handed something that cannot verify. */
|
|
5
|
+
function adapterTarget(target) {
|
|
6
|
+
if (typeof target === "object" && target !== null && "challenge" in target) {
|
|
7
|
+
const { verifier, challenge } = target;
|
|
8
|
+
assertVerifier(verifier);
|
|
9
|
+
return {
|
|
10
|
+
verifier,
|
|
11
|
+
challenge,
|
|
12
|
+
metadata: (method) => metadataResponse(target, method)
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
assertVerifier(target);
|
|
16
|
+
return {
|
|
17
|
+
verifier: target,
|
|
18
|
+
challenge: void 0,
|
|
19
|
+
metadata: () => {
|
|
20
|
+
throw new PassflowUsageError("[passflow] metadata needs a protected resource from createProtectedResource");
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The document is public, so any origin may read it. A browser client may send a preflight request first. */
|
|
25
|
+
function metadataResponse(resource, method) {
|
|
26
|
+
const cors = { "Access-Control-Allow-Origin": "*" };
|
|
27
|
+
switch (method) {
|
|
28
|
+
case "GET":
|
|
29
|
+
case "HEAD": return {
|
|
30
|
+
status: 200,
|
|
31
|
+
headers: {
|
|
32
|
+
...cors,
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
"Cache-Control": "max-age=300"
|
|
35
|
+
},
|
|
36
|
+
body: method === "GET" ? JSON.stringify(resource.metadata()) : null
|
|
37
|
+
};
|
|
38
|
+
case "OPTIONS": return {
|
|
39
|
+
status: 204,
|
|
40
|
+
headers: {
|
|
41
|
+
...cors,
|
|
42
|
+
"Access-Control-Allow-Methods": METHODS,
|
|
43
|
+
"Access-Control-Allow-Headers": "*"
|
|
44
|
+
},
|
|
45
|
+
body: null
|
|
46
|
+
};
|
|
47
|
+
default: return {
|
|
48
|
+
status: 405,
|
|
49
|
+
headers: {
|
|
50
|
+
...cors,
|
|
51
|
+
Allow: METHODS
|
|
52
|
+
},
|
|
53
|
+
body: null
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export { adapterTarget as t };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const require_evaluate = require("./evaluate-Yv4mWPRI.cjs");
|
|
2
|
+
// src/adapter.ts
|
|
3
|
+
const METHODS = "GET, HEAD, OPTIONS";
|
|
4
|
+
/** Internal: the adapters fail at construction when handed something that cannot verify. */
|
|
5
|
+
function adapterTarget(target) {
|
|
6
|
+
if (typeof target === "object" && target !== null && "challenge" in target) {
|
|
7
|
+
const { verifier, challenge } = target;
|
|
8
|
+
require_evaluate.assertVerifier(verifier);
|
|
9
|
+
return {
|
|
10
|
+
verifier,
|
|
11
|
+
challenge,
|
|
12
|
+
metadata: (method) => metadataResponse(target, method)
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
require_evaluate.assertVerifier(target);
|
|
16
|
+
return {
|
|
17
|
+
verifier: target,
|
|
18
|
+
challenge: void 0,
|
|
19
|
+
metadata: () => {
|
|
20
|
+
throw new require_evaluate.PassflowUsageError("[passflow] metadata needs a protected resource from createProtectedResource");
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The document is public, so any origin may read it. A browser client may send a preflight request first. */
|
|
25
|
+
function metadataResponse(resource, method) {
|
|
26
|
+
const cors = { "Access-Control-Allow-Origin": "*" };
|
|
27
|
+
switch (method) {
|
|
28
|
+
case "GET":
|
|
29
|
+
case "HEAD": return {
|
|
30
|
+
status: 200,
|
|
31
|
+
headers: {
|
|
32
|
+
...cors,
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
"Cache-Control": "max-age=300"
|
|
35
|
+
},
|
|
36
|
+
body: method === "GET" ? JSON.stringify(resource.metadata()) : null
|
|
37
|
+
};
|
|
38
|
+
case "OPTIONS": return {
|
|
39
|
+
status: 204,
|
|
40
|
+
headers: {
|
|
41
|
+
...cors,
|
|
42
|
+
"Access-Control-Allow-Methods": METHODS,
|
|
43
|
+
"Access-Control-Allow-Headers": "*"
|
|
44
|
+
},
|
|
45
|
+
body: null
|
|
46
|
+
};
|
|
47
|
+
default: return {
|
|
48
|
+
status: 405,
|
|
49
|
+
headers: {
|
|
50
|
+
...cors,
|
|
51
|
+
Allow: METHODS
|
|
52
|
+
},
|
|
53
|
+
body: null
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
Object.defineProperty(exports, "adapterTarget", {
|
|
58
|
+
enumerable: true,
|
|
59
|
+
get: function() {
|
|
60
|
+
return adapterTarget;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
@@ -0,0 +1,141 @@
|
|
|
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
|
+
/**
|
|
22
|
+
* The space-separated `scope` claim, or the `scopes` array of a token without a `scope` claim. A `scope` claim
|
|
23
|
+
* that is not a string means no scopes.
|
|
24
|
+
*/
|
|
25
|
+
scopes: string[];
|
|
26
|
+
/** The client the token was issued to. */
|
|
27
|
+
clientId?: string;
|
|
28
|
+
sid?: string;
|
|
29
|
+
type: string;
|
|
30
|
+
tenants: Record<string, TenantMembership>;
|
|
31
|
+
/** The verifier's clock at verification, in Unix seconds. `requireFresh` measures from it. */
|
|
32
|
+
verifiedAt: number;
|
|
33
|
+
raw: Record<string, unknown>;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The structural part of a verifier. Declared here, with `verifiedBy`, so that provenance needs nothing
|
|
37
|
+
* from the verifier module.
|
|
38
|
+
*/
|
|
39
|
+
interface Verifier {
|
|
40
|
+
verify(token: string): Promise<PassflowClaims>;
|
|
41
|
+
refresh(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* True only for the exact object `verifier.verify` returned. A spread or clone loses provenance, which
|
|
45
|
+
* costs one more verification and never a bypass. So does any wrapper or decorator object that delegates
|
|
46
|
+
* to `verifier.verify`: it is a different identity, and this verifier's adapter re-verifies claims it
|
|
47
|
+
* returns. Two verifiers built from the same configuration are different identities too.
|
|
48
|
+
*/
|
|
49
|
+
declare function verifiedBy(claims: PassflowClaims, verifier: Verifier): boolean;
|
|
50
|
+
/**
|
|
51
|
+
* The roles a user holds in a tenant: `groups[rootGroupId]`, the rule the server's `CalcTenantRoles` and
|
|
52
|
+
* `@passflow/core`'s `parseMembership` apply. A missing tenant, root group or map gives an empty list.
|
|
53
|
+
* So does an empty `rootGroupId`, unlike the server: no role is granted from a group keyed by "".
|
|
54
|
+
* `tenantRoles` is a copy the server derives from the same root group, and is not consulted.
|
|
55
|
+
*/
|
|
56
|
+
declare function rolesOf(claims: PassflowClaims, tenantId: string): string[];
|
|
57
|
+
type Requirement = {
|
|
58
|
+
kind: 'acr';
|
|
59
|
+
min: string;
|
|
60
|
+
} | {
|
|
61
|
+
kind: 'fresh';
|
|
62
|
+
maxAgeSeconds: number;
|
|
63
|
+
} | {
|
|
64
|
+
kind: 'scope';
|
|
65
|
+
scopes: string[];
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* What the challenges of a protected resource carry. Both values are written unescaped, so they must never hold
|
|
69
|
+
* untrusted input. `createProtectedResource` builds a checked one.
|
|
70
|
+
*/
|
|
71
|
+
type ResourceChallenge = {
|
|
72
|
+
/** The URL of the RFC 9728 metadata document. */
|
|
73
|
+
resourceMetadata: string;
|
|
74
|
+
/** Space-separated. The scope parameter of a 401. */
|
|
75
|
+
scope?: string;
|
|
76
|
+
};
|
|
77
|
+
/** The RFC 9728 document. */
|
|
78
|
+
type ResourceMetadata = {
|
|
79
|
+
resource: string;
|
|
80
|
+
authorization_servers: string[];
|
|
81
|
+
scopes_supported?: string[];
|
|
82
|
+
bearer_methods_supported: string[];
|
|
83
|
+
resource_name?: string;
|
|
84
|
+
};
|
|
85
|
+
/** What `createProtectedResource` returns. */
|
|
86
|
+
type ProtectedResource = {
|
|
87
|
+
verifier: Verifier;
|
|
88
|
+
/** The path of the metadata URL the challenges name. */
|
|
89
|
+
metadataPath: string;
|
|
90
|
+
metadata(): ResourceMetadata;
|
|
91
|
+
/**
|
|
92
|
+
* A requirement that the token carries every scope. It checks what the user delegated to the client, not what the
|
|
93
|
+
* user may do: the user's own permissions stay the handler's check. Throws `TypeError` without a scope, or on one
|
|
94
|
+
* that is not an RFC 6749 scope token.
|
|
95
|
+
*/
|
|
96
|
+
requireScopes(...scopes: string[]): Requirement;
|
|
97
|
+
challenge: ResourceChallenge;
|
|
98
|
+
};
|
|
99
|
+
type Decision = {
|
|
100
|
+
kind: 'allow';
|
|
101
|
+
} | {
|
|
102
|
+
kind: 'reject';
|
|
103
|
+
status: 401 | 403 | 500 | 503;
|
|
104
|
+
headers: Record<string, string>;
|
|
105
|
+
};
|
|
106
|
+
/** A rejected `Decision`: a `ResponseInit` as it stands (`new Response(null, rejection)`). */
|
|
107
|
+
type Rejection = Extract<Decision, {
|
|
108
|
+
kind: 'reject';
|
|
109
|
+
}>;
|
|
110
|
+
/**
|
|
111
|
+
* Decides one requirement against claims. No claims means the middleware was composed wrongly, so the answer
|
|
112
|
+
* is a 500 with no challenge: never a step-up, which the SDK would try to satisfy, and never a 401, because a
|
|
113
|
+
* wiring bug must not be reported as a bad token. Throws `TypeError` on an invalid requirement. With `challenge`, a
|
|
114
|
+
* rejection names the resource metadata.
|
|
115
|
+
*/
|
|
116
|
+
declare function evaluate(claims: PassflowClaims | undefined, requirement: Requirement, challenge?: ResourceChallenge): Decision;
|
|
117
|
+
/**
|
|
118
|
+
* Authenticates a request. `existing` claims are reused only when `verifier` produced that exact object;
|
|
119
|
+
* otherwise the presented header is verified with `verifier`, so a token outside this verifier's trust policy
|
|
120
|
+
* is rejected as not valid here, never as insufficient. Never rejects: a failure is a `{ reject }` value. With
|
|
121
|
+
* `challenge`, a 401 carries the resource's scope and metadata URL.
|
|
122
|
+
*/
|
|
123
|
+
declare function authenticate(verifier: Verifier, authorization: string | undefined | null, existing?: PassflowClaims, challenge?: ResourceChallenge): Promise<{
|
|
124
|
+
claims: PassflowClaims;
|
|
125
|
+
} | {
|
|
126
|
+
reject: Rejection;
|
|
127
|
+
}>;
|
|
128
|
+
/**
|
|
129
|
+
* Authenticates a web `Request`, for a fetch-style server or a framework route handler with no adapter here.
|
|
130
|
+
* Verifies the `Authorization` header with `verifier`, then applies `requirement` if there is one. A rejection
|
|
131
|
+
* comes back as a ready `Response`: empty body, the challenge when there is one, and `Cache-Control: no-store`.
|
|
132
|
+
*
|
|
133
|
+
* Throws `TypeError` before it reads a header when the verifier or the request is missing, or the requirement
|
|
134
|
+
* is invalid: those are programming errors, not a bad token.
|
|
135
|
+
*/
|
|
136
|
+
declare function authenticateRequest(verifier: Verifier, request: Request, requirement?: Requirement): Promise<{
|
|
137
|
+
claims: PassflowClaims;
|
|
138
|
+
} | {
|
|
139
|
+
response: Response;
|
|
140
|
+
}>;
|
|
141
|
+
export { ResourceChallenge as a, authenticateRequest as c, TenantMembership as d, Verifier as f, Requirement as i, evaluate as l, verifiedBy as m, ProtectedResource as n, ResourceMetadata as o, rolesOf as p, Rejection as r, authenticate as s, Decision as t, PassflowClaims as u };
|
|
@@ -0,0 +1,141 @@
|
|
|
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
|
+
/**
|
|
22
|
+
* The space-separated `scope` claim, or the `scopes` array of a token without a `scope` claim. A `scope` claim
|
|
23
|
+
* that is not a string means no scopes.
|
|
24
|
+
*/
|
|
25
|
+
scopes: string[];
|
|
26
|
+
/** The client the token was issued to. */
|
|
27
|
+
clientId?: string;
|
|
28
|
+
sid?: string;
|
|
29
|
+
type: string;
|
|
30
|
+
tenants: Record<string, TenantMembership>;
|
|
31
|
+
/** The verifier's clock at verification, in Unix seconds. `requireFresh` measures from it. */
|
|
32
|
+
verifiedAt: number;
|
|
33
|
+
raw: Record<string, unknown>;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The structural part of a verifier. Declared here, with `verifiedBy`, so that provenance needs nothing
|
|
37
|
+
* from the verifier module.
|
|
38
|
+
*/
|
|
39
|
+
interface Verifier {
|
|
40
|
+
verify(token: string): Promise<PassflowClaims>;
|
|
41
|
+
refresh(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* True only for the exact object `verifier.verify` returned. A spread or clone loses provenance, which
|
|
45
|
+
* costs one more verification and never a bypass. So does any wrapper or decorator object that delegates
|
|
46
|
+
* to `verifier.verify`: it is a different identity, and this verifier's adapter re-verifies claims it
|
|
47
|
+
* returns. Two verifiers built from the same configuration are different identities too.
|
|
48
|
+
*/
|
|
49
|
+
declare function verifiedBy(claims: PassflowClaims, verifier: Verifier): boolean;
|
|
50
|
+
/**
|
|
51
|
+
* The roles a user holds in a tenant: `groups[rootGroupId]`, the rule the server's `CalcTenantRoles` and
|
|
52
|
+
* `@passflow/core`'s `parseMembership` apply. A missing tenant, root group or map gives an empty list.
|
|
53
|
+
* So does an empty `rootGroupId`, unlike the server: no role is granted from a group keyed by "".
|
|
54
|
+
* `tenantRoles` is a copy the server derives from the same root group, and is not consulted.
|
|
55
|
+
*/
|
|
56
|
+
declare function rolesOf(claims: PassflowClaims, tenantId: string): string[];
|
|
57
|
+
type Requirement = {
|
|
58
|
+
kind: 'acr';
|
|
59
|
+
min: string;
|
|
60
|
+
} | {
|
|
61
|
+
kind: 'fresh';
|
|
62
|
+
maxAgeSeconds: number;
|
|
63
|
+
} | {
|
|
64
|
+
kind: 'scope';
|
|
65
|
+
scopes: string[];
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* What the challenges of a protected resource carry. Both values are written unescaped, so they must never hold
|
|
69
|
+
* untrusted input. `createProtectedResource` builds a checked one.
|
|
70
|
+
*/
|
|
71
|
+
type ResourceChallenge = {
|
|
72
|
+
/** The URL of the RFC 9728 metadata document. */
|
|
73
|
+
resourceMetadata: string;
|
|
74
|
+
/** Space-separated. The scope parameter of a 401. */
|
|
75
|
+
scope?: string;
|
|
76
|
+
};
|
|
77
|
+
/** The RFC 9728 document. */
|
|
78
|
+
type ResourceMetadata = {
|
|
79
|
+
resource: string;
|
|
80
|
+
authorization_servers: string[];
|
|
81
|
+
scopes_supported?: string[];
|
|
82
|
+
bearer_methods_supported: string[];
|
|
83
|
+
resource_name?: string;
|
|
84
|
+
};
|
|
85
|
+
/** What `createProtectedResource` returns. */
|
|
86
|
+
type ProtectedResource = {
|
|
87
|
+
verifier: Verifier;
|
|
88
|
+
/** The path of the metadata URL the challenges name. */
|
|
89
|
+
metadataPath: string;
|
|
90
|
+
metadata(): ResourceMetadata;
|
|
91
|
+
/**
|
|
92
|
+
* A requirement that the token carries every scope. It checks what the user delegated to the client, not what the
|
|
93
|
+
* user may do: the user's own permissions stay the handler's check. Throws `TypeError` without a scope, or on one
|
|
94
|
+
* that is not an RFC 6749 scope token.
|
|
95
|
+
*/
|
|
96
|
+
requireScopes(...scopes: string[]): Requirement;
|
|
97
|
+
challenge: ResourceChallenge;
|
|
98
|
+
};
|
|
99
|
+
type Decision = {
|
|
100
|
+
kind: 'allow';
|
|
101
|
+
} | {
|
|
102
|
+
kind: 'reject';
|
|
103
|
+
status: 401 | 403 | 500 | 503;
|
|
104
|
+
headers: Record<string, string>;
|
|
105
|
+
};
|
|
106
|
+
/** A rejected `Decision`: a `ResponseInit` as it stands (`new Response(null, rejection)`). */
|
|
107
|
+
type Rejection = Extract<Decision, {
|
|
108
|
+
kind: 'reject';
|
|
109
|
+
}>;
|
|
110
|
+
/**
|
|
111
|
+
* Decides one requirement against claims. No claims means the middleware was composed wrongly, so the answer
|
|
112
|
+
* is a 500 with no challenge: never a step-up, which the SDK would try to satisfy, and never a 401, because a
|
|
113
|
+
* wiring bug must not be reported as a bad token. Throws `TypeError` on an invalid requirement. With `challenge`, a
|
|
114
|
+
* rejection names the resource metadata.
|
|
115
|
+
*/
|
|
116
|
+
declare function evaluate(claims: PassflowClaims | undefined, requirement: Requirement, challenge?: ResourceChallenge): Decision;
|
|
117
|
+
/**
|
|
118
|
+
* Authenticates a request. `existing` claims are reused only when `verifier` produced that exact object;
|
|
119
|
+
* otherwise the presented header is verified with `verifier`, so a token outside this verifier's trust policy
|
|
120
|
+
* is rejected as not valid here, never as insufficient. Never rejects: a failure is a `{ reject }` value. With
|
|
121
|
+
* `challenge`, a 401 carries the resource's scope and metadata URL.
|
|
122
|
+
*/
|
|
123
|
+
declare function authenticate(verifier: Verifier, authorization: string | undefined | null, existing?: PassflowClaims, challenge?: ResourceChallenge): Promise<{
|
|
124
|
+
claims: PassflowClaims;
|
|
125
|
+
} | {
|
|
126
|
+
reject: Rejection;
|
|
127
|
+
}>;
|
|
128
|
+
/**
|
|
129
|
+
* Authenticates a web `Request`, for a fetch-style server or a framework route handler with no adapter here.
|
|
130
|
+
* Verifies the `Authorization` header with `verifier`, then applies `requirement` if there is one. A rejection
|
|
131
|
+
* comes back as a ready `Response`: empty body, the challenge when there is one, and `Cache-Control: no-store`.
|
|
132
|
+
*
|
|
133
|
+
* Throws `TypeError` before it reads a header when the verifier or the request is missing, or the requirement
|
|
134
|
+
* is invalid: those are programming errors, not a bad token.
|
|
135
|
+
*/
|
|
136
|
+
declare function authenticateRequest(verifier: Verifier, request: Request, requirement?: Requirement): Promise<{
|
|
137
|
+
claims: PassflowClaims;
|
|
138
|
+
} | {
|
|
139
|
+
response: Response;
|
|
140
|
+
}>;
|
|
141
|
+
export { ResourceChallenge as a, authenticateRequest as c, TenantMembership as d, Verifier as f, Requirement as i, evaluate as l, verifiedBy as m, ProtectedResource as n, ResourceMetadata as o, rolesOf as p, Rejection as r, authenticate as s, Decision as t, PassflowClaims as u };
|
|
@@ -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,
|
|
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:
|
|
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,
|
|
281
|
-
case "invalid_token": return reject(401, "
|
|
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 }
|
|
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" } :
|
|
318
|
-
|
|
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
|
/**
|
|
@@ -367,4 +404,4 @@ async function authenticateRequest(verifier, request, requirement) {
|
|
|
367
404
|
function assertVerifier(verifier) {
|
|
368
405
|
if (typeof verifier !== "object" || verifier === null || typeof verifier.verify !== "function") throw new TypeError("[passflow] an adapter needs a verifier from createVerifier");
|
|
369
406
|
}
|
|
370
|
-
export {
|
|
407
|
+
export { AAL3 as C, acrSatisfies as E, AAL2 as S, acrLevel as T, verifiedBy as _, authenticateRequest as a, extractBearer as b, PassflowAuthError as c, CHALLENGE_HEADER as d, CORS_EXPOSED_HEADERS as f, rolesOf as g, recordProvenance as h, authenticate as i, PassflowUsageError as l, extractClaims as m, assertScopes as n, evaluate as o, withChallengeHeader as p, assertVerifier as r, guard as s, assertRequirement as t, isPassflowAuthError as u, assertMaxAge as v, ACR_NONE as w, AAL1 as x, formatChallenge as y };
|