nextidp 0.1.2 → 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/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,7 +1,7 @@
1
1
  {
2
2
  "name": "nextidp",
3
- "version": "0.1.2",
4
- "description": "Sign people in to Next.js, Express and Node apps, and protect NestJS, Express and Next.js APIs, with authserver-oidc, in one call.",
3
+ "version": "0.1.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",
7
7
  "openid-connect",
@@ -10,6 +10,9 @@
10
10
  "nextjs",
11
11
  "nestjs",
12
12
  "express",
13
+ "hono",
14
+ "cloudflare-workers",
15
+ "edge",
13
16
  "jwt",
14
17
  "idp"
15
18
  ],
@@ -34,6 +37,9 @@
34
37
  "node": [
35
38
  "./dist/cjs/node.d.ts"
36
39
  ],
40
+ "hono": [
41
+ "./dist/cjs/hono.d.ts"
42
+ ],
37
43
  "nestjs": [
38
44
  "./dist/cjs/nestjs.d.ts"
39
45
  ]
@@ -85,6 +91,16 @@
85
91
  "default": "./dist/cjs/node.js"
86
92
  }
87
93
  },
94
+ "./hono": {
95
+ "import": {
96
+ "types": "./dist/esm/hono.d.ts",
97
+ "default": "./dist/esm/hono.js"
98
+ },
99
+ "require": {
100
+ "types": "./dist/cjs/hono.d.ts",
101
+ "default": "./dist/cjs/hono.js"
102
+ }
103
+ },
88
104
  "./nestjs": {
89
105
  "import": {
90
106
  "types": "./dist/esm/nestjs.d.ts",
@@ -109,6 +125,7 @@
109
125
  "peerDependencies": {
110
126
  "@nestjs/common": "^11.0.0 || ^12.0.0",
111
127
  "@nestjs/core": "^11.0.0 || ^12.0.0",
128
+ "hono": "^4.0.0",
112
129
  "next": "^15.0.0 || ^16.0.0"
113
130
  },
114
131
  "peerDependenciesMeta": {
@@ -118,6 +135,9 @@
118
135
  "@nestjs/core": {
119
136
  "optional": true
120
137
  },
138
+ "hono": {
139
+ "optional": true
140
+ },
121
141
  "next": {
122
142
  "optional": true
123
143
  }
@@ -132,6 +152,8 @@
132
152
  "@types/node": "26.6.5",
133
153
  "esbuild": "0.28.2",
134
154
  "express": "5.3.0",
155
+ "hono": "4.13.22",
156
+ "miniflare": "4.20260730.0",
135
157
  "next": "16.4.6",
136
158
  "publint": "0.3.25",
137
159
  "react": "19.3.1",