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/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";
@@ -0,0 +1,67 @@
1
+ import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify";
2
+ import { type AccessToken, type TokenRequirements } from "./access-token.js";
3
+ import type { IdpOptions } from "./config.js";
4
+ import { type Idp } from "./idp.js";
5
+ import { type SessionOptions } from "./node-adapter.js";
6
+ import type { Session } from "./session.js";
7
+ /** A hook for a route's `onRequest` (or `preHandler`): it answers, or lets the request on. */
8
+ export type IdpHook = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
9
+ export type FastifyIdp = Idp & {
10
+ /**
11
+ * The sign-in plugin, before your routes: `await app.register(auth.fastify())`. It answers
12
+ * nextidp's routes under `basePath`, and for every other request reads the session
13
+ * (refreshing the access token when it's about to expire) for `sessionOf(request)`. It
14
+ * applies to the whole app, routes under a prefix included.
15
+ */
16
+ fastify(options?: SessionOptions): FastifyPluginAsync;
17
+ /**
18
+ * Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
19
+ * comes back after; anything else gets 401.
20
+ *
21
+ * ```ts
22
+ * app.get("/dashboard", { onRequest: auth.requireSession() }, async (request) => {
23
+ * return `Hello, ${auth.sessionOf(request)?.user.name}`;
24
+ * });
25
+ * ```
26
+ */
27
+ requireSession(): IdpHook;
28
+ /** The session read for this request, or null when signed out. */
29
+ sessionOf(request: FastifyRequest): Session | null;
30
+ /**
31
+ * Lets a request through only with a valid access token that has every scope in
32
+ * `requirements`. A refused one gets 401 or 403 with WWW-Authenticate (RFC 6750); one that
33
+ * can't be checked now (the auth server is down) 503. Needs no plugin.
34
+ *
35
+ * ```ts
36
+ * app.get("/orders", { onRequest: auth.requireToken({ scopes: ["orders:read"] }) }, async (request) => {
37
+ * return ordersOf(auth.tokenOf(request)?.subject);
38
+ * });
39
+ * ```
40
+ */
41
+ requireToken(requirements?: TokenRequirements): IdpHook;
42
+ /** The access token `requireToken` checked for this request. */
43
+ tokenOf(request: FastifyRequest): AccessToken | undefined;
44
+ };
45
+ /**
46
+ * The client for a Fastify app or API. An app that signs people in needs the sign-in settings
47
+ * (`IDP_ISSUER`, `IDP_CLIENT_ID`, `IDP_APP_URL`, `IDP_SECRET`); an API only `issuer` and
48
+ * `audience`:
49
+ *
50
+ * ```ts
51
+ * import Fastify from "fastify";
52
+ * import { idp } from "nextidp/fastify";
53
+ *
54
+ * const auth = idp(); // the IDP_* environment variables, read on first use
55
+ * const app = Fastify();
56
+ * await app.register(auth.fastify());
57
+ * ```
58
+ */
59
+ export declare function idp(options?: IdpOptions | (() => IdpOptions)): FastifyIdp;
60
+ export type { AccessToken, TokenRequirements } from "./access-token.js";
61
+ export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
62
+ export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
63
+ export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
64
+ export type { SessionOptions } from "./node-adapter.js";
65
+ export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
66
+ export type { IdpUser, Session } from "./session.js";
67
+ export { memoryStore, type SessionStore } from "./store.js";
@@ -0,0 +1,118 @@
1
+ import { tokenRefusal } from "./access-token.js";
2
+ import { isIdpError, isTokenError } from "./errors.js";
3
+ import { createIdp } from "./idp.js";
4
+ import { nodeAdapter } from "./node-adapter.js";
5
+ import { pathOf, urlOf } from "./node-http.js";
6
+ function authorizationOf(request) {
7
+ const value = request.headers.authorization;
8
+ return Array.isArray(value) ? void 0 : value;
9
+ }
10
+ function isRead(method) {
11
+ const upper = method.toUpperCase();
12
+ return upper === "GET" || upper === "HEAD";
13
+ }
14
+ function idp(options) {
15
+ const core = createIdp(options);
16
+ const node = nodeAdapter(core);
17
+ const sessions = /* @__PURE__ */ new WeakMap();
18
+ const read = /* @__PURE__ */ new WeakMap();
19
+ const tokens = /* @__PURE__ */ new WeakMap();
20
+ const sessionFor = (request, reply, refresh = true) => {
21
+ const known = sessions.get(request);
22
+ if (known) return known;
23
+ const reading = (async () => {
24
+ const cookie = request.raw.headers.cookie;
25
+ if (!refresh || reply.sent) return core.getSession(cookie);
26
+ const { session, setCookies, cookieHeader } = await core.refreshIfNeeded(cookie);
27
+ for (const setCookie of setCookies) reply.header("set-cookie", setCookie);
28
+ if (cookieHeader !== void 0) request.raw.headers.cookie = cookieHeader;
29
+ return session;
30
+ })();
31
+ sessions.set(request, reading);
32
+ return reading.then((session) => {
33
+ read.set(request, session);
34
+ return session;
35
+ });
36
+ };
37
+ return {
38
+ ...core,
39
+ fastify({ refresh = true } = {}) {
40
+ const plugin = async (app) => {
41
+ app.addHook("onRequest", async (request, reply) => {
42
+ const { appUrl, basePath } = core.config();
43
+ const { pathname } = urlOf(request.raw, appUrl);
44
+ if (pathname === basePath || pathname.startsWith(`${basePath}/`)) {
45
+ reply.hijack();
46
+ await node.handle(request.raw, reply.raw);
47
+ return;
48
+ }
49
+ await sessionFor(request, reply, refresh);
50
+ });
51
+ };
52
+ Object.assign(plugin, { [/* @__PURE__ */ Symbol.for("skip-override")]: true });
53
+ return plugin;
54
+ },
55
+ requireSession() {
56
+ return async (request, reply) => {
57
+ const session = await sessionFor(request, reply);
58
+ if (session) return;
59
+ if (!isRead(request.method)) {
60
+ await reply.code(401).header("cache-control", "no-store").type("text/plain; charset=utf-8").send("Sign in first.");
61
+ return;
62
+ }
63
+ const signIn = new URL(core.signInPath(pathOf(request.raw)), core.config().appUrl);
64
+ await reply.header("cache-control", "no-store").redirect(signIn.toString(), 302);
65
+ };
66
+ },
67
+ sessionOf(request) {
68
+ const session = read.get(request);
69
+ if (session === void 0) {
70
+ throw new Error(
71
+ "nextidp: no session was read for this request. Register auth.fastify() first."
72
+ );
73
+ }
74
+ return session;
75
+ },
76
+ requireToken(requirements = {}) {
77
+ return async (request, reply) => {
78
+ let token;
79
+ try {
80
+ token = await core.verifyBearer(authorizationOf(request), requirements);
81
+ } catch (error) {
82
+ if (isTokenError(error)) {
83
+ const refusal = tokenRefusal(error);
84
+ await reply.code(refusal.status).headers(refusal.headers).send(refusal.body);
85
+ return;
86
+ }
87
+ request.log.error(
88
+ `nextidp: a token couldn't be checked: ${isIdpError(error) ? error.code : "unexpected error"}`
89
+ );
90
+ await reply.code(503).headers({ "retry-after": "5", "cache-control": "no-store" }).send({
91
+ error: "temporarily_unavailable",
92
+ error_description: "The token can't be checked now."
93
+ });
94
+ return;
95
+ }
96
+ tokens.set(request, token);
97
+ };
98
+ },
99
+ tokenOf: (request) => tokens.get(request)
100
+ };
101
+ }
102
+ import {
103
+ IdpError,
104
+ isIdpError as isIdpError2,
105
+ isSignInErrorCode,
106
+ isTokenError as isTokenError2,
107
+ SIGN_IN_ERROR_CODES
108
+ } from "./errors.js";
109
+ import { memoryStore } from "./store.js";
110
+ export {
111
+ IdpError,
112
+ SIGN_IN_ERROR_CODES,
113
+ idp,
114
+ isIdpError2 as isIdpError,
115
+ isSignInErrorCode,
116
+ isTokenError2 as isTokenError,
117
+ memoryStore
118
+ };
@@ -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";