nextidp 0.1.3 → 0.1.4

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,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Sign-in
6
+
7
+ - `GET <basePath>/login?prompt=…` passes `prompt` on to the auth server: `login`, `consent`
8
+ or `select_account`, or several separated by spaces. Any other value, `none` included, is
9
+ left out, and nothing else in the query is passed on. `signInPath(returnTo, { prompt })`
10
+ builds the link.
11
+ - `reauthenticateAfterSignOut` (default `false`): a sign-out leaves a small marker cookie
12
+ (`<prefix>.signed-out`, `__Secure-` on https, on `basePath` only, 30 days), and the next
13
+ sign-in sends `prompt=login` and clears it, so a shared computer doesn't sign the next person
14
+ in as the last. A link with `reauthenticate=false` (a "Create account" link) opts out and
15
+ leaves the marker; a `prompt` in the link wins over it.
16
+ - `userinfo` (default `false`): the email, `email_verified`, name and picture from the
17
+ userinfo endpoint, merged into `session.user` after sign-in and after a refresh that brings
18
+ a new ID token (kept otherwise), for auth servers that leave them out of the ID token.
19
+ Best effort: a failure, or an answer about another `sub`, goes to `onError` and the
20
+ sign-in goes ahead. `session.claims` stays the ID token's.
21
+
22
+ ### Next.js
23
+
24
+ - `routes()` answers a fetch of the login route by Next's client router (a `<Link>`,
25
+ `router.push` or a prefetch: the `rsc` header) with a 200 "Sign-in needs a full page load."
26
+ and no cookie, instead of a redirect it can't follow. The router then loads it as a whole
27
+ page, and a sign-in under way keeps its flow cookie.
28
+
3
29
  ## 0.1.3
4
30
 
5
31
  ### Hono, and edge runtimes
