@passflow/node 0.1.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -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-BTuol-Oa.mjs → evaluate-CHts4VKy.mjs} +77 -18
- package/dist/{evaluate-C20MecTf.cjs → evaluate-Yv4mWPRI.cjs} +88 -17
- package/dist/express.cjs +22 -8
- package/dist/express.d.cts +15 -6
- package/dist/express.d.mts +15 -6
- package/dist/express.mjs +22 -8
- package/dist/fastify.cjs +22 -8
- package/dist/fastify.d.cts +17 -8
- package/dist/fastify.d.mts +17 -8
- package/dist/fastify.mjs +22 -8
- package/dist/hono.cjs +22 -8
- package/dist/hono.d.cts +16 -7
- package/dist/hono.d.mts +16 -7
- package/dist/hono.mjs +22 -8
- package/dist/index.cjs +85 -18
- package/dist/index.d.cts +34 -41
- package/dist/index.d.mts +34 -41
- package/dist/index.mjs +83 -18
- package/dist/loopback-ADMM_GlW.cjs +22 -0
- package/dist/loopback-CDiL_KzV.mjs +17 -0
- package/dist/manager-Bm3vM2Aw.d.cts +93 -0
- package/dist/manager-Bm3vM2Aw.d.mts +93 -0
- package/dist/session-browser.cjs +17 -0
- package/dist/session-browser.d.cts +5 -0
- package/dist/session-browser.d.mts +5 -0
- package/dist/session-browser.mjs +14 -0
- package/dist/session.cjs +923 -0
- package/dist/session.d.cts +7 -0
- package/dist/session.d.mts +7 -0
- package/dist/session.mjs +898 -0
- package/package.json +30 -3
- package/dist/claims-BHJhnzch.d.cts +0 -51
- package/dist/claims-BHJhnzch.d.mts +0 -51
package/README.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Protect your own API with Passflow tokens. One import and one middleware call give you token verification, an authentication-level floor, a freshness requirement, and the exact RFC 9470 challenge the Passflow browser SDK needs to run a step-up.
|
|
4
4
|
|
|
5
|
+
It also carries `@passflow/node/session`, the server-side sign-in session that the Next.js and TanStack Start packages build on (see [Sign users in on the server](#sign-users-in-on-the-server-passflownodesession)).
|
|
6
|
+
|
|
5
7
|
Requires Node.js 22.12 or newer, and Express, Fastify and Hono are optional peers, so you install only the framework you use.
|
|
6
8
|
|
|
7
9
|
```bash
|
|
@@ -52,7 +54,7 @@ app.get('/invoices', { preHandler: app.passflow.requireACR(AAL2) }, async (reque
|
|
|
52
54
|
}));
|
|
53
55
|
```
|
|
54
56
|
|
|
55
|
-
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.
|
|
56
58
|
|
|
57
59
|
### Hono
|
|
58
60
|
|
|
@@ -69,6 +71,106 @@ const app = new Hono();
|
|
|
69
71
|
app.get('/invoices', passflow.requireACR(AAL2), (c) => c.json({ subject: getAuth(c).sub }));
|
|
70
72
|
```
|
|
71
73
|
|
|
74
|
+
### Fetch-style servers and route handlers
|
|
75
|
+
|
|
76
|
+
`authenticateRequest(verifier, request, requirement?)` takes a web `Request`, for Bun, Deno, a Next.js route handler or any server built on `fetch`. It answers `{ claims }`, or `{ response }`, which is the finished rejection to return as it is.
|
|
77
|
+
|
|
78
|
+
```js
|
|
79
|
+
import { AAL2, authenticateRequest, createVerifier } from '@passflow/node';
|
|
80
|
+
|
|
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
|
+
});
|
|
87
|
+
|
|
88
|
+
export async function GET(request) {
|
|
89
|
+
const result = await authenticateRequest(verifier, request, { kind: 'acr', min: AAL2 });
|
|
90
|
+
if ('response' in result) return result.response;
|
|
91
|
+
return Response.json({ sub: result.claims.sub });
|
|
92
|
+
}
|
|
93
|
+
```
|
|
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
|
+
|
|
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.
|
|
98
|
+
|
|
99
|
+
### Any other framework
|
|
100
|
+
|
|
101
|
+
`authenticate(verifier, authorization)` takes the `Authorization` header's value and never throws. It answers `{ claims }` or `{ reject }`. A `Rejection` is a `ResponseInit` as it stands, so `new Response(null, result.reject)` is the response to send; elsewhere, send `reject.status` with every entry of `reject.headers`. `evaluate(claims, requirement)` then applies a level or freshness requirement to the claims and answers a `Decision`, whose rejected form is the same `Rejection`.
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
import { authenticate } from '@passflow/node';
|
|
105
|
+
|
|
106
|
+
const result = await authenticate(verifier, request.headers.get('authorization'));
|
|
107
|
+
if ('reject' in result) return new Response(null, result.reject);
|
|
108
|
+
```
|
|
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
|
+
|
|
150
|
+
## Sign users in on the server: `@passflow/node/session`
|
|
151
|
+
|
|
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`.
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
import { configFromEnv, createSessionManager } from '@passflow/node/session';
|
|
156
|
+
|
|
157
|
+
// PASSFLOW_ISSUER, PASSFLOW_CLIENT_ID, PASSFLOW_CLIENT_SECRET, PASSFLOW_SECRET (32+ characters), APP_BASE_URL
|
|
158
|
+
const sessions = createSessionManager(configFromEnv());
|
|
159
|
+
|
|
160
|
+
const result = await sessions.handle(request);
|
|
161
|
+
if (result.kind === 'response') return result.response; // /auth/login, /auth/callback, /auth/logout
|
|
162
|
+
// Otherwise run the app: replace the request's Cookie header with result.cookieHeader when it is present,
|
|
163
|
+
// append each of result.setCookies as its own Set-Cookie header, and send Cache-Control: no-store when there is any.
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
- **Routes.** `GET /auth/login?returnTo=/path` starts sign-in with PKCE, `state` and `nonce`. `GET /auth/callback` redeems the code with the client secret, checks the ID token and UserInfo, and sets the session cookie. `GET /auth/logout` revokes the refresh token, clears the cookie, and sends the user to Passflow's end-session endpoint with the session's ID token as `id_token_hint`, so Passflow ends its own session at once and returns them to the app's home page. A session signed in before the SDK kept the ID token goes without the hint, and Passflow asks the user to confirm. `routes` changes the paths; a configured path must not end in `/`. `returnTo` must be a relative path on the app's origin, checked after its dot segments are resolved, else it is `/`. Each route also matches with one trailing slash (`/auth/login/`), for an app with Next.js's `trailingSlash: true`; the redirect URI sent to Passflow stays the configured one. Sign-out ignores a prefetch the request declares and a navigation another site started, including one from a sibling subdomain: it answers 204 and changes nothing, so sign-out links must be plain anchors on the app's own origin. Each call to Passflow gives up after 10 seconds. When Passflow is unreachable (a network error, no answer in time, or a 5xx), sign-in and its callback answer a plain 503 with `Cache-Control: no-store`; sign-out still clears the cookies and sends the user to the app's home page; a due refresh counts as a failed refresh (below). A session and a sign-in in progress are bound to the issuer and client ID that started them: after either changes, the cookie reads as signed out.
|
|
167
|
+
- **The session.** `getSession(cookieHeader)` answers `{ user, expiresAt }` or `null`, with no network call. It holds no token, so it is safe to pass to the browser. `getAccessToken(cookieHeader)` is for server code that calls an API. The refresh token, the ID token and the client secret have no accessor. The ID token is kept in the cookie only for sign-out's hint, and a refresh that returns a new one replaces it.
|
|
168
|
+
- **The cookie.** When `APP_BASE_URL` is https the session cookie is `__Host-passflow_session`: `Secure`, `Path=/` and no `Domain`, so a sibling subdomain cannot plant one. Over http on a loopback host, where browsers refuse `Secure`, it is `passflow_session`. Only the name that matches the scheme is read. It is HttpOnly, SameSite=Lax and encrypted (JWE `dir`/`A256GCM` under a key derived from `PASSFLOW_SECRET` with HKDF). A large session is split into `<name>.0`, `.1`, `.2`. The sign-in transaction cookie follows the same rule: `__Host-passflow_txn` or `passflow_txn`, `Path=/`. `hasSessionCookie(cookieHeader)` is true for either name, the base or any chunk.
|
|
169
|
+
- **Session length follows the server.** The session ends when its refresh token does: the project's sign-in max age and refresh lifetime decide it. `handle` refreshes when the access token has 60 seconds or half its lifetime left, whichever is less. When Passflow answers `invalid_grant` or `invalid_client`, the session is over and its cookie is cleared. Any other failure (a rate limit, a 5xx, a timeout, a network error, or another OAuth error such as `invalid_request`) leaves the cookie, and the next request tries again. That request runs with the existing session while both the session's `expiresAt` and the access token's expiry are still in the future, and signed out otherwise.
|
|
170
|
+
- **CSRF.** `isSameOrigin(request)` is true when `Origin` is the app's own, or, with no `Origin`, when `Sec-Fetch-Site` is `same-origin` or `none`. Check it in every handler that changes data.
|
|
171
|
+
- **Config.** It is checked on first use, so a build passes without the environment. A missing or wrong value throws `TypeError` naming the variable. `http://` is accepted for the issuer and the app only on a loopback host.
|
|
172
|
+
- **Browser bundles.** Under the `browser` export condition, `./session` resolves to a stub that throws when called and carries none of the server code.
|
|
173
|
+
|
|
72
174
|
## Responses and CORS
|
|
73
175
|
|
|
74
176
|
| Situation | Status | `WWW-Authenticate` |
|
|
@@ -79,7 +181,7 @@ app.get('/invoices', passflow.requireACR(AAL2), (c) => c.json({ subject: getAuth
|
|
|
79
181
|
| Authentication too old | 401 | `Bearer error="insufficient_user_authentication", max_age=300` |
|
|
80
182
|
| Key set unavailable | 503 | none |
|
|
81
183
|
|
|
82
|
-
Every rejection has `Cache-Control: no-store` and an empty body, and the middleware writes it directly, so your own error handler cannot drop the challenge. The browser SDK acts only on the step-up challenge, and the library never sends one for an authentication failure. Nothing from the token, the request or the key set URL appears in any error or response, and
|
|
184
|
+
Every rejection has `Cache-Control: no-store` and an empty body, and the middleware writes it directly, so your own error handler cannot drop the challenge. The browser SDK acts only on the step-up challenge, and the library never sends one for an authentication failure. Nothing from the token, the request or the key set URL appears in any error or response, and token verification writes no logs. The session core writes one line, to `console.error`, when a sealed session is too large for its cookies; it names the size and nothing else.
|
|
83
185
|
|
|
84
186
|
A browser hides `WWW-Authenticate` from a cross-origin page unless the response names it in `Access-Control-Expose-Headers`. The SDK then sees a bare 401 and cannot start the step-up, and a `*` entry does not cover the header on a credentialed request.
|
|
85
187
|
|
|
@@ -110,7 +212,8 @@ type PassflowClaims = {
|
|
|
110
212
|
authTime?: number; // whole Unix seconds; absent when the claim is absent, not a number or beyond ±2^53
|
|
111
213
|
acr: string; // '0' when the claim is absent or not a string
|
|
112
214
|
amr: string[];
|
|
113
|
-
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
|
|
114
217
|
sid?: string;
|
|
115
218
|
type: string;
|
|
116
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 };
|