nextidp 0.0.1 → 0.1.3

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +502 -4
  3. package/dist/cjs/access-token.d.ts +56 -0
  4. package/dist/cjs/access-token.js +196 -0
  5. package/dist/cjs/config.d.ts +128 -0
  6. package/dist/cjs/config.js +233 -0
  7. package/dist/cjs/cookies.d.ts +23 -0
  8. package/dist/cjs/cookies.js +118 -0
  9. package/dist/cjs/discovery.d.ts +24 -0
  10. package/dist/cjs/discovery.js +91 -0
  11. package/dist/cjs/errors.d.ts +63 -0
  12. package/dist/cjs/errors.js +69 -0
  13. package/dist/cjs/express.d.ts +71 -0
  14. package/dist/cjs/express.js +114 -0
  15. package/dist/cjs/hono.d.ts +65 -0
  16. package/dist/cjs/hono.js +130 -0
  17. package/dist/cjs/http.d.ts +10 -0
  18. package/dist/cjs/http.js +68 -0
  19. package/dist/cjs/id-token.d.ts +19 -0
  20. package/dist/cjs/id-token.js +77 -0
  21. package/dist/cjs/idp.d.ts +81 -0
  22. package/dist/cjs/idp.js +482 -0
  23. package/dist/cjs/index.d.ts +9 -0
  24. package/dist/cjs/index.js +53 -0
  25. package/dist/cjs/logout-token.d.ts +13 -0
  26. package/dist/cjs/logout-token.js +63 -0
  27. package/dist/cjs/nestjs.d.ts +53 -0
  28. package/dist/cjs/nestjs.js +142 -0
  29. package/dist/cjs/next.d.ts +61 -0
  30. package/dist/cjs/next.js +118 -0
  31. package/dist/cjs/node-adapter.d.ts +16 -0
  32. package/dist/cjs/node-adapter.js +76 -0
  33. package/dist/cjs/node-http.d.ts +22 -0
  34. package/dist/cjs/node-http.js +127 -0
  35. package/dist/cjs/node.d.ts +50 -0
  36. package/dist/cjs/node.js +57 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/pkce.d.ts +6 -0
  39. package/dist/cjs/pkce.js +49 -0
  40. package/dist/cjs/return-path.d.ts +6 -0
  41. package/dist/cjs/return-path.js +41 -0
  42. package/dist/cjs/sealed.d.ts +12 -0
  43. package/dist/cjs/sealed.js +78 -0
  44. package/dist/cjs/service.d.ts +61 -0
  45. package/dist/cjs/service.js +173 -0
  46. package/dist/cjs/session.d.ts +51 -0
  47. package/dist/cjs/session.js +97 -0
  48. package/dist/cjs/store.d.ts +58 -0
  49. package/dist/cjs/store.js +145 -0
  50. package/dist/cjs/tokens.d.ts +38 -0
  51. package/dist/cjs/tokens.js +138 -0
  52. package/dist/esm/access-token.d.ts +56 -0
  53. package/dist/esm/access-token.js +156 -0
  54. package/dist/esm/config.d.ts +128 -0
  55. package/dist/esm/config.js +206 -0
  56. package/dist/esm/cookies.d.ts +23 -0
  57. package/dist/esm/cookies.js +89 -0
  58. package/dist/esm/discovery.d.ts +24 -0
  59. package/dist/esm/discovery.js +56 -0
  60. package/dist/esm/errors.d.ts +63 -0
  61. package/dist/esm/errors.js +41 -0
  62. package/dist/esm/express.d.ts +71 -0
  63. package/dist/esm/express.js +90 -0
  64. package/dist/esm/hono.d.ts +65 -0
  65. package/dist/esm/hono.js +106 -0
  66. package/dist/esm/http.d.ts +10 -0
  67. package/dist/esm/http.js +44 -0
  68. package/dist/esm/id-token.d.ts +19 -0
  69. package/dist/esm/id-token.js +51 -0
  70. package/dist/esm/idp.d.ts +81 -0
  71. package/dist/esm/idp.js +488 -0
  72. package/dist/esm/index.d.ts +9 -0
  73. package/dist/esm/index.js +30 -0
  74. package/dist/esm/logout-token.d.ts +13 -0
  75. package/dist/esm/logout-token.js +39 -0
  76. package/dist/esm/nestjs.d.ts +53 -0
  77. package/dist/esm/nestjs.js +118 -0
  78. package/dist/esm/next.d.ts +61 -0
  79. package/dist/esm/next.js +94 -0
  80. package/dist/esm/node-adapter.d.ts +16 -0
  81. package/dist/esm/node-adapter.js +60 -0
  82. package/dist/esm/node-http.d.ts +22 -0
  83. package/dist/esm/node-http.js +96 -0
  84. package/dist/esm/node.d.ts +50 -0
  85. package/dist/esm/node.js +33 -0
  86. package/dist/esm/package.json +1 -0
  87. package/dist/esm/pkce.d.ts +6 -0
  88. package/dist/esm/pkce.js +23 -0
  89. package/dist/esm/return-path.d.ts +6 -0
  90. package/dist/esm/return-path.js +17 -0
  91. package/dist/esm/sealed.d.ts +12 -0
  92. package/dist/esm/sealed.js +54 -0
  93. package/dist/esm/service.d.ts +61 -0
  94. package/dist/esm/service.js +148 -0
  95. package/dist/esm/session.d.ts +51 -0
  96. package/dist/esm/session.js +58 -0
  97. package/dist/esm/store.d.ts +58 -0
  98. package/dist/esm/store.js +119 -0
  99. package/dist/esm/tokens.d.ts +38 -0
  100. package/dist/esm/tokens.js +100 -0
  101. package/package.json +152 -5
