nextidp 0.1.3 → 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 CHANGED
@@ -1,5 +1,43 @@
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
+
15
+ ## 0.1.4
16
+
17
+ ### Sign-in
18
+
19
+ - `GET <basePath>/login?prompt=…` passes `prompt` on to the auth server: `login`, `consent`
20
+ or `select_account`, or several separated by spaces. Any other value, `none` included, is
21
+ left out, and nothing else in the query is passed on. `signInPath(returnTo, { prompt })`
22
+ builds the link.
23
+ - `reauthenticateAfterSignOut` (default `false`): a sign-out leaves a small marker cookie
24
+ (`<prefix>.signed-out`, `__Secure-` on https, on `basePath` only, 30 days), and the next
25
+ sign-in sends `prompt=login` and clears it, so a shared computer doesn't sign the next person
26
+ in as the last. A link with `reauthenticate=false` (a "Create account" link) opts out and
27
+ leaves the marker; a `prompt` in the link wins over it.
28
+ - `userinfo` (default `false`): the email, `email_verified`, name and picture from the
29
+ userinfo endpoint, merged into `session.user` after sign-in and after a refresh that brings
30
+ a new ID token (kept otherwise), for auth servers that leave them out of the ID token.
31
+ Best effort: a failure, or an answer about another `sub`, goes to `onError` and the
32
+ sign-in goes ahead. `session.claims` stays the ID token's.
33
+
34
+ ### Next.js
35
+
36
+ - `routes()` answers a fetch of the login route by Next's client router (a `<Link>`,
37
+ `router.push` or a prefetch: the `rsc` header) with a 200 "Sign-in needs a full page load."
38
+ and no cookie, instead of a redirect it can't follow. The router then loads it as a whole
39
+ page, and a sign-in under way keeps its flow cookie.
40
+
3
41
  ## 0.1.3
4
42
 
