@udibo/oauth2 0.43.0 → 0.45.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 +31 -28
- package/dist/adapters/express/_common.d.ts +111 -0
- package/dist/adapters/express/_common.js +229 -0
- package/dist/adapters/express/authorization-server.d.ts +214 -0
- package/dist/adapters/express/authorization-server.js +229 -0
- package/dist/adapters/express/resource-server.d.ts +105 -0
- package/dist/adapters/express/resource-server.js +112 -0
- package/dist/identity/service.d.ts +22 -5
- package/dist/identity/service.js +27 -8
- package/package.json +14 -2
package/README.md
CHANGED
|
@@ -39,8 +39,9 @@ npx jsr add @udibo/oauth2 # or, with Deno: deno add jsr:@udibo/oauth2
|
|
|
39
39
|
`hono`, `react`, and `react-dom` are optional peer dependencies. Install the
|
|
40
40
|
ones for the entrypoints you import: `hono` for the `/hono/*` adapters, `react`
|
|
41
41
|
and `react-dom` for `/react` and `/react/components`. `vitest` is an optional
|
|
42
|
-
peer dependency of the testing helpers.
|
|
43
|
-
|
|
42
|
+
peer dependency of the testing helpers. The `/express/*` adapters need no extra
|
|
43
|
+
dependency: they accept the request and response of Express 4 or 5. Import the
|
|
44
|
+
part you use; there is no root barrel or default export.
|
|
44
45
|
|
|
45
46
|
## Protect an API
|
|
46
47
|
|
|
@@ -152,31 +153,33 @@ development.
|
|
|
152
153
|
All paths below start with `@udibo/oauth2`. Each entrypoint has typed API docs
|
|
153
154
|
and examples in the [reference](https://jsr.io/@udibo/oauth2/doc).
|
|
154
155
|
|
|
155
|
-
| Subpath
|
|
156
|
-
|
|
|
157
|
-
| `/client`
|
|
158
|
-
| `/server`
|
|
159
|
-
| `/server/authorization`
|
|
160
|
-
| `/server/resource`
|
|
161
|
-
| `/server/public-suffix`
|
|
162
|
-
| `/hono/authorization-server`
|
|
163
|
-
| `/hono/resource-server`
|
|
164
|
-
| `/hono/bff`
|
|
165
|
-
| `/
|
|
166
|
-
| `/
|
|
167
|
-
| `/identity
|
|
168
|
-
| `/identity/
|
|
169
|
-
| `/identity/
|
|
170
|
-
| `/
|
|
171
|
-
| `/
|
|
172
|
-
| `/
|
|
173
|
-
| `/
|
|
174
|
-
| `/
|
|
175
|
-
| `/
|
|
176
|
-
| `/
|
|
177
|
-
| `/
|
|
178
|
-
| `/
|
|
179
|
-
| `/
|
|
156
|
+
| Subpath | Purpose |
|
|
157
|
+
| ------------------------------- | ----------------------------------------------------------------------------------------------- |
|
|
158
|
+
| `/client` | `BffClient`, `DirectClient`, token storage, discovery caching |
|
|
159
|
+
| `/server` | Shared models, errors, scope types, and service contracts |
|
|
160
|
+
| `/server/authorization` | Authorization server, grants, token/code services, signing keys |
|
|
161
|
+
| `/server/resource` | Resource server, introspection and JWKS token readers |
|
|
162
|
+
| `/server/public-suffix` | Public Suffix List checks for optional wildcard redirect registration |
|
|
163
|
+
| `/hono/authorization-server` | Hono authorization endpoints |
|
|
164
|
+
| `/hono/resource-server` | Bearer authentication and scope middleware |
|
|
165
|
+
| `/hono/bff` | BFF routes, server-held tokens, session and pending-login stores |
|
|
166
|
+
| `/express/authorization-server` | Express authorization endpoints |
|
|
167
|
+
| `/express/resource-server` | Bearer authentication and scope middleware for Express |
|
|
168
|
+
| `/identity` | App-owned signup, login, password reset, email verification, passwordless, and protection hooks |
|
|
169
|
+
| `/identity/mfa` | TOTP, recovery codes, and MFA storage contract |
|
|
170
|
+
| `/identity/passkeys` | Passkey (WebAuthn) registration and sign-in, as a first or second factor |
|
|
171
|
+
| `/identity/external` | Social and external OIDC sign-in for your own login pages |
|
|
172
|
+
| `/identity/migration` | Verify imported password hashes and upgrade them at login |
|
|
173
|
+
| `/hono/identity` | Hono routes for `IdentityService` |
|
|
174
|
+
| `/hono/log` | Request logger and URL helper that redact every query value |
|
|
175
|
+
| `/react` | Context, hooks, authentication guards, and callback handling |
|
|
176
|
+
| `/react/components` | Optional forms for login, signup, password reset, and MFA |
|
|
177
|
+
| `/crypto` | Random tokens, hashing, encoding, authenticated encryption |
|
|
178
|
+
| `/url` | Safe return paths and login continuation |
|
|
179
|
+
| `/testing` | In-memory fixtures and authorization-server test helpers |
|
|
180
|
+
| `/testing/contract` | Tests for app-owned service and storage implementations |
|
|
181
|
+
| `/hono/bff/testing` | BFF session fixtures and session-store contract tests |
|
|
182
|
+
| `/react/testing` | Mock clients and providers for component tests |
|
|
180
183
|
|
|
181
184
|
## Runtime support
|
|
182
185
|
|
|
@@ -188,7 +191,7 @@ checks a consumer of every entrypoint, and imports each one on Node.
|
|
|
188
191
|
| Surface | Node 22+ | Browser | Deno, Bun |
|
|
189
192
|
| ---------------------------------------------------------------------- | --------------------- | ------------------------------------------- | ------------- |
|
|
190
193
|
| `/client`, `/react`, `/react/components` | Tested, including SSR | Intended for client code; no secrets | Not verified |
|
|
191
|
-
| `/server/*`, `/identity/*`, `/hono/*`, `/crypto`, `/url`
|
|
194
|
+
| `/server/*`, `/identity/*`, `/hono/*`, `/express/*`, `/crypto`, `/url` | Tested | Server functionality belongs on the backend | Not verified |
|
|
192
195
|
| `/testing`, `/testing/contract`, `/hono/bff/testing`, `/react/testing` | Tested; need Vitest | Not supported | Not verified |
|
|
193
196
|
| `udibo-oauth2` command (`bin`) | Tested | Not supported | Not supported |
|
|
194
197
|
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal helpers shared by the Express adapters.
|
|
3
|
+
*
|
|
4
|
+
* Not part of the public API — use {@link ExpressResourceServer} or
|
|
5
|
+
* {@link ExpressAuthorizationServer} instead. The structural request,
|
|
6
|
+
* response and middleware types are re-exported publicly.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
11
|
+
import type { RequireConditions } from "../../models/authorization.ts";
|
|
12
|
+
import type { ClientInterface } from "../../models/client.ts";
|
|
13
|
+
import type { AbstractScope } from "../../models/scope.ts";
|
|
14
|
+
import type { AuthenticatedContext } from "../../server/resource-server.ts";
|
|
15
|
+
import { ResourceServer } from "../../server/resource-server.ts";
|
|
16
|
+
/**
|
|
17
|
+
* Key under which the authenticated OAuth2 context is stored on
|
|
18
|
+
* `res.locals`. Namespaced to avoid collisions with other middleware.
|
|
19
|
+
*/
|
|
20
|
+
export declare const OAUTH2_CONTEXT_KEY: "@udibo/oauth2";
|
|
21
|
+
/**
|
|
22
|
+
* The parts of an Express request the adapters read. An Express 4 or 5
|
|
23
|
+
* `Request` satisfies it, so handlers accept either without a dependency on
|
|
24
|
+
* `express` or its types.
|
|
25
|
+
*/
|
|
26
|
+
export interface ExpressRequestLike extends IncomingMessage {
|
|
27
|
+
/** The URL as received, before any mount path was stripped. */
|
|
28
|
+
originalUrl?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Express's scheme, which reads `X-Forwarded-Proto` under `trust proxy`.
|
|
31
|
+
* Only an exact `https` makes the request URL `https`; anything else is
|
|
32
|
+
* `http`.
|
|
33
|
+
*/
|
|
34
|
+
protocol?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Express's host name, which reads `X-Forwarded-Host` under `trust proxy`.
|
|
37
|
+
* A request whose `hostname` differs from its `Host` header is refused.
|
|
38
|
+
*/
|
|
39
|
+
hostname?: string;
|
|
40
|
+
/** Whatever a body parser that already ran left behind. */
|
|
41
|
+
body?: unknown;
|
|
42
|
+
}
|
|
43
|
+
/** The parts of an Express response the adapters write. */
|
|
44
|
+
export interface ExpressResponseLike extends ServerResponse {
|
|
45
|
+
/** Express's per-request locals, where `protect` stores its context. */
|
|
46
|
+
locals: Record<string, unknown>;
|
|
47
|
+
}
|
|
48
|
+
/** Express's `next`: call with no argument to continue, or with an error. */
|
|
49
|
+
export type ExpressNextFunction = (error?: unknown) => void;
|
|
50
|
+
/** A middleware or route handler Express can mount. */
|
|
51
|
+
export type ExpressMiddleware<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike> = (req: Req, res: Res, next: ExpressNextFunction) => void;
|
|
52
|
+
/**
|
|
53
|
+
* How {@link toFetchRequest} supplies the body: `stream` hands the core the
|
|
54
|
+
* unread request stream, and refuses one a body parser already consumed;
|
|
55
|
+
* `parsed` never drains the stream, re-encoding the single-valued fields of a
|
|
56
|
+
* form body a parser left on `req.body` so a form-encoded bearer token still
|
|
57
|
+
* reaches the core; a repeated or nested field is left out.
|
|
58
|
+
*/
|
|
59
|
+
export type BodySource = "stream" | "parsed";
|
|
60
|
+
/**
|
|
61
|
+
* Builds the web {@link Request} the core servers read from an Express
|
|
62
|
+
* request: the full original URL, every header as received, and the body as
|
|
63
|
+
* `source` says.
|
|
64
|
+
*
|
|
65
|
+
* @throws {Error} When `Host` is missing or not a plain host and port, when
|
|
66
|
+
* `req.hostname` or the request target would give the URL another host, when
|
|
67
|
+
* the target has a backslash or a `.` or `..` segment, which the URL would
|
|
68
|
+
* read differently from the path Express routes on, or,
|
|
69
|
+
* with `stream`, when a body parser already read the body.
|
|
70
|
+
*/
|
|
71
|
+
export declare function toFetchRequest(req: ExpressRequestLike, source: BodySource): Request;
|
|
72
|
+
/**
|
|
73
|
+
* Writes a core {@link Response} to `res`, keeping headers earlier
|
|
74
|
+
* middleware set — `Set-Cookie` values are added to theirs, not replaced.
|
|
75
|
+
*/
|
|
76
|
+
export declare function sendFetchResponse(res: ServerResponse, response: Response): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Wraps a core handler as Express middleware that writes its response, and
|
|
79
|
+
* passes anything it throws to `next` (Express 4 does not catch a rejected
|
|
80
|
+
* handler on its own).
|
|
81
|
+
*/
|
|
82
|
+
export declare function fetchHandler<Req extends ExpressRequestLike, Res extends ExpressResponseLike>(handle: (request: Request, req: Req, res: Res) => Promise<Response>): ExpressMiddleware<Req, Res>;
|
|
83
|
+
/**
|
|
84
|
+
* Builds an Express middleware that authenticates bearer tokens, stores the
|
|
85
|
+
* authenticated context at `res.locals[OAUTH2_CONTEXT_KEY]`, and on failure
|
|
86
|
+
* writes the server's auth error response.
|
|
87
|
+
*/
|
|
88
|
+
export declare function createProtectMiddleware<Client extends ClientInterface, User, S extends AbstractScope>(server: ResourceServer<Client, User, S>, requiredScope?: S | string): ExpressMiddleware;
|
|
89
|
+
/**
|
|
90
|
+
* Builds an Express middleware that asserts the **already-authenticated**
|
|
91
|
+
* request carries `requiredScope`, without re-validating the token.
|
|
92
|
+
* `adapterName` names the class in the "context missing" developer error.
|
|
93
|
+
*/
|
|
94
|
+
export declare function createRequireScopeMiddleware<Client extends ClientInterface, User, S extends AbstractScope>(server: ResourceServer<Client, User, S>, adapterName: string, requiredScope: S | string): ExpressMiddleware;
|
|
95
|
+
/**
|
|
96
|
+
* Builds an Express middleware that asserts the **already-authenticated**
|
|
97
|
+
* request satisfies `conditions`, without re-validating the token.
|
|
98
|
+
*/
|
|
99
|
+
export declare function createRequireMiddleware<Client extends ClientInterface, User, S extends AbstractScope>(server: ResourceServer<Client, User, S>, adapterName: string, conditions: RequireConditions): ExpressMiddleware;
|
|
100
|
+
/**
|
|
101
|
+
* Authenticates an Express request or a raw {@link Request} with the base
|
|
102
|
+
* {@link ResourceServer.authenticate}, bypassing the adapters' override.
|
|
103
|
+
*/
|
|
104
|
+
export declare function authenticateExpressRequest<Client extends ClientInterface, User, S extends AbstractScope>(server: ResourceServer<Client, User, S>, req: ExpressRequestLike | Request, requiredScope?: S | string): Promise<AuthenticatedContext<Client, User, S>>;
|
|
105
|
+
/**
|
|
106
|
+
* Reads the authenticated OAuth2 context off `res.locals`.
|
|
107
|
+
*
|
|
108
|
+
* @throws {Error} If no `protect` middleware set it first; the message names
|
|
109
|
+
* `adapterName`.
|
|
110
|
+
*/
|
|
111
|
+
export declare function readContext<Client extends ClientInterface, User, S extends AbstractScope>(res: ExpressResponseLike, adapterName: string): AuthenticatedContext<Client, User, S>;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal helpers shared by the Express adapters.
|
|
3
|
+
*
|
|
4
|
+
* Not part of the public API — use {@link ExpressResourceServer} or
|
|
5
|
+
* {@link ExpressAuthorizationServer} instead. The structural request,
|
|
6
|
+
* response and middleware types are re-exported publicly.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { Readable } from "node:stream";
|
|
11
|
+
import { ResourceServer } from "../../server/resource-server.js";
|
|
12
|
+
/**
|
|
13
|
+
* Key under which the authenticated OAuth2 context is stored on
|
|
14
|
+
* `res.locals`. Namespaced to avoid collisions with other middleware.
|
|
15
|
+
*/
|
|
16
|
+
export const OAUTH2_CONTEXT_KEY = "@udibo/oauth2";
|
|
17
|
+
const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
|
|
18
|
+
const FORM_TYPE = "application/x-www-form-urlencoded";
|
|
19
|
+
/**
|
|
20
|
+
* Builds the web {@link Request} the core servers read from an Express
|
|
21
|
+
* request: the full original URL, every header as received, and the body as
|
|
22
|
+
* `source` says.
|
|
23
|
+
*
|
|
24
|
+
* @throws {Error} When `Host` is missing or not a plain host and port, when
|
|
25
|
+
* `req.hostname` or the request target would give the URL another host, when
|
|
26
|
+
* the target has a backslash or a `.` or `..` segment, which the URL would
|
|
27
|
+
* read differently from the path Express routes on, or,
|
|
28
|
+
* with `stream`, when a body parser already read the body.
|
|
29
|
+
*/
|
|
30
|
+
export function toFetchRequest(req, source) {
|
|
31
|
+
const method = req.method ?? "GET";
|
|
32
|
+
const headers = new Headers();
|
|
33
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
34
|
+
const name = req.rawHeaders[i];
|
|
35
|
+
if (!name.startsWith(":"))
|
|
36
|
+
headers.append(name, req.rawHeaders[i + 1]);
|
|
37
|
+
}
|
|
38
|
+
const url = requestUrl(req);
|
|
39
|
+
if (BODYLESS_METHODS.has(method)) {
|
|
40
|
+
return new Request(url, { method, headers });
|
|
41
|
+
}
|
|
42
|
+
if (source === "stream") {
|
|
43
|
+
if (req.readableEnded) {
|
|
44
|
+
throw new Error("The request body was already read, likely by a body parser. Mount " +
|
|
45
|
+
"the @udibo/oauth2 Express handlers before any body-parsing " +
|
|
46
|
+
"middleware.");
|
|
47
|
+
}
|
|
48
|
+
const init = {
|
|
49
|
+
method,
|
|
50
|
+
headers,
|
|
51
|
+
body: Readable.toWeb(req),
|
|
52
|
+
duplex: "half",
|
|
53
|
+
};
|
|
54
|
+
return new Request(url, init);
|
|
55
|
+
}
|
|
56
|
+
headers.delete("content-length");
|
|
57
|
+
headers.delete("transfer-encoding");
|
|
58
|
+
return new Request(url, { method, headers, body: parsedFormBody(req) });
|
|
59
|
+
}
|
|
60
|
+
function requestUrl(req) {
|
|
61
|
+
const host = req.headers.host?.toLowerCase();
|
|
62
|
+
if (!host)
|
|
63
|
+
throw new Error("The request has no Host header.");
|
|
64
|
+
const scheme = req.protocol === "https" ? "https" : "http";
|
|
65
|
+
const origin = new URL(`${scheme}://${host}`);
|
|
66
|
+
const defaultPort = scheme === "https" ? "443" : "80";
|
|
67
|
+
if (host !== origin.host && host !== `${origin.host}:${defaultPort}`) {
|
|
68
|
+
throw new Error("The Host header is not a plain host and port.");
|
|
69
|
+
}
|
|
70
|
+
if (req.hostname !== undefined &&
|
|
71
|
+
req.hostname.toLowerCase() !== origin.hostname) {
|
|
72
|
+
throw new Error("req.hostname differs from the Host header, likely through " +
|
|
73
|
+
"X-Forwarded-Host under trust proxy. Have the proxy forward the " +
|
|
74
|
+
"original Host header.");
|
|
75
|
+
}
|
|
76
|
+
const target = req.originalUrl ?? req.url ?? "/";
|
|
77
|
+
const url = new URL(target, origin);
|
|
78
|
+
if (!target.startsWith("/") || url.origin !== origin.origin) {
|
|
79
|
+
throw new Error("The request target is not a path on this host.");
|
|
80
|
+
}
|
|
81
|
+
if (!isPlainPath(target)) {
|
|
82
|
+
throw new Error("The request target has a backslash or a dot segment, which the URL " +
|
|
83
|
+
"would read differently from Express's routing.");
|
|
84
|
+
}
|
|
85
|
+
return url;
|
|
86
|
+
}
|
|
87
|
+
function isPlainPath(target) {
|
|
88
|
+
const path = target.split(/[?#]/, 1)[0];
|
|
89
|
+
return (!path.includes("\\") &&
|
|
90
|
+
!path.split("/").some((segment) => /^(?:\.|%2e){1,2}$/i.test(segment)));
|
|
91
|
+
}
|
|
92
|
+
function parsedFormBody(req) {
|
|
93
|
+
if (!req.readableEnded)
|
|
94
|
+
return null;
|
|
95
|
+
if (!req.headers["content-type"]?.includes(FORM_TYPE))
|
|
96
|
+
return null;
|
|
97
|
+
const { body } = req;
|
|
98
|
+
if (typeof body === "string")
|
|
99
|
+
return body;
|
|
100
|
+
if (Buffer.isBuffer(body))
|
|
101
|
+
return body.toString("utf8");
|
|
102
|
+
if (body === null || typeof body !== "object")
|
|
103
|
+
return null;
|
|
104
|
+
const params = new URLSearchParams();
|
|
105
|
+
for (const [name, value] of Object.entries(body)) {
|
|
106
|
+
if (typeof value === "string")
|
|
107
|
+
params.append(name, value);
|
|
108
|
+
}
|
|
109
|
+
return params.toString();
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Writes a core {@link Response} to `res`, keeping headers earlier
|
|
113
|
+
* middleware set — `Set-Cookie` values are added to theirs, not replaced.
|
|
114
|
+
*/
|
|
115
|
+
export async function sendFetchResponse(res, response) {
|
|
116
|
+
res.statusCode = response.status;
|
|
117
|
+
for (const [name, value] of response.headers) {
|
|
118
|
+
if (name !== "set-cookie")
|
|
119
|
+
res.setHeader(name, value);
|
|
120
|
+
}
|
|
121
|
+
const cookies = response.headers.getSetCookie();
|
|
122
|
+
if (cookies.length > 0) {
|
|
123
|
+
const existing = res.getHeader("set-cookie");
|
|
124
|
+
const earlier = existing === undefined
|
|
125
|
+
? []
|
|
126
|
+
: Array.isArray(existing)
|
|
127
|
+
? existing
|
|
128
|
+
: [String(existing)];
|
|
129
|
+
res.setHeader("set-cookie", [...earlier, ...cookies]);
|
|
130
|
+
}
|
|
131
|
+
const body = response.body
|
|
132
|
+
? Buffer.from(await response.arrayBuffer())
|
|
133
|
+
: undefined;
|
|
134
|
+
res.end(body);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Wraps a core handler as Express middleware that writes its response, and
|
|
138
|
+
* passes anything it throws to `next` (Express 4 does not catch a rejected
|
|
139
|
+
* handler on its own).
|
|
140
|
+
*/
|
|
141
|
+
export function fetchHandler(handle) {
|
|
142
|
+
return (req, res, next) => {
|
|
143
|
+
Promise.resolve()
|
|
144
|
+
.then(() => handle(toFetchRequest(req, "stream"), req, res))
|
|
145
|
+
.then((response) => sendFetchResponse(res, response))
|
|
146
|
+
.catch(next);
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Builds an Express middleware that authenticates bearer tokens, stores the
|
|
151
|
+
* authenticated context at `res.locals[OAUTH2_CONTEXT_KEY]`, and on failure
|
|
152
|
+
* writes the server's auth error response.
|
|
153
|
+
*/
|
|
154
|
+
export function createProtectMiddleware(server, requiredScope) {
|
|
155
|
+
return (req, res, next) => {
|
|
156
|
+
Promise.resolve()
|
|
157
|
+
.then(() => baseAuthenticate(server, toFetchRequest(req, "parsed"), requiredScope))
|
|
158
|
+
.then((context) => {
|
|
159
|
+
res.locals[OAUTH2_CONTEXT_KEY] = context;
|
|
160
|
+
next();
|
|
161
|
+
}, (error) => sendFetchResponse(res, server.handleAuthError(error)))
|
|
162
|
+
.catch(next);
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Builds an Express middleware that asserts the **already-authenticated**
|
|
167
|
+
* request carries `requiredScope`, without re-validating the token.
|
|
168
|
+
* `adapterName` names the class in the "context missing" developer error.
|
|
169
|
+
*/
|
|
170
|
+
export function createRequireScopeMiddleware(server, adapterName, requiredScope) {
|
|
171
|
+
return assertingMiddleware(server, adapterName, ({ scope }) => server.assertScope(scope, requiredScope));
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Builds an Express middleware that asserts the **already-authenticated**
|
|
175
|
+
* request satisfies `conditions`, without re-validating the token.
|
|
176
|
+
*/
|
|
177
|
+
export function createRequireMiddleware(server, adapterName, conditions) {
|
|
178
|
+
return assertingMiddleware(server, adapterName, (context) => server.assertAuthorized(context, conditions));
|
|
179
|
+
}
|
|
180
|
+
function assertingMiddleware(server, adapterName, assert) {
|
|
181
|
+
return (_req, res, next) => {
|
|
182
|
+
let context;
|
|
183
|
+
try {
|
|
184
|
+
context = readContext(res, adapterName);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
next(error);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
assert(context);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
Promise.resolve()
|
|
195
|
+
.then(() => sendFetchResponse(res, server.handleAuthError(error)))
|
|
196
|
+
.catch(next);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
next();
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Authenticates an Express request or a raw {@link Request} with the base
|
|
204
|
+
* {@link ResourceServer.authenticate}, bypassing the adapters' override.
|
|
205
|
+
*/
|
|
206
|
+
export function authenticateExpressRequest(server, req, requiredScope) {
|
|
207
|
+
const request = req instanceof Request ? req : toFetchRequest(req, "parsed");
|
|
208
|
+
return baseAuthenticate(server, request, requiredScope);
|
|
209
|
+
}
|
|
210
|
+
// Base method on purpose: the Express subclasses' override would recurse.
|
|
211
|
+
function baseAuthenticate(server, request, requiredScope) {
|
|
212
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
213
|
+
const base = ResourceServer.prototype;
|
|
214
|
+
return base.authenticate.call(server, request, requiredScope);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Reads the authenticated OAuth2 context off `res.locals`.
|
|
218
|
+
*
|
|
219
|
+
* @throws {Error} If no `protect` middleware set it first; the message names
|
|
220
|
+
* `adapterName`.
|
|
221
|
+
*/
|
|
222
|
+
export function readContext(res, adapterName) {
|
|
223
|
+
const context = res.locals[OAUTH2_CONTEXT_KEY];
|
|
224
|
+
if (!context) {
|
|
225
|
+
throw new Error(`OAuth2 context missing; ensure ${adapterName}.protect() middleware ` +
|
|
226
|
+
`runs before this handler.`);
|
|
227
|
+
}
|
|
228
|
+
return context;
|
|
229
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express adapter for the core {@link AuthorizationServer}.
|
|
3
|
+
*
|
|
4
|
+
* Provides Express handler factories for each OAuth2 endpoint and a
|
|
5
|
+
* `routes()` middleware that serves all standard endpoints at conventional
|
|
6
|
+
* paths. Also inherits resource-server-shaped helpers (`protect`,
|
|
7
|
+
* `authenticate`, `getContext`) so the same instance can protect API routes.
|
|
8
|
+
* The adapter depends on neither `express` nor its types, and works with
|
|
9
|
+
* Express 4 and 5.
|
|
10
|
+
*
|
|
11
|
+
* The endpoint handlers read the raw request body themselves, so mount them
|
|
12
|
+
* before any body-parsing middleware; a handler that finds the body already
|
|
13
|
+
* consumed passes an error to `next` instead of guessing at it.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import express from "express";
|
|
18
|
+
* import {
|
|
19
|
+
* type ExpressAuthenticateUserFn,
|
|
20
|
+
* ExpressAuthorizationServer,
|
|
21
|
+
* } from "@udibo/oauth2/express/authorization-server";
|
|
22
|
+
* import type { AuthorizationServerOptions } from "@udibo/oauth2/server/authorization";
|
|
23
|
+
* import type { BasicScope } from "@udibo/oauth2/server";
|
|
24
|
+
*
|
|
25
|
+
* interface Client { id: string }
|
|
26
|
+
* interface User { id: string }
|
|
27
|
+
* declare const options: AuthorizationServerOptions<Client, User, BasicScope>;
|
|
28
|
+
* declare const authenticateUser: ExpressAuthenticateUserFn<User, express.Request>;
|
|
29
|
+
*
|
|
30
|
+
* const authServer = new ExpressAuthorizationServer<Client, User>(options);
|
|
31
|
+
* const app = express();
|
|
32
|
+
*
|
|
33
|
+
* app.use("/oauth2", authServer.routes({ authenticateUser }));
|
|
34
|
+
* app.use(express.json());
|
|
35
|
+
* app.use("/api", authServer.protect());
|
|
36
|
+
* app.get("/api/me", (_req, res) => {
|
|
37
|
+
* res.json(authServer.getContext(res).user);
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @module
|
|
42
|
+
*/
|
|
43
|
+
import type { RequireConditions } from "../../models/authorization.ts";
|
|
44
|
+
import type { AuthenticationContext, AuthenticationRequest } from "../../models/authentication.ts";
|
|
45
|
+
import type { ClientInterface } from "../../models/client.ts";
|
|
46
|
+
import type { AbstractScope, BasicScope } from "../../models/scope.ts";
|
|
47
|
+
import { AuthorizationServer, type AuthorizationServerOptions } from "../../server/authorization-server.ts";
|
|
48
|
+
import type { AuthenticatedContext } from "../../server/resource-server.ts";
|
|
49
|
+
import { type ExpressMiddleware, type ExpressRequestLike, type ExpressResponseLike } from "./_common.ts";
|
|
50
|
+
export type { ExpressMiddleware, ExpressNextFunction, ExpressRequestLike, ExpressResponseLike, } from "./_common.ts";
|
|
51
|
+
/**
|
|
52
|
+
* Authenticates the resource owner during an authorization request.
|
|
53
|
+
*
|
|
54
|
+
* Receives the Express request and response, so the callback can read the
|
|
55
|
+
* app's own session (`req.session` under `express-session`). Return one of:
|
|
56
|
+
*
|
|
57
|
+
* - `{ user, authorizedScope?, authenticationContext?, reauthenticated? }` —
|
|
58
|
+
* user is authenticated; the authorize flow continues. Supply only verified
|
|
59
|
+
* event claims in `authenticationContext`. Set `reauthenticated: true` only
|
|
60
|
+
* when the user actively authenticated in response to this request.
|
|
61
|
+
* - `null` — explicit denial; the framework redirects to `redirect_uri` with
|
|
62
|
+
* `error=access_denied`.
|
|
63
|
+
* - A web `Response` — typically a 302 to your login page,
|
|
64
|
+
* `new Response(null, { status: 302, headers: { location } })` — which
|
|
65
|
+
* short-circuits the flow and is written to the browser as-is. Under
|
|
66
|
+
* `prompt=none` the server answers `login_required` instead.
|
|
67
|
+
*
|
|
68
|
+
* Do not write to `res` yourself; the adapter writes the response.
|
|
69
|
+
*/
|
|
70
|
+
export type ExpressAuthenticateUserFn<User, Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike> = (req: Req, res: Res, authentication?: AuthenticationRequest) => Promise<{
|
|
71
|
+
user: User;
|
|
72
|
+
authorizedScope?: AbstractScope;
|
|
73
|
+
authenticationContext?: AuthenticationContext;
|
|
74
|
+
reauthenticated?: boolean;
|
|
75
|
+
} | Response | null>;
|
|
76
|
+
/**
|
|
77
|
+
* Collects consent from the resource owner for the requested scope. Return
|
|
78
|
+
* `{ approved: true, scope? }`, `{ approved: false }` (redirects with
|
|
79
|
+
* `error=access_denied`), or a web `Response` rendering your consent page.
|
|
80
|
+
* `scope`, when set, replaces the granted scope and is not checked against
|
|
81
|
+
* the request, so return a subset. Do not write to `res` yourself.
|
|
82
|
+
*/
|
|
83
|
+
export type ExpressHandleConsentFn<Client extends ClientInterface, S extends AbstractScope, Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike> = (req: Req, res: Res, client: Client, requestedScope: S | undefined, user: unknown, authentication?: AuthenticationRequest) => Promise<{
|
|
84
|
+
approved: boolean;
|
|
85
|
+
scope?: S;
|
|
86
|
+
} | Response>;
|
|
87
|
+
/** Options for {@link ExpressAuthorizationServer.routes}. */
|
|
88
|
+
export interface ExpressRoutesOptions<Client extends ClientInterface, User, S extends AbstractScope, Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike> {
|
|
89
|
+
/** Authenticates the resource owner at the authorize endpoint. */
|
|
90
|
+
authenticateUser: ExpressAuthenticateUserFn<User, Req, Res>;
|
|
91
|
+
/** Collects consent for the requested scope. Omit to auto-consent. */
|
|
92
|
+
handleConsent?: ExpressHandleConsentFn<Client, S, Req, Res>;
|
|
93
|
+
}
|
|
94
|
+
/** Options for {@link ExpressAuthorizationServer.authorizeHandler}. */
|
|
95
|
+
export type ExpressAuthorizeHandlerOptions<Client extends ClientInterface, User, S extends AbstractScope, Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike> = ExpressRoutesOptions<Client, User, S, Req, Res>;
|
|
96
|
+
/**
|
|
97
|
+
* Express-specific wrapper around {@link AuthorizationServer}. Adds endpoint
|
|
98
|
+
* handler factories and the resource-server-shaped helpers (`protect`,
|
|
99
|
+
* `requireScope`, `require`, `authenticate`, `getContext`) against this same
|
|
100
|
+
* instance.
|
|
101
|
+
*/
|
|
102
|
+
export declare class ExpressAuthorizationServer<Client extends ClientInterface, User, S extends AbstractScope = BasicScope> extends AuthorizationServer<Client, User, S> {
|
|
103
|
+
/** Forwards `options` to the core {@linkcode AuthorizationServer}. */
|
|
104
|
+
constructor(options: AuthorizationServerOptions<Client, User, S>);
|
|
105
|
+
/**
|
|
106
|
+
* Returns an Express middleware that validates the bearer token against
|
|
107
|
+
* this server's token service and stores the authenticated context on
|
|
108
|
+
* `res.locals`. See {@link ExpressResourceServer.protect}.
|
|
109
|
+
*/
|
|
110
|
+
protect(requiredScope?: S | string): ExpressMiddleware;
|
|
111
|
+
/**
|
|
112
|
+
* Returns an Express middleware that asserts an **already-authenticated**
|
|
113
|
+
* request carries `requiredScope` without re-validating the token. See
|
|
114
|
+
* {@link ExpressResourceServer.requireScope}.
|
|
115
|
+
*/
|
|
116
|
+
requireScope(requiredScope: S | string): ExpressMiddleware;
|
|
117
|
+
/**
|
|
118
|
+
* Middleware asserting the already-authenticated request satisfies every
|
|
119
|
+
* condition (scope, permission, role, organization). See
|
|
120
|
+
* {@link ExpressResourceServer.require}.
|
|
121
|
+
*/
|
|
122
|
+
require(conditions: RequireConditions): ExpressMiddleware;
|
|
123
|
+
/**
|
|
124
|
+
* Authenticates an Express request or a raw {@link Request} inline. Throws
|
|
125
|
+
* on failure — pair with {@link AuthorizationServer.handleAuthError} to
|
|
126
|
+
* convert to a response.
|
|
127
|
+
*/
|
|
128
|
+
authenticate(req: ExpressRequestLike | Request, requiredScope?: S | string): Promise<AuthenticatedContext<Client, User, S>>;
|
|
129
|
+
/**
|
|
130
|
+
* Typed accessor for the authenticated OAuth2 context {@link protect}
|
|
131
|
+
* stored on `res.locals`.
|
|
132
|
+
*
|
|
133
|
+
* @throws {Error} If `protect` did not run first for this request.
|
|
134
|
+
*/
|
|
135
|
+
getContext(res: ExpressResponseLike): AuthenticatedContext<Client, User, S>;
|
|
136
|
+
/**
|
|
137
|
+
* Handler for the token endpoint (RFC 6749 Section 3.2).
|
|
138
|
+
* Mount at `POST /token`, before any body parser.
|
|
139
|
+
*/
|
|
140
|
+
tokenHandler(): ExpressMiddleware;
|
|
141
|
+
/**
|
|
142
|
+
* Handler for the authorization endpoint (RFC 6749 Section 3.1).
|
|
143
|
+
* Mount at `GET /authorize`. Callbacks receive the Express request and
|
|
144
|
+
* response; annotate their `req` parameter to type it as your app's
|
|
145
|
+
* request.
|
|
146
|
+
*/
|
|
147
|
+
authorizeHandler<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike>(options: ExpressAuthorizeHandlerOptions<Client, User, S, Req, Res>): ExpressMiddleware<Req, Res>;
|
|
148
|
+
/**
|
|
149
|
+
* Handler for the token revocation endpoint (RFC 7009).
|
|
150
|
+
* Mount at `POST /revoke`, before any body parser.
|
|
151
|
+
*/
|
|
152
|
+
revocationHandler(): ExpressMiddleware;
|
|
153
|
+
/**
|
|
154
|
+
* Handler for the token introspection endpoint (RFC 7662).
|
|
155
|
+
* Mount at `POST /introspect`, before any body parser.
|
|
156
|
+
*/
|
|
157
|
+
introspectionHandler(): ExpressMiddleware;
|
|
158
|
+
/**
|
|
159
|
+
* Handler for the authorization server metadata endpoint (RFC 8414).
|
|
160
|
+
* Mount at `GET /.well-known/oauth-authorization-server`.
|
|
161
|
+
*/
|
|
162
|
+
metadataHandler(): ExpressMiddleware;
|
|
163
|
+
/**
|
|
164
|
+
* Handler for the OIDC discovery endpoint.
|
|
165
|
+
* Mount at `GET /.well-known/openid-configuration`. 404s when OIDC issuance
|
|
166
|
+
* is not configured.
|
|
167
|
+
*/
|
|
168
|
+
oidcMetadataHandler(): ExpressMiddleware;
|
|
169
|
+
/**
|
|
170
|
+
* Handler for the JWKS endpoint (OIDC Discovery).
|
|
171
|
+
* Mount at `GET /jwks`. 404s when OIDC issuance is not configured.
|
|
172
|
+
*/
|
|
173
|
+
jwksHandler(): ExpressMiddleware;
|
|
174
|
+
/**
|
|
175
|
+
* Handler for the OIDC UserInfo endpoint.
|
|
176
|
+
* Mount at `GET`/`POST /userinfo`, before any body parser.
|
|
177
|
+
*/
|
|
178
|
+
userInfoHandler(): ExpressMiddleware;
|
|
179
|
+
/**
|
|
180
|
+
* Handler for the OIDC RP-Initiated Logout end-session endpoint.
|
|
181
|
+
* Mount at `GET|POST /end_session`, before any body parser. Answers 404
|
|
182
|
+
* unless the server was constructed with an `endSession` callback.
|
|
183
|
+
*/
|
|
184
|
+
endSessionHandler(): ExpressMiddleware;
|
|
185
|
+
/**
|
|
186
|
+
* Handler for the device authorization endpoint (RFC 8628).
|
|
187
|
+
* Mount at `POST /device_authorization`, before any body parser.
|
|
188
|
+
*/
|
|
189
|
+
deviceAuthorizationHandler(): ExpressMiddleware;
|
|
190
|
+
/**
|
|
191
|
+
* Returns one Express middleware serving all standard OAuth2 endpoints at
|
|
192
|
+
* conventional paths, relative to wherever it is mounted:
|
|
193
|
+
*
|
|
194
|
+
* - `POST /token`
|
|
195
|
+
* - `GET /authorize`
|
|
196
|
+
* - `POST /revoke`
|
|
197
|
+
* - `POST /introspect`
|
|
198
|
+
* - `POST /device_authorization`
|
|
199
|
+
* - `GET /.well-known/oauth-authorization-server`
|
|
200
|
+
* - `GET /.well-known/openid-configuration`
|
|
201
|
+
* - `GET /jwks` and `GET`/`POST /userinfo` (live when OIDC issuance is
|
|
202
|
+
* configured via `signingKeys`)
|
|
203
|
+
* - `GET`/`POST /end_session` (live when the server has an `endSession`
|
|
204
|
+
* callback)
|
|
205
|
+
*
|
|
206
|
+
* Mount with `app.use("/oauth2", server.routes({...}))`, before any body
|
|
207
|
+
* parser. Any other path or verb falls through to `next()`. Every path and
|
|
208
|
+
* verb comes from {@link ENDPOINT_PATHS}/{@link ENDPOINT_METHODS}; a `GET`
|
|
209
|
+
* endpoint answers `HEAD` too, as an Express `get` route does. The
|
|
210
|
+
* advertised URLs match the mount only when the issuer (or each explicit
|
|
211
|
+
* `*Endpoint` in the resolved context) points at where you mounted it.
|
|
212
|
+
*/
|
|
213
|
+
routes<Req extends ExpressRequestLike = ExpressRequestLike, Res extends ExpressResponseLike = ExpressResponseLike>(options: ExpressRoutesOptions<Client, User, S, Req, Res>): ExpressMiddleware<Req, Res>;
|
|
214
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express adapter for the core {@link AuthorizationServer}.
|
|
3
|
+
*
|
|
4
|
+
* Provides Express handler factories for each OAuth2 endpoint and a
|
|
5
|
+
* `routes()` middleware that serves all standard endpoints at conventional
|
|
6
|
+
* paths. Also inherits resource-server-shaped helpers (`protect`,
|
|
7
|
+
* `authenticate`, `getContext`) so the same instance can protect API routes.
|
|
8
|
+
* The adapter depends on neither `express` nor its types, and works with
|
|
9
|
+
* Express 4 and 5.
|
|
10
|
+
*
|
|
11
|
+
* The endpoint handlers read the raw request body themselves, so mount them
|
|
12
|
+
* before any body-parsing middleware; a handler that finds the body already
|
|
13
|
+
* consumed passes an error to `next` instead of guessing at it.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import express from "express";
|
|
18
|
+
* import {
|
|
19
|
+
* type ExpressAuthenticateUserFn,
|
|
20
|
+
* ExpressAuthorizationServer,
|
|
21
|
+
* } from "@udibo/oauth2/express/authorization-server";
|
|
22
|
+
* import type { AuthorizationServerOptions } from "@udibo/oauth2/server/authorization";
|
|
23
|
+
* import type { BasicScope } from "@udibo/oauth2/server";
|
|
24
|
+
*
|
|
25
|
+
* interface Client { id: string }
|
|
26
|
+
* interface User { id: string }
|
|
27
|
+
* declare const options: AuthorizationServerOptions<Client, User, BasicScope>;
|
|
28
|
+
* declare const authenticateUser: ExpressAuthenticateUserFn<User, express.Request>;
|
|
29
|
+
*
|
|
30
|
+
* const authServer = new ExpressAuthorizationServer<Client, User>(options);
|
|
31
|
+
* const app = express();
|
|
32
|
+
*
|
|
33
|
+
* app.use("/oauth2", authServer.routes({ authenticateUser }));
|
|
34
|
+
* app.use(express.json());
|
|
35
|
+
* app.use("/api", authServer.protect());
|
|
36
|
+
* app.get("/api/me", (_req, res) => {
|
|
37
|
+
* res.json(authServer.getContext(res).user);
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @module
|
|
42
|
+
*/
|
|
43
|
+
import { AuthorizationServer, ENDPOINT_METHODS, ENDPOINT_PATHS, } from "../../server/authorization-server.js";
|
|
44
|
+
import { authenticateExpressRequest, createProtectMiddleware, createRequireMiddleware, createRequireScopeMiddleware, fetchHandler, readContext, } from "./_common.js";
|
|
45
|
+
/**
|
|
46
|
+
* Express-specific wrapper around {@link AuthorizationServer}. Adds endpoint
|
|
47
|
+
* handler factories and the resource-server-shaped helpers (`protect`,
|
|
48
|
+
* `requireScope`, `require`, `authenticate`, `getContext`) against this same
|
|
49
|
+
* instance.
|
|
50
|
+
*/
|
|
51
|
+
export class ExpressAuthorizationServer extends AuthorizationServer {
|
|
52
|
+
/** Forwards `options` to the core {@linkcode AuthorizationServer}. */
|
|
53
|
+
constructor(options) {
|
|
54
|
+
super(options);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Returns an Express middleware that validates the bearer token against
|
|
58
|
+
* this server's token service and stores the authenticated context on
|
|
59
|
+
* `res.locals`. See {@link ExpressResourceServer.protect}.
|
|
60
|
+
*/
|
|
61
|
+
protect(requiredScope) {
|
|
62
|
+
return createProtectMiddleware(this, requiredScope);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Returns an Express middleware that asserts an **already-authenticated**
|
|
66
|
+
* request carries `requiredScope` without re-validating the token. See
|
|
67
|
+
* {@link ExpressResourceServer.requireScope}.
|
|
68
|
+
*/
|
|
69
|
+
requireScope(requiredScope) {
|
|
70
|
+
return createRequireScopeMiddleware(this, "ExpressAuthorizationServer", requiredScope);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Middleware asserting the already-authenticated request satisfies every
|
|
74
|
+
* condition (scope, permission, role, organization). See
|
|
75
|
+
* {@link ExpressResourceServer.require}.
|
|
76
|
+
*/
|
|
77
|
+
require(conditions) {
|
|
78
|
+
return createRequireMiddleware(this, "ExpressAuthorizationServer", conditions);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Authenticates an Express request or a raw {@link Request} inline. Throws
|
|
82
|
+
* on failure — pair with {@link AuthorizationServer.handleAuthError} to
|
|
83
|
+
* convert to a response.
|
|
84
|
+
*/
|
|
85
|
+
authenticate(req, requiredScope) {
|
|
86
|
+
return authenticateExpressRequest(this, req, requiredScope);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Typed accessor for the authenticated OAuth2 context {@link protect}
|
|
90
|
+
* stored on `res.locals`.
|
|
91
|
+
*
|
|
92
|
+
* @throws {Error} If `protect` did not run first for this request.
|
|
93
|
+
*/
|
|
94
|
+
getContext(res) {
|
|
95
|
+
return readContext(res, "ExpressAuthorizationServer");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Handler for the token endpoint (RFC 6749 Section 3.2).
|
|
99
|
+
* Mount at `POST /token`, before any body parser.
|
|
100
|
+
*/
|
|
101
|
+
tokenHandler() {
|
|
102
|
+
return fetchHandler((request) => this.handleTokenRequest(request));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Handler for the authorization endpoint (RFC 6749 Section 3.1).
|
|
106
|
+
* Mount at `GET /authorize`. Callbacks receive the Express request and
|
|
107
|
+
* response; annotate their `req` parameter to type it as your app's
|
|
108
|
+
* request.
|
|
109
|
+
*/
|
|
110
|
+
authorizeHandler(options) {
|
|
111
|
+
const { authenticateUser, handleConsent } = options;
|
|
112
|
+
return fetchHandler((request, req, res) => this.handleAuthorizeRequest(request, (_request, authentication) => authenticateUser(req, res, authentication), handleConsent
|
|
113
|
+
? (client, requestedScope, user, authentication) => handleConsent(req, res, client, requestedScope, user, authentication)
|
|
114
|
+
: undefined));
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Handler for the token revocation endpoint (RFC 7009).
|
|
118
|
+
* Mount at `POST /revoke`, before any body parser.
|
|
119
|
+
*/
|
|
120
|
+
revocationHandler() {
|
|
121
|
+
return fetchHandler((request) => this.handleRevocationRequest(request));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Handler for the token introspection endpoint (RFC 7662).
|
|
125
|
+
* Mount at `POST /introspect`, before any body parser.
|
|
126
|
+
*/
|
|
127
|
+
introspectionHandler() {
|
|
128
|
+
return fetchHandler((request) => this.handleIntrospectionRequest(request));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Handler for the authorization server metadata endpoint (RFC 8414).
|
|
132
|
+
* Mount at `GET /.well-known/oauth-authorization-server`.
|
|
133
|
+
*/
|
|
134
|
+
metadataHandler() {
|
|
135
|
+
return fetchHandler((request) => this.handleMetadataRequest(request));
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Handler for the OIDC discovery endpoint.
|
|
139
|
+
* Mount at `GET /.well-known/openid-configuration`. 404s when OIDC issuance
|
|
140
|
+
* is not configured.
|
|
141
|
+
*/
|
|
142
|
+
oidcMetadataHandler() {
|
|
143
|
+
return fetchHandler((request) => this.handleOidcMetadataRequest(request));
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Handler for the JWKS endpoint (OIDC Discovery).
|
|
147
|
+
* Mount at `GET /jwks`. 404s when OIDC issuance is not configured.
|
|
148
|
+
*/
|
|
149
|
+
jwksHandler() {
|
|
150
|
+
return fetchHandler((request) => this.handleJwksRequest(request));
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Handler for the OIDC UserInfo endpoint.
|
|
154
|
+
* Mount at `GET`/`POST /userinfo`, before any body parser.
|
|
155
|
+
*/
|
|
156
|
+
userInfoHandler() {
|
|
157
|
+
return fetchHandler((request) => this.handleUserInfoRequest(request));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Handler for the OIDC RP-Initiated Logout end-session endpoint.
|
|
161
|
+
* Mount at `GET|POST /end_session`, before any body parser. Answers 404
|
|
162
|
+
* unless the server was constructed with an `endSession` callback.
|
|
163
|
+
*/
|
|
164
|
+
endSessionHandler() {
|
|
165
|
+
return fetchHandler((request) => this.handleEndSessionRequest(request));
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Handler for the device authorization endpoint (RFC 8628).
|
|
169
|
+
* Mount at `POST /device_authorization`, before any body parser.
|
|
170
|
+
*/
|
|
171
|
+
deviceAuthorizationHandler() {
|
|
172
|
+
return fetchHandler((request) => this.handleDeviceAuthorizationRequest(request));
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Returns one Express middleware serving all standard OAuth2 endpoints at
|
|
176
|
+
* conventional paths, relative to wherever it is mounted:
|
|
177
|
+
*
|
|
178
|
+
* - `POST /token`
|
|
179
|
+
* - `GET /authorize`
|
|
180
|
+
* - `POST /revoke`
|
|
181
|
+
* - `POST /introspect`
|
|
182
|
+
* - `POST /device_authorization`
|
|
183
|
+
* - `GET /.well-known/oauth-authorization-server`
|
|
184
|
+
* - `GET /.well-known/openid-configuration`
|
|
185
|
+
* - `GET /jwks` and `GET`/`POST /userinfo` (live when OIDC issuance is
|
|
186
|
+
* configured via `signingKeys`)
|
|
187
|
+
* - `GET`/`POST /end_session` (live when the server has an `endSession`
|
|
188
|
+
* callback)
|
|
189
|
+
*
|
|
190
|
+
* Mount with `app.use("/oauth2", server.routes({...}))`, before any body
|
|
191
|
+
* parser. Any other path or verb falls through to `next()`. Every path and
|
|
192
|
+
* verb comes from {@link ENDPOINT_PATHS}/{@link ENDPOINT_METHODS}; a `GET`
|
|
193
|
+
* endpoint answers `HEAD` too, as an Express `get` route does. The
|
|
194
|
+
* advertised URLs match the mount only when the issuer (or each explicit
|
|
195
|
+
* `*Endpoint` in the resolved context) points at where you mounted it.
|
|
196
|
+
*/
|
|
197
|
+
routes(options) {
|
|
198
|
+
const handlers = {
|
|
199
|
+
authorization: this.authorizeHandler(options),
|
|
200
|
+
token: this.tokenHandler(),
|
|
201
|
+
revocation: this.revocationHandler(),
|
|
202
|
+
introspection: this.introspectionHandler(),
|
|
203
|
+
deviceAuthorization: this.deviceAuthorizationHandler(),
|
|
204
|
+
jwks: this.jwksHandler(),
|
|
205
|
+
userinfo: this.userInfoHandler(),
|
|
206
|
+
endSession: this.endSessionHandler(),
|
|
207
|
+
metadata: this.metadataHandler(),
|
|
208
|
+
oidcMetadata: this.oidcMetadataHandler(),
|
|
209
|
+
};
|
|
210
|
+
const table = new Map();
|
|
211
|
+
for (const [key, handler] of Object.entries(handlers)) {
|
|
212
|
+
const endpoint = key;
|
|
213
|
+
for (const method of ENDPOINT_METHODS[endpoint]) {
|
|
214
|
+
table.set(`${method} ${ENDPOINT_PATHS[endpoint]}`, handler);
|
|
215
|
+
if (method === "GET") {
|
|
216
|
+
table.set(`HEAD ${ENDPOINT_PATHS[endpoint]}`, handler);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return (req, res, next) => {
|
|
221
|
+
const path = (req.url ?? "/").split("?", 1)[0] || "/";
|
|
222
|
+
const handler = table.get(`${req.method} ${path}`);
|
|
223
|
+
if (handler)
|
|
224
|
+
handler(req, res, next);
|
|
225
|
+
else
|
|
226
|
+
next();
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express adapter for the core {@link ResourceServer}.
|
|
3
|
+
*
|
|
4
|
+
* Provides middleware and accessors that let an Express 4 or 5 app
|
|
5
|
+
* authenticate requests against an OAuth2 authorization server. The adapter
|
|
6
|
+
* depends on neither `express` nor its types: its handlers are typed
|
|
7
|
+
* structurally, so any Express request and response satisfy them.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import express from "express";
|
|
12
|
+
* import { ExpressResourceServer } from "@udibo/oauth2/express/resource-server";
|
|
13
|
+
* import type { TokenReaderInterface } from "@udibo/oauth2/server";
|
|
14
|
+
*
|
|
15
|
+
* interface Client { id: string }
|
|
16
|
+
* interface User { id: string }
|
|
17
|
+
* declare const tokenService: TokenReaderInterface<Client, User>;
|
|
18
|
+
*
|
|
19
|
+
* const resourceServer = new ExpressResourceServer<Client, User>({
|
|
20
|
+
* resolve: () => ({ services: { tokenService } }),
|
|
21
|
+
* });
|
|
22
|
+
* const app = express();
|
|
23
|
+
*
|
|
24
|
+
* app.use("/api", resourceServer.protect());
|
|
25
|
+
* app.get("/api/me", (_req, res) => {
|
|
26
|
+
* res.json(resourceServer.getContext(res).user);
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @module
|
|
31
|
+
*/
|
|
32
|
+
import type { RequireConditions } from "../../models/authorization.ts";
|
|
33
|
+
import type { ClientInterface } from "../../models/client.ts";
|
|
34
|
+
import type { AbstractScope, BasicScope } from "../../models/scope.ts";
|
|
35
|
+
import { type AuthenticatedContext, ResourceServer } from "../../server/resource-server.ts";
|
|
36
|
+
import { type ExpressMiddleware, type ExpressRequestLike, type ExpressResponseLike } from "./_common.ts";
|
|
37
|
+
export { type ExpressMiddleware, type ExpressNextFunction, type ExpressRequestLike, type ExpressResponseLike, OAUTH2_CONTEXT_KEY, } from "./_common.ts";
|
|
38
|
+
/**
|
|
39
|
+
* Express-specific wrapper around {@link ResourceServer}. Construction options
|
|
40
|
+
* are identical to the core server; the subclass only adds Express middleware
|
|
41
|
+
* helpers.
|
|
42
|
+
*
|
|
43
|
+
* `protect` reads the bearer token from the `Authorization` header. It never
|
|
44
|
+
* reads the request stream, so routes behind it keep their body for later
|
|
45
|
+
* middleware; a form-encoded `access_token` (RFC 6750 Section 2.2) is honored
|
|
46
|
+
* only when a body parser has already parsed it onto `req.body`.
|
|
47
|
+
*/
|
|
48
|
+
export declare class ExpressResourceServer<Client extends ClientInterface, User, S extends AbstractScope = BasicScope> extends ResourceServer<Client, User, S> {
|
|
49
|
+
/**
|
|
50
|
+
* Returns an Express middleware that validates the bearer token.
|
|
51
|
+
*
|
|
52
|
+
* On success, stores the authenticated context on `res.locals` (read it
|
|
53
|
+
* with {@link getContext}) and calls `next()`. On failure, writes the error
|
|
54
|
+
* response, with a `WWW-Authenticate` challenge (RFC 6750 Section 3) on a
|
|
55
|
+
* 401 or 403, or passes the error to `next` when `throwOnError` is set.
|
|
56
|
+
*/
|
|
57
|
+
protect(requiredScope?: S | string): ExpressMiddleware;
|
|
58
|
+
/**
|
|
59
|
+
* Returns an Express middleware that asserts the **already-authenticated**
|
|
60
|
+
* request carries `requiredScope`, **without** re-validating the token.
|
|
61
|
+
*
|
|
62
|
+
* Mount it after {@link protect} when one authenticated mount exposes
|
|
63
|
+
* routes needing different scopes. On insufficient scope it writes the same
|
|
64
|
+
* RFC 6750 `insufficient_scope` response (403 with a `WWW-Authenticate`
|
|
65
|
+
* header) as `protect`.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* import express from "express";
|
|
70
|
+
* import { ExpressResourceServer } from "@udibo/oauth2/express/resource-server";
|
|
71
|
+
*
|
|
72
|
+
* declare const resourceServer: ExpressResourceServer<{ id: string }, { id: string }>;
|
|
73
|
+
* declare const list: express.RequestHandler;
|
|
74
|
+
* declare const create: express.RequestHandler;
|
|
75
|
+
* const app = express();
|
|
76
|
+
*
|
|
77
|
+
* app.use("/api", resourceServer.protect());
|
|
78
|
+
* app.get("/api/items", resourceServer.requireScope("read"), list);
|
|
79
|
+
* app.post("/api/items", resourceServer.requireScope("write"), create);
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
requireScope(requiredScope: S | string): ExpressMiddleware;
|
|
83
|
+
/**
|
|
84
|
+
* Middleware asserting the already-authenticated request satisfies every
|
|
85
|
+
* condition — AND semantics across keys, arrays mean all-of (see
|
|
86
|
+
* {@linkcode RequireConditions}). Scope failures answer the RFC 6750
|
|
87
|
+
* `insufficient_scope` challenge exactly as {@linkcode requireScope} does;
|
|
88
|
+
* permission, role, and organization failures answer a plain 403. Mount
|
|
89
|
+
* {@linkcode protect} first — this middleware does not validate the token.
|
|
90
|
+
*/
|
|
91
|
+
require(conditions: RequireConditions): ExpressMiddleware;
|
|
92
|
+
/**
|
|
93
|
+
* Authenticates an Express request or a raw {@link Request} inline, for
|
|
94
|
+
* handlers that do not use {@link protect}. Throws on failure — pair with
|
|
95
|
+
* {@link ResourceServer.handleAuthError} to convert to a response.
|
|
96
|
+
*/
|
|
97
|
+
authenticate(req: ExpressRequestLike | Request, requiredScope?: S | string): Promise<AuthenticatedContext<Client, User, S>>;
|
|
98
|
+
/**
|
|
99
|
+
* Typed accessor for the authenticated OAuth2 context {@link protect}
|
|
100
|
+
* stored on `res.locals`.
|
|
101
|
+
*
|
|
102
|
+
* @throws {Error} If `protect` did not run first for this request.
|
|
103
|
+
*/
|
|
104
|
+
getContext(res: ExpressResponseLike): AuthenticatedContext<Client, User, S>;
|
|
105
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express adapter for the core {@link ResourceServer}.
|
|
3
|
+
*
|
|
4
|
+
* Provides middleware and accessors that let an Express 4 or 5 app
|
|
5
|
+
* authenticate requests against an OAuth2 authorization server. The adapter
|
|
6
|
+
* depends on neither `express` nor its types: its handlers are typed
|
|
7
|
+
* structurally, so any Express request and response satisfy them.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import express from "express";
|
|
12
|
+
* import { ExpressResourceServer } from "@udibo/oauth2/express/resource-server";
|
|
13
|
+
* import type { TokenReaderInterface } from "@udibo/oauth2/server";
|
|
14
|
+
*
|
|
15
|
+
* interface Client { id: string }
|
|
16
|
+
* interface User { id: string }
|
|
17
|
+
* declare const tokenService: TokenReaderInterface<Client, User>;
|
|
18
|
+
*
|
|
19
|
+
* const resourceServer = new ExpressResourceServer<Client, User>({
|
|
20
|
+
* resolve: () => ({ services: { tokenService } }),
|
|
21
|
+
* });
|
|
22
|
+
* const app = express();
|
|
23
|
+
*
|
|
24
|
+
* app.use("/api", resourceServer.protect());
|
|
25
|
+
* app.get("/api/me", (_req, res) => {
|
|
26
|
+
* res.json(resourceServer.getContext(res).user);
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @module
|
|
31
|
+
*/
|
|
32
|
+
import { ResourceServer, } from "../../server/resource-server.js";
|
|
33
|
+
import { authenticateExpressRequest, createProtectMiddleware, createRequireMiddleware, createRequireScopeMiddleware, readContext, } from "./_common.js";
|
|
34
|
+
export { OAUTH2_CONTEXT_KEY, } from "./_common.js";
|
|
35
|
+
/**
|
|
36
|
+
* Express-specific wrapper around {@link ResourceServer}. Construction options
|
|
37
|
+
* are identical to the core server; the subclass only adds Express middleware
|
|
38
|
+
* helpers.
|
|
39
|
+
*
|
|
40
|
+
* `protect` reads the bearer token from the `Authorization` header. It never
|
|
41
|
+
* reads the request stream, so routes behind it keep their body for later
|
|
42
|
+
* middleware; a form-encoded `access_token` (RFC 6750 Section 2.2) is honored
|
|
43
|
+
* only when a body parser has already parsed it onto `req.body`.
|
|
44
|
+
*/
|
|
45
|
+
export class ExpressResourceServer extends ResourceServer {
|
|
46
|
+
/**
|
|
47
|
+
* Returns an Express middleware that validates the bearer token.
|
|
48
|
+
*
|
|
49
|
+
* On success, stores the authenticated context on `res.locals` (read it
|
|
50
|
+
* with {@link getContext}) and calls `next()`. On failure, writes the error
|
|
51
|
+
* response, with a `WWW-Authenticate` challenge (RFC 6750 Section 3) on a
|
|
52
|
+
* 401 or 403, or passes the error to `next` when `throwOnError` is set.
|
|
53
|
+
*/
|
|
54
|
+
protect(requiredScope) {
|
|
55
|
+
return createProtectMiddleware(this, requiredScope);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Returns an Express middleware that asserts the **already-authenticated**
|
|
59
|
+
* request carries `requiredScope`, **without** re-validating the token.
|
|
60
|
+
*
|
|
61
|
+
* Mount it after {@link protect} when one authenticated mount exposes
|
|
62
|
+
* routes needing different scopes. On insufficient scope it writes the same
|
|
63
|
+
* RFC 6750 `insufficient_scope` response (403 with a `WWW-Authenticate`
|
|
64
|
+
* header) as `protect`.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* import express from "express";
|
|
69
|
+
* import { ExpressResourceServer } from "@udibo/oauth2/express/resource-server";
|
|
70
|
+
*
|
|
71
|
+
* declare const resourceServer: ExpressResourceServer<{ id: string }, { id: string }>;
|
|
72
|
+
* declare const list: express.RequestHandler;
|
|
73
|
+
* declare const create: express.RequestHandler;
|
|
74
|
+
* const app = express();
|
|
75
|
+
*
|
|
76
|
+
* app.use("/api", resourceServer.protect());
|
|
77
|
+
* app.get("/api/items", resourceServer.requireScope("read"), list);
|
|
78
|
+
* app.post("/api/items", resourceServer.requireScope("write"), create);
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
requireScope(requiredScope) {
|
|
82
|
+
return createRequireScopeMiddleware(this, "ExpressResourceServer", requiredScope);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Middleware asserting the already-authenticated request satisfies every
|
|
86
|
+
* condition — AND semantics across keys, arrays mean all-of (see
|
|
87
|
+
* {@linkcode RequireConditions}). Scope failures answer the RFC 6750
|
|
88
|
+
* `insufficient_scope` challenge exactly as {@linkcode requireScope} does;
|
|
89
|
+
* permission, role, and organization failures answer a plain 403. Mount
|
|
90
|
+
* {@linkcode protect} first — this middleware does not validate the token.
|
|
91
|
+
*/
|
|
92
|
+
require(conditions) {
|
|
93
|
+
return createRequireMiddleware(this, "ExpressResourceServer", conditions);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Authenticates an Express request or a raw {@link Request} inline, for
|
|
97
|
+
* handlers that do not use {@link protect}. Throws on failure — pair with
|
|
98
|
+
* {@link ResourceServer.handleAuthError} to convert to a response.
|
|
99
|
+
*/
|
|
100
|
+
authenticate(req, requiredScope) {
|
|
101
|
+
return authenticateExpressRequest(this, req, requiredScope);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Typed accessor for the authenticated OAuth2 context {@link protect}
|
|
105
|
+
* stored on `res.locals`.
|
|
106
|
+
*
|
|
107
|
+
* @throws {Error} If `protect` did not run first for this request.
|
|
108
|
+
*/
|
|
109
|
+
getContext(res) {
|
|
110
|
+
return readContext(res, "ExpressResourceServer");
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -45,7 +45,14 @@ export interface IdentityUserStore<User extends IdentityUser> {
|
|
|
45
45
|
create(profile: Record<string, unknown>, credential: PasswordCredential): Promise<User>;
|
|
46
46
|
/** Find a user by a sign-in identifier (email/username/phone). */
|
|
47
47
|
findByIdentifier(identifier: string): Promise<User | undefined>;
|
|
48
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Find a user by email (password-reset / sign-in-link requests).
|
|
50
|
+
*
|
|
51
|
+
* Also called when a mailed reset, sign-in or account-unlock link is
|
|
52
|
+
* redeemed: the link works only while this still resolves the address it
|
|
53
|
+
* was sent to to the same user. Normalize as at write time; a lookup that
|
|
54
|
+
* case-folds lets a link requested with different casing still redeem.
|
|
55
|
+
*/
|
|
49
56
|
findByEmail(email: string): Promise<User | undefined>;
|
|
50
57
|
/**
|
|
51
58
|
* The user's stored password credential, or `undefined`.
|
|
@@ -482,7 +489,10 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
482
489
|
* was configured) revoke **all** of the user's sessions via
|
|
483
490
|
* `revokeAllByUser`. Clears any failed-attempt lockout — the emailed token
|
|
484
491
|
* proves the same account ownership the unlock flow does. Returns
|
|
485
|
-
* `{ userId }`, or `null` for an invalid/expired/used token
|
|
492
|
+
* `{ userId }`, or `null` for an invalid/expired/used token — including one
|
|
493
|
+
* whose address no longer finds this user through
|
|
494
|
+
* {@link IdentityUserStore.findByEmail}, because the account's email moved
|
|
495
|
+
* after the link was mailed. That refusal leaves the token unspent.
|
|
486
496
|
*
|
|
487
497
|
* A reset is the user's "lock everyone else out" action, so the outstanding
|
|
488
498
|
* passwordless credentials for the same account are voided too: sign-in links
|
|
@@ -558,7 +568,10 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
558
568
|
* Mint + deliver a single-use account-unlock link after a lockout. Call it
|
|
559
569
|
* with the locked account's email (typically from your `lockout` event
|
|
560
570
|
* handler — the service only knows opaque user ids). Requires `tokens` and
|
|
561
|
-
* a `delivery.sendAccountUnlock` hook to actually send.
|
|
571
|
+
* a `delivery.sendAccountUnlock` hook to actually send. `email` must be an
|
|
572
|
+
* address {@link IdentityUserStore.findByEmail} resolves to `userId`:
|
|
573
|
+
* {@link IdentityService.unlockAccount} refuses the link once it does not.
|
|
574
|
+
* With a `rateLimiter`
|
|
562
575
|
* (or a tighter `rateLimiters.accountUnlock`), requests throttle per user and
|
|
563
576
|
* throw {@link IdentityError} `rate_limited` when exceeded.
|
|
564
577
|
*/
|
|
@@ -568,7 +581,9 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
568
581
|
}): Promise<void>;
|
|
569
582
|
/**
|
|
570
583
|
* Consume an unlock token and clear the account's lockout state (failures
|
|
571
|
-
* and lock). The self-service unlock path: the emailed link lands here.
|
|
584
|
+
* and lock). The self-service unlock path: the emailed link lands here. A
|
|
585
|
+
* link whose address no longer finds this user through
|
|
586
|
+
* {@link IdentityUserStore.findByEmail} reports `invalid` and stays unspent.
|
|
572
587
|
*/
|
|
573
588
|
unlockAccount(token: string): Promise<UnlockAccountResult>;
|
|
574
589
|
/**
|
|
@@ -598,7 +613,9 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
598
613
|
* stays your app's job. So does re-resolving the user: a user deleted or
|
|
599
614
|
* disabled since the link was minted must be treated as `invalid` by your
|
|
600
615
|
* user store, not signed in. `expired` and `invalid` are distinguished so
|
|
601
|
-
* the UI can offer a fresh link.
|
|
616
|
+
* the UI can offer a fresh link. A link whose address no longer finds this
|
|
617
|
+
* user through {@link IdentityUserStore.findByEmail} — the account's email
|
|
618
|
+
* moved after it was mailed — reports `invalid` and stays unspent.
|
|
602
619
|
*/
|
|
603
620
|
consumeSignInLink(token: string): Promise<ConsumeSignInLinkResult>;
|
|
604
621
|
/**
|
package/dist/identity/service.js
CHANGED
|
@@ -236,7 +236,6 @@ export class IdentityService {
|
|
|
236
236
|
hook: "sendPasswordReset",
|
|
237
237
|
to: normalized,
|
|
238
238
|
subject: user.id,
|
|
239
|
-
data: { email: normalized },
|
|
240
239
|
ttlMs: this.#ttl.passwordReset,
|
|
241
240
|
requested: {
|
|
242
241
|
type: "password_reset.requested",
|
|
@@ -250,7 +249,10 @@ export class IdentityService {
|
|
|
250
249
|
* was configured) revoke **all** of the user's sessions via
|
|
251
250
|
* `revokeAllByUser`. Clears any failed-attempt lockout — the emailed token
|
|
252
251
|
* proves the same account ownership the unlock flow does. Returns
|
|
253
|
-
* `{ userId }`, or `null` for an invalid/expired/used token
|
|
252
|
+
* `{ userId }`, or `null` for an invalid/expired/used token — including one
|
|
253
|
+
* whose address no longer finds this user through
|
|
254
|
+
* {@link IdentityUserStore.findByEmail}, because the account's email moved
|
|
255
|
+
* after the link was mailed. That refusal leaves the token unspent.
|
|
254
256
|
*
|
|
255
257
|
* A reset is the user's "lock everyone else out" action, so the outstanding
|
|
256
258
|
* passwordless credentials for the same account are voided too: sign-in links
|
|
@@ -298,6 +300,7 @@ export class IdentityService {
|
|
|
298
300
|
type: "password_reset.failed",
|
|
299
301
|
reason: "invalid_token",
|
|
300
302
|
}),
|
|
303
|
+
addressBound: true,
|
|
301
304
|
});
|
|
302
305
|
if (consumed.status !== "success")
|
|
303
306
|
return null;
|
|
@@ -371,7 +374,6 @@ export class IdentityService {
|
|
|
371
374
|
to: input.email,
|
|
372
375
|
subject: input.userId,
|
|
373
376
|
ttlMs: this.#ttl.emailVerification,
|
|
374
|
-
data: { email: input.email },
|
|
375
377
|
requested: {
|
|
376
378
|
type: "email_verification.requested",
|
|
377
379
|
userId: input.userId,
|
|
@@ -421,7 +423,10 @@ export class IdentityService {
|
|
|
421
423
|
* Mint + deliver a single-use account-unlock link after a lockout. Call it
|
|
422
424
|
* with the locked account's email (typically from your `lockout` event
|
|
423
425
|
* handler — the service only knows opaque user ids). Requires `tokens` and
|
|
424
|
-
* a `delivery.sendAccountUnlock` hook to actually send.
|
|
426
|
+
* a `delivery.sendAccountUnlock` hook to actually send. `email` must be an
|
|
427
|
+
* address {@link IdentityUserStore.findByEmail} resolves to `userId`:
|
|
428
|
+
* {@link IdentityService.unlockAccount} refuses the link once it does not.
|
|
429
|
+
* With a `rateLimiter`
|
|
425
430
|
* (or a tighter `rateLimiters.accountUnlock`), requests throttle per user and
|
|
426
431
|
* throw {@link IdentityError} `rate_limited` when exceeded.
|
|
427
432
|
*/
|
|
@@ -446,7 +451,9 @@ export class IdentityService {
|
|
|
446
451
|
}
|
|
447
452
|
/**
|
|
448
453
|
* Consume an unlock token and clear the account's lockout state (failures
|
|
449
|
-
* and lock). The self-service unlock path: the emailed link lands here.
|
|
454
|
+
* and lock). The self-service unlock path: the emailed link lands here. A
|
|
455
|
+
* link whose address no longer finds this user through
|
|
456
|
+
* {@link IdentityUserStore.findByEmail} reports `invalid` and stays unspent.
|
|
450
457
|
*/
|
|
451
458
|
async unlockAccount(token) {
|
|
452
459
|
const tokens = this.#requireTokens("unlockAccount");
|
|
@@ -455,6 +462,7 @@ export class IdentityService {
|
|
|
455
462
|
purpose: TokenPurpose.AccountUnlock,
|
|
456
463
|
token,
|
|
457
464
|
failed: (reason) => ({ type: "account_unlock.failed", reason }),
|
|
465
|
+
addressBound: true,
|
|
458
466
|
});
|
|
459
467
|
if (result.status !== "success")
|
|
460
468
|
return result;
|
|
@@ -527,7 +535,9 @@ export class IdentityService {
|
|
|
527
535
|
* stays your app's job. So does re-resolving the user: a user deleted or
|
|
528
536
|
* disabled since the link was minted must be treated as `invalid` by your
|
|
529
537
|
* user store, not signed in. `expired` and `invalid` are distinguished so
|
|
530
|
-
* the UI can offer a fresh link.
|
|
538
|
+
* the UI can offer a fresh link. A link whose address no longer finds this
|
|
539
|
+
* user through {@link IdentityUserStore.findByEmail} — the account's email
|
|
540
|
+
* moved after it was mailed — reports `invalid` and stays unspent.
|
|
531
541
|
*/
|
|
532
542
|
async consumeSignInLink(token) {
|
|
533
543
|
const tokens = this.#requireTokens("consumeSignInLink");
|
|
@@ -536,6 +546,7 @@ export class IdentityService {
|
|
|
536
546
|
purpose: TokenPurpose.SignIn,
|
|
537
547
|
token,
|
|
538
548
|
failed: (reason) => ({ type: "signin_link.failed", reason }),
|
|
549
|
+
addressBound: true,
|
|
539
550
|
});
|
|
540
551
|
if (result.status !== "success")
|
|
541
552
|
return result;
|
|
@@ -783,7 +794,7 @@ export class IdentityService {
|
|
|
783
794
|
const { token, expiresAt } = await tokens.create({
|
|
784
795
|
purpose: DELIVERY_PURPOSES[request.hook],
|
|
785
796
|
subject: request.subject,
|
|
786
|
-
data: request.
|
|
797
|
+
data: { email: request.to },
|
|
787
798
|
ttlMs: request.ttlMs,
|
|
788
799
|
invalidateExisting: true,
|
|
789
800
|
});
|
|
@@ -797,7 +808,9 @@ export class IdentityService {
|
|
|
797
808
|
await this.#emit(input.failed("expired"));
|
|
798
809
|
return { status: "expired" };
|
|
799
810
|
}
|
|
800
|
-
if (status.status !== "valid"
|
|
811
|
+
if (status.status !== "valid" ||
|
|
812
|
+
(input.addressBound &&
|
|
813
|
+
!(await this.#stillAddressedTo(status.subject, status.data)))) {
|
|
801
814
|
await this.#emit(input.failed("invalid"));
|
|
802
815
|
return { status: "invalid" };
|
|
803
816
|
}
|
|
@@ -809,6 +822,12 @@ export class IdentityService {
|
|
|
809
822
|
}
|
|
810
823
|
return { status: "success", resolved };
|
|
811
824
|
}
|
|
825
|
+
async #stillAddressedTo(subject, data) {
|
|
826
|
+
const email = emailFromData(data);
|
|
827
|
+
if (email === undefined)
|
|
828
|
+
return true;
|
|
829
|
+
return (await this.#users.findByEmail(email))?.id === subject;
|
|
830
|
+
}
|
|
812
831
|
#emit(event) {
|
|
813
832
|
return dispatchIdentityEvent(this.#onEvent, "identity", event);
|
|
814
833
|
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@udibo/oauth2",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), and React bindings.",
|
|
3
|
+
"version": "0.45.0",
|
|
4
|
+
"description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), Express adapters, and React bindings.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"authorization-server",
|
|
7
7
|
"bff",
|
|
8
|
+
"express",
|
|
8
9
|
"hono",
|
|
9
10
|
"oauth2",
|
|
10
11
|
"oidc",
|
|
@@ -99,6 +100,14 @@
|
|
|
99
100
|
"types": "./dist/adapters/hono/log.d.ts",
|
|
100
101
|
"default": "./dist/adapters/hono/log.js"
|
|
101
102
|
},
|
|
103
|
+
"./express/resource-server": {
|
|
104
|
+
"types": "./dist/adapters/express/resource-server.d.ts",
|
|
105
|
+
"default": "./dist/adapters/express/resource-server.js"
|
|
106
|
+
},
|
|
107
|
+
"./express/authorization-server": {
|
|
108
|
+
"types": "./dist/adapters/express/authorization-server.d.ts",
|
|
109
|
+
"default": "./dist/adapters/express/authorization-server.js"
|
|
110
|
+
},
|
|
102
111
|
"./react": {
|
|
103
112
|
"types": "./dist/react/mod.d.ts",
|
|
104
113
|
"default": "./dist/react/mod.js"
|
|
@@ -170,12 +179,15 @@
|
|
|
170
179
|
"@simplewebauthn/browser": "^14.0.0",
|
|
171
180
|
"@testing-library/dom": "^10.4.2",
|
|
172
181
|
"@testing-library/react": "^16.3.3",
|
|
182
|
+
"@types/express": "^5.0.6",
|
|
173
183
|
"@types/node": "^26.6.4",
|
|
174
184
|
"@types/react": "^19.3.0",
|
|
175
185
|
"@types/react-dom": "^19.3.0",
|
|
176
186
|
"@vitest/coverage-v8": "^5.0.3",
|
|
177
187
|
"axe-core": "^4.14.0",
|
|
178
188
|
"conventional-changelog-conventionalcommits": "9.3.1",
|
|
189
|
+
"express": "^5.3.0",
|
|
190
|
+
"express4": "npm:express@^4.21.2",
|
|
179
191
|
"hono": "^4.13.13",
|
|
180
192
|
"jsdom": "^30.1.2",
|
|
181
193
|
"jsr": "^0.14.3",
|