package/CHANGELOG.md ADDED
@@ -0,0 +1,98 @@
1
+ # Changelog
2
+
3
+ ## 0.1.3
4
+
5
+ ### Hono, and edge runtimes
6
+
7
+ - `nextidp/hono`: `routes()`, `middleware()` (the session as `c.get("session")`, refreshed
8
+ before it expires), `requireSession()` and `requireToken()` (the token as
9
+ `c.get("token")`), with the `IdpEnv` type for `new Hono<IdpEnv>()`. A refreshed cookie
10
+ reaches any response the handler makes, its own `Response` included.
11
+ - Runs on edge runtimes (Cloudflare Workers, Vercel Edge, Deno, Bun): the tests bundle the
12
+ core and the Hono adapter for a platform without Node built-ins and run them in Cloudflare's
13
+ `workerd`, with no Node compatibility: sign-in, refresh, sign-out, back-channel logout,
14
+ API tokens and service tokens.
15
+
16
+ ## 0.1.2
17
+
18
+ The first release with code in it: sign-in for Next.js, Express and Node, API protection
19
+ for NestJS, Express and Next.js, service tokens, and sessions in a store with back-channel
20
+ logout.
21
+
22
+ ### Sign-in for Next.js (App Router)
23
+
24
+ - `idp()` from `nextidp/next`: `routes()`, `proxy()`, `session()`, `requireSession()`.
25
+ - The core from `nextidp`, without a framework: `handler()`, `getSession()`,
26
+ `refreshIfNeeded()`, `userInfo()`, `signInPath()`.
27
+ - The authorization code flow with PKCE (S256), the state and nonce checked, and the ID token
28
+ verified (signature, `iss`, `aud`, `azp`, `exp`, `iat`, nonce).
29
+ - The session in an encrypted cookie (A256GCM, a key per purpose from HKDF), split when it's
30
+ over 4 KB, with secret rotation.
31
+ - Refresh before expiry in the proxy, shared between concurrent requests. Sign-out revokes
32
+ the refresh token, and can end the auth server's session too (RP-initiated logout).
33
+ - ES module and CommonJS builds, with types for each.
34
+
35
+ ### Sign-in for Express and Node
36
+
37
+ - `nextidp/express`: `express()` middleware (nextidp's routes, and the session read and
38
+ refreshed on every other request), `requireSession()` and `sessionOf(req)`.
39
+ - `nextidp/node` for Node's own HTTP server: `handle(req, res)`, `session(req, res)` and
40
+ `requireSession(req, res)`.
41
+ - A signed-out GET goes to sign in and comes back after; anything else gets 401.
42
+ - The URL is always on `appUrl`'s origin, never from the Host header. Forms a body parser
43
+ already read are taken from it; others are read up to 64 KB (413 past that).
44
+ - A refresh happens only while the response's headers can still be set, so a rotated refresh
45
+ token is never lost.
46
+
47
+ ### Sessions in a store, and back-channel logout
48
+
49
+ - The `store` option (`SessionStore`: `get`, `set`, `delete` over strings), and
50
+ `memoryStore()` for one process. The cookie then holds only a sealed reference, and the
51
+ stored session is sealed too.
52
+ - Signing out deletes the stored session, so a copy of the old cookie is signed out as well.
53
+ A new sign-in replaces the browser's previous session.
54
+ - `POST <basePath>/backchannel-logout` (OIDC Back-Channel Logout 1.0), with a store only:
55
+ the logout token is checked (signature, `iss`, `aud`, `iat`, `exp`, the logout event, a
56
+ `sid` or `sub`, no `nonce`, `typ` logout+jwt when there is one), then the app's sessions
57
+ from that auth-server session end; a token with only `sub` ends all of the person's
58
+ sessions begun before it. 400 for a token that doesn't verify (`invalid_logout_token`).
59
+ - A refresh refused because another instance sharing the store refreshed first keeps the
60
+ session that instance stored.
61
+ - Apps sharing a store are kept apart by their client ID.
62
+
63
+ ### Service tokens
64
+
65
+ - `serviceToken({ scopes, resource })` in the core: a service's own access token (client
66
+ credentials, a confidential client), kept until a minute before it expires (half its life
67
+ if that's shorter), per scopes and API, with one request at a time.
68
+ - `dropServiceToken(token)` forgets one an API refused. `useServiceToken(client, options)`
69
+ puts tokens on the requests of a fast-http-client client to the API's origin (that of
70
+ `resource`, or `origins`) and nowhere else, and on a 401 gets a new one and sends the
71
+ request once more.
72
+ - A refusal is `IdpError` with the code `service_token_failed`, and isn't kept.
73
+ - NestJS: inject `IDP` and call `serviceToken()`.
74
+
75
+ ### Protecting an API
76
+
77
+ - `verifyAccessToken()` and `verifyBearer()` in the core: a JWT access token checked against
78
+ the issuer's keys (signature, `typ` at+jwt, `iss`, `aud`, expiry), an opaque one by
79
+ introspection (kept a minute at most), then the scopes a route needs.
80
+ - 401 and 403 with RFC 6750's `WWW-Authenticate` challenge (`tokenErrorResponse()`), 503
81
+ when a token can't be checked at all.
82
+ - `nextidp/nestjs`: `IdpModule.forRoot()` and `forRootAsync()`, a guard on every route by
83
+ default, `@Scopes()`, `@Public()`, `@CurrentToken()`. NestJS 11 (CommonJS) and 12 (ES
84
+ modules).
85
+ - `nextidp/express`: `requireToken()` middleware and `tokenOf(req)`.
86
+ - `nextidp/next`: `withToken()` for route handlers.
87
+ - An API needs only `issuer` and `audience` (IDP_AUDIENCE), required and never taken from
88
+ `resource`. A JWT access token must have `typ` at+jwt. An introspected token must name the
89
+ audience too, unless `acceptOwnTokens` lets this client's own tokens through.
90
+ - Nothing from the HTTP client reaches an error or a log: a failed request keeps only its
91
+ message, and the adapters log error codes.
92
+ - `resource` and `audience` are kept exactly as written: the auth server compares them as
93
+ strings.
94
+ - Node 24 or later.
95
+
96
+ ## 0.0.1
97
+
98
+ The name, reserved.
package/README.md CHANGED
@@ -1,7 +1,505 @@
1
1
  # nextidp
