nextidp 0.1.4 → 0.1.5
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/CHANGELOG.md +12 -0
- package/README.md +51 -11
- package/dist/cjs/fastify.d.ts +67 -0
- package/dist/cjs/fastify.js +142 -0
- package/dist/esm/fastify.d.ts +67 -0
- package/dist/esm/fastify.js +118 -0
- package/package.json +24 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.5
|
|
4
|
+
|
|
5
|
+
### Fastify
|
|
6
|
+
|
|
7
|
+
- `nextidp/fastify`, for Fastify 5 (an optional peer dependency). `auth.fastify()` is a
|
|
8
|
+
plugin that answers nextidp's routes and reads the session for every request, refreshed
|
|
9
|
+
before it expires, in every plugin and prefix of the app; `auth.sessionOf(request)` gives
|
|
10
|
+
it. `auth.requireSession()` and `auth.requireToken({ scopes })` are hooks for a route's
|
|
11
|
+
`onRequest` (or `preHandler`), and `auth.tokenOf(request)` gives the checked token. As with
|
|
12
|
+
Hono, a token that can't be checked now gets 503. The sign-out form needs no form parser,
|
|
13
|
+
and a refreshed session's cookie goes out beside the route's own.
|
|
14
|
+
|
|
3
15
|
## 0.1.4
|
|
4
16
|
|
|
5
17
|
### Sign-in
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# nextidp
|
|
2
2
|
|
|
3
|
-
Sign people in to your Next.js, Express, Hono or Node app, and protect your APIs, with
|
|
4
|
-
[
|
|
3
|
+
Sign people in to your Next.js, Express, Fastify, Hono or Node app, and protect your APIs, with
|
|
4
|
+
[Next-Identity Server](https://github.com/sajanv88/next-identity-server), in one call. It does the
|
|
5
5
|
OpenID Connect work for you:
|
|
6
6
|
|
|
7
7
|
- the authorization code flow with PKCE;
|
|
@@ -12,11 +12,11 @@ OpenID Connect work for you:
|
|
|
12
12
|
- refreshing tokens before they expire;
|
|
13
13
|
- signing out, of your app or of the auth server too;
|
|
14
14
|
- checking the access tokens your API is called with, and their scopes, in NestJS, Express,
|
|
15
|
-
Hono or a Next.js route handler ([below](#protecting-an-api));
|
|
15
|
+
Fastify, Hono or a Next.js route handler ([below](#protecting-an-api));
|
|
16
16
|
- tokens for a service to call other APIs as itself ([below](#calling-an-api-as-a-service)).
|
|
17
17
|
|
|
18
18
|
It works with any OpenID Connect provider that supports the code flow with PKCE, but it's
|
|
19
|
-
made for, and tested against,
|
|
19
|
+
made for, and tested against, Next-Identity Server.
|
|
20
20
|
|
|
21
21
|
```sh
|
|
22
22
|
npm i nextidp
|
|
@@ -24,8 +24,8 @@ npm i nextidp
|
|
|
24
24
|
|
|
25
25
|
ES module and CommonJS builds, with types. Node 24 or later, or an edge runtime
|
|
26
26
|
(Cloudflare Workers, Vercel Edge, Deno, Bun: [below](#edge-runtimes)). Next.js 15 or 16 (App
|
|
27
|
-
Router), Express (tested with 5) or anything else that takes Node middleware,
|
|
28
|
-
HTTP server, Hono 4, and NestJS 11 or 12 for APIs.
|
|
27
|
+
Router), Express (tested with 5) or anything else that takes Node middleware, Fastify 5,
|
|
28
|
+
Node's own HTTP server, Hono 4, and NestJS 11 or 12 for APIs.
|
|
29
29
|
|
|
30
30
|
## 1. Register your app on the auth server
|
|
31
31
|
|
|
@@ -51,7 +51,8 @@ IDP_SECRET=… # ≥ 32 characters: openssl rand -
|
|
|
51
51
|
|
|
52
52
|
## 3. Wire it up
|
|
53
53
|
|
|
54
|
-
In a Next.js app (for Express or Node's own server, see [below](#express-or-node)
|
|
54
|
+
In a Next.js app (for Express or Node's own server, see [below](#express-or-node); for
|
|
55
|
+
Fastify, [Fastify](#fastify); for Hono, [Hono](#hono)):
|
|
55
56
|
|
|
56
57
|
```ts
|
|
57
58
|
// src/auth.ts
|
|
@@ -162,6 +163,33 @@ createServer(async (req, res) => {
|
|
|
162
163
|
Read the session before you start the response: a refresh sets a new cookie. Read twice in
|
|
163
164
|
one request, it's refreshed once.
|
|
164
165
|
|
|
166
|
+
## Fastify
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import Fastify from "fastify";
|
|
170
|
+
import { idp } from "nextidp/fastify";
|
|
171
|
+
|
|
172
|
+
const auth = idp();
|
|
173
|
+
const app = Fastify();
|
|
174
|
+
|
|
175
|
+
// Before your routes: answers nextidp's routes, and reads the session (refreshing it before
|
|
176
|
+
// it expires) for every other request, in every plugin and prefix of the app.
|
|
177
|
+
await app.register(auth.fastify());
|
|
178
|
+
|
|
179
|
+
app.get("/", async (request) => {
|
|
180
|
+
const session = auth.sessionOf(request); // null if signed out
|
|
181
|
+
return session ? `Hello, ${session.user.name}` : "Signed out";
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// Signed out, a GET goes to sign in and comes back; anything else gets 401.
|
|
185
|
+
app.get("/dashboard", { onRequest: auth.requireSession() }, async (request) => {
|
|
186
|
+
return { user: auth.sessionOf(request)?.user };
|
|
187
|
+
});
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
The sign-out form needs no form parser: nextidp reads it before Fastify parses bodies. A
|
|
191
|
+
refreshed session's cookie goes out through the reply, beside the cookies your route sets.
|
|
192
|
+
|
|
165
193
|
## Hono
|
|
166
194
|
|
|
167
195
|
On any runtime Hono runs on:
|
|
@@ -197,7 +225,7 @@ A refreshed session's cookie is added to whatever response the handler makes, it
|
|
|
197
225
|
|
|
198
226
|
The core uses only Web APIs (`fetch`, `Request`/`Response`, `crypto.subtle`), so it runs on
|
|
199
227
|
Cloudflare Workers, Vercel Edge, Deno and Bun as well as Node: everything but `nextidp/node`,
|
|
200
|
-
`nextidp/express` and `nextidp/nestjs`, which are for Node. Its tests run it in Cloudflare's
|
|
228
|
+
`nextidp/express`, `nextidp/fastify` and `nextidp/nestjs`, which are for Node. Its tests run it in Cloudflare's
|
|
201
229
|
own runtime, `workerd`, with no Node compatibility turned on.
|
|
202
230
|
|
|
203
231
|
Where there's no `process.env` (Cloudflare Workers), pass the settings from the Worker's
|
|
@@ -283,7 +311,7 @@ type Session = {
|
|
|
283
311
|
The refresh token and the ID token stay inside the encrypted cookie: nothing in the browser
|
|
284
312
|
can read them.
|
|
285
313
|
|
|
286
|
-
`user` comes from the ID token's claims. Some auth servers (
|
|
314
|
+
`user` comes from the ID token's claims. Some auth servers (Next-Identity Server among them) put
|
|
287
315
|
the email and the name in userinfo instead: with `userinfo: true`, nextidp asks userinfo after
|
|
288
316
|
sign-in, and again when a refresh brings a new ID token, and fills `user`'s `email`,
|
|
289
317
|
`emailVerified`, `name` and `picture` from it (only those, so the cookie stays small; an email
|
|
@@ -399,6 +427,18 @@ app.get("/orders", auth.requireToken({ scopes: ["orders:read"] }), (req, res) =>
|
|
|
399
427
|
});
|
|
400
428
|
```
|
|
401
429
|
|
|
430
|
+
**Fastify** (no plugin needed for an API):
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
import { idp } from "nextidp/fastify";
|
|
434
|
+
|
|
435
|
+
const auth = idp(); // IDP_ISSUER and IDP_AUDIENCE
|
|
436
|
+
|
|
437
|
+
app.get("/orders", { onRequest: auth.requireToken({ scopes: ["orders:read"] }) }, async (request) =>
|
|
438
|
+
ordersOf(auth.tokenOf(request)?.subject),
|
|
439
|
+
);
|
|
440
|
+
```
|
|
441
|
+
|
|
402
442
|
**A Next.js route handler:**
|
|
403
443
|
|
|
404
444
|
```ts
|
|
@@ -447,7 +487,7 @@ IDP_RESOURCE=https://orders.example.com # optional: the API, when a call names
|
|
|
447
487
|
```
|
|
448
488
|
|
|
449
489
|
```ts
|
|
450
|
-
import { idp } from "nextidp"; // or nextidp/express, nextidp/node, nextidp/next
|
|
490
|
+
import { idp } from "nextidp"; // or nextidp/express, nextidp/fastify, nextidp/node, nextidp/next
|
|
451
491
|
|
|
452
492
|
const auth = idp();
|
|
453
493
|
|
|
@@ -508,7 +548,7 @@ server can't end it, and signing out can't take back a copy of the cookie. Give
|
|
|
508
548
|
`store` and sessions live there instead, with only a sealed reference in the cookie:
|
|
509
549
|
|
|
510
550
|
```ts
|
|
511
|
-
import { idp, memoryStore } from "nextidp/next"; // or nextidp/express, nextidp/node
|
|
551
|
+
import { idp, memoryStore } from "nextidp/next"; // or nextidp/express, nextidp/fastify, nextidp/node
|
|
512
552
|
|
|
513
553
|
export const auth = idp({ store: memoryStore() }); // one process only: use Redis to share
|
|
514
554
|
```
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import { type AccessToken, type TokenRequirements } from "./access-token.js";
|
|
3
|
+
import type { IdpOptions } from "./config.js";
|
|
4
|
+
import { type Idp } from "./idp.js";
|
|
5
|
+
import { type SessionOptions } from "./node-adapter.js";
|
|
6
|
+
import type { Session } from "./session.js";
|
|
7
|
+
/** A hook for a route's `onRequest` (or `preHandler`): it answers, or lets the request on. */
|
|
8
|
+
export type IdpHook = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
9
|
+
export type FastifyIdp = Idp & {
|
|
10
|
+
/**
|
|
11
|
+
* The sign-in plugin, before your routes: `await app.register(auth.fastify())`. It answers
|
|
12
|
+
* nextidp's routes under `basePath`, and for every other request reads the session
|
|
13
|
+
* (refreshing the access token when it's about to expire) for `sessionOf(request)`. It
|
|
14
|
+
* applies to the whole app, routes under a prefix included.
|
|
15
|
+
*/
|
|
16
|
+
fastify(options?: SessionOptions): FastifyPluginAsync;
|
|
17
|
+
/**
|
|
18
|
+
* Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
|
|
19
|
+
* comes back after; anything else gets 401.
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* app.get("/dashboard", { onRequest: auth.requireSession() }, async (request) => {
|
|
23
|
+
* return `Hello, ${auth.sessionOf(request)?.user.name}`;
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
requireSession(): IdpHook;
|
|
28
|
+
/** The session read for this request, or null when signed out. */
|
|
29
|
+
sessionOf(request: FastifyRequest): Session | null;
|
|
30
|
+
/**
|
|
31
|
+
* Lets a request through only with a valid access token that has every scope in
|
|
32
|
+
* `requirements`. A refused one gets 401 or 403 with WWW-Authenticate (RFC 6750); one that
|
|
33
|
+
* can't be checked now (the auth server is down) 503. Needs no plugin.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* app.get("/orders", { onRequest: auth.requireToken({ scopes: ["orders:read"] }) }, async (request) => {
|
|
37
|
+
* return ordersOf(auth.tokenOf(request)?.subject);
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
requireToken(requirements?: TokenRequirements): IdpHook;
|
|
42
|
+
/** The access token `requireToken` checked for this request. */
|
|
43
|
+
tokenOf(request: FastifyRequest): AccessToken | undefined;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The client for a Fastify app or API. An app that signs people in needs the sign-in settings
|
|
47
|
+
* (`IDP_ISSUER`, `IDP_CLIENT_ID`, `IDP_APP_URL`, `IDP_SECRET`); an API only `issuer` and
|
|
48
|
+
* `audience`:
|
|
49
|
+
*
|
|
50
|
+
* ```ts
|
|
51
|
+
* import Fastify from "fastify";
|
|
52
|
+
* import { idp } from "nextidp/fastify";
|
|
53
|
+
*
|
|
54
|
+
* const auth = idp(); // the IDP_* environment variables, read on first use
|
|
55
|
+
* const app = Fastify();
|
|
56
|
+
* await app.register(auth.fastify());
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare function idp(options?: IdpOptions | (() => IdpOptions)): FastifyIdp;
|
|
60
|
+
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
61
|
+
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
62
|
+
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
63
|
+
export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
|
|
64
|
+
export type { SessionOptions } from "./node-adapter.js";
|
|
65
|
+
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
66
|
+
export type { IdpUser, Session } from "./session.js";
|
|
67
|
+
export { memoryStore, type SessionStore } from "./store.js";
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var fastify_exports = {};
|
|
20
|
+
__export(fastify_exports, {
|
|
21
|
+
IdpError: () => import_errors2.IdpError,
|
|
22
|
+
SIGN_IN_ERROR_CODES: () => import_errors2.SIGN_IN_ERROR_CODES,
|
|
23
|
+
idp: () => idp,
|
|
24
|
+
isIdpError: () => import_errors2.isIdpError,
|
|
25
|
+
isSignInErrorCode: () => import_errors2.isSignInErrorCode,
|
|
26
|
+
isTokenError: () => import_errors2.isTokenError,
|
|
27
|
+
memoryStore: () => import_store.memoryStore
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(fastify_exports);
|
|
30
|
+
var import_access_token = require("./access-token.js");
|
|
31
|
+
var import_errors = require("./errors.js");
|
|
32
|
+
var import_idp = require("./idp.js");
|
|
33
|
+
var import_node_adapter = require("./node-adapter.js");
|
|
34
|
+
var import_node_http = require("./node-http.js");
|
|
35
|
+
var import_errors2 = require("./errors.js");
|
|
36
|
+
var import_store = require("./store.js");
|
|
37
|
+
function authorizationOf(request) {
|
|
38
|
+
const value = request.headers.authorization;
|
|
39
|
+
return Array.isArray(value) ? void 0 : value;
|
|
40
|
+
}
|
|
41
|
+
function isRead(method) {
|
|
42
|
+
const upper = method.toUpperCase();
|
|
43
|
+
return upper === "GET" || upper === "HEAD";
|
|
44
|
+
}
|
|
45
|
+
function idp(options) {
|
|
46
|
+
const core = (0, import_idp.createIdp)(options);
|
|
47
|
+
const node = (0, import_node_adapter.nodeAdapter)(core);
|
|
48
|
+
const sessions = /* @__PURE__ */ new WeakMap();
|
|
49
|
+
const read = /* @__PURE__ */ new WeakMap();
|
|
50
|
+
const tokens = /* @__PURE__ */ new WeakMap();
|
|
51
|
+
const sessionFor = (request, reply, refresh = true) => {
|
|
52
|
+
const known = sessions.get(request);
|
|
53
|
+
if (known) return known;
|
|
54
|
+
const reading = (async () => {
|
|
55
|
+
const cookie = request.raw.headers.cookie;
|
|
56
|
+
if (!refresh || reply.sent) return core.getSession(cookie);
|
|
57
|
+
const { session, setCookies, cookieHeader } = await core.refreshIfNeeded(cookie);
|
|
58
|
+
for (const setCookie of setCookies) reply.header("set-cookie", setCookie);
|
|
59
|
+
if (cookieHeader !== void 0) request.raw.headers.cookie = cookieHeader;
|
|
60
|
+
return session;
|
|
61
|
+
})();
|
|
62
|
+
sessions.set(request, reading);
|
|
63
|
+
return reading.then((session) => {
|
|
64
|
+
read.set(request, session);
|
|
65
|
+
return session;
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
...core,
|
|
70
|
+
fastify({ refresh = true } = {}) {
|
|
71
|
+
const plugin = async (app) => {
|
|
72
|
+
app.addHook("onRequest", async (request, reply) => {
|
|
73
|
+
const { appUrl, basePath } = core.config();
|
|
74
|
+
const { pathname } = (0, import_node_http.urlOf)(request.raw, appUrl);
|
|
75
|
+
if (pathname === basePath || pathname.startsWith(`${basePath}/`)) {
|
|
76
|
+
reply.hijack();
|
|
77
|
+
await node.handle(request.raw, reply.raw);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
await sessionFor(request, reply, refresh);
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
Object.assign(plugin, { [/* @__PURE__ */ Symbol.for("skip-override")]: true });
|
|
84
|
+
return plugin;
|
|
85
|
+
},
|
|
86
|
+
requireSession() {
|
|
87
|
+
return async (request, reply) => {
|
|
88
|
+
const session = await sessionFor(request, reply);
|
|
89
|
+
if (session) return;
|
|
90
|
+
if (!isRead(request.method)) {
|
|
91
|
+
await reply.code(401).header("cache-control", "no-store").type("text/plain; charset=utf-8").send("Sign in first.");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const signIn = new URL(core.signInPath((0, import_node_http.pathOf)(request.raw)), core.config().appUrl);
|
|
95
|
+
await reply.header("cache-control", "no-store").redirect(signIn.toString(), 302);
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
sessionOf(request) {
|
|
99
|
+
const session = read.get(request);
|
|
100
|
+
if (session === void 0) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
"nextidp: no session was read for this request. Register auth.fastify() first."
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
return session;
|
|
106
|
+
},
|
|
107
|
+
requireToken(requirements = {}) {
|
|
108
|
+
return async (request, reply) => {
|
|
109
|
+
let token;
|
|
110
|
+
try {
|
|
111
|
+
token = await core.verifyBearer(authorizationOf(request), requirements);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if ((0, import_errors.isTokenError)(error)) {
|
|
114
|
+
const refusal = (0, import_access_token.tokenRefusal)(error);
|
|
115
|
+
await reply.code(refusal.status).headers(refusal.headers).send(refusal.body);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
request.log.error(
|
|
119
|
+
`nextidp: a token couldn't be checked: ${(0, import_errors.isIdpError)(error) ? error.code : "unexpected error"}`
|
|
120
|
+
);
|
|
121
|
+
await reply.code(503).headers({ "retry-after": "5", "cache-control": "no-store" }).send({
|
|
122
|
+
error: "temporarily_unavailable",
|
|
123
|
+
error_description: "The token can't be checked now."
|
|
124
|
+
});
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
tokens.set(request, token);
|
|
128
|
+
};
|
|
129
|
+
},
|
|
130
|
+
tokenOf: (request) => tokens.get(request)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
134
|
+
0 && (module.exports = {
|
|
135
|
+
IdpError,
|
|
136
|
+
SIGN_IN_ERROR_CODES,
|
|
137
|
+
idp,
|
|
138
|
+
isIdpError,
|
|
139
|
+
isSignInErrorCode,
|
|
140
|
+
isTokenError,
|
|
141
|
+
memoryStore
|
|
142
|
+
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify";
|
|
2
|
+
import { type AccessToken, type TokenRequirements } from "./access-token.js";
|
|
3
|
+
import type { IdpOptions } from "./config.js";
|
|
4
|
+
import { type Idp } from "./idp.js";
|
|
5
|
+
import { type SessionOptions } from "./node-adapter.js";
|
|
6
|
+
import type { Session } from "./session.js";
|
|
7
|
+
/** A hook for a route's `onRequest` (or `preHandler`): it answers, or lets the request on. */
|
|
8
|
+
export type IdpHook = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
9
|
+
export type FastifyIdp = Idp & {
|
|
10
|
+
/**
|
|
11
|
+
* The sign-in plugin, before your routes: `await app.register(auth.fastify())`. It answers
|
|
12
|
+
* nextidp's routes under `basePath`, and for every other request reads the session
|
|
13
|
+
* (refreshing the access token when it's about to expire) for `sessionOf(request)`. It
|
|
14
|
+
* applies to the whole app, routes under a prefix included.
|
|
15
|
+
*/
|
|
16
|
+
fastify(options?: SessionOptions): FastifyPluginAsync;
|
|
17
|
+
/**
|
|
18
|
+
* Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
|
|
19
|
+
* comes back after; anything else gets 401.
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* app.get("/dashboard", { onRequest: auth.requireSession() }, async (request) => {
|
|
23
|
+
* return `Hello, ${auth.sessionOf(request)?.user.name}`;
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
requireSession(): IdpHook;
|
|
28
|
+
/** The session read for this request, or null when signed out. */
|
|
29
|
+
sessionOf(request: FastifyRequest): Session | null;
|
|
30
|
+
/**
|
|
31
|
+
* Lets a request through only with a valid access token that has every scope in
|
|
32
|
+
* `requirements`. A refused one gets 401 or 403 with WWW-Authenticate (RFC 6750); one that
|
|
33
|
+
* can't be checked now (the auth server is down) 503. Needs no plugin.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* app.get("/orders", { onRequest: auth.requireToken({ scopes: ["orders:read"] }) }, async (request) => {
|
|
37
|
+
* return ordersOf(auth.tokenOf(request)?.subject);
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
requireToken(requirements?: TokenRequirements): IdpHook;
|
|
42
|
+
/** The access token `requireToken` checked for this request. */
|
|
43
|
+
tokenOf(request: FastifyRequest): AccessToken | undefined;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The client for a Fastify app or API. An app that signs people in needs the sign-in settings
|
|
47
|
+
* (`IDP_ISSUER`, `IDP_CLIENT_ID`, `IDP_APP_URL`, `IDP_SECRET`); an API only `issuer` and
|
|
48
|
+
* `audience`:
|
|
49
|
+
*
|
|
50
|
+
* ```ts
|
|
51
|
+
* import Fastify from "fastify";
|
|
52
|
+
* import { idp } from "nextidp/fastify";
|
|
53
|
+
*
|
|
54
|
+
* const auth = idp(); // the IDP_* environment variables, read on first use
|
|
55
|
+
* const app = Fastify();
|
|
56
|
+
* await app.register(auth.fastify());
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare function idp(options?: IdpOptions | (() => IdpOptions)): FastifyIdp;
|
|
60
|
+
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
61
|
+
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
62
|
+
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
63
|
+
export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
|
|
64
|
+
export type { SessionOptions } from "./node-adapter.js";
|
|
65
|
+
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
66
|
+
export type { IdpUser, Session } from "./session.js";
|
|
67
|
+
export { memoryStore, type SessionStore } from "./store.js";
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { tokenRefusal } from "./access-token.js";
|
|
2
|
+
import { isIdpError, isTokenError } from "./errors.js";
|
|
3
|
+
import { createIdp } from "./idp.js";
|
|
4
|
+
import { nodeAdapter } from "./node-adapter.js";
|
|
5
|
+
import { pathOf, urlOf } from "./node-http.js";
|
|
6
|
+
function authorizationOf(request) {
|
|
7
|
+
const value = request.headers.authorization;
|
|
8
|
+
return Array.isArray(value) ? void 0 : value;
|
|
9
|
+
}
|
|
10
|
+
function isRead(method) {
|
|
11
|
+
const upper = method.toUpperCase();
|
|
12
|
+
return upper === "GET" || upper === "HEAD";
|
|
13
|
+
}
|
|
14
|
+
function idp(options) {
|
|
15
|
+
const core = createIdp(options);
|
|
16
|
+
const node = nodeAdapter(core);
|
|
17
|
+
const sessions = /* @__PURE__ */ new WeakMap();
|
|
18
|
+
const read = /* @__PURE__ */ new WeakMap();
|
|
19
|
+
const tokens = /* @__PURE__ */ new WeakMap();
|
|
20
|
+
const sessionFor = (request, reply, refresh = true) => {
|
|
21
|
+
const known = sessions.get(request);
|
|
22
|
+
if (known) return known;
|
|
23
|
+
const reading = (async () => {
|
|
24
|
+
const cookie = request.raw.headers.cookie;
|
|
25
|
+
if (!refresh || reply.sent) return core.getSession(cookie);
|
|
26
|
+
const { session, setCookies, cookieHeader } = await core.refreshIfNeeded(cookie);
|
|
27
|
+
for (const setCookie of setCookies) reply.header("set-cookie", setCookie);
|
|
28
|
+
if (cookieHeader !== void 0) request.raw.headers.cookie = cookieHeader;
|
|
29
|
+
return session;
|
|
30
|
+
})();
|
|
31
|
+
sessions.set(request, reading);
|
|
32
|
+
return reading.then((session) => {
|
|
33
|
+
read.set(request, session);
|
|
34
|
+
return session;
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
...core,
|
|
39
|
+
fastify({ refresh = true } = {}) {
|
|
40
|
+
const plugin = async (app) => {
|
|
41
|
+
app.addHook("onRequest", async (request, reply) => {
|
|
42
|
+
const { appUrl, basePath } = core.config();
|
|
43
|
+
const { pathname } = urlOf(request.raw, appUrl);
|
|
44
|
+
if (pathname === basePath || pathname.startsWith(`${basePath}/`)) {
|
|
45
|
+
reply.hijack();
|
|
46
|
+
await node.handle(request.raw, reply.raw);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
await sessionFor(request, reply, refresh);
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
Object.assign(plugin, { [/* @__PURE__ */ Symbol.for("skip-override")]: true });
|
|
53
|
+
return plugin;
|
|
54
|
+
},
|
|
55
|
+
requireSession() {
|
|
56
|
+
return async (request, reply) => {
|
|
57
|
+
const session = await sessionFor(request, reply);
|
|
58
|
+
if (session) return;
|
|
59
|
+
if (!isRead(request.method)) {
|
|
60
|
+
await reply.code(401).header("cache-control", "no-store").type("text/plain; charset=utf-8").send("Sign in first.");
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const signIn = new URL(core.signInPath(pathOf(request.raw)), core.config().appUrl);
|
|
64
|
+
await reply.header("cache-control", "no-store").redirect(signIn.toString(), 302);
|
|
65
|
+
};
|
|
66
|
+
},
|
|
67
|
+
sessionOf(request) {
|
|
68
|
+
const session = read.get(request);
|
|
69
|
+
if (session === void 0) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
"nextidp: no session was read for this request. Register auth.fastify() first."
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return session;
|
|
75
|
+
},
|
|
76
|
+
requireToken(requirements = {}) {
|
|
77
|
+
return async (request, reply) => {
|
|
78
|
+
let token;
|
|
79
|
+
try {
|
|
80
|
+
token = await core.verifyBearer(authorizationOf(request), requirements);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (isTokenError(error)) {
|
|
83
|
+
const refusal = tokenRefusal(error);
|
|
84
|
+
await reply.code(refusal.status).headers(refusal.headers).send(refusal.body);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
request.log.error(
|
|
88
|
+
`nextidp: a token couldn't be checked: ${isIdpError(error) ? error.code : "unexpected error"}`
|
|
89
|
+
);
|
|
90
|
+
await reply.code(503).headers({ "retry-after": "5", "cache-control": "no-store" }).send({
|
|
91
|
+
error: "temporarily_unavailable",
|
|
92
|
+
error_description: "The token can't be checked now."
|
|
93
|
+
});
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
tokens.set(request, token);
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
tokenOf: (request) => tokens.get(request)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
import {
|
|
103
|
+
IdpError,
|
|
104
|
+
isIdpError as isIdpError2,
|
|
105
|
+
isSignInErrorCode,
|
|
106
|
+
isTokenError as isTokenError2,
|
|
107
|
+
SIGN_IN_ERROR_CODES
|
|
108
|
+
} from "./errors.js";
|
|
109
|
+
import { memoryStore } from "./store.js";
|
|
110
|
+
export {
|
|
111
|
+
IdpError,
|
|
112
|
+
SIGN_IN_ERROR_CODES,
|
|
113
|
+
idp,
|
|
114
|
+
isIdpError2 as isIdpError,
|
|
115
|
+
isSignInErrorCode,
|
|
116
|
+
isTokenError2 as isTokenError,
|
|
117
|
+
memoryStore
|
|
118
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nextidp",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Sign people in to Next.js, Express, Hono and Node apps, and protect NestJS, Express, Hono and Next.js APIs, with
|
|
3
|
+
"version": "0.1.5",
|
|
4
|
+
"description": "Sign people in to Next.js, Express, Fastify, Hono and Node apps, and protect NestJS, Express, Fastify, Hono and Next.js APIs, with Next-Identity Server, in one call. Runs on Node and edge runtimes.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"oidc",
|
|
7
7
|
"openid-connect",
|
|
@@ -10,17 +10,18 @@
|
|
|
10
10
|
"nextjs",
|
|
11
11
|
"nestjs",
|
|
12
12
|
"express",
|
|
13
|
+
"fastify",
|
|
13
14
|
"hono",
|
|
14
15
|
"cloudflare-workers",
|
|
15
16
|
"edge",
|
|
16
17
|
"jwt",
|
|
17
18
|
"idp"
|
|
18
19
|
],
|
|
19
|
-
"homepage": "https://sajanv88.github.io/
|
|
20
|
-
"bugs": "https://github.com/sajanv88/
|
|
20
|
+
"homepage": "https://sajanv88.github.io/next-identity-server/docs/#nextidp",
|
|
21
|
+
"bugs": "https://github.com/sajanv88/next-identity-server/issues",
|
|
21
22
|
"repository": {
|
|
22
23
|
"type": "git",
|
|
23
|
-
"url": "git+https://github.com/sajanv88/
|
|
24
|
+
"url": "git+https://github.com/sajanv88/next-identity-server.git",
|
|
24
25
|
"directory": "packages/nextidp"
|
|
25
26
|
},
|
|
26
27
|
"license": "MIT",
|
|
@@ -34,6 +35,9 @@
|
|
|
34
35
|
"express": [
|
|
35
36
|
"./dist/cjs/express.d.ts"
|
|
36
37
|
],
|
|
38
|
+
"fastify": [
|
|
39
|
+
"./dist/cjs/fastify.d.ts"
|
|
40
|
+
],
|
|
37
41
|
"node": [
|
|
38
42
|
"./dist/cjs/node.d.ts"
|
|
39
43
|
],
|
|
@@ -81,6 +85,16 @@
|
|
|
81
85
|
"default": "./dist/cjs/express.js"
|
|
82
86
|
}
|
|
83
87
|
},
|
|
88
|
+
"./fastify": {
|
|
89
|
+
"import": {
|
|
90
|
+
"types": "./dist/esm/fastify.d.ts",
|
|
91
|
+
"default": "./dist/esm/fastify.js"
|
|
92
|
+
},
|
|
93
|
+
"require": {
|
|
94
|
+
"types": "./dist/cjs/fastify.d.ts",
|
|
95
|
+
"default": "./dist/cjs/fastify.js"
|
|
96
|
+
}
|
|
97
|
+
},
|
|
84
98
|
"./node": {
|
|
85
99
|
"import": {
|
|
86
100
|
"types": "./dist/esm/node.d.ts",
|
|
@@ -125,6 +139,7 @@
|
|
|
125
139
|
"peerDependencies": {
|
|
126
140
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|
|
127
141
|
"@nestjs/core": "^11.0.0 || ^12.0.0",
|
|
142
|
+
"fastify": "^5.0.0",
|
|
128
143
|
"hono": "^4.0.0",
|
|
129
144
|
"next": "^15.0.0 || ^16.0.0"
|
|
130
145
|
},
|
|
@@ -135,6 +150,9 @@
|
|
|
135
150
|
"@nestjs/core": {
|
|
136
151
|
"optional": true
|
|
137
152
|
},
|
|
153
|
+
"fastify": {
|
|
154
|
+
"optional": true
|
|
155
|
+
},
|
|
138
156
|
"hono": {
|
|
139
157
|
"optional": true
|
|
140
158
|
},
|
|
@@ -152,6 +170,7 @@
|
|
|
152
170
|
"@types/node": "26.6.5",
|
|
153
171
|
"esbuild": "0.28.2",
|
|
154
172
|
"express": "5.3.0",
|
|
173
|
+
"fastify": "5.12.8",
|
|
155
174
|
"hono": "4.13.22",
|
|
156
175
|
"miniflare": "4.20260730.0",
|
|
157
176
|
"next": "16.4.6",
|