package/README.md CHANGED
@@ -99,6 +99,13 @@ export default async function Dashboard() {
99
99
  </form>
100
100
  ```
101
101
 
102
+ Link to `/auth/login` with a plain `<a>`, as above. A `<Link>`, a `router.push` or a prefetch
103
+ makes Next's client router fetch the route itself, and that fetch can't follow the redirect to
104
+ the auth server (another origin). So `auth.routes()` answers such a fetch (it carries the
105
+ `rsc` header) with a plain 200, "Sign-in needs a full page load.", and no cookie: the router
106
+ then loads the address as a whole page, which signs in as usual, and a sign-in already under
107
+ way keeps its cookie.
108
+
102
109
  Calling an API as the signed-in person:
103
110
 
104
111
  ```ts
@@ -228,13 +235,38 @@ All under `basePath` (default `/auth`):
228
235
 
229
236
  | Route | What it does |
230
237
  |---|---|
231
- | `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). |
238
+ | `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
239
  | `GET /auth/callback` | Finishes it: the redirect URI you registered. |
233
240
  | `POST /auth/logout` | Revokes the refresh token and ends this app's session. With `signOutOfIdp=true`, the auth server's too. |
234
241
  | `POST /auth/refresh` | New tokens now, then back to the form's `returnTo`. |
235
242
 
236
243
  The POST routes accept forms from this app's own pages only (they check `Origin`).
237
244
 
245
+ ### Asking for the password again
246
+
247
+ `GET /auth/login?prompt=login` makes the auth server ask for the password even while its own
248
+ session is still live; `consent` shows the consent screen again; `select_account` asks which
249
+ account. Several go together, separated by spaces (`prompt=login consent`). Any other value
250
+ (`none` included) is left out, and nothing else in the query reaches the auth server.
251
+
252
+ Signing out of the app alone leaves the auth server's session live, so by default the next
253
+ sign-in goes straight through: on a shared computer, as the person before. With
254
+ `reauthenticateAfterSignOut: true`, signing out leaves a small cookie
255
+ (`__Secure-nextidp.signed-out` on https, on `basePath` only, 30 days; its value means
256
+ nothing) and the next sign-in sends `prompt=login`, once.
257
+
258
+ A "Create account" link starts at `/auth/login` too, and `prompt=login` would show the
259
+ sign-in form again once the account exists. Opt it out with `reauthenticate=false`: no
260
+ `prompt`, and the cookie stays for the next real sign-in. A `prompt` in the link wins over the
261
+ cookie.
262
+
263
+ ```tsx
264
+ <a href="/auth/login?reauthenticate=false">Create account</a>
265
+ <a href={auth.signInPath("/settings", { prompt: "consent" })}>Review permissions</a>
266
+ ```
267
+
268
+ `auth.signInPath(returnTo, { prompt, reauthenticate })` builds these links.
269
+
238
270
  ## The session
239
271
 
240
272
  ```ts
@@ -251,6 +283,14 @@ type Session = {
251
283
  The refresh token and the ID token stay inside the encrypted cookie: nothing in the browser
252
284
  can read them.
253
285
 
286
+ `user` comes from the ID token's claims. Some auth servers (authserver-oidc among them) put
287
+ the email and the name in userinfo instead: with `userinfo: true`, nextidp asks userinfo after
288
+ sign-in, and again when a refresh brings a new ID token, and fills `user`'s `email`,
289
+ `emailVerified`, `name` and `picture` from it (only those, so the cookie stays small; an email
290
+ comes with userinfo's own `email_verified` or none). If userinfo fails, or answers for another
291
+ `sub`, the sign-in goes ahead with what the ID token had, and `onError` is told. `claims`
292
+ stays the ID token's.
293
+
254
294
  ## All the settings
255
295
 
256
296
  Pass them to `idp({...})`, or set the variable in brackets. A function works too,
@@ -272,6 +312,8 @@ Pass them to `idp({...})`, or set the variable in brackets. A function works too
272
312
  | `afterSignOut` | `/` | Where sign-out lands: also the post-logout redirect URI. |
273
313
  | `errorPath` | `/` | Where a failed sign-in lands, with `?error=<code>`. |
274
314
  | `signOutOfIdp` | `false` | Sign out of the auth server too, unless the form says otherwise. |
315
+ | `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)). |
316
+ | `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
317
  | `sessionMaxAge` | 7 days | Renewed at every refresh. |
276
318
  | `cookiePrefix` | `nextidp` | Cookies are `__Host-nextidp.session` on https. |
277
319
  | `store` | none: sessions live in the cookie | Keep sessions in a store instead ([below](#sessions-in-a-store-and-back-channel-logout)). |
@@ -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";
@@ -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
package/dist/cjs/idp.js CHANGED
@@ -36,6 +36,14 @@ var import_service = require("./service.js");
36
36
  var import_session = require("./session.js");
37
37
  var import_store = require("./store.js");
38
38
  var import_tokens = require("./tokens.js");
39
+ const PROMPTS = /* @__PURE__ */ new Set(["login", "consent", "select_account"]);
40
+ function promptFrom(value) {
41
+ if (!value) return void 0;
42
+ const values = value.split(" ").filter(Boolean);
43
+ if (values.length === 0 || !values.every((each) => PROMPTS.has(each))) return void 0;
44
+ return [...new Set(values)].join(" ");
45
+ }
46
+ const SIGNED_OUT_MAX_AGE = 30 * 24 * 60 * 60;
39
47
  const INTROSPECTION_CACHE_MS = 6e4;
40
48
  const INTROSPECTION_CACHE_SIZE = 1e3;
41
49
  async function sha256(value) {
@@ -177,7 +185,7 @@ function createIdp(options = {}) {
177
185
  nonce,
178
186
  algorithms: discovery.id_token_signing_alg_values_supported
179
187
  });
180
- const storedFrom = (tokens, claims, previous) => {
188
+ const storedFrom = (tokens, claims, previous, profile) => {
181
189
  const stored = {
182
190
  claims,
183
191
  accessToken: tokens.access_token,
@@ -186,11 +194,27 @@ function createIdp(options = {}) {
186
194
  const refreshToken = tokens.refresh_token ?? previous?.refreshToken;
187
195
  const idToken = tokens.id_token ?? previous?.idToken;
188
196
  const scope = tokens.scope ?? previous?.scope;
197
+ const kept = profile ?? previous?.profile;
189
198
  if (refreshToken) stored.refreshToken = refreshToken;
190
199
  if (idToken) stored.idToken = idToken;
191
200
  if (scope) stored.scope = scope;
201
+ if (kept) stored.profile = kept;
192
202
  return stored;
193
203
  };
204
+ const profileFor = async (s, discovery, accessToken, sub) => {
205
+ if (!s.config.userinfo) return void 0;
206
+ try {
207
+ const answer = await (0, import_tokens.fetchUserInfo)(s.http, discovery, accessToken);
208
+ if (typeof sub !== "string" || answer.sub !== sub) {
209
+ fail(new import_errors.IdpError("userinfo_failed", "The userinfo answer is for another subject."));
210
+ return void 0;
211
+ }
212
+ return (0, import_session.profileFrom)(answer);
213
+ } catch (error) {
214
+ fail(error);
215
+ return void 0;
216
+ }
217
+ };
194
218
  const refreshStored = (s, stored) => {
195
219
  const refreshToken = stored.refreshToken;
196
220
  if (!refreshToken) {
@@ -207,14 +231,16 @@ function createIdp(options = {}) {
207
231
  resource: s.config.resource
208
232
  });
209
233
  let claims = stored.claims;
234
+ let profile;
210
235
  if (tokens.id_token) {
211
236
  const fresh = await verify(s, discovery, tokens.id_token);
212
237
  if (fresh.sub !== stored.claims.sub) {
213
238
  throw new import_errors.IdpError("refresh_failed", "The refreshed ID token is for someone else.");
214
239
  }
215
240
  claims = fresh;
241
+ profile = await profileFor(s, discovery, tokens.access_token, fresh.sub);
216
242
  }
217
- return storedFrom(tokens, claims, stored);
243
+ return storedFrom(tokens, claims, stored, profile);
218
244
  })();
219
245
  s.refreshing.set(refreshToken, { result, until: now + REFRESH_SHARE_MS });
220
246
  result.catch(() => s.refreshing.delete(refreshToken));
@@ -225,8 +251,27 @@ function createIdp(options = {}) {
225
251
  const latest = await s.backend.load(jar);
226
252
  return latest?.stored.refreshToken && latest.stored.refreshToken !== stale.refreshToken ? latest : void 0;
227
253
  };
228
- async function login(s, url) {
254
+ function promptOf(s, request, url) {
255
+ const { signedOut } = s.config.cookies;
256
+ const jar = (0, import_cookies.parseCookies)(request.headers.get("cookie"));
257
+ const marked = jar.has(signedOut);
258
+ const clear = () => (0, import_cookies.clearCookie)(jar, signedOut, s.config.secure, s.config.basePath);
259
+ const asked = promptFrom(url.searchParams.get("prompt"));
260
+ if (asked) {
261
+ const usedUp = marked && asked.split(" ").includes("login");
262
+ return { prompt: asked, setCookies: usedUp ? clear() : [] };
263
+ }
264
+ if (url.searchParams.get("reauthenticate") === "false" || !marked) {
265
+ return { prompt: void 0, setCookies: [] };
266
+ }
267
+ return {
268
+ prompt: s.config.reauthenticateAfterSignOut ? "login" : void 0,
269
+ setCookies: clear()
270
+ };
271
+ }
272
+ async function login(s, request, url) {
229
273
  const returnTo = (0, import_return_path.safePath)(url.searchParams.get("returnTo")) ?? s.config.afterSignIn;
274
+ const { prompt, setCookies } = promptOf(s, request, url);
230
275
  let discovery;
231
276
  try {
232
277
  discovery = await s.discovery();
@@ -245,18 +290,18 @@ function createIdp(options = {}) {
245
290
  nonce: flow.nonce,
246
291
  code_challenge: await (0, import_pkce.challengeFor)(flow.verifier),
247
292
  code_challenge_method: "S256",
248
- ...s.config.resource ? { resource: s.config.resource } : {}
293
+ ...s.config.resource ? { resource: s.config.resource } : {},
294
+ ...prompt ? { prompt } : {}
249
295
  }).toString();
250
296
  const sealed = await s.sealer.seal(flow, import_session.FLOW_PURPOSE, import_session.FLOW_MAX_AGE);
251
- return redirect(
252
- authorize.toString(),
253
- 302,
297
+ return redirect(authorize.toString(), 302, [
254
298
  // Lax: the cookie comes back on the top-level redirect from the auth server.
255
- (0, import_cookies.writeCookie)(/* @__PURE__ */ new Map(), s.config.cookies.flow, sealed, {
299
+ ...(0, import_cookies.writeCookie)(/* @__PURE__ */ new Map(), s.config.cookies.flow, sealed, {
256
300
  secure: s.config.secure,
257
301
  maxAge: import_session.FLOW_MAX_AGE
258
- })
259
- );
302
+ }),
303
+ ...setCookies
304
+ ]);
260
305
  }
261
306
  async function callback(s, request, url) {
262
307
  const jar = (0, import_cookies.parseCookies)(request.headers.get("cookie"));
@@ -287,7 +332,8 @@ function createIdp(options = {}) {
287
332
  throw new import_errors.IdpError("invalid_id_token", "No ID token came back: was openid asked for?");
288
333
  }
289
334
  const claims = await verify(s, discovery, tokens.id_token, flow.nonce);
290
- const session = await s.backend.create(jar, storedFrom(tokens, claims));
335
+ const profile = await profileFor(s, discovery, tokens.access_token, claims.sub);
336
+ const session = await s.backend.create(jar, storedFrom(tokens, claims, void 0, profile));
291
337
  return redirect(new URL(flow.returnTo, s.config.appUrl).toString(), 302, [
292
338
  ...done,
293
339
  ...session
@@ -305,7 +351,15 @@ function createIdp(options = {}) {
305
351
  const signOutOfIdp = choice === "true" ? true : choice === "false" ? false : s.config.signOutOfIdp;
306
352
  const jar = (0, import_cookies.parseCookies)(request.headers.get("cookie"));
307
353
  const stored = (await s.backend.load(jar))?.stored;
308
- const cleared = await s.backend.remove(jar);
354
+ const cleared = [
355
+ ...await s.backend.remove(jar),
356
+ // The next sign-in asks for the password again (reauthenticateAfterSignOut).
357
+ ...s.config.reauthenticateAfterSignOut ? (0, import_cookies.writeCookie)(/* @__PURE__ */ new Map(), s.config.cookies.signedOut, "1", {
358
+ secure: s.config.secure,
359
+ maxAge: SIGNED_OUT_MAX_AGE,
360
+ path: s.config.basePath
361
+ }) : []
362
+ ];
309
363
  const home = new URL(s.config.afterSignOut, s.config.appUrl).toString();
310
364
  let discovery;
311
365
  try {
@@ -391,7 +445,7 @@ function createIdp(options = {}) {
391
445
  const only = (allowed, run) => method === allowed ? run() : Promise.resolve(plain(405, "Method not allowed", { allow: allowed }));
392
446
  switch (route) {
393
447
  case "/login":
394
- return only("GET", () => login(s, url));
448
+ return only("GET", () => login(s, request, url));
395
449
  case "/callback":
396
450
  return only("GET", () => callback(s, request, url));
397
451
  case "/logout":
@@ -468,11 +522,16 @@ function createIdp(options = {}) {
468
522
  useServiceToken(client, options2) {
469
523
  return (0, import_service.useServiceToken)(serviceReady(), client, options2);
470
524
  },
471
- signInPath(returnTo) {
525
+ signInPath(returnTo, options2 = {}) {
472
526
  const s = ready();
527
+ const query = new URLSearchParams();
473
528
  const safe = (0, import_return_path.safePath)(returnTo);
529
+ const prompt = promptFrom(options2.prompt);
530
+ if (safe) query.set("returnTo", safe);
531
+ if (prompt) query.set("prompt", prompt);
532
+ if (options2.reauthenticate === false) query.set("reauthenticate", "false");
474
533
  const login2 = `${s.config.basePath}/login`;
475
- return safe ? `${login2}?${new URLSearchParams({ returnTo: safe })}` : login2;
534
+ return query.size > 0 ? `${login2}?${query}` : login2;
476
535
  }
477
536
  };
478
537
  }
@@ -2,7 +2,7 @@ export { type AccessToken, bearerChallenge, bearerToken, type TokenRequirements,
2
2
  export type { ApiConfig, IdpConfig, IdpOptions, ServiceConfig } from "./config.js";
3
3
  export { DEFAULT_SCOPES } from "./config.js";
4
4
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
5
- export { type CookieSource, createIdp as idp, type Idp, type Refreshed, } from "./idp.js";
5
+ export { type CookieSource, createIdp as idp, type Idp, type Refreshed, type SignInPathOptions, } from "./idp.js";
6
6
  export { safePath } from "./return-path.js";
7
7
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
8
8
  export type { IdpUser, Session } from "./session.js";
@@ -55,7 +55,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): NextIdp;
55
55
  export type { AccessToken, TokenRequirements } from "./access-token.js";
56
56
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
57
57
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
58
- export type { Idp, Refreshed } from "./idp.js";
58
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
59
59
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
60
60
  export type { IdpUser, Session } from "./session.js";
61
61
  export { memoryStore, type SessionStore } from "./store.js";
package/dist/cjs/next.js CHANGED
@@ -41,8 +41,22 @@ function isProtected(protect, pathname) {
41
41
  }
42
42
  function idp(options) {
43
43
  const core = (0, import_idp.createIdp)(options);
44
+ const isRouterFetchOfLogin = (request) => {
45
+ if (request.method.toUpperCase() !== "GET" || !request.headers.has("rsc")) return false;
46
+ try {
47
+ return new URL(request.url).pathname === `${core.config().basePath}/login`;
48
+ } catch {
49
+ return false;
50
+ }
51
+ };
44
52
  const handle = async (request) => {
45
53
  await (0, import_server.connection)();
54
+ if (isRouterFetchOfLogin(request)) {
55
+ return new Response("Sign-in needs a full page load.", {
56
+ status: 200,
57
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }
58
+ });
59
+ }
46
60
  return core.handler(request);
47
61
  };
48
62
  const session = async () => {
@@ -43,7 +43,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): NodeIdp;
43
43
  export type { AccessToken, TokenRequirements } from "./access-token.js";
44
44
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
45
45
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
46
- export type { Idp, Refreshed } from "./idp.js";
46
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
47
47
  export type { SessionOptions } from "./node-adapter.js";
48
48
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
49
49
  export type { IdpUser, Session } from "./session.js";
@@ -12,6 +12,19 @@ declare const FlowSchema: v.ObjectSchema<{
12
12
  }, undefined>;
13
13
  export type Flow = v.InferOutput<typeof FlowSchema>;
14
14
  export declare function parseFlow(payload: unknown): Flow | undefined;
15
+ /**
16
+ * What userinfo said about the person (the `userinfo` option): only these fields, so the
17
+ * cookie stays small. Kept apart from `claims`, which are the ID token's alone.
18
+ */
19
+ declare const ProfileSchema: v.ObjectSchema<{
20
+ readonly email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
21
+ readonly email_verified: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
22
+ readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
23
+ readonly picture: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
24
+ }, undefined>;
25
+ export type Profile = v.InferOutput<typeof ProfileSchema>;
26
+ /** The profile fields of a userinfo answer, and nothing else; undefined if it has none. */
27
+ export declare function profileFrom(answer: Record<string, unknown>): Profile | undefined;
15
28
  declare const StoredSessionSchema: v.ObjectSchema<{
16
29
  readonly claims: v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>;
17
30
  readonly accessToken: v.StringSchema<undefined>;
@@ -21,10 +34,20 @@ declare const StoredSessionSchema: v.ObjectSchema<{
21
34
  /** As received: the hint when signing out of the auth server too. */
22
35
  readonly idToken: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
23
36
  readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
37
+ /** From userinfo, when the `userinfo` option is on. */
38
+ readonly profile: v.OptionalSchema<v.ObjectSchema<{
39
+ readonly email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
40
+ readonly email_verified: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
41
+ readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
42
+ readonly picture: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
43
+ }, undefined>, undefined>;
24
44
  }, undefined>;
25
45
  export type StoredSession = v.InferOutput<typeof StoredSessionSchema>;
26
46
  export declare function parseStoredSession(payload: unknown): StoredSession | undefined;
27
- /** The person signed in, from the ID token's standard claims. */
47
+ /**
48
+ * The person signed in, from the ID token's standard claims, and from userinfo with the
49
+ * `userinfo` option (which wins where it has a value).
50
+ */
28
51
  export type IdpUser = {
29
52
  /** The `sub` claim: stable for this person at this auth server. */
30
53
  id: string;
@@ -33,6 +33,7 @@ __export(session_exports, {
33
33
  SESSION_PURPOSE: () => SESSION_PURPOSE,
34
34
  parseFlow: () => parseFlow,
35
35
  parseStoredSession: () => parseStoredSession,
36
+ profileFrom: () => profileFrom,
36
37
  toSession: () => toSession
37
38
  });
38
39
  module.exports = __toCommonJS(session_exports);
@@ -50,6 +51,27 @@ function parseFlow(payload) {
50
51
  const parsed = v.safeParse(FlowSchema, payload);
51
52
  return parsed.success ? parsed.output : void 0;
52
53
  }
54
+ const ProfileSchema = v.object({
55
+ email: v.optional(v.string()),
56
+ email_verified: v.optional(v.boolean()),
57
+ name: v.optional(v.string()),
58
+ picture: v.optional(v.string())
59
+ });
60
+ const MAX_PROFILE_TEXT = 1024;
61
+ function short(value) {
62
+ return typeof value === "string" && value && value.length <= MAX_PROFILE_TEXT ? value : void 0;
63
+ }
64
+ function profileFrom(answer) {
65
+ const profile = {};
66
+ const email = short(answer.email);
67
+ const name = short(answer.name);
68
+ const picture = short(answer.picture);
69
+ if (email) profile.email = email;
70
+ if (typeof answer.email_verified === "boolean") profile.email_verified = answer.email_verified;
71
+ if (name) profile.name = name;
72
+ if (picture) profile.picture = picture;
73
+ return Object.keys(profile).length > 0 ? profile : void 0;
74
+ }
53
75
  const StoredSessionSchema = v.object({
54
76
  claims: v.record(v.string(), v.unknown()),
55
77
  accessToken: v.string(),
@@ -58,7 +80,9 @@ const StoredSessionSchema = v.object({
58
80
  refreshToken: v.optional(v.string()),
59
81
  /** As received: the hint when signing out of the auth server too. */
60
82
  idToken: v.optional(v.string()),
61
- scope: v.optional(v.string())
83
+ scope: v.optional(v.string()),
84
+ /** From userinfo, when the `userinfo` option is on. */
85
+ profile: v.optional(ProfileSchema)
62
86
  });
63
87
  function parseStoredSession(payload) {
64
88
  const parsed = v.safeParse(StoredSessionSchema, payload);
@@ -69,12 +93,15 @@ function text(value) {
69
93
  }
70
94
  function toSession(stored) {
71
95
  const claims = stored.claims;
96
+ const profile = stored.profile;
72
97
  const user = { id: String(claims.sub ?? "") };
73
- const email = text(claims.email);
74
- const name = text(claims.name);
75
- const picture = text(claims.picture);
98
+ const fromProfile = Boolean(text(profile?.email));
99
+ const email = fromProfile ? text(profile?.email) : text(claims.email);
100
+ const emailVerified = fromProfile ? profile?.email_verified : claims.email_verified;
101
+ const name = text(profile?.name) ?? text(claims.name);
102
+ const picture = text(profile?.picture) ?? text(claims.picture);
76
103
  if (email) user.email = email;
77
- if (typeof claims.email_verified === "boolean") user.emailVerified = claims.email_verified;
104
+ if (typeof emailVerified === "boolean") user.emailVerified = emailVerified;
78
105
  if (name) user.name = name;
79
106
  if (picture) user.picture = picture;
80
107
  return {
@@ -93,5 +120,6 @@ function toSession(stored) {
93
120
  SESSION_PURPOSE,
94
121
  parseFlow,
95
122
  parseStoredSession,
123
+ profileFrom,
96
124
  toSession
97
125
  });
@@ -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. */
@@ -191,9 +191,16 @@ function resolveConfig(options) {
191
191
  postLogoutRedirectUri: `${appUrl}${afterSignOut}`,
192
192
  errorPath,
193
193
  signOutOfIdp: options.signOutOfIdp ?? false,
194
+ reauthenticateAfterSignOut: options.reauthenticateAfterSignOut ?? false,
195
+ userinfo: options.userinfo ?? false,
194
196
  sessionMaxAge,
195
197
  secure,
196
- cookies: { session: name("session"), flow: name("flow") },
198
+ cookies: {
199
+ session: name("session"),
200
+ flow: name("flow"),
201
+ // Path=<basePath>, which a __Host- name doesn't allow: __Secure- keeps it https-only.
202
+ signedOut: `${secure ? "__Secure-" : ""}${prefix}.signed-out`
203
+ },
197
204
  store,
198
205
  backchannelLogoutUri: `${appUrl}${basePath}/backchannel-logout`
199
206
  };
@@ -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.
@@ -13,10 +13,10 @@ function parseCookies(header) {
13
13
  }
14
14
  return jar;
15
15
  }
16
- function serialize(name, value, { secure, maxAge }) {
16
+ function serialize(name, value, { secure, maxAge, path = "/" }) {
17
17
  return [
18
18
  `${name}=${value}`,
19
- "Path=/",
19
+ `Path=${path}`,
20
20
  `Max-Age=${maxAge}`,
21
21
  "HttpOnly",
22
22
  "SameSite=Lax",
@@ -62,9 +62,9 @@ function writeCookie(jar, name, value, attributes) {
62
62
  }
63
63
  return headers;
64
64
  }
65
- function clearCookie(jar, name, secure) {
65
+ function clearCookie(jar, name, secure, path = "/") {
66
66
  const names = /* @__PURE__ */ new Set([name, ...chunkNames(jar, name)]);
67
- return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0 }));
67
+ return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0, path }));
68
68
  }
69
69
  function applySetCookies(header, setCookies) {
70
70
  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";
@@ -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/esm/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
package/dist/esm/idp.js CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  FLOW_MAX_AGE,
35
35
  FLOW_PURPOSE,
36
36
  parseFlow,
37
+ profileFrom,
37
38
  toSession
38
39
  } from "./session.js";
39
40
  import { cookieBackend, storeBackend } from "./store.js";
@@ -43,6 +44,14 @@ import {
43
44
  refreshTokens,
44
45
  revokeRefreshToken
45
46
  } from "./tokens.js";
47
+ const PROMPTS = /* @__PURE__ */ new Set(["login", "consent", "select_account"]);
48
+ function promptFrom(value) {
49
+ if (!value) return void 0;
50
+ const values = value.split(" ").filter(Boolean);
51
+ if (values.length === 0 || !values.every((each) => PROMPTS.has(each))) return void 0;
52
+ return [...new Set(values)].join(" ");
53
+ }
54
+ const SIGNED_OUT_MAX_AGE = 30 * 24 * 60 * 60;
46
55
  const INTROSPECTION_CACHE_MS = 6e4;
47
56
  const INTROSPECTION_CACHE_SIZE = 1e3;
48
57
  async function sha256(value) {
@@ -184,7 +193,7 @@ function createIdp(options = {}) {
184
193
  nonce,
185
194
  algorithms: discovery.id_token_signing_alg_values_supported
186
195
  });
187
- const storedFrom = (tokens, claims, previous) => {
196
+ const storedFrom = (tokens, claims, previous, profile) => {
188
197
  const stored = {
189
198
  claims,
190
199
  accessToken: tokens.access_token,
@@ -193,11 +202,27 @@ function createIdp(options = {}) {
193
202
  const refreshToken = tokens.refresh_token ?? previous?.refreshToken;
194
203
  const idToken = tokens.id_token ?? previous?.idToken;
195
204
  const scope = tokens.scope ?? previous?.scope;
205
+ const kept = profile ?? previous?.profile;
196
206
  if (refreshToken) stored.refreshToken = refreshToken;
197
207
  if (idToken) stored.idToken = idToken;
198
208
  if (scope) stored.scope = scope;
209
+ if (kept) stored.profile = kept;
199
210
  return stored;
200
211
  };
212
+ const profileFor = async (s, discovery, accessToken, sub) => {
213
+ if (!s.config.userinfo) return void 0;
214
+ try {
215
+ const answer = await fetchUserInfo(s.http, discovery, accessToken);
216
+ if (typeof sub !== "string" || answer.sub !== sub) {
217
+ fail(new IdpError("userinfo_failed", "The userinfo answer is for another subject."));
218
+ return void 0;
219
+ }
220
+ return profileFrom(answer);
221
+ } catch (error) {
222
+ fail(error);
223
+ return void 0;
224
+ }
225
+ };
201
226
  const refreshStored = (s, stored) => {
202
227
  const refreshToken = stored.refreshToken;
203
228
  if (!refreshToken) {
@@ -214,14 +239,16 @@ function createIdp(options = {}) {
214
239
  resource: s.config.resource
215
240
  });
216
241
  let claims = stored.claims;
242
+ let profile;
217
243
  if (tokens.id_token) {
218
244
  const fresh = await verify(s, discovery, tokens.id_token);
219
245
  if (fresh.sub !== stored.claims.sub) {
220
246
  throw new IdpError("refresh_failed", "The refreshed ID token is for someone else.");
221
247
  }
222
248
  claims = fresh;
249
+ profile = await profileFor(s, discovery, tokens.access_token, fresh.sub);
223
250
  }
224
- return storedFrom(tokens, claims, stored);
251
+ return storedFrom(tokens, claims, stored, profile);
225
252
  })();
226
253
  s.refreshing.set(refreshToken, { result, until: now + REFRESH_SHARE_MS });
227
254
  result.catch(() => s.refreshing.delete(refreshToken));
@@ -232,8 +259,27 @@ function createIdp(options = {}) {
232
259
  const latest = await s.backend.load(jar);
233
260
  return latest?.stored.refreshToken && latest.stored.refreshToken !== stale.refreshToken ? latest : void 0;
234
261
  };
235
- async function login(s, url) {
262
+ function promptOf(s, request, url) {
263
+ const { signedOut } = s.config.cookies;
264
+ const jar = parseCookies(request.headers.get("cookie"));
265
+ const marked = jar.has(signedOut);
266
+ const clear = () => clearCookie(jar, signedOut, s.config.secure, s.config.basePath);
267
+ const asked = promptFrom(url.searchParams.get("prompt"));
268
+ if (asked) {
269
+ const usedUp = marked && asked.split(" ").includes("login");
270
+ return { prompt: asked, setCookies: usedUp ? clear() : [] };
271
+ }
272
+ if (url.searchParams.get("reauthenticate") === "false" || !marked) {
273
+ return { prompt: void 0, setCookies: [] };
274
+ }
275
+ return {
276
+ prompt: s.config.reauthenticateAfterSignOut ? "login" : void 0,
277
+ setCookies: clear()
278
+ };
279
+ }
280
+ async function login(s, request, url) {
236
281
  const returnTo = safePath(url.searchParams.get("returnTo")) ?? s.config.afterSignIn;
282
+ const { prompt, setCookies } = promptOf(s, request, url);
237
283
  let discovery;
238
284
  try {
239
285
  discovery = await s.discovery();
@@ -252,18 +298,18 @@ function createIdp(options = {}) {
252
298
  nonce: flow.nonce,
253
299
  code_challenge: await challengeFor(flow.verifier),
254
300
  code_challenge_method: "S256",
255
- ...s.config.resource ? { resource: s.config.resource } : {}
301
+ ...s.config.resource ? { resource: s.config.resource } : {},
302
+ ...prompt ? { prompt } : {}
256
303
  }).toString();
257
304
  const sealed = await s.sealer.seal(flow, FLOW_PURPOSE, FLOW_MAX_AGE);
258
- return redirect(
259
- authorize.toString(),
260
- 302,
305
+ return redirect(authorize.toString(), 302, [
261
306
  // Lax: the cookie comes back on the top-level redirect from the auth server.
262
- writeCookie(/* @__PURE__ */ new Map(), s.config.cookies.flow, sealed, {
307
+ ...writeCookie(/* @__PURE__ */ new Map(), s.config.cookies.flow, sealed, {
263
308
  secure: s.config.secure,
264
309
  maxAge: FLOW_MAX_AGE
265
- })
266
- );
310
+ }),
311
+ ...setCookies
312
+ ]);
267
313
  }
268
314
  async function callback(s, request, url) {
269
315
  const jar = parseCookies(request.headers.get("cookie"));
@@ -294,7 +340,8 @@ function createIdp(options = {}) {
294
340
  throw new IdpError("invalid_id_token", "No ID token came back: was openid asked for?");
295
341
  }
296
342
  const claims = await verify(s, discovery, tokens.id_token, flow.nonce);
297
- const session = await s.backend.create(jar, storedFrom(tokens, claims));
343
+ const profile = await profileFor(s, discovery, tokens.access_token, claims.sub);
344
+ const session = await s.backend.create(jar, storedFrom(tokens, claims, void 0, profile));
298
345
  return redirect(new URL(flow.returnTo, s.config.appUrl).toString(), 302, [
299
346
  ...done,
300
347
  ...session
@@ -312,7 +359,15 @@ function createIdp(options = {}) {
312
359
  const signOutOfIdp = choice === "true" ? true : choice === "false" ? false : s.config.signOutOfIdp;
313
360
  const jar = parseCookies(request.headers.get("cookie"));
314
361
  const stored = (await s.backend.load(jar))?.stored;
315
- const cleared = await s.backend.remove(jar);
362
+ const cleared = [
363
+ ...await s.backend.remove(jar),
364
+ // The next sign-in asks for the password again (reauthenticateAfterSignOut).
365
+ ...s.config.reauthenticateAfterSignOut ? writeCookie(/* @__PURE__ */ new Map(), s.config.cookies.signedOut, "1", {
366
+ secure: s.config.secure,
367
+ maxAge: SIGNED_OUT_MAX_AGE,
368
+ path: s.config.basePath
369
+ }) : []
370
+ ];
316
371
  const home = new URL(s.config.afterSignOut, s.config.appUrl).toString();
317
372
  let discovery;
318
373
  try {
@@ -398,7 +453,7 @@ function createIdp(options = {}) {
398
453
  const only = (allowed, run) => method === allowed ? run() : Promise.resolve(plain(405, "Method not allowed", { allow: allowed }));
399
454
  switch (route) {
400
455
  case "/login":
401
- return only("GET", () => login(s, url));
456
+ return only("GET", () => login(s, request, url));
402
457
  case "/callback":
403
458
  return only("GET", () => callback(s, request, url));
404
459
  case "/logout":
@@ -475,11 +530,16 @@ function createIdp(options = {}) {
475
530
  useServiceToken(client, options2) {
476
531
  return useServiceToken(serviceReady(), client, options2);
477
532
  },
478
- signInPath(returnTo) {
533
+ signInPath(returnTo, options2 = {}) {
479
534
  const s = ready();
535
+ const query = new URLSearchParams();
480
536
  const safe = safePath(returnTo);
537
+ const prompt = promptFrom(options2.prompt);
538
+ if (safe) query.set("returnTo", safe);
539
+ if (prompt) query.set("prompt", prompt);
540
+ if (options2.reauthenticate === false) query.set("reauthenticate", "false");
481
541
  const login2 = `${s.config.basePath}/login`;
482
- return safe ? `${login2}?${new URLSearchParams({ returnTo: safe })}` : login2;
542
+ return query.size > 0 ? `${login2}?${query}` : login2;
483
543
  }
484
544
  };
485
545
  }
@@ -2,7 +2,7 @@ export { type AccessToken, bearerChallenge, bearerToken, type TokenRequirements,
2
2
  export type { ApiConfig, IdpConfig, IdpOptions, ServiceConfig } from "./config.js";
3
3
  export { DEFAULT_SCOPES } from "./config.js";
4
4
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
5
- export { type CookieSource, createIdp as idp, type Idp, type Refreshed, } from "./idp.js";
5
+ export { type CookieSource, createIdp as idp, type Idp, type Refreshed, type SignInPathOptions, } from "./idp.js";
6
6
  export { safePath } from "./return-path.js";
7
7
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
8
8
  export type { IdpUser, Session } from "./session.js";
@@ -55,7 +55,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): NextIdp;
55
55
  export type { AccessToken, TokenRequirements } from "./access-token.js";
56
56
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
57
57
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
58
- export type { Idp, Refreshed } from "./idp.js";
58
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
59
59
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
60
60
  export type { IdpUser, Session } from "./session.js";
61
61
  export { memoryStore, type SessionStore } from "./store.js";
package/dist/esm/next.js CHANGED
@@ -10,8 +10,22 @@ function isProtected(protect, pathname) {
10
10
  }
11
11
  function idp(options) {
12
12
  const core = createIdp(options);
13
+ const isRouterFetchOfLogin = (request) => {
14
+ if (request.method.toUpperCase() !== "GET" || !request.headers.has("rsc")) return false;
15
+ try {
16
+ return new URL(request.url).pathname === `${core.config().basePath}/login`;
17
+ } catch {
18
+ return false;
19
+ }
20
+ };
13
21
  const handle = async (request) => {
14
22
  await connection();
23
+ if (isRouterFetchOfLogin(request)) {
24
+ return new Response("Sign-in needs a full page load.", {
25
+ status: 200,
26
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }
27
+ });
28
+ }
15
29
  return core.handler(request);
16
30
  };
17
31
  const session = async () => {
@@ -43,7 +43,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): NodeIdp;
43
43
  export type { AccessToken, TokenRequirements } from "./access-token.js";
44
44
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
45
45
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
46
- export type { Idp, Refreshed } from "./idp.js";
46
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
47
47
  export type { SessionOptions } from "./node-adapter.js";
48
48
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
49
49
  export type { IdpUser, Session } from "./session.js";
@@ -12,6 +12,19 @@ declare const FlowSchema: v.ObjectSchema<{
12
12
  }, undefined>;
13
13
  export type Flow = v.InferOutput<typeof FlowSchema>;
14
14
  export declare function parseFlow(payload: unknown): Flow | undefined;
15
+ /**
16
+ * What userinfo said about the person (the `userinfo` option): only these fields, so the
17
+ * cookie stays small. Kept apart from `claims`, which are the ID token's alone.
18
+ */
19
+ declare const ProfileSchema: v.ObjectSchema<{
20
+ readonly email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
21
+ readonly email_verified: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
22
+ readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
23
+ readonly picture: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
24
+ }, undefined>;
25
+ export type Profile = v.InferOutput<typeof ProfileSchema>;
26
+ /** The profile fields of a userinfo answer, and nothing else; undefined if it has none. */
27
+ export declare function profileFrom(answer: Record<string, unknown>): Profile | undefined;
15
28
  declare const StoredSessionSchema: v.ObjectSchema<{
16
29
  readonly claims: v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>;
17
30
  readonly accessToken: v.StringSchema<undefined>;
@@ -21,10 +34,20 @@ declare const StoredSessionSchema: v.ObjectSchema<{
21
34
  /** As received: the hint when signing out of the auth server too. */
22
35
  readonly idToken: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
23
36
  readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
37
+ /** From userinfo, when the `userinfo` option is on. */
38
+ readonly profile: v.OptionalSchema<v.ObjectSchema<{
39
+ readonly email: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
40
+ readonly email_verified: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
41
+ readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
42
+ readonly picture: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
43
+ }, undefined>, undefined>;
24
44
  }, undefined>;
25
45
  export type StoredSession = v.InferOutput<typeof StoredSessionSchema>;
26
46
  export declare function parseStoredSession(payload: unknown): StoredSession | undefined;
27
- /** The person signed in, from the ID token's standard claims. */
47
+ /**
48
+ * The person signed in, from the ID token's standard claims, and from userinfo with the
49
+ * `userinfo` option (which wins where it has a value).
50
+ */
28
51
  export type IdpUser = {
29
52
  /** The `sub` claim: stable for this person at this auth server. */
30
53
  id: string;
@@ -12,6 +12,27 @@ function parseFlow(payload) {
12
12
  const parsed = v.safeParse(FlowSchema, payload);
13
13
  return parsed.success ? parsed.output : void 0;
14
14
  }
15
+ const ProfileSchema = v.object({
16
+ email: v.optional(v.string()),
17
+ email_verified: v.optional(v.boolean()),
18
+ name: v.optional(v.string()),
19
+ picture: v.optional(v.string())
20
+ });
21
+ const MAX_PROFILE_TEXT = 1024;
22
+ function short(value) {
23
+ return typeof value === "string" && value && value.length <= MAX_PROFILE_TEXT ? value : void 0;
24
+ }
25
+ function profileFrom(answer) {
26
+ const profile = {};
27
+ const email = short(answer.email);
28
+ const name = short(answer.name);
29
+ const picture = short(answer.picture);
30
+ if (email) profile.email = email;
31
+ if (typeof answer.email_verified === "boolean") profile.email_verified = answer.email_verified;
32
+ if (name) profile.name = name;
33
+ if (picture) profile.picture = picture;
34
+ return Object.keys(profile).length > 0 ? profile : void 0;
35
+ }
15
36
  const StoredSessionSchema = v.object({
16
37
  claims: v.record(v.string(), v.unknown()),
17
38
  accessToken: v.string(),
@@ -20,7 +41,9 @@ const StoredSessionSchema = v.object({
20
41
  refreshToken: v.optional(v.string()),
21
42
  /** As received: the hint when signing out of the auth server too. */
22
43
  idToken: v.optional(v.string()),
23
- scope: v.optional(v.string())
44
+ scope: v.optional(v.string()),
45
+ /** From userinfo, when the `userinfo` option is on. */
46
+ profile: v.optional(ProfileSchema)
24
47
  });
25
48
  function parseStoredSession(payload) {
26
49
  const parsed = v.safeParse(StoredSessionSchema, payload);
@@ -31,12 +54,15 @@ function text(value) {
31
54
  }
32
55
  function toSession(stored) {
33
56
  const claims = stored.claims;
57
+ const profile = stored.profile;
34
58
  const user = { id: String(claims.sub ?? "") };
35
- const email = text(claims.email);
36
- const name = text(claims.name);
37
- const picture = text(claims.picture);
59
+ const fromProfile = Boolean(text(profile?.email));
60
+ const email = fromProfile ? text(profile?.email) : text(claims.email);
61
+ const emailVerified = fromProfile ? profile?.email_verified : claims.email_verified;
62
+ const name = text(profile?.name) ?? text(claims.name);
63
+ const picture = text(profile?.picture) ?? text(claims.picture);
38
64
  if (email) user.email = email;
39
- if (typeof claims.email_verified === "boolean") user.emailVerified = claims.email_verified;
65
+ if (typeof emailVerified === "boolean") user.emailVerified = emailVerified;
40
66
  if (name) user.name = name;
41
67
  if (picture) user.picture = picture;
42
68
  return {
@@ -54,5 +80,6 @@ export {
54
80
  SESSION_PURPOSE,
55
81
  parseFlow,
56
82
  parseStoredSession,
83
+ profileFrom,
57
84
  toSession
58
85
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nextidp",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Sign people in to Next.js, Express, Hono and Node apps, and protect NestJS, Express, Hono and Next.js APIs, with authserver-oidc, in one call. Runs on Node and edge runtimes.",
5
5
  "keywords": [
6
6
  "oidc",