2
2
 
3
- Hello, nextidp.
3
+ Sign people in to your Next.js, Express, Hono or Node app, and protect your APIs, with
4
+ [authserver-oidc](https://github.com/sajanv88/authserver-oidc), in one call. It does the
5
+ OpenID Connect work for you:
4
6
 
5
- This package will sign people in to Next.js, Node and NestJS apps through
6
- [authserver-oidc](https://github.com/sajanv88/authserver-oidc), in one call. It's a
7
- placeholder for now: the first working release is on its way.
7
+ - the authorization code flow with PKCE;
8
+ - the ID token's checks (signature, issuer, audience, expiry, nonce);
9
+ - an encrypted session cookie, so no database is needed, or sessions in your own store
10
+ (Redis, a database), which the auth server can then end ([back-channel
11
+ logout](#sessions-in-a-store-and-back-channel-logout));
12
+ - refreshing tokens before they expire;
13
+ - signing out, of your app or of the auth server too;
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));
16
+ - tokens for a service to call other APIs as itself ([below](#calling-an-api-as-a-service)).
17
+
18
+ It works with any OpenID Connect provider that supports the code flow with PKCE, but it's
19
+ made for, and tested against, authserver-oidc.
20
+
21
+ ```sh
22
+ npm i nextidp
23
+ ```
24
+
25
+ ES module and CommonJS builds, with types. Node 24 or later, or an edge runtime
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, Node's own
28
+ HTTP server, Hono 4, and NestJS 11 or 12 for APIs.
29
+
30
+ ## 1. Register your app on the auth server
31
+
32
+ In the auth server's **Admin → OIDC clients**, create a client (or declare it in
33
+ `clients:provision`):
34
+
35
+ - **Redirect URI:** `https://app.example.com/auth/callback`
36
+ - **Post-logout redirect URI:** `https://app.example.com/`, only if you want "sign out of the
37
+ auth server too" (through `clients:provision`)
38
+ - **Public** (PKCE only, no secret), or **confidential** if your app should keep a secret.
39
+
40
+ ## 2. Settings
41
+
42
+ Put these in your app's environment:
43
+
44
+ ```sh
45
+ IDP_ISSUER=https://auth.example.com # the auth server
46
+ IDP_CLIENT_ID=… # from step 1
47
+ IDP_CLIENT_SECRET=… # confidential clients only
48
+ IDP_APP_URL=https://app.example.com # this app's origin
49
+ IDP_SECRET=… # ≥ 32 characters: openssl rand -base64 32
50
+ ```
51
+
52
+ ## 3. Wire it up
53
+
54
+ In a Next.js app (for Express or Node's own server, see [below](#express-or-node)):
55
+
56
+ ```ts
57
+ // src/auth.ts
58
+ import { idp } from "nextidp/next";
59
+
60
+ export const auth = idp(); // reads IDP_* on first use, so `next build` needs none of them
61
+ ```
62
+
63
+ ```ts
64
+ // src/app/auth/[...nextidp]/route.ts
65
+ import { auth } from "@/auth";
66
+
67
+ export const { GET, POST } = auth.routes();
68
+ ```
69
+
70
+ ```ts
71
+ // src/proxy.ts (middleware.ts before Next.js 16)
72
+ import { auth } from "@/auth";
73
+
74
+ // Sends signed-out visitors of /dashboard to sign in, and refreshes tokens before they expire.
75
+ export const proxy = auth.proxy({ protect: ["/dashboard"] });
76
+
77
+ export const config = { matcher: ["/((?!auth/|_next/|favicon.ico).*)"] };
78
+ ```
79
+
80
+ That's all. Now use the session:
81
+
82
+ ```tsx
83
+ // src/app/dashboard/page.tsx
84
+ import { auth } from "@/auth";
85
+
86
+ export default async function Dashboard() {
87
+ const session = await auth.requireSession("/dashboard"); // or auth.session(): null if signed out
88
+ return <h1>Hello, {session.user.name ?? session.user.email}</h1>;
89
+ }
90
+ ```
91
+
92
+ ```tsx
93
+ // Signing in and out: plain links and forms to nextidp's routes
94
+ <a href="/auth/login?returnTo=/dashboard">Sign in</a>
95
+
96
+ <form method="post" action="/auth/logout">
97
+ <button type="submit">Sign out</button>
98
+ <button type="submit" name="signOutOfIdp" value="true">Sign out everywhere</button>
99
+ </form>
100
+ ```
101
+
102
+ Calling an API as the signed-in person:
103
+
104
+ ```ts
105
+ const session = await auth.session();
106
+ await fetch("https://api.example.com/orders", {
107
+ headers: { authorization: `Bearer ${session?.accessToken}` },
108
+ });
109
+ ```
110
+
111
+ ## Express or Node
112
+
113
+ The same settings, the same routes. With **Express**:
114
+
115
+ ```ts
116
+ import express from "express";
117
+ import { idp } from "nextidp/express";
118
+
119
+ const auth = idp(); // the IDP_* settings, read on first use
120
+ const app = express();
121
+
122
+ // Before your routes: answers nextidp's routes, and reads the session (refreshing it
123
+ // before it expires) for every other request.
124
+ app.use(auth.express());
125
+
126
+ app.get("/", (req, res) => {
127
+ const session = auth.sessionOf(req); // null if signed out
128
+ res.send(session ? `Hello, ${session.user.name}` : `<a href="/auth/login">Sign in</a>`);
129
+ });
130
+
131
+ // Signed out, a GET goes to sign in and comes back; anything else gets 401.
132
+ app.get("/dashboard", auth.requireSession(), (req, res) => {
133
+ res.render("dashboard", { user: auth.sessionOf(req)?.user });
134
+ });
135
+ ```
136
+
137
+ A body parser before it is fine: the sign-out form is read from what it parsed.
138
+
139
+ With **Node's own HTTP server**:
140
+
141
+ ```ts
142
+ import { createServer } from "node:http";
143
+ import { idp } from "nextidp/node";
144
+
145
+ const auth = idp();
146
+
147
+ createServer(async (req, res) => {
148
+ if (await auth.handle(req, res)) return; // nextidp's routes
149
+ const session = await auth.requireSession(req, res); // or auth.session(req, res): null if signed out
150
+ if (!session) return; // sent to sign in
151
+ res.end(`Hello, ${session.user.name}`);
152
+ }).listen(3000);
153
+ ```
154
+
155
+ Read the session before you start the response: a refresh sets a new cookie. Read twice in
156
+ one request, it's refreshed once.
157
+
158
+ ## Hono
159
+
160
+ On any runtime Hono runs on:
161
+
162
+ ```ts
163
+ import { Hono } from "hono";
164
+ import { idp, type IdpEnv } from "nextidp/hono";
165
+
166
+ const auth = idp();
167
+ const app = new Hono<IdpEnv>();
168
+
169
+ app.all("/auth/*", auth.routes()); // nextidp's routes
170
+ app.use(auth.middleware()); // the session on every request, refreshed before it expires
171
+
172
+ app.get("/", (c) => {
173
+ const session = c.get("session"); // null if signed out
174
+ return c.text(session ? `Hello, ${session.user.name}` : "Signed out");
175
+ });
176
+
177
+ // Signed out, a GET goes to sign in and comes back; anything else gets 401.
178
+ app.get("/dashboard", auth.requireSession(), (c) => c.text(`Hello, ${c.get("session")?.user.name}`));
179
+
180
+ // An API: 401 or 403 with the RFC 6750 challenge, 503 if the token can't be checked.
181
+ app.get("/api/orders", auth.requireToken({ scopes: ["orders:read"] }), (c) =>
182
+ c.json(ordersOf(c.get("token").subject)),
183
+ );
184
+ ```
185
+
186
+ A refreshed session's cookie is added to whatever response the handler makes, its own
187
+ `Response` included.
188
+
189
+ ## Edge runtimes
190
+
191
+ The core uses only Web APIs (`fetch`, `Request`/`Response`, `crypto.subtle`), so it runs on
192
+ Cloudflare Workers, Vercel Edge, Deno and Bun as well as Node: everything but `nextidp/node`,
193
+ `nextidp/express` and `nextidp/nestjs`, which are for Node. Its tests run it in Cloudflare's
194
+ own runtime, `workerd`, with no Node compatibility turned on.
195
+
196
+ Where there's no `process.env` (Cloudflare Workers), pass the settings from the Worker's
197
+ bindings, read on first use:
198
+
199
+ ```ts
200
+ import { Hono } from "hono";
201
+ import { idp, type IdpEnv } from "nextidp/hono";
202
+
203
+ type Bindings = { IDP_ISSUER: string; IDP_CLIENT_ID: string; IDP_APP_URL: string; IDP_SECRET: string };
204
+
205
+ let bindings: Bindings;
206
+ const auth = idp(() => ({ env: bindings })); // the IDP_* names, from the bindings
207
+
208
+ const app = new Hono<IdpEnv>();
209
+ app.all("/auth/*", auth.routes());
210
+ app.use(auth.middleware());
211
+
212
+ export default {
213
+ fetch(request: Request, env: Bindings) {
214
+ bindings = env;
215
+ return app.fetch(request, env);
216
+ },
217
+ };
218
+ ```
219
+
220
+ Each isolate has its own memory, so `memoryStore()` there is per isolate. For sessions in a
221
+ store, use one every isolate reaches: a database, or Durable Objects. Cloudflare KV works too,
222
+ but it's eventually consistent: a back-channel logout can take a little while (up to about a
223
+ minute) to reach every location.
224
+
225
+ ## The routes
226
+
227
+ All under `basePath` (default `/auth`):
228
+
229
+ | Route | What it does |
230
+ |---|---|
231
+ | `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). |
232
+ | `GET /auth/callback` | Finishes it: the redirect URI you registered. |
233
+ | `POST /auth/logout` | Revokes the refresh token and ends this app's session. With `signOutOfIdp=true`, the auth server's too. |
234
+ | `POST /auth/refresh` | New tokens now, then back to the form's `returnTo`. |
235
+
236
+ The POST routes accept forms from this app's own pages only (they check `Origin`).
237
+
238
+ ## The session
239
+
240
+ ```ts
241
+ type Session = {
242
+ user: { id: string; email?: string; emailVerified?: boolean; name?: string; picture?: string };
243
+ claims: JWTPayload; // every claim of the ID token, checked
244
+ accessToken: string; // for APIs: Authorization: Bearer …
245
+ accessTokenExpiresAt: number; // seconds since the epoch
246
+ scope: string | undefined;
247
+ canRefresh: boolean; // offline_access was granted
248
+ };
249
+ ```
250
+
251
+ The refresh token and the ID token stay inside the encrypted cookie: nothing in the browser
252
+ can read them.
253
+
254
+ ## All the settings
255
+
256
+ Pass them to `idp({...})`, or set the variable in brackets. A function works too,
257
+ `idp(() => ({...}))`, called on first use.
258
+
259
+ | Option | Default | |
260
+ |---|---|---|
261
+ | `issuer` (IDP_ISSUER) | | The auth server's URL. |
262
+ | `clientId` (IDP_CLIENT_ID) | | |
263
+ | `clientSecret` (IDP_CLIENT_SECRET) | none: a public client | Sent with HTTP Basic. |
264
+ | `appUrl` (IDP_APP_URL) | | This app's origin. |
265
+ | `secret` (IDP_SECRET) | | At least 32 characters. A list rotates it: the first encrypts, all decrypt (comma-separated in the variable). |
266
+ | `scopes` (IDP_SCOPES) | `openid profile email offline_access` | `offline_access` gets a refresh token. |
267
+ | `resource` (IDP_RESOURCE) | none | An API's URI (RFC 8707): the access token is then a JWT for it. |
268
+ | `audience` (IDP_AUDIENCE) | none: required to check tokens | For an API: its own URI, exactly as in the auth server's `OAUTH_RESOURCES`. Every token must name it. Never taken from `resource`, which is the API an app asks tokens *for*. |
269
+ | `acceptOwnTokens` | `false` | For an API: also accept an opaque token issued to its own `clientId` that doesn't name `audience`. |
270
+ | `basePath` | `/auth` | Where the routes live. |
271
+ | `afterSignIn` | `/` | Where a sign-in lands without a `returnTo`. |
272
+ | `afterSignOut` | `/` | Where sign-out lands: also the post-logout redirect URI. |
273
+ | `errorPath` | `/` | Where a failed sign-in lands, with `?error=<code>`. |
274
+ | `signOutOfIdp` | `false` | Sign out of the auth server too, unless the form says otherwise. |
275
+ | `sessionMaxAge` | 7 days | Renewed at every refresh. |
276
+ | `cookiePrefix` | `nextidp` | Cookies are `__Host-nextidp.session` on https. |
277
+ | `store` | none: sessions live in the cookie | Keep sessions in a store instead ([below](#sessions-in-a-store-and-back-channel-logout)). |
278
+ | `onError` | one `console.error` line | Told about every failure. Messages never hold tokens or claims. |
279
+
280
+ Anything missing or wrong is reported on the first request, with every setting named, in
281
+ `IdpError` with the code `misconfigured`.
282
+
283
+ ## When a sign-in fails
284
+
285
+ The browser goes to `errorPath?error=<code>`, so your page can explain:
286
+
287
+ | Code | Meaning |
288
+ |---|---|
289
+ | `access_denied` | The person chose Deny. |
290
+ | `expired` | The sign-in took more than 10 minutes, or its cookie was lost. |
291
+ | `state_mismatch` | The answer wasn't for a sign-in this browser started. |
292
+ | `token_failed` | The auth server refused the code. |
293
+ | `invalid_id_token` | The ID token's signature, issuer, audience, expiry or nonce was wrong. |
294
+ | `refresh_failed` | The refresh token was refused. |
295
+
296
+ ```ts
297
+ import { isSignInErrorCode } from "nextidp/next";
298
+
299
+ if (isSignInErrorCode(searchParams.error)) { /* … */ }
300
+ ```
301
+
302
+ ## Protecting an API
303
+
304
+ An API needs two settings: the auth server, and its own URI as the auth server lists it
305
+ in `OAUTH_RESOURCES`.
306
+
307
+ ```sh
308
+ IDP_ISSUER=https://auth.example.com
309
+ IDP_AUDIENCE=https://api.example.com # exactly as in OAUTH_RESOURCES
310
+ ```
311
+
312
+ The apps that call it ask for tokens with `resource` set to that URI, and must be linked to
313
+ it on the auth server (`clients:provision`'s `resources`). Their access tokens are then JWTs
314
+ for this API: nextidp checks each one against the auth server's published keys (signature,
315
+ `typ` at+jwt, required, so no other kind of JWT passes for one; issuer, audience, expiry) and the scopes the route needs, with no call to the
316
+ auth server per request.
317
+
318
+ **NestJS** (11 or 12):
319
+
320
+ ```ts
321
+ import { CurrentToken, IdpModule, Public, Scopes, type AccessToken } from "nextidp/nestjs";
322
+
323
+ @Module({ imports: [IdpModule.forRoot()] }) // reads IDP_*; or forRoot({ issuer, audience })
324
+ export class AppModule {}
325
+
326
+ @Controller("orders")
327
+ @Scopes("orders:read") // every route here needs it
328
+ export class OrdersController {
329
+ @Get()
330
+ list(@CurrentToken() token: AccessToken) {
331
+ return this.orders.of(token.subject);
332
+ }
333
+
334
+ @Post()
335
+ @Scopes("orders:write") // and this one needs this too
336
+ create() {}
337
+
338
+ @Public() // no token needed
339
+ @Get("health")
340
+ health() {}
341
+ }
342
+ ```
343
+
344
+ The guard protects every route of the app by default; pass `{ protectAll: false }` and use
345
+ `@UseGuards(IdpGuard)` to pick routes yourself. With `ConfigService`:
346
+ `IdpModule.forRootAsync({ inject: [ConfigService], useFactory: (config) => ({ issuer: …, audience: … }) })`.
347
+
348
+ **Express** (or anything with Connect-style middleware):
349
+
350
+ ```ts
351
+ import { idp } from "nextidp/express";
352
+
353
+ const auth = idp(); // IDP_ISSUER and IDP_AUDIENCE
354
+
355
+ app.get("/orders", auth.requireToken({ scopes: ["orders:read"] }), (req, res) => {
356
+ res.json(ordersOf(auth.tokenOf(req)?.subject));
357
+ });
358
+ ```
359
+
360
+ **A Next.js route handler:**
361
+
362
+ ```ts
363
+ // src/app/api/orders/route.ts
364
+ export const GET = auth.withToken({ scopes: ["orders:read"] }, async (request, { token }) =>
365
+ Response.json(await ordersOf(token.subject)),
366
+ );
367
+ ```
368
+
369
+ A refused call gets 401 (no token, or a bad one) or 403 (a scope missing), with the
370
+ `WWW-Authenticate` challenge of RFC 6750. If the token can't be checked at all (the auth
371
+ server is down), the answer is 503, never a pass. The checked token:
372
+
373
+ ```ts
374
+ type AccessToken = {
375
+ subject: string | undefined; // the person, or for a service its client ID
376
+ clientId: string | undefined; // the app the token was issued to
377
+ isService: boolean; // client credentials: no person involved
378
+ scopes: string[];
379
+ audience: string[];
380
+ expiresAt: number | undefined;
381
+ claims: Record<string, unknown>;
382
+ };
383
+ ```
384
+
385
+ **Opaque tokens.** A token asked for without `resource` isn't a JWT, and only introspection
386
+ can check it. Pass the API's own `clientId` and `clientSecret` (a confidential client) for
387
+ that. The auth server answers only for tokens this client was issued, or tokens for an API
388
+ it's linked to, and nextidp still requires the token to name `audience`: a token this client
389
+ was issued for something else passes only with `acceptOwnTokens: true`. Answers are kept
390
+ for a minute at most, so a revoked token is refused within a minute. For APIs, prefer JWTs:
391
+ ask for tokens with `resource`.
392
+
393
+ ## Calling an API as a service
394
+
395
+ A service that calls another API as itself, with no person involved, gets its own tokens
396
+ (the client credentials grant). It needs a **machine** client on the auth server (in
397
+ `clients:provision`: `"type": "machine"`, with the `scopes` it may ask for and the
398
+ `resources` it may call), and its credentials:
399
+
400
+ ```sh
401
+ IDP_ISSUER=https://auth.example.com
402
+ IDP_CLIENT_ID=…
403
+ IDP_CLIENT_SECRET=…
404
+ IDP_RESOURCE=https://orders.example.com # optional: the API, when a call names none
405
+ ```
406
+
407
+ ```ts
408
+ import { idp } from "nextidp"; // or nextidp/express, nextidp/node, nextidp/next
409
+
410
+ const auth = idp();
411
+
412
+ const token = await auth.serviceToken({
413
+ scopes: ["orders:read"],
414
+ resource: "https://orders.example.com",
415
+ });
416
+ await fetch("https://orders.example.com/orders", {
417
+ headers: { authorization: `Bearer ${token}` },
418
+ });
419
+ ```
420
+
421
+ A token is kept until a minute before it expires (half its life, if that's shorter), one per
422
+ scopes and API, and calls at the same time share one request to the auth server. If an API
423
+ refuses one (401), `auth.dropServiceToken(token)` forgets it. With
424
+ [fast-http-client](https://www.npmjs.com/package/fast-http-client), that's done for you:
425
+
426
+ ```ts
427
+ import { createHttp } from "fast-http-client";
428
+
429
+ const orders = createHttp({ baseUrl: "https://orders.example.com" });
430
+ auth.useServiceToken(orders, { scopes: ["orders:read"], resource: "https://orders.example.com" });
431
+
432
+ const { data } = await orders.get("/orders"); // with the token; a 401 gets a new one, once
433
+ ```
434
+
435
+ The token goes only to the API's origin: that of `resource` (here
436
+ `https://orders.example.com`), or the ones you list in `origins`. A request through the same
437
+ client to any other origin goes out without it, so a URL from elsewhere can't carry the token
438
+ away. Without an http(s) `resource` or `origins`, `useServiceToken` refuses to start.
439
+
440
+ In **NestJS**, inject the instance `IdpModule` holds (with `{ protectAll: false }` if the app
441
+ doesn't check tokens itself):
442
+
443
+ ```ts
444
+ import { Inject, Injectable } from "@nestjs/common";
445
+ import { IDP, type Idp } from "nextidp/nestjs";
446
+
447
+ @Injectable()
448
+ export class OrdersClient {
449
+ constructor(@Inject(IDP) private readonly auth: Idp) {}
450
+
451
+ async list() {
452
+ const token = await this.auth.serviceToken({ scopes: ["orders:read"] });
453
+ // …
454
+ }
455
+ }
456
+ ```
457
+
458
+ A refusal throws `IdpError` with the code `service_token_failed` and the auth server's
459
+ status (`invalid_scope` for a scope the client may not have, `invalid_target` for an API it
460
+ isn't linked to).
461
+
462
+ ## Sessions in a store, and back-channel logout
463
+
464
+ By default a session lives in its encrypted cookie, which only the browser holds: the auth
465
+ server can't end it, and signing out can't take back a copy of the cookie. Give nextidp a
466
+ `store` and sessions live there instead, with only a sealed reference in the cookie:
467
+
468
+ ```ts
469
+ import { idp, memoryStore } from "nextidp/next"; // or nextidp/express, nextidp/node
470
+
471
+ export const auth = idp({ store: memoryStore() }); // one process only: use Redis to share
472
+ ```
473
+
474
+ A store is three functions over strings nextidp has already encrypted, so a copy of the
475
+ store holds no readable tokens. With Redis (ioredis):
476
+
477
+ ```ts
478
+ import type { SessionStore } from "nextidp";
479
+
480
+ const store: SessionStore = {
481
+ get: (key) => redis.get(key),
482
+ set: async (key, value, ttlSeconds) => { await redis.set(key, value, "EX", ttlSeconds); },
483
+ delete: async (key) => { await redis.del(key); },
484
+ };
485
+ ```
486
+
487
+ Then:
488
+
489
+ - **Signing out ends the session for good**: an old copy of the cookie is signed out too.
490
+ - **Back-channel logout**: when someone's session ends on the auth server (they sign out
491
+ there, an admin signs them out everywhere, the account is disabled), it posts a signed
492
+ logout token to `POST /auth/backchannel-logout`, and nextidp ends this app's sessions from
493
+ that auth-server session. Register the address with the client, in `clients:provision`:
494
+ `"backchannelLogoutUri": "https://app.example.com/auth/backchannel-logout"` (https, or a
495
+ loopback address in development). The auth server sends it only to apps that hold a
496
+ refresh token for that session, so keep `offline_access` in the scopes.
497
+ - **Several instances** sharing the store share sessions, and one that refreshes a session
498
+ just after another did keeps it, instead of signing the person out.
499
+
500
+ Each read of a session costs a store lookup or three (the session, and whether the auth
501
+ server ended it). Apps sharing a store are kept apart by their client ID.
502
+
503
+ ## License
504
+
505
+ MIT
@@ -0,0 +1,56 @@
1
+ import { type JWTVerifyGetKey } from "jose";
2
+ import type { ApiConfig } from "./config.js";
3
+ import type { Discovery } from "./discovery.js";
4
+ import { IdpError } from "./errors.js";
5
+ import type { Http } from "./http.js";
6
+ /** An access token that checked out. */
7
+ export type AccessToken = {
8
+ /** `sub`: the person, or for a service calling as itself, its client ID. */
9
+ subject: string | undefined;
10
+ /** The app the token was issued to. */
11
+ clientId: string | undefined;
12
+ /** A service calling as itself (client credentials), not on a person's behalf. */
13
+ isService: boolean;
14
+ scopes: string[];
15
+ audience: string[];
16
+ /** Seconds since the epoch. */
17
+ expiresAt: number | undefined;
18
+ /** Every claim, or every field of the introspection answer. */
19
+ claims: Record<string, unknown>;
20
+ };
21
+ export type TokenRequirements = {
22
+ /** Every one of these scopes must be granted. */
23
+ scopes?: readonly string[] | undefined;
24
+ };
25
+ /** The token in an `Authorization: Bearer …` header, or undefined. */
26
+ export declare function bearerToken(authorization: string | null | undefined): string | undefined;
27
+ /** Throws insufficient_scope (403) unless every required scope was granted. */
28
+ export declare function requireScopes(token: AccessToken, required?: readonly string[]): AccessToken;
29
+ /** Whether a token is a JWT (three parts, a header that decodes) rather than opaque. */
30
+ export declare function isJwt(token: string): boolean;
31
+ /**
32
+ * A JWT access token (RFC 9068): `typ` at+jwt, so no other kind of JWT (an ID token, a logout
33
+ * token) passes for one; a signature by one of the issuer's keys (asymmetric algorithms
34
+ * only); `iss`; `aud` naming this API; and not expired (60 seconds of clock skew).
35
+ */
36
+ export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<AccessToken>;
37
+ /**
38
+ * Asks the auth server whether an opaque token is active, with this API's client
39
+ * credentials. The auth server answers only for tokens this client issued, or tokens for an
40
+ * API this client is linked to; to anything else it answers inactive.
41
+ */
42
+ export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<AccessToken>;
43
+ /**
44
+ * The WWW-Authenticate challenge for a refused request (RFC 6750 3): no error code when
45
+ * there was no token at all, else invalid_token or insufficient_scope with the scopes needed.
46
+ */
47
+ export declare function bearerChallenge(error: IdpError): string;
48
+ /** The status, challenge and JSON body to answer a refused request with. */
49
+ export declare function tokenRefusal(error: IdpError): {
50
+ status: 401 | 403;
51
+ headers: Record<string, string>;
52
+ body: {
53
+ error: string;
54
+ error_description: string;
55
+ };
56
+ };