nextidp 0.0.1 → 0.1.2

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.
Files changed (97) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +434 -4
  3. package/dist/cjs/access-token.d.ts +56 -0
  4. package/dist/cjs/access-token.js +196 -0
  5. package/dist/cjs/config.d.ts +128 -0
  6. package/dist/cjs/config.js +233 -0
  7. package/dist/cjs/cookies.d.ts +23 -0
  8. package/dist/cjs/cookies.js +118 -0
  9. package/dist/cjs/discovery.d.ts +24 -0
  10. package/dist/cjs/discovery.js +91 -0
  11. package/dist/cjs/errors.d.ts +63 -0
  12. package/dist/cjs/errors.js +69 -0
  13. package/dist/cjs/express.d.ts +71 -0
  14. package/dist/cjs/express.js +114 -0
  15. package/dist/cjs/http.d.ts +10 -0
  16. package/dist/cjs/http.js +68 -0
  17. package/dist/cjs/id-token.d.ts +19 -0
  18. package/dist/cjs/id-token.js +77 -0
  19. package/dist/cjs/idp.d.ts +81 -0
  20. package/dist/cjs/idp.js +482 -0
  21. package/dist/cjs/index.d.ts +9 -0
  22. package/dist/cjs/index.js +53 -0
  23. package/dist/cjs/logout-token.d.ts +13 -0
  24. package/dist/cjs/logout-token.js +63 -0
  25. package/dist/cjs/nestjs.d.ts +53 -0
  26. package/dist/cjs/nestjs.js +142 -0
  27. package/dist/cjs/next.d.ts +61 -0
  28. package/dist/cjs/next.js +118 -0
  29. package/dist/cjs/node-adapter.d.ts +16 -0
  30. package/dist/cjs/node-adapter.js +76 -0
  31. package/dist/cjs/node-http.d.ts +22 -0
  32. package/dist/cjs/node-http.js +127 -0
  33. package/dist/cjs/node.d.ts +50 -0
  34. package/dist/cjs/node.js +57 -0
  35. package/dist/cjs/package.json +1 -0
  36. package/dist/cjs/pkce.d.ts +6 -0
  37. package/dist/cjs/pkce.js +49 -0
  38. package/dist/cjs/return-path.d.ts +6 -0
  39. package/dist/cjs/return-path.js +41 -0
  40. package/dist/cjs/sealed.d.ts +12 -0
  41. package/dist/cjs/sealed.js +78 -0
  42. package/dist/cjs/service.d.ts +61 -0
  43. package/dist/cjs/service.js +173 -0
  44. package/dist/cjs/session.d.ts +51 -0
  45. package/dist/cjs/session.js +97 -0
  46. package/dist/cjs/store.d.ts +58 -0
  47. package/dist/cjs/store.js +145 -0
  48. package/dist/cjs/tokens.d.ts +38 -0
  49. package/dist/cjs/tokens.js +138 -0
  50. package/dist/esm/access-token.d.ts +56 -0
  51. package/dist/esm/access-token.js +156 -0
  52. package/dist/esm/config.d.ts +128 -0
  53. package/dist/esm/config.js +206 -0
  54. package/dist/esm/cookies.d.ts +23 -0
  55. package/dist/esm/cookies.js +89 -0
  56. package/dist/esm/discovery.d.ts +24 -0
  57. package/dist/esm/discovery.js +56 -0
  58. package/dist/esm/errors.d.ts +63 -0
  59. package/dist/esm/errors.js +41 -0
  60. package/dist/esm/express.d.ts +71 -0
  61. package/dist/esm/express.js +90 -0
  62. package/dist/esm/http.d.ts +10 -0
  63. package/dist/esm/http.js +44 -0
  64. package/dist/esm/id-token.d.ts +19 -0
  65. package/dist/esm/id-token.js +51 -0
  66. package/dist/esm/idp.d.ts +81 -0
  67. package/dist/esm/idp.js +488 -0
  68. package/dist/esm/index.d.ts +9 -0
  69. package/dist/esm/index.js +30 -0
  70. package/dist/esm/logout-token.d.ts +13 -0
  71. package/dist/esm/logout-token.js +39 -0
  72. package/dist/esm/nestjs.d.ts +53 -0
  73. package/dist/esm/nestjs.js +118 -0
  74. package/dist/esm/next.d.ts +61 -0
  75. package/dist/esm/next.js +94 -0
  76. package/dist/esm/node-adapter.d.ts +16 -0
  77. package/dist/esm/node-adapter.js +60 -0
  78. package/dist/esm/node-http.d.ts +22 -0
  79. package/dist/esm/node-http.js +96 -0
  80. package/dist/esm/node.d.ts +50 -0
  81. package/dist/esm/node.js +33 -0
  82. package/dist/esm/package.json +1 -0
  83. package/dist/esm/pkce.d.ts +6 -0
  84. package/dist/esm/pkce.js +23 -0
  85. package/dist/esm/return-path.d.ts +6 -0
  86. package/dist/esm/return-path.js +17 -0
  87. package/dist/esm/sealed.d.ts +12 -0
  88. package/dist/esm/sealed.js +54 -0
  89. package/dist/esm/service.d.ts +61 -0
  90. package/dist/esm/service.js +148 -0
  91. package/dist/esm/session.d.ts +51 -0
  92. package/dist/esm/session.js +58 -0
  93. package/dist/esm/store.d.ts +58 -0
  94. package/dist/esm/store.js +119 -0
  95. package/dist/esm/tokens.d.ts +38 -0
  96. package/dist/esm/tokens.js +100 -0
  97. package/package.json +130 -5
