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/CHANGELOG.md +39 -0
- package/README.md +116 -6
- package/dist/cjs/config.d.ts +20 -1
- package/dist/cjs/config.js +8 -1
- package/dist/cjs/cookies.d.ts +3 -1
- package/dist/cjs/cookies.js +4 -4
- package/dist/cjs/express.d.ts +1 -1
- package/dist/cjs/hono.d.ts +65 -0
- package/dist/cjs/hono.js +130 -0
- package/dist/cjs/idp.d.ts +14 -2
- package/dist/cjs/idp.js +74 -15
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/next.d.ts +1 -1
- package/dist/cjs/next.js +14 -0
- package/dist/cjs/node.d.ts +1 -1
- package/dist/cjs/session.d.ts +24 -1
- package/dist/cjs/session.js +33 -5
- package/dist/esm/config.d.ts +20 -1
- package/dist/esm/config.js +8 -1
- package/dist/esm/cookies.d.ts +3 -1
- package/dist/esm/cookies.js +4 -4
- package/dist/esm/express.d.ts +1 -1
- package/dist/esm/hono.d.ts +65 -0
- package/dist/esm/hono.js +106 -0
- package/dist/esm/idp.d.ts +14 -2
- package/dist/esm/idp.js +75 -15
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/next.d.ts +1 -1
- package/dist/esm/next.js +14 -0
- package/dist/esm/node.d.ts +1 -1
- package/dist/esm/session.d.ts +24 -1
- package/dist/esm/session.js +32 -5
- package/package.json +24 -2
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
|
-
|
|
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
|
|
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 =
|
|
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
|
|
534
|
+
return query.size > 0 ? `${login2}?${query}` : login2;
|
|
476
535
|
}
|
|
477
536
|
};
|
|
478
537
|
}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/cjs/next.d.ts
CHANGED
|
@@ -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 () => {
|
package/dist/cjs/node.d.ts
CHANGED
|
@@ -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";
|
package/dist/cjs/session.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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;
|
package/dist/cjs/session.js
CHANGED
|
@@ -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
|
|
74
|
-
const
|
|
75
|
-
const
|
|
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
|
|
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
|
});
|
package/dist/esm/config.d.ts
CHANGED
|
@@ -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. */
|
package/dist/esm/config.js
CHANGED
|
@@ -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: {
|
|
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
|
};
|
package/dist/esm/cookies.d.ts
CHANGED
|
@@ -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.
|
package/dist/esm/cookies.js
CHANGED
|
@@ -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
|
-
|
|
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));
|
package/dist/esm/express.d.ts
CHANGED
|
@@ -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,65 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
3
|
+
import type { IdpOptions } from "./config.js";
|
|
4
|
+
import { type Idp } from "./idp.js";
|
|
5
|
+
import type { Session } from "./session.js";
|
|
6
|
+
/**
|
|
7
|
+
* The context variables nextidp sets: `session` (by `middleware()`, null when signed out) and
|
|
8
|
+
* `token` (by `requireToken()`). Give it to your app: `new Hono<IdpEnv>()`.
|
|
9
|
+
*/
|
|
10
|
+
export type IdpEnv = {
|
|
11
|
+
Variables: {
|
|
12
|
+
session: Session | null;
|
|
13
|
+
token: AccessToken;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
export type HonoSessionOptions = {
|
|
17
|
+
/** Refresh the access token when it expires within a minute (default true). */
|
|
18
|
+
refresh?: boolean;
|
|
19
|
+
};
|
|
20
|
+
export type HonoIdp = Idp & {
|
|
21
|
+
/** nextidp's routes, for `app.all("/auth/*", auth.routes())` (under `basePath`). */
|
|
22
|
+
routes(): (c: Context) => Promise<Response>;
|
|
23
|
+
/**
|
|
24
|
+
* Reads the session for every request (refreshing the access token when it's about to
|
|
25
|
+
* expire, with the new cookie on the response) and puts it on the context:
|
|
26
|
+
* `c.get("session")`, null when signed out. `app.use(auth.middleware())`.
|
|
27
|
+
*/
|
|
28
|
+
middleware(options?: HonoSessionOptions): MiddlewareHandler<IdpEnv>;
|
|
29
|
+
/**
|
|
30
|
+
* Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
|
|
31
|
+
* comes back after; anything else gets 401.
|
|
32
|
+
*/
|
|
33
|
+
requireSession(): MiddlewareHandler<IdpEnv>;
|
|
34
|
+
/**
|
|
35
|
+
* Lets a request through only with a valid access token that has every scope in
|
|
36
|
+
* `requirements`, put on the context as `c.get("token")`. A refused one gets 401 or 403 with
|
|
37
|
+
* WWW-Authenticate (RFC 6750); one that can't be checked now (the auth server is down) 503.
|
|
38
|
+
*/
|
|
39
|
+
requireToken(requirements?: TokenRequirements): MiddlewareHandler<IdpEnv>;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The client for a Hono app or API:
|
|
43
|
+
*
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { Hono } from "hono";
|
|
46
|
+
* import { idp, type IdpEnv } from "nextidp/hono";
|
|
47
|
+
*
|
|
48
|
+
* const auth = idp({ issuer: "https://auth.example.com", clientId: "…", appUrl: "…", secret: "…" });
|
|
49
|
+
* const app = new Hono<IdpEnv>();
|
|
50
|
+
* app.all("/auth/*", auth.routes());
|
|
51
|
+
* app.use(auth.middleware());
|
|
52
|
+
* app.get("/dashboard", auth.requireSession(), (c) => c.text(`Hello, ${c.get("session")?.user.name}`));
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* On a runtime without `process.env` (Cloudflare Workers), pass the settings, or `env`:
|
|
56
|
+
* `idp(() => ({ env: workerEnv }))`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function idp(options?: IdpOptions | (() => IdpOptions)): HonoIdp;
|
|
59
|
+
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
60
|
+
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
61
|
+
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
62
|
+
export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
|
|
63
|
+
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
64
|
+
export type { IdpUser, Session } from "./session.js";
|
|
65
|
+
export { memoryStore, type SessionStore } from "./store.js";
|
package/dist/esm/hono.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { isIdpError, isTokenError } from "./errors.js";
|
|
2
|
+
import { createIdp } from "./idp.js";
|
|
3
|
+
function putCookies(c, cookies) {
|
|
4
|
+
if (cookies.length === 0) return;
|
|
5
|
+
try {
|
|
6
|
+
for (const cookie of cookies) c.res.headers.append("set-cookie", cookie);
|
|
7
|
+
} catch {
|
|
8
|
+
const copy = new Response(c.res.body, c.res);
|
|
9
|
+
for (const cookie of cookies) copy.headers.append("set-cookie", cookie);
|
|
10
|
+
c.res = void 0;
|
|
11
|
+
c.res = copy;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function underBasePath(pathname, basePath) {
|
|
15
|
+
return pathname === basePath || pathname.startsWith(`${basePath}/`);
|
|
16
|
+
}
|
|
17
|
+
function idp(options) {
|
|
18
|
+
const core = createIdp(options);
|
|
19
|
+
const sessionOf = async (c, refresh) => {
|
|
20
|
+
if (!refresh) return { session: await core.getSession(c.req.raw), setCookies: [] };
|
|
21
|
+
const { session, setCookies } = await core.refreshIfNeeded(c.req.raw);
|
|
22
|
+
return { session, setCookies };
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
...core,
|
|
26
|
+
routes: () => (c) => core.handler(c.req.raw),
|
|
27
|
+
middleware({ refresh = true } = {}) {
|
|
28
|
+
return async (c, next) => {
|
|
29
|
+
if (underBasePath(new URL(c.req.url).pathname, core.config().basePath)) {
|
|
30
|
+
await next();
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const { session, setCookies } = await sessionOf(c, refresh);
|
|
34
|
+
c.set("session", session);
|
|
35
|
+
await next();
|
|
36
|
+
putCookies(c, setCookies);
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
requireSession() {
|
|
40
|
+
return async (c, next) => {
|
|
41
|
+
const known = c.get("session");
|
|
42
|
+
const { session, setCookies } = known === void 0 ? await sessionOf(c, true) : { session: known, setCookies: [] };
|
|
43
|
+
if (session) {
|
|
44
|
+
c.set("session", session);
|
|
45
|
+
await next();
|
|
46
|
+
putCookies(c, setCookies);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const method = c.req.method.toUpperCase();
|
|
50
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
51
|
+
c.res = c.text("Sign in first.", 401, { "cache-control": "no-store" });
|
|
52
|
+
} else {
|
|
53
|
+
const url = new URL(c.req.url);
|
|
54
|
+
const signIn = new URL(
|
|
55
|
+
core.signInPath(`${url.pathname}${url.search}`),
|
|
56
|
+
core.config().appUrl
|
|
57
|
+
);
|
|
58
|
+
c.res = c.redirect(signIn.toString(), 302);
|
|
59
|
+
c.res.headers.set("cache-control", "no-store");
|
|
60
|
+
}
|
|
61
|
+
putCookies(c, setCookies);
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
requireToken(requirements = {}) {
|
|
65
|
+
return async (c, next) => {
|
|
66
|
+
let token;
|
|
67
|
+
try {
|
|
68
|
+
token = await core.verifyBearer(c.req.header("authorization"), requirements);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (isTokenError(error)) return core.tokenErrorResponse(error);
|
|
71
|
+
console.error(
|
|
72
|
+
`nextidp: a token couldn't be checked: ${isIdpError(error) ? error.code : "unexpected error"}`
|
|
73
|
+
);
|
|
74
|
+
return c.json(
|
|
75
|
+
{
|
|
76
|
+
error: "temporarily_unavailable",
|
|
77
|
+
error_description: "The token can't be checked now."
|
|
78
|
+
},
|
|
79
|
+
503,
|
|
80
|
+
{ "retry-after": "5", "cache-control": "no-store" }
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
c.set("token", token);
|
|
84
|
+
await next();
|
|
85
|
+
return void 0;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
import {
|
|
91
|
+
IdpError,
|
|
92
|
+
isIdpError as isIdpError2,
|
|
93
|
+
isSignInErrorCode,
|
|
94
|
+
isTokenError as isTokenError2,
|
|
95
|
+
SIGN_IN_ERROR_CODES
|
|
96
|
+
} from "./errors.js";
|
|
97
|
+
import { memoryStore } from "./store.js";
|
|
98
|
+
export {
|
|
99
|
+
IdpError,
|
|
100
|
+
SIGN_IN_ERROR_CODES,
|
|
101
|
+
idp,
|
|
102
|
+
isIdpError2 as isIdpError,
|
|
103
|
+
isSignInErrorCode,
|
|
104
|
+
isTokenError2 as isTokenError,
|
|
105
|
+
memoryStore
|
|
106
|
+
};
|
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
|
-
/**
|
|
38
|
-
|
|
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
|