5
43
  ### Hono, and edge runtimes
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
- [authserver-oidc](https://github.com/sajanv88/authserver-oidc), in one call. It does the
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, authserver-oidc.
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, Node's own
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
@@ -99,6 +100,13 @@ export default async function Dashboard() {
99
100
  </form>
100
101
  ```
101
102
 
103
+ Link to `/auth/login` with a plain `<a>`, as above. A `<Link>`, a `router.push` or a prefetch
104
+ makes Next's client router fetch the route itself, and that fetch can't follow the redirect to
105
+ the auth server (another origin). So `auth.routes()` answers such a fetch (it carries the
106
+ `rsc` header) with a plain 200, "Sign-in needs a full page load.", and no cookie: the router
107
+ then loads the address as a whole page, which signs in as usual, and a sign-in already under
108
+ way keeps its cookie.
109
+
102
110
  Calling an API as the signed-in person:
103
111
 
104
112
  ```ts
@@ -155,6 +163,33 @@ createServer(async (req, res) => {
155
163
  Read the session before you start the response: a refresh sets a new cookie. Read twice in
156
164
  one request, it's refreshed once.
157
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
+
158
193
  ## Hono
159
194
 
160
195
  On any runtime Hono runs on:
@@ -190,7 +225,7 @@ A refreshed session's cookie is added to whatever response the handler makes, it
190
225
 
191
226
  The core uses only Web APIs (`fetch`, `Request`/`Response`, `crypto.subtle`), so it runs on
192
227
  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
228
+ `nextidp/express`, `nextidp/fastify` and `nextidp/nestjs`, which are for Node. Its tests run it in Cloudflare's
194
229
  own runtime, `workerd`, with no Node compatibility turned on.
195
230
 
196
231
  Where there's no `process.env` (Cloudflare Workers), pass the settings from the Worker's
@@ -228,13 +263,38 @@ All under `basePath` (default `/auth`):
228
263
 
229
264
  | Route | What it does |
230
265
  |---|---|
231
- | `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). |
266
+ | `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). Takes `prompt` and `reauthenticate=false` too ([below](#asking-for-the-password-again)). |
232
267
  | `GET /auth/callback` | Finishes it: the redirect URI you registered. |
233
268
  | `POST /auth/logout` | Revokes the refresh token and ends this app's session. With `signOutOfIdp=true`, the auth server's too. |
234
269
  | `POST /auth/refresh` | New tokens now, then back to the form's `returnTo`. |
235
270
 
236
271
  The POST routes accept forms from this app's own pages only (they check `Origin`).
237
272
 
273
+ ### Asking for the password again
274
+
275
+ `GET /auth/login?prompt=login` makes the auth server ask for the password even while its own
276
+ session is still live; `consent` shows the consent screen again; `select_account` asks which
277
+ account. Several go together, separated by spaces (`prompt=login consent`). Any other value
278
+ (`none` included) is left out, and nothing else in the query reaches the auth server.
279
+
280
+ Signing out of the app alone leaves the auth server's session live, so by default the next
281
+ sign-in goes straight through: on a shared computer, as the person before. With
282
+ `reauthenticateAfterSignOut: true`, signing out leaves a small cookie
283
+ (`__Secure-nextidp.signed-out` on https, on `basePath` only, 30 days; its value means
284
+ nothing) and the next sign-in sends `prompt=login`, once.
285
+
286
+ A "Create account" link starts at `/auth/login` too, and `prompt=login` would show the
287
+ sign-in form again once the account exists. Opt it out with `reauthenticate=false`: no
288
+ `prompt`, and the cookie stays for the next real sign-in. A `prompt` in the link wins over the
289
+ cookie.
290
+
291
+ ```tsx
292
+ <a href="/auth/login?reauthenticate=false">Create account</a>
293
+ <a href={auth.signInPath("/settings", { prompt: "consent" })}>Review permissions</a>
294
+ ```
295
+
296
+ `auth.signInPath(returnTo, { prompt, reauthenticate })` builds these links.
297
+
238
298
  ## The session
239
299
 
240
300
  ```ts
@@ -251,6 +311,14 @@ type Session = {
251
311
  The refresh token and the ID token stay inside the encrypted cookie: nothing in the browser
252
312
  can read them.
253
313
 
314
+ `user` comes from the ID token's claims. Some auth servers (Next-Identity Server among them) put
315
+ the email and the name in userinfo instead: with `userinfo: true`, nextidp asks userinfo after
316
+ sign-in, and again when a refresh brings a new ID token, and fills `user`'s `email`,
317
+ `emailVerified`, `name` and `picture` from it (only those, so the cookie stays small; an email
318
+ comes with userinfo's own `email_verified` or none). If userinfo fails, or answers for another
319
+ `sub`, the sign-in goes ahead with what the ID token had, and `onError` is told. `claims`
320
+ stays the ID token's.
321
+
254
322
  ## All the settings
255
323
 
256
324
  Pass them to `idp({...})`, or set the variable in brackets. A function works too,
@@ -272,6 +340,8 @@ Pass them to `idp({...})`, or set the variable in brackets. A function works too
272
340
  | `afterSignOut` | `/` | Where sign-out lands: also the post-logout redirect URI. |
273
341
  | `errorPath` | `/` | Where a failed sign-in lands, with `?error=<code>`. |
274
342
  | `signOutOfIdp` | `false` | Sign out of the auth server too, unless the form says otherwise. |
343
+ | `reauthenticateAfterSignOut` | `false` | After a sign-out, the next sign-in asks for the password again (`prompt=login`), unless its link says `reauthenticate=false` ([above](#asking-for-the-password-again)). |
344
+ | `userinfo` | `false` | Fill the session's email, name and picture from userinfo: one more request at sign-in, and at each refresh that brings a new ID token ([above](#the-session)). |
275
345
  | `sessionMaxAge` | 7 days | Renewed at every refresh. |
276
346
  | `cookiePrefix` | `nextidp` | Cookies are `__Host-nextidp.session` on https. |
277
347
  | `store` | none: sessions live in the cookie | Keep sessions in a store instead ([below](#sessions-in-a-store-and-back-channel-logout)). |
@@ -357,6 +427,18 @@ app.get("/orders", auth.requireToken({ scopes: ["orders:read"] }), (req, res) =>
357
427
  });
358
428
  ```
359
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
+
360
442
  **A Next.js route handler:**
361
443
 
362
444
  ```ts
@@ -405,7 +487,7 @@ IDP_RESOURCE=https://orders.example.com # optional: the API, when a call names
405
487
  ```
406
488
 
407
489
  ```ts
408
- 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
409
491
 
410
492
  const auth = idp();
411
493
 
@@ -466,7 +548,7 @@ server can't end it, and signing out can't take back a copy of the cookie. Give
466
548
  `store` and sessions live there instead, with only a sealed reference in the cookie:
467
549
 
468
550
  ```ts
469
- 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
470
552
 
471
553
  export const auth = idp({ store: memoryStore() }); // one process only: use Redis to share
472
554
  ```
@@ -42,6 +42,21 @@ export type IdpOptions = {
42
42
  errorPath?: string | undefined;
43
43
  /** Sign out of the auth server too, by default. A form field can still choose. Default false. */
44
44
  signOutOfIdp?: boolean | undefined;
45
+ /**
46
+ * After someone signs out of this app, the next sign-in asks for their password again
47
+ * (`prompt=login`), even while their session at the auth server is still live: on a shared
48
+ * computer, the next person isn't signed in as them. A small cookie remembers the sign-out.
49
+ * A sign-in link opts out with `?reauthenticate=false` (a "Create account" link). Default
50
+ * false.
51
+ */
52
+ reauthenticateAfterSignOut?: boolean | undefined;
53
+ /**
54
+ * Also read the email, name and picture from the userinfo endpoint after sign-in (and after
55
+ * a refresh that brings a new ID token), for auth servers that leave them out of the ID
56
+ * token. Best effort: if it fails, the sign-in goes ahead with what the ID token had, and
57
+ * `onError` is told. Costs one more request. Default false.
58
+ */
59
+ userinfo?: boolean | undefined;
45
60
  /** How long the session cookie lasts, in seconds, renewed at every refresh. Default 7 days. */
46
61
  sessionMaxAge?: number | undefined;
47
62
  /** The start of this app's cookie names. Default `nextidp`. */
@@ -99,12 +114,16 @@ export type IdpConfig = {
99
114
  postLogoutRedirectUri: string;
100
115
  errorPath: string;
101
116
  signOutOfIdp: boolean;
117
+ reauthenticateAfterSignOut: boolean;
118
+ userinfo: boolean;
102
119
  sessionMaxAge: number;
103
- /** https: cookies are Secure, with `__Host-` names. */
120
+ /** https: cookies are Secure, with `__Host-` names (`__Secure-` for `signedOut`). */
104
121
  secure: boolean;
122
+ /** `signedOut` is the marker `reauthenticateAfterSignOut` sets, on `basePath` only. */
105
123
  cookies: {
106
124
  session: string;
107
125
  flow: string;
126
+ signedOut: string;
108
127
  };
109
128
  store: SessionStore | undefined;
110
129
  /** Where the auth server sends logout tokens, with a store. */
@@ -217,9 +217,16 @@ function resolveConfig(options) {
217
217
  postLogoutRedirectUri: `${appUrl}${afterSignOut}`,
218
218
  errorPath,
219
219
  signOutOfIdp: options.signOutOfIdp ?? false,
220
+ reauthenticateAfterSignOut: options.reauthenticateAfterSignOut ?? false,
221
+ userinfo: options.userinfo ?? false,
220
222
  sessionMaxAge,
221
223
  secure,
222
- cookies: { session: name("session"), flow: name("flow") },
224
+ cookies: {
225
+ session: name("session"),
226
+ flow: name("flow"),
227
+ // Path=<basePath>, which a __Host- name doesn't allow: __Secure- keeps it https-only.
228
+ signedOut: `${secure ? "__Secure-" : ""}${prefix}.signed-out`
229
+ },
223
230
  store,
224
231
  backchannelLogoutUri: `${appUrl}${basePath}/backchannel-logout`
225
232
  };
@@ -3,9 +3,11 @@ export declare const CHUNK_SIZE = 3800;
3
3
  export type CookieJar = ReadonlyMap<string, string>;
4
4
  /** The cookies a request carries. When a name comes twice, the first is kept. */
5
5
  export declare function parseCookies(header: string | null | undefined): CookieJar;
6
+ /** `path` defaults to `/`. */
6
7
  export type CookieAttributes = {
7
8
  secure: boolean;
8
9
  maxAge: number;
10
+ path?: string;
9
11
  };
10
12
  /** A value written by `writeCookie`: the one cookie, or its chunks joined in order. */
11
13
  export declare function readCookie(jar: CookieJar, name: string): string | undefined;
@@ -15,7 +17,7 @@ export declare function readCookie(jar: CookieJar, name: string): string | undef
15
17
  */
16
18
  export declare function writeCookie(jar: CookieJar, name: string, value: string, attributes: CookieAttributes): string[];
17
19
  /** Set-Cookie headers that expire `name` and every chunk of it the request holds. */
18
- export declare function clearCookie(jar: CookieJar, name: string, secure: boolean): string[];
20
+ export declare function clearCookie(jar: CookieJar, name: string, secure: boolean, path?: string): string[];
19
21
  /**
20
22
  * The Cookie header the rest of this request should see once `setCookies` apply: what a
21
23
  * proxy hands on, so the page renders with the refreshed session and not the old one.
@@ -41,10 +41,10 @@ function parseCookies(header) {
41
41
  }
42
42
  return jar;
43
43
  }
44
- function serialize(name, value, { secure, maxAge }) {
44
+ function serialize(name, value, { secure, maxAge, path = "/" }) {
45
45
  return [
46
46
  `${name}=${value}`,
47
- "Path=/",
47
+ `Path=${path}`,
48
48
  `Max-Age=${maxAge}`,
49
49
  "HttpOnly",
50
50
  "SameSite=Lax",
@@ -90,9 +90,9 @@ function writeCookie(jar, name, value, attributes) {
90
90
  }
91
91
  return headers;
92
92
  }
93
- function clearCookie(jar, name, secure) {
93
+ function clearCookie(jar, name, secure, path = "/") {
94
94
  const names = /* @__PURE__ */ new Set([name, ...chunkNames(jar, name)]);
95
- return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0 }));
95
+ return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0, path }));
96
96
  }
97
97
  function applySetCookies(header, setCookies) {
98
98
  const jar = new Map(parseCookies(header));
@@ -64,7 +64,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): ExpressI
64
64
  export type { AccessToken, TokenRequirements } from "./access-token.js";
65
65
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
66
66
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
67
- export type { Idp, Refreshed } from "./idp.js";
67
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
68
68
  export type { SessionOptions } from "./node-adapter.js";
69
69
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
70
70
  export type { IdpUser, Session } from "./session.js";
@@ -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
+ });
@@ -59,7 +59,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): HonoIdp;
59
59
  export type { AccessToken, TokenRequirements } from "./access-token.js";
60
60
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
61
61
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
62
- export type { Idp, Refreshed } from "./idp.js";
62
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
63
63
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
64
64
  export type { IdpUser, Session } from "./session.js";
65
65
  export { memoryStore, type SessionStore } from "./store.js";
package/dist/cjs/idp.d.ts CHANGED
@@ -34,8 +34,13 @@ export type Idp = {
34
34
  }): Promise<Refreshed>;
35
35
  /** The userinfo endpoint's claims for an access token. */
36
36
  userInfo(accessToken: string): Promise<Record<string, unknown>>;
37
- /** The path that starts a sign-in, returning to `returnTo` (a path of this app) after. */
38
- signInPath(returnTo?: string): string;
37
+ /**
38
+ * The path that starts a sign-in, returning to `returnTo` (a path of this app) after.
39
+ * `prompt` asks the auth server for `login`, `consent` or `select_account` (others are left
40
+ * out); `reauthenticate: false` is for a "Create account" link, which mustn't ask for a
41
+ * password again after a sign-out (see `reauthenticateAfterSignOut`).
42
+ */
43
+ signInPath(returnTo?: string, options?: SignInPathOptions): string;
39
44
  /** For an API: the checked settings it needs (issuer and audience). */
40
45
  apiConfig(): ApiConfig;
41
46
  /**
@@ -73,6 +78,13 @@ export type Idp = {
73
78
  */
74
79
  useServiceToken(client: InterceptableClient, options?: UseServiceTokenOptions): () => void;
75
80
  };
81
+ /** What `signInPath` can add to the sign-in link. */
82
+ export type SignInPathOptions = {
83
+ /** `login`, `consent` or `select_account`, or several separated by spaces. */
84
+ prompt?: string | undefined;
85
+ /** false: no `prompt=login` from an earlier sign-out (see `reauthenticateAfterSignOut`). */
86
+ reauthenticate?: boolean | undefined;
87
+ };
76
88
  /**
77
89
  * The client for one app. Settings are checked on first use, not here, so a module that
78
90
  * calls `idp()` can be imported where they aren't set (a build). Pass a function to read