@@ -0,0 +1,156 @@
1
+ import { decodeProtectedHeader, jwtVerify } from "jose";
2
+ import * as v from "valibot";
3
+ import { IdpError } from "./errors.js";
4
+ const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
5
+ const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
6
+ const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
7
+ const invalid = (message, cause) => new IdpError("invalid_token", message, { status: 401, cause });
8
+ function bearerToken(authorization) {
9
+ return authorization ? BEARER.exec(authorization)?.[1] : void 0;
10
+ }
11
+ function list(value) {
12
+ if (typeof value === "string") return value.split(" ").filter(Boolean);
13
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
14
+ }
15
+ function toAccessToken(claims) {
16
+ const subject = typeof claims.sub === "string" ? claims.sub : void 0;
17
+ const clientId = typeof claims.client_id === "string" ? claims.client_id : typeof claims.azp === "string" ? claims.azp : void 0;
18
+ return {
19
+ subject,
20
+ clientId,
21
+ isService: subject !== void 0 && subject === clientId,
22
+ scopes: list(claims.scope),
23
+ audience: list(claims.aud),
24
+ expiresAt: typeof claims.exp === "number" ? claims.exp : void 0,
25
+ claims
26
+ };
27
+ }
28
+ function requireScopes(token, required = []) {
29
+ const missing = required.filter((scope) => !token.scopes.includes(scope));
30
+ if (missing.length > 0) {
31
+ throw new IdpError("insufficient_scope", `The access token lacks: ${missing.join(" ")}.`, {
32
+ status: 403,
33
+ scopes: required
34
+ });
35
+ }
36
+ return token;
37
+ }
38
+ function isJwt(token) {
39
+ if (token.split(".").length !== 3) return false;
40
+ try {
41
+ decodeProtectedHeader(token);
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+ async function verifyJwtAccessToken(token, keys, config) {
48
+ const { typ } = decodeProtectedHeader(token);
49
+ if (typ === void 0 || !ACCESS_TOKEN_TYPES.has(typ.toLowerCase())) {
50
+ throw invalid("The token isn't a JWT access token (its typ isn't at+jwt).");
51
+ }
52
+ try {
53
+ const { payload } = await jwtVerify(token, keys, {
54
+ algorithms: ALGORITHMS,
55
+ issuer: config.issuer,
56
+ audience: config.audience,
57
+ requiredClaims: ["exp"],
58
+ clockTolerance: 60
59
+ });
60
+ return toAccessToken(payload);
61
+ } catch (cause) {
62
+ throw invalid(
63
+ "The access token didn't verify: expired, for another API, or not signed by the issuer.",
64
+ cause
65
+ );
66
+ }
67
+ }
68
+ const IntrospectionSchema = v.looseObject({
69
+ active: v.boolean(),
70
+ scope: v.optional(v.string()),
71
+ client_id: v.optional(v.string()),
72
+ sub: v.optional(v.string()),
73
+ exp: v.optional(v.number()),
74
+ aud: v.optional(v.union([v.string(), v.array(v.string())])),
75
+ iss: v.optional(v.string())
76
+ });
77
+ async function introspect(http, discovery, config, token) {
78
+ if (!discovery.introspection_endpoint) {
79
+ throw invalid("The auth server has no introspection endpoint, and the token isn't a JWT.");
80
+ }
81
+ if (!config.clientId || !config.clientSecret) {
82
+ throw invalid(
83
+ "An opaque access token can only be checked by introspection, which needs clientId and clientSecret. Ask for tokens with `resource` to get JWTs instead."
84
+ );
85
+ }
86
+ const pair = `${encodeURIComponent(config.clientId)}:${encodeURIComponent(config.clientSecret)}`;
87
+ let answer;
88
+ try {
89
+ answer = await http.postForm(
90
+ discovery.introspection_endpoint,
91
+ new URLSearchParams({ token, token_type_hint: "access_token" }),
92
+ { authorization: `Basic ${btoa(pair)}` }
93
+ );
94
+ } catch (cause) {
95
+ throw new IdpError("discovery_failed", "The introspection endpoint didn't answer.", { cause });
96
+ }
97
+ if (!answer.ok) {
98
+ throw new IdpError(
99
+ "misconfigured",
100
+ `Introspection answered ${answer.status}: check clientId and clientSecret.`,
101
+ {
102
+ status: answer.status
103
+ }
104
+ );
105
+ }
106
+ const parsed = v.safeParse(IntrospectionSchema, answer.data);
107
+ if (!parsed.success) throw invalid("The introspection answer isn't valid.");
108
+ if (!parsed.output.active) throw invalid("The access token isn't active.");
109
+ if (parsed.output.iss !== void 0 && parsed.output.iss.replace(/\/+$/, "") !== config.issuer) {
110
+ throw invalid("The access token is from another issuer.");
111
+ }
112
+ const checked = toAccessToken(parsed.output);
113
+ const own = config.acceptOwnTokens && checked.clientId === config.clientId;
114
+ if (!checked.audience.includes(config.audience) && !own) {
115
+ throw invalid("The access token is for another API.");
116
+ }
117
+ if (checked.expiresAt !== void 0 && checked.expiresAt <= Math.floor(Date.now() / 1e3)) {
118
+ throw invalid("The access token has expired.");
119
+ }
120
+ return checked;
121
+ }
122
+ function quoted(value) {
123
+ return `"${value.replace(/[\\"]/g, "\\$&")}"`;
124
+ }
125
+ function bearerChallenge(error) {
126
+ if (error.code === "missing_token") return "Bearer";
127
+ const parts = [
128
+ `error=${quoted(error.code === "insufficient_scope" ? "insufficient_scope" : "invalid_token")}`
129
+ ];
130
+ parts.push(`error_description=${quoted(error.message)}`);
131
+ if (error.code === "insufficient_scope" && error.scopes?.length) {
132
+ parts.push(`scope=${quoted(error.scopes.join(" "))}`);
133
+ }
134
+ return `Bearer ${parts.join(", ")}`;
135
+ }
136
+ function tokenRefusal(error) {
137
+ const status = error.code === "insufficient_scope" ? 403 : 401;
138
+ return {
139
+ status,
140
+ headers: {
141
+ "www-authenticate": bearerChallenge(error),
142
+ "content-type": "application/json",
143
+ "cache-control": "no-store"
144
+ },
145
+ body: { error: error.code, error_description: error.message }
146
+ };
147
+ }
148
+ export {
149
+ bearerChallenge,
150
+ bearerToken,
151
+ introspect,
152
+ isJwt,
153
+ requireScopes,
154
+ tokenRefusal,
155
+ verifyJwtAccessToken
156
+ };
@@ -0,0 +1,128 @@
1
+ import { IdpError } from "./errors.js";
2
+ import type { SessionStore } from "./store.js";
3
+ /** What `idp()` takes. Every setting can also come from the environment (in brackets). */
4
+ export type IdpOptions = {
5
+ /** The auth server, also the OIDC issuer: `https://auth.example.com` (IDP_ISSUER). */
6
+ issuer?: string | undefined;
7
+ /** This app's client ID, from the auth server's admin screen (IDP_CLIENT_ID). */
8
+ clientId?: string | undefined;
9
+ /** A confidential client's secret. Leave it out for a public one (IDP_CLIENT_SECRET). */
10
+ clientSecret?: string | undefined;
11
+ /** This app's own origin: `https://app.example.com` (IDP_APP_URL). */
12
+ appUrl?: string | undefined;
13
+ /**
14
+ * At least 32 characters: encrypts this app's cookies (IDP_SECRET). A list rotates it: the
15
+ * first encrypts, every one decrypts (IDP_SECRET, comma-separated).
16
+ */
17
+ secret?: string | readonly string[] | undefined;
18
+ /** What to ask for. Default `openid profile email offline_access` (IDP_SCOPES). */
19
+ scopes?: string | readonly string[] | undefined;
20
+ /** An API's URI (RFC 8707): the access token is then a JWT for that API (IDP_RESOURCE). */
21
+ resource?: string | undefined;
22
+ /**
23
+ * For an API that checks tokens: its own URI, as the auth server lists it in
24
+ * OAUTH_RESOURCES. Every access token must name it in `aud` (IDP_AUDIENCE). Never taken
25
+ * from `resource`: that's the API an app asks tokens *for*, and accepting those here would
26
+ * let an app take tokens meant for the API it calls.
27
+ */
28
+ audience?: string | undefined;
29
+ /**
30
+ * Also accept an opaque token, by introspection, that doesn't name `audience` but was
31
+ * issued to this very client (`clientId`): an app checking its own tokens. Off by default,
32
+ * so only tokens for this API pass.
33
+ */
34
+ acceptOwnTokens?: boolean | undefined;
35
+ /** Where nextidp's routes live. Default `/auth`: the redirect URI is `<appUrl>/auth/callback`. */
36
+ basePath?: string | undefined;
37
+ /** Where a sign-in lands when it wasn't asked to return somewhere. Default `/`. */
38
+ afterSignIn?: string | undefined;
39
+ /** Where sign-out lands, and the post-logout redirect URI on the auth server. Default `/`. */
40
+ afterSignOut?: string | undefined;
41
+ /** Where a failed sign-in lands, with `?error=<code>`. Default `/`. */
42
+ errorPath?: string | undefined;
43
+ /** Sign out of the auth server too, by default. A form field can still choose. Default false. */
44
+ signOutOfIdp?: boolean | undefined;
45
+ /** How long the session cookie lasts, in seconds, renewed at every refresh. Default 7 days. */
46
+ sessionMaxAge?: number | undefined;
47
+ /** The start of this app's cookie names. Default `nextidp`. */
48
+ cookiePrefix?: string | undefined;
49
+ /**
50
+ * Keep sessions here instead of in the cookie, which then holds only a sealed reference.
51
+ * Needed for back-channel logout (`<basePath>/backchannel-logout`): the auth server can
52
+ * then end this app's sessions. Default: none, sessions live in the cookie.
53
+ */
54
+ store?: SessionStore | undefined;
55
+ /**
56
+ * Where the IDP_* settings are read from, when an option isn't passed. Default
57
+ * `process.env`.
58
+ */
59
+ env?: Readonly<Record<string, string | undefined>> | undefined;
60
+ /**
61
+ * Told about every sign-in, refresh or setting that failed. Default: one `console.error`
62
+ * line with the code and message, which never hold a token or a claim.
63
+ */
64
+ onError?: ((error: IdpError) => void) | undefined;
65
+ };
66
+ /** What checking access tokens needs: an API has no sign-in of its own. */
67
+ export type ApiConfig = {
68
+ issuer: string;
69
+ audience: string;
70
+ /** For introspecting opaque tokens; a JWT needs neither. */
71
+ clientId: string | undefined;
72
+ clientSecret: string | undefined;
73
+ /** See IdpOptions.acceptOwnTokens. */
74
+ acceptOwnTokens: boolean;
75
+ };
76
+ /** What a service needs to get tokens of its own: a confidential client. */
77
+ export type ServiceConfig = {
78
+ issuer: string;
79
+ clientId: string;
80
+ clientSecret: string;
81
+ /** The API to ask tokens for when a call names none (IDP_RESOURCE). */
82
+ resource: string | undefined;
83
+ };
84
+ /** The settings once checked, as nextidp uses them. */
85
+ export type IdpConfig = {
86
+ issuer: string;
87
+ clientId: string;
88
+ clientSecret: string | undefined;
89
+ /** This app's origin. */
90
+ appUrl: string;
91
+ /** The first one encrypts. */
92
+ secrets: readonly string[];
93
+ scope: string;
94
+ resource: string | undefined;
95
+ basePath: string;
96
+ redirectUri: string;
97
+ afterSignIn: string;
98
+ afterSignOut: string;
99
+ postLogoutRedirectUri: string;
100
+ errorPath: string;
101
+ signOutOfIdp: boolean;
102
+ sessionMaxAge: number;
103
+ /** https: cookies are Secure, with `__Host-` names. */
104
+ secure: boolean;
105
+ cookies: {
106
+ session: string;
107
+ flow: string;
108
+ };
109
+ store: SessionStore | undefined;
110
+ /** Where the auth server sends logout tokens, with a store. */
111
+ backchannelLogoutUri: string;
112
+ };
113
+ export declare const DEFAULT_SCOPES: readonly ["openid", "profile", "email", "offline_access"];
114
+ /**
115
+ * What checking access tokens needs: the issuer and this API's audience. The client ID and
116
+ * secret are optional: only introspection (an opaque token) uses them.
117
+ */
118
+ export declare function resolveApiConfig(options: IdpOptions): ApiConfig;
119
+ /**
120
+ * What getting a service's own tokens (client credentials) needs: the issuer, and a
121
+ * confidential client's ID and secret. Sign-in's `appUrl` and `secret` aren't needed.
122
+ */
123
+ export declare function resolveServiceConfig(options: IdpOptions): ServiceConfig;
124
+ /**
125
+ * The checked settings for signing people in. Throws an IdpError("misconfigured") that
126
+ * names every setting that's missing or wrong, and never repeats a value.
127
+ */
128
+ export declare function resolveConfig(options: IdpOptions): IdpConfig;
@@ -0,0 +1,206 @@
1
+ import { IdpError } from "./errors.js";
2
+ import { safePath } from "./return-path.js";
3
+ const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
4
+ const SEVEN_DAYS = 7 * 24 * 60 * 60;
5
+ const MIN_SECRET_LENGTH = 32;
6
+ function pick(option, env, variable) {
7
+ const value = option ?? env?.[variable];
8
+ const trimmed = value?.trim();
9
+ return trimmed ? trimmed : void 0;
10
+ }
11
+ function httpUrl(value, label, problems, production) {
12
+ if (value === void 0) {
13
+ problems.push(`${label} is required`);
14
+ return void 0;
15
+ }
16
+ let url;
17
+ try {
18
+ url = new URL(value);
19
+ } catch {
20
+ problems.push(`${label} must be a URL like https://example.com`);
21
+ return void 0;
22
+ }
23
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
24
+ problems.push(`${label} must be an http(s) URL`);
25
+ return void 0;
26
+ }
27
+ if (production && url.protocol !== "https:") {
28
+ problems.push(`${label} must be https in production`);
29
+ return void 0;
30
+ }
31
+ if (url.search || url.hash || url.username || url.password) {
32
+ problems.push(`${label} must have no query, fragment or credentials`);
33
+ return void 0;
34
+ }
35
+ return url;
36
+ }
37
+ function path(value, label, fallback, problems) {
38
+ if (value === void 0) return fallback;
39
+ const safe = safePath(value);
40
+ if (!safe) problems.push(`${label} must be a path of this app, like /dashboard`);
41
+ return safe ?? fallback;
42
+ }
43
+ function secretsFrom(option, env, problems) {
44
+ const list = option === void 0 ? (env?.IDP_SECRET ?? "").split(",") : typeof option === "string" ? [option] : [...option];
45
+ const secrets = list.map((secret) => secret.trim()).filter(Boolean);
46
+ if (secrets.length === 0) problems.push("secret (IDP_SECRET) is required");
47
+ if (secrets.some((secret) => secret.length < MIN_SECRET_LENGTH)) {
48
+ problems.push(`secret (IDP_SECRET) must be at least ${MIN_SECRET_LENGTH} characters`);
49
+ }
50
+ return secrets;
51
+ }
52
+ function scopesFrom(option, env, problems) {
53
+ const raw = option ?? env?.IDP_SCOPES;
54
+ const list = raw === void 0 || typeof raw === "string" && !raw.trim() ? [...DEFAULT_SCOPES] : (typeof raw === "string" ? raw.split(/\s+/) : [...raw]).filter(Boolean);
55
+ if (!list.includes("openid")) problems.push("scopes (IDP_SCOPES) must include openid");
56
+ return [...new Set(list)].join(" ");
57
+ }
58
+ function envOf(options) {
59
+ return options.env ?? (typeof process === "undefined" ? void 0 : process.env);
60
+ }
61
+ function absoluteUri(value, label, problems) {
62
+ if (value === void 0) return void 0;
63
+ try {
64
+ new URL(value);
65
+ return value;
66
+ } catch {
67
+ problems.push(`${label} must be an absolute URI`);
68
+ return void 0;
69
+ }
70
+ }
71
+ function misconfigured(problems) {
72
+ return new IdpError("misconfigured", `nextidp is misconfigured: ${problems.join("; ")}.`);
73
+ }
74
+ function resolveApiConfig(options) {
75
+ const env = envOf(options);
76
+ const problems = [];
77
+ const issuer = httpUrl(
78
+ pick(options.issuer, env, "IDP_ISSUER"),
79
+ "issuer (IDP_ISSUER)",
80
+ problems,
81
+ env?.NODE_ENV === "production"
82
+ );
83
+ const audience = absoluteUri(
84
+ pick(options.audience, env, "IDP_AUDIENCE"),
85
+ "audience (IDP_AUDIENCE)",
86
+ problems
87
+ );
88
+ if (!audience && !problems.some((p) => p.startsWith("audience"))) {
89
+ problems.push("audience (IDP_AUDIENCE) is required to check access tokens: this API's URI");
90
+ }
91
+ if (problems.length > 0 || !issuer || !audience) throw misconfigured(problems);
92
+ return {
93
+ issuer: issuer.href.replace(/\/+$/, ""),
94
+ audience,
95
+ clientId: pick(options.clientId, env, "IDP_CLIENT_ID"),
96
+ clientSecret: pick(options.clientSecret, env, "IDP_CLIENT_SECRET"),
97
+ acceptOwnTokens: options.acceptOwnTokens ?? false
98
+ };
99
+ }
100
+ function resolveServiceConfig(options) {
101
+ const env = envOf(options);
102
+ const problems = [];
103
+ const issuer = httpUrl(
104
+ pick(options.issuer, env, "IDP_ISSUER"),
105
+ "issuer (IDP_ISSUER)",
106
+ problems,
107
+ env?.NODE_ENV === "production"
108
+ );
109
+ const clientId = pick(options.clientId, env, "IDP_CLIENT_ID");
110
+ if (!clientId) problems.push("clientId (IDP_CLIENT_ID) is required for service tokens");
111
+ const clientSecret = pick(options.clientSecret, env, "IDP_CLIENT_SECRET");
112
+ if (!clientSecret) {
113
+ problems.push(
114
+ "clientSecret (IDP_CLIENT_SECRET) is required for service tokens: a confidential client"
115
+ );
116
+ }
117
+ const resource = absoluteUri(
118
+ pick(options.resource, env, "IDP_RESOURCE"),
119
+ "resource (IDP_RESOURCE)",
120
+ problems
121
+ );
122
+ if (problems.length > 0 || !issuer || !clientId || !clientSecret) throw misconfigured(problems);
123
+ return { issuer: issuer.href.replace(/\/+$/, ""), clientId, clientSecret, resource };
124
+ }
125
+ function resolveConfig(options) {
126
+ const env = envOf(options);
127
+ const production = env?.NODE_ENV === "production";
128
+ const problems = [];
129
+ const issuer = httpUrl(
130
+ pick(options.issuer, env, "IDP_ISSUER"),
131
+ "issuer (IDP_ISSUER)",
132
+ problems,
133
+ production
134
+ );
135
+ const app = httpUrl(
136
+ pick(options.appUrl, env, "IDP_APP_URL"),
137
+ "appUrl (IDP_APP_URL)",
138
+ problems,
139
+ production
140
+ );
141
+ if (app && app.pathname !== "/") {
142
+ problems.push("appUrl (IDP_APP_URL) must be an origin, like https://app.example.com");
143
+ }
144
+ const clientId = pick(options.clientId, env, "IDP_CLIENT_ID");
145
+ if (!clientId) problems.push("clientId (IDP_CLIENT_ID) is required");
146
+ const clientSecret = pick(options.clientSecret, env, "IDP_CLIENT_SECRET");
147
+ const secrets = secretsFrom(options.secret, env, problems);
148
+ const scope = scopesFrom(options.scopes, env, problems);
149
+ const resource = absoluteUri(
150
+ pick(options.resource, env, "IDP_RESOURCE"),
151
+ "resource (IDP_RESOURCE)",
152
+ problems
153
+ );
154
+ const basePath = options.basePath ?? "/auth";
155
+ if (!/^\/[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)*$/.test(basePath)) {
156
+ problems.push("basePath must be a path like /auth, without a trailing slash");
157
+ }
158
+ const afterSignIn = path(options.afterSignIn, "afterSignIn", "/", problems);
159
+ const afterSignOut = path(options.afterSignOut, "afterSignOut", "/", problems);
160
+ const errorPath = path(options.errorPath, "errorPath", "/", problems);
161
+ const sessionMaxAge = options.sessionMaxAge ?? SEVEN_DAYS;
162
+ if (!Number.isInteger(sessionMaxAge) || sessionMaxAge < 60) {
163
+ problems.push("sessionMaxAge must be a whole number of seconds, at least 60");
164
+ }
165
+ const prefix = options.cookiePrefix ?? "nextidp";
166
+ if (!/^[A-Za-z0-9._-]{1,32}$/.test(prefix)) {
167
+ problems.push("cookiePrefix may hold letters, digits, dots, dashes and underscores only");
168
+ }
169
+ const store = options.store;
170
+ if (store !== void 0 && (typeof store?.get !== "function" || typeof store.set !== "function" || typeof store.delete !== "function")) {
171
+ problems.push("store must have get, set and delete functions");
172
+ }
173
+ if (problems.length > 0 || !issuer || !app || !clientId) throw misconfigured(problems);
174
+ const appUrl = app.origin;
175
+ const secure = app.protocol === "https:";
176
+ const name = (purpose) => `${secure ? "__Host-" : ""}${prefix}.${purpose}`;
177
+ return {
178
+ // Kept exactly as written, without a trailing slash: it's compared with the discovery
179
+ // document's issuer and every token's `iss`.
180
+ issuer: issuer.href.replace(/\/+$/, ""),
181
+ clientId,
182
+ clientSecret,
183
+ appUrl,
184
+ secrets,
185
+ scope,
186
+ resource,
187
+ basePath,
188
+ redirectUri: `${appUrl}${basePath}/callback`,
189
+ afterSignIn,
190
+ afterSignOut,
191
+ postLogoutRedirectUri: `${appUrl}${afterSignOut}`,
192
+ errorPath,
193
+ signOutOfIdp: options.signOutOfIdp ?? false,
194
+ sessionMaxAge,
195
+ secure,
196
+ cookies: { session: name("session"), flow: name("flow") },
197
+ store,
198
+ backchannelLogoutUri: `${appUrl}${basePath}/backchannel-logout`
199
+ };
200
+ }
201
+ export {
202
+ DEFAULT_SCOPES,
203
+ resolveApiConfig,
204
+ resolveConfig,
205
+ resolveServiceConfig
206
+ };
@@ -0,0 +1,23 @@
1
+ /** A sealed session is base64url with dots: under this, one cookie; over it, several. */
2
+ export declare const CHUNK_SIZE = 3800;
3
+ export type CookieJar = ReadonlyMap<string, string>;
4
+ /** The cookies a request carries. When a name comes twice, the first is kept. */
5
+ export declare function parseCookies(header: string | null | undefined): CookieJar;
6
+ export type CookieAttributes = {
7
+ secure: boolean;
8
+ maxAge: number;
9
+ };
10
+ /** A value written by `writeCookie`: the one cookie, or its chunks joined in order. */
11
+ export declare function readCookie(jar: CookieJar, name: string): string | undefined;
12
+ /**
13
+ * Set-Cookie headers that store `value` under `name`, split if it's too big, and expire
14
+ * whatever the request still holds under that name that the new value doesn't overwrite.
15
+ */
16
+ export declare function writeCookie(jar: CookieJar, name: string, value: string, attributes: CookieAttributes): string[];
17
+ /** 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[];
19
+ /**
20
+ * The Cookie header the rest of this request should see once `setCookies` apply: what a
21
+ * proxy hands on, so the page renders with the refreshed session and not the old one.
22
+ */
23
+ export declare function applySetCookies(header: string | null | undefined, setCookies: readonly string[]): string;
@@ -0,0 +1,89 @@
1
+ const CHUNK_SIZE = 3800;
2
+ const MAX_CHUNKS = 10;
3
+ function parseCookies(header) {
4
+ const jar = /* @__PURE__ */ new Map();
5
+ for (const pair of (header ?? "").split(";")) {
6
+ const index = pair.indexOf("=");
7
+ if (index <= 0) continue;
8
+ const name = pair.slice(0, index).trim();
9
+ if (!name || jar.has(name)) continue;
10
+ let value = pair.slice(index + 1).trim();
11
+ if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
12
+ jar.set(name, value);
13
+ }
14
+ return jar;
15
+ }
16
+ function serialize(name, value, { secure, maxAge }) {
17
+ return [
18
+ `${name}=${value}`,
19
+ "Path=/",
20
+ `Max-Age=${maxAge}`,
21
+ "HttpOnly",
22
+ "SameSite=Lax",
23
+ ...secure ? ["Secure"] : []
24
+ ].join("; ");
25
+ }
26
+ function chunkNames(jar, name) {
27
+ return [...jar.keys()].filter(
28
+ (key) => key.startsWith(`${name}.`) && /^\d+$/.test(key.slice(name.length + 1))
29
+ );
30
+ }
31
+ function readCookie(jar, name) {
32
+ const whole = jar.get(name);
33
+ if (whole) return whole;
34
+ const parts = [];
35
+ for (let index = 0; index < MAX_CHUNKS; index += 1) {
36
+ const part = jar.get(`${name}.${index}`);
37
+ if (part === void 0) break;
38
+ parts.push(part);
39
+ }
40
+ return parts.length > 0 ? parts.join("") : void 0;
41
+ }
42
+ function writeCookie(jar, name, value, attributes) {
43
+ const headers = [];
44
+ const written = /* @__PURE__ */ new Set();
45
+ if (value.length <= CHUNK_SIZE) {
46
+ headers.push(serialize(name, value, attributes));
47
+ written.add(name);
48
+ } else {
49
+ const count = Math.ceil(value.length / CHUNK_SIZE);
50
+ if (count > MAX_CHUNKS) throw new Error("The session is too big to keep in cookies.");
51
+ for (let index = 0; index < count; index += 1) {
52
+ const chunk = `${name}.${index}`;
53
+ headers.push(
54
+ serialize(chunk, value.slice(index * CHUNK_SIZE, (index + 1) * CHUNK_SIZE), attributes)
55
+ );
56
+ written.add(chunk);
57
+ }
58
+ }
59
+ for (const stale of [name, ...chunkNames(jar, name)]) {
60
+ if (!written.has(stale) && jar.has(stale))
61
+ headers.push(serialize(stale, "", { ...attributes, maxAge: 0 }));
62
+ }
63
+ return headers;
64
+ }
65
+ function clearCookie(jar, name, secure) {
66
+ const names = /* @__PURE__ */ new Set([name, ...chunkNames(jar, name)]);
67
+ return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0 }));
68
+ }
69
+ function applySetCookies(header, setCookies) {
70
+ const jar = new Map(parseCookies(header));
71
+ for (const line of setCookies) {
72
+ const [pair = ""] = line.split(";");
73
+ const index = pair.indexOf("=");
74
+ if (index <= 0) continue;
75
+ const name = pair.slice(0, index);
76
+ const value = pair.slice(index + 1);
77
+ if (/;\s*Max-Age=0(?:;|$)/i.test(line)) jar.delete(name);
78
+ else jar.set(name, value);
79
+ }
80
+ return [...jar].map(([name, value]) => `${name}=${value}`).join("; ");
81
+ }
82
+ export {
83
+ CHUNK_SIZE,
84
+ applySetCookies,
85
+ clearCookie,
86
+ parseCookies,
87
+ readCookie,
88
+ writeCookie
89
+ };
@@ -0,0 +1,24 @@
1
+ import * as v from "valibot";
2
+ import type { Http } from "./http.js";
3
+ declare const DiscoverySchema: v.ObjectSchema<{
4
+ readonly issuer: v.StringSchema<undefined>;
5
+ readonly authorization_endpoint: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>;
6
+ readonly token_endpoint: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>;
7
+ readonly jwks_uri: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>;
8
+ readonly userinfo_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
9
+ readonly revocation_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
10
+ /** RFC 7662: whether an opaque access token is active, asked with a client's credentials. */
11
+ readonly introspection_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
12
+ /** RP-initiated logout: where to send someone to sign out of the auth server too. */
13
+ readonly end_session_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
14
+ readonly id_token_signing_alg_values_supported: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
15
+ }, undefined>;
16
+ export type Discovery = v.InferOutput<typeof DiscoverySchema>;
17
+ /**
18
+ * Checks a discovery document. Its `issuer` must be the issuer it was fetched for (Discovery
19
+ * 4.3), or tokens could be accepted from a server that only claims to be it.
20
+ */
21
+ export declare function parseDiscovery(document: unknown, expectedIssuer: string): Discovery;
22
+ /** The issuer's discovery document, fetched once an hour; concurrent callers share a fetch. */
23
+ export declare function createDiscovery(http: Http, issuer: string): () => Promise<Discovery>;
24
+ export {};
@@ -0,0 +1,56 @@
1
+ import * as v from "valibot";
2
+ import { IdpError } from "./errors.js";
3
+ const Url = v.pipe(v.string(), v.url());
4
+ const DiscoverySchema = v.object({
5
+ issuer: v.string(),
6
+ authorization_endpoint: Url,
7
+ token_endpoint: Url,
8
+ jwks_uri: Url,
9
+ userinfo_endpoint: v.optional(Url),
10
+ revocation_endpoint: v.optional(Url),
11
+ /** RFC 7662: whether an opaque access token is active, asked with a client's credentials. */
12
+ introspection_endpoint: v.optional(Url),
13
+ /** RP-initiated logout: where to send someone to sign out of the auth server too. */
14
+ end_session_endpoint: v.optional(Url),
15
+ id_token_signing_alg_values_supported: v.optional(v.array(v.string()))
16
+ });
17
+ const ONE_HOUR = 60 * 60 * 1e3;
18
+ function parseDiscovery(document, expectedIssuer) {
19
+ const parsed = v.safeParse(DiscoverySchema, document);
20
+ if (!parsed.success) {
21
+ throw new IdpError("discovery_failed", "The discovery document is missing endpoints.");
22
+ }
23
+ if (parsed.output.issuer.replace(/\/+$/, "") !== expectedIssuer) {
24
+ throw new IdpError("discovery_failed", "The discovery document names a different issuer.");
25
+ }
26
+ return parsed.output;
27
+ }
28
+ function createDiscovery(http, issuer) {
29
+ let cached;
30
+ return () => {
31
+ if (cached && cached.until > Date.now()) return cached.value;
32
+ const value = (async () => {
33
+ let answer;
34
+ try {
35
+ answer = await http.get(`${issuer}/.well-known/openid-configuration`);
36
+ } catch (cause) {
37
+ throw new IdpError("discovery_failed", "The auth server didn't answer.", { cause });
38
+ }
39
+ if (!answer.ok) {
40
+ throw new IdpError("discovery_failed", `Discovery answered ${answer.status}.`, {
41
+ status: answer.status
42
+ });
43
+ }
44
+ return parseDiscovery(answer.data, issuer);
45
+ })();
46
+ cached = { value, until: Date.now() + ONE_HOUR };
47
+ value.catch(() => {
48
+ if (cached?.value === value) cached = void 0;
49
+ });
50
+ return value;
51
+ };
52
+ }
53
+ export {
54
+ createDiscovery,
55
+ parseDiscovery
56
+ };