nextidp 0.0.0-stage → 0.1.2

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