nextidp 0.0.0-stage → 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 (98) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/LICENSE +21 -0
  3. package/README.md +436 -2
  4. package/dist/cjs/access-token.d.ts +56 -0
  5. package/dist/cjs/access-token.js +196 -0
  6. package/dist/cjs/config.d.ts +128 -0
  7. package/dist/cjs/config.js +233 -0
  8. package/dist/cjs/cookies.d.ts +23 -0
  9. package/dist/cjs/cookies.js +118 -0
  10. package/dist/cjs/discovery.d.ts +24 -0
  11. package/dist/cjs/discovery.js +91 -0
  12. package/dist/cjs/errors.d.ts +63 -0
  13. package/dist/cjs/errors.js +69 -0
  14. package/dist/cjs/express.d.ts +71 -0
  15. package/dist/cjs/express.js +114 -0
  16. package/dist/cjs/http.d.ts +10 -0
  17. package/dist/cjs/http.js +68 -0
  18. package/dist/cjs/id-token.d.ts +19 -0
  19. package/dist/cjs/id-token.js +77 -0
  20. package/dist/cjs/idp.d.ts +81 -0
  21. package/dist/cjs/idp.js +482 -0
  22. package/dist/cjs/index.d.ts +9 -0
  23. package/dist/cjs/index.js +53 -0
  24. package/dist/cjs/logout-token.d.ts +13 -0
  25. package/dist/cjs/logout-token.js +63 -0
  26. package/dist/cjs/nestjs.d.ts +53 -0
  27. package/dist/cjs/nestjs.js +142 -0
  28. package/dist/cjs/next.d.ts +61 -0
  29. package/dist/cjs/next.js +118 -0
  30. package/dist/cjs/node-adapter.d.ts +16 -0
  31. package/dist/cjs/node-adapter.js +76 -0
  32. package/dist/cjs/node-http.d.ts +22 -0
  33. package/dist/cjs/node-http.js +127 -0
  34. package/dist/cjs/node.d.ts +50 -0
  35. package/dist/cjs/node.js +57 -0
  36. package/dist/cjs/package.json +1 -0
  37. package/dist/cjs/pkce.d.ts +6 -0
  38. package/dist/cjs/pkce.js +49 -0
  39. package/dist/cjs/return-path.d.ts +6 -0
  40. package/dist/cjs/return-path.js +41 -0
  41. package/dist/cjs/sealed.d.ts +12 -0
  42. package/dist/cjs/sealed.js +78 -0
  43. package/dist/cjs/service.d.ts +61 -0
  44. package/dist/cjs/service.js +173 -0
  45. package/dist/cjs/session.d.ts +51 -0
  46. package/dist/cjs/session.js +97 -0
  47. package/dist/cjs/store.d.ts +58 -0
  48. package/dist/cjs/store.js +145 -0
  49. package/dist/cjs/tokens.d.ts +38 -0
  50. package/dist/cjs/tokens.js +138 -0
  51. package/dist/esm/access-token.d.ts +56 -0
  52. package/dist/esm/access-token.js +156 -0
  53. package/dist/esm/config.d.ts +128 -0
  54. package/dist/esm/config.js +206 -0
  55. package/dist/esm/cookies.d.ts +23 -0
  56. package/dist/esm/cookies.js +89 -0
  57. package/dist/esm/discovery.d.ts +24 -0
  58. package/dist/esm/discovery.js +56 -0
  59. package/dist/esm/errors.d.ts +63 -0
  60. package/dist/esm/errors.js +41 -0
  61. package/dist/esm/express.d.ts +71 -0
  62. package/dist/esm/express.js +90 -0
  63. package/dist/esm/http.d.ts +10 -0
  64. package/dist/esm/http.js +44 -0
  65. package/dist/esm/id-token.d.ts +19 -0
  66. package/dist/esm/id-token.js +51 -0
  67. package/dist/esm/idp.d.ts +81 -0
  68. package/dist/esm/idp.js +488 -0
  69. package/dist/esm/index.d.ts +9 -0
  70. package/dist/esm/index.js +30 -0
  71. package/dist/esm/logout-token.d.ts +13 -0
  72. package/dist/esm/logout-token.js +39 -0
  73. package/dist/esm/nestjs.d.ts +53 -0
  74. package/dist/esm/nestjs.js +118 -0
  75. package/dist/esm/next.d.ts +61 -0
  76. package/dist/esm/next.js +94 -0
  77. package/dist/esm/node-adapter.d.ts +16 -0
  78. package/dist/esm/node-adapter.js +60 -0
  79. package/dist/esm/node-http.d.ts +22 -0
  80. package/dist/esm/node-http.js +96 -0
  81. package/dist/esm/node.d.ts +50 -0
  82. package/dist/esm/node.js +33 -0
  83. package/dist/esm/package.json +1 -0
  84. package/dist/esm/pkce.d.ts +6 -0
  85. package/dist/esm/pkce.js +23 -0
  86. package/dist/esm/return-path.d.ts +6 -0
  87. package/dist/esm/return-path.js +17 -0
  88. package/dist/esm/sealed.d.ts +12 -0
  89. package/dist/esm/sealed.js +54 -0
  90. package/dist/esm/service.d.ts +61 -0
  91. package/dist/esm/service.js +148 -0
  92. package/dist/esm/session.d.ts +51 -0
  93. package/dist/esm/session.js +58 -0
  94. package/dist/esm/store.d.ts +58 -0
  95. package/dist/esm/store.js +119 -0
  96. package/dist/esm/tokens.d.ts +38 -0
  97. package/dist/esm/tokens.js +100 -0
  98. package/package.json +147 -3
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var access_token_exports = {};
30
+ __export(access_token_exports, {
31
+ bearerChallenge: () => bearerChallenge,
32
+ bearerToken: () => bearerToken,
33
+ introspect: () => introspect,
34
+ isJwt: () => isJwt,
35
+ requireScopes: () => requireScopes,
36
+ tokenRefusal: () => tokenRefusal,
37
+ verifyJwtAccessToken: () => verifyJwtAccessToken
38
+ });
39
+ module.exports = __toCommonJS(access_token_exports);
40
+ var import_jose = require("jose");
41
+ var v = __toESM(require("valibot"), 1);
42
+ var import_errors = require("./errors.js");
43
+ const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
44
+ const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
45
+ const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
46
+ const invalid = (message, cause) => new import_errors.IdpError("invalid_token", message, { status: 401, cause });
47
+ function bearerToken(authorization) {
48
+ return authorization ? BEARER.exec(authorization)?.[1] : void 0;
49
+ }
50
+ function list(value) {
51
+ if (typeof value === "string") return value.split(" ").filter(Boolean);
52
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
53
+ }
54
+ function toAccessToken(claims) {
55
+ const subject = typeof claims.sub === "string" ? claims.sub : void 0;
56
+ const clientId = typeof claims.client_id === "string" ? claims.client_id : typeof claims.azp === "string" ? claims.azp : void 0;
57
+ return {
58
+ subject,
59
+ clientId,
60
+ isService: subject !== void 0 && subject === clientId,
61
+ scopes: list(claims.scope),
62
+ audience: list(claims.aud),
63
+ expiresAt: typeof claims.exp === "number" ? claims.exp : void 0,
64
+ claims
65
+ };
66
+ }
67
+ function requireScopes(token, required = []) {
68
+ const missing = required.filter((scope) => !token.scopes.includes(scope));
69
+ if (missing.length > 0) {
70
+ throw new import_errors.IdpError("insufficient_scope", `The access token lacks: ${missing.join(" ")}.`, {
71
+ status: 403,
72
+ scopes: required
73
+ });
74
+ }
75
+ return token;
76
+ }
77
+ function isJwt(token) {
78
+ if (token.split(".").length !== 3) return false;
79
+ try {
80
+ (0, import_jose.decodeProtectedHeader)(token);
81
+ return true;
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+ async function verifyJwtAccessToken(token, keys, config) {
87
+ const { typ } = (0, import_jose.decodeProtectedHeader)(token);
88
+ if (typ === void 0 || !ACCESS_TOKEN_TYPES.has(typ.toLowerCase())) {
89
+ throw invalid("The token isn't a JWT access token (its typ isn't at+jwt).");
90
+ }
91
+ try {
92
+ const { payload } = await (0, import_jose.jwtVerify)(token, keys, {
93
+ algorithms: ALGORITHMS,
94
+ issuer: config.issuer,
95
+ audience: config.audience,
96
+ requiredClaims: ["exp"],
97
+ clockTolerance: 60
98
+ });
99
+ return toAccessToken(payload);
100
+ } catch (cause) {
101
+ throw invalid(
102
+ "The access token didn't verify: expired, for another API, or not signed by the issuer.",
103
+ cause
104
+ );
105
+ }
106
+ }
107
+ const IntrospectionSchema = v.looseObject({
108
+ active: v.boolean(),
109
+ scope: v.optional(v.string()),
110
+ client_id: v.optional(v.string()),
111
+ sub: v.optional(v.string()),
112
+ exp: v.optional(v.number()),
113
+ aud: v.optional(v.union([v.string(), v.array(v.string())])),
114
+ iss: v.optional(v.string())
115
+ });
116
+ async function introspect(http, discovery, config, token) {
117
+ if (!discovery.introspection_endpoint) {
118
+ throw invalid("The auth server has no introspection endpoint, and the token isn't a JWT.");
119
+ }
120
+ if (!config.clientId || !config.clientSecret) {
121
+ throw invalid(
122
+ "An opaque access token can only be checked by introspection, which needs clientId and clientSecret. Ask for tokens with `resource` to get JWTs instead."
123
+ );
124
+ }
125
+ const pair = `${encodeURIComponent(config.clientId)}:${encodeURIComponent(config.clientSecret)}`;
126
+ let answer;
127
+ try {
128
+ answer = await http.postForm(
129
+ discovery.introspection_endpoint,
130
+ new URLSearchParams({ token, token_type_hint: "access_token" }),
131
+ { authorization: `Basic ${btoa(pair)}` }
132
+ );
133
+ } catch (cause) {
134
+ throw new import_errors.IdpError("discovery_failed", "The introspection endpoint didn't answer.", { cause });
135
+ }
136
+ if (!answer.ok) {
137
+ throw new import_errors.IdpError(
138
+ "misconfigured",
139
+ `Introspection answered ${answer.status}: check clientId and clientSecret.`,
140
+ {
141
+ status: answer.status
142
+ }
143
+ );
144
+ }
145
+ const parsed = v.safeParse(IntrospectionSchema, answer.data);
146
+ if (!parsed.success) throw invalid("The introspection answer isn't valid.");
147
+ if (!parsed.output.active) throw invalid("The access token isn't active.");
148
+ if (parsed.output.iss !== void 0 && parsed.output.iss.replace(/\/+$/, "") !== config.issuer) {
149
+ throw invalid("The access token is from another issuer.");
150
+ }
151
+ const checked = toAccessToken(parsed.output);
152
+ const own = config.acceptOwnTokens && checked.clientId === config.clientId;
153
+ if (!checked.audience.includes(config.audience) && !own) {
154
+ throw invalid("The access token is for another API.");
155
+ }
156
+ if (checked.expiresAt !== void 0 && checked.expiresAt <= Math.floor(Date.now() / 1e3)) {
157
+ throw invalid("The access token has expired.");
158
+ }
159
+ return checked;
160
+ }
161
+ function quoted(value) {
162
+ return `"${value.replace(/[\\"]/g, "\\$&")}"`;
163
+ }
164
+ function bearerChallenge(error) {
165
+ if (error.code === "missing_token") return "Bearer";
166
+ const parts = [
167
+ `error=${quoted(error.code === "insufficient_scope" ? "insufficient_scope" : "invalid_token")}`
168
+ ];
169
+ parts.push(`error_description=${quoted(error.message)}`);
170
+ if (error.code === "insufficient_scope" && error.scopes?.length) {
171
+ parts.push(`scope=${quoted(error.scopes.join(" "))}`);
172
+ }
173
+ return `Bearer ${parts.join(", ")}`;
174
+ }
175
+ function tokenRefusal(error) {
176
+ const status = error.code === "insufficient_scope" ? 403 : 401;
177
+ return {
178
+ status,
179
+ headers: {
180
+ "www-authenticate": bearerChallenge(error),
181
+ "content-type": "application/json",
182
+ "cache-control": "no-store"
183
+ },
184
+ body: { error: error.code, error_description: error.message }
185
+ };
186
+ }
187
+ // Annotate the CommonJS export names for ESM import in node:
188
+ 0 && (module.exports = {
189
+ bearerChallenge,
190
+ bearerToken,
191
+ introspect,
192
+ isJwt,
193
+ requireScopes,
194
+ tokenRefusal,
195
+ verifyJwtAccessToken
196
+ });
@@ -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,233 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var config_exports = {};
20
+ __export(config_exports, {
21
+ DEFAULT_SCOPES: () => DEFAULT_SCOPES,
22
+ resolveApiConfig: () => resolveApiConfig,
23
+ resolveConfig: () => resolveConfig,
24
+ resolveServiceConfig: () => resolveServiceConfig
25
+ });
26
+ module.exports = __toCommonJS(config_exports);
27
+ var import_errors = require("./errors.js");
28
+ var import_return_path = require("./return-path.js");
29
+ const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
30
+ const SEVEN_DAYS = 7 * 24 * 60 * 60;
31
+ const MIN_SECRET_LENGTH = 32;
32
+ function pick(option, env, variable) {
33
+ const value = option ?? env?.[variable];
34
+ const trimmed = value?.trim();
35
+ return trimmed ? trimmed : void 0;
36
+ }
37
+ function httpUrl(value, label, problems, production) {
38
+ if (value === void 0) {
39
+ problems.push(`${label} is required`);
40
+ return void 0;
41
+ }
42
+ let url;
43
+ try {
44
+ url = new URL(value);
45
+ } catch {
46
+ problems.push(`${label} must be a URL like https://example.com`);
47
+ return void 0;
48
+ }
49
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
50
+ problems.push(`${label} must be an http(s) URL`);
51
+ return void 0;
52
+ }
53
+ if (production && url.protocol !== "https:") {
54
+ problems.push(`${label} must be https in production`);
55
+ return void 0;
56
+ }
57
+ if (url.search || url.hash || url.username || url.password) {
58
+ problems.push(`${label} must have no query, fragment or credentials`);
59
+ return void 0;
60
+ }
61
+ return url;
62
+ }
63
+ function path(value, label, fallback, problems) {
64
+ if (value === void 0) return fallback;
65
+ const safe = (0, import_return_path.safePath)(value);
66
+ if (!safe) problems.push(`${label} must be a path of this app, like /dashboard`);
67
+ return safe ?? fallback;
68
+ }
69
+ function secretsFrom(option, env, problems) {
70
+ const list = option === void 0 ? (env?.IDP_SECRET ?? "").split(",") : typeof option === "string" ? [option] : [...option];
71
+ const secrets = list.map((secret) => secret.trim()).filter(Boolean);
72
+ if (secrets.length === 0) problems.push("secret (IDP_SECRET) is required");
73
+ if (secrets.some((secret) => secret.length < MIN_SECRET_LENGTH)) {
74
+ problems.push(`secret (IDP_SECRET) must be at least ${MIN_SECRET_LENGTH} characters`);
75
+ }
76
+ return secrets;
77
+ }
78
+ function scopesFrom(option, env, problems) {
79
+ const raw = option ?? env?.IDP_SCOPES;
80
+ const list = raw === void 0 || typeof raw === "string" && !raw.trim() ? [...DEFAULT_SCOPES] : (typeof raw === "string" ? raw.split(/\s+/) : [...raw]).filter(Boolean);
81
+ if (!list.includes("openid")) problems.push("scopes (IDP_SCOPES) must include openid");
82
+ return [...new Set(list)].join(" ");
83
+ }
84
+ function envOf(options) {
85
+ return options.env ?? (typeof process === "undefined" ? void 0 : process.env);
86
+ }
87
+ function absoluteUri(value, label, problems) {
88
+ if (value === void 0) return void 0;
89
+ try {
90
+ new URL(value);
91
+ return value;
92
+ } catch {
93
+ problems.push(`${label} must be an absolute URI`);
94
+ return void 0;
95
+ }
96
+ }
97
+ function misconfigured(problems) {
98
+ return new import_errors.IdpError("misconfigured", `nextidp is misconfigured: ${problems.join("; ")}.`);
99
+ }
100
+ function resolveApiConfig(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 audience = absoluteUri(
110
+ pick(options.audience, env, "IDP_AUDIENCE"),
111
+ "audience (IDP_AUDIENCE)",
112
+ problems
113
+ );
114
+ if (!audience && !problems.some((p) => p.startsWith("audience"))) {
115
+ problems.push("audience (IDP_AUDIENCE) is required to check access tokens: this API's URI");
116
+ }
117
+ if (problems.length > 0 || !issuer || !audience) throw misconfigured(problems);
118
+ return {
119
+ issuer: issuer.href.replace(/\/+$/, ""),
120
+ audience,
121
+ clientId: pick(options.clientId, env, "IDP_CLIENT_ID"),
122
+ clientSecret: pick(options.clientSecret, env, "IDP_CLIENT_SECRET"),
123
+ acceptOwnTokens: options.acceptOwnTokens ?? false
124
+ };
125
+ }
126
+ function resolveServiceConfig(options) {
127
+ const env = envOf(options);
128
+ const problems = [];
129
+ const issuer = httpUrl(
130
+ pick(options.issuer, env, "IDP_ISSUER"),
131
+ "issuer (IDP_ISSUER)",
132
+ problems,
133
+ env?.NODE_ENV === "production"
134
+ );
135
+ const clientId = pick(options.clientId, env, "IDP_CLIENT_ID");
136
+ if (!clientId) problems.push("clientId (IDP_CLIENT_ID) is required for service tokens");
137
+ const clientSecret = pick(options.clientSecret, env, "IDP_CLIENT_SECRET");
138
+ if (!clientSecret) {
139
+ problems.push(
140
+ "clientSecret (IDP_CLIENT_SECRET) is required for service tokens: a confidential client"
141
+ );
142
+ }
143
+ const resource = absoluteUri(
144
+ pick(options.resource, env, "IDP_RESOURCE"),
145
+ "resource (IDP_RESOURCE)",
146
+ problems
147
+ );
148
+ if (problems.length > 0 || !issuer || !clientId || !clientSecret) throw misconfigured(problems);
149
+ return { issuer: issuer.href.replace(/\/+$/, ""), clientId, clientSecret, resource };
150
+ }
151
+ function resolveConfig(options) {
152
+ const env = envOf(options);
153
+ const production = env?.NODE_ENV === "production";
154
+ const problems = [];
155
+ const issuer = httpUrl(
156
+ pick(options.issuer, env, "IDP_ISSUER"),
157
+ "issuer (IDP_ISSUER)",
158
+ problems,
159
+ production
160
+ );
161
+ const app = httpUrl(
162
+ pick(options.appUrl, env, "IDP_APP_URL"),
163
+ "appUrl (IDP_APP_URL)",
164
+ problems,
165
+ production
166
+ );
167
+ if (app && app.pathname !== "/") {
168
+ problems.push("appUrl (IDP_APP_URL) must be an origin, like https://app.example.com");
169
+ }
170
+ const clientId = pick(options.clientId, env, "IDP_CLIENT_ID");
171
+ if (!clientId) problems.push("clientId (IDP_CLIENT_ID) is required");
172
+ const clientSecret = pick(options.clientSecret, env, "IDP_CLIENT_SECRET");
173
+ const secrets = secretsFrom(options.secret, env, problems);
174
+ const scope = scopesFrom(options.scopes, env, problems);
175
+ const resource = absoluteUri(
176
+ pick(options.resource, env, "IDP_RESOURCE"),
177
+ "resource (IDP_RESOURCE)",
178
+ problems
179
+ );
180
+ const basePath = options.basePath ?? "/auth";
181
+ if (!/^\/[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)*$/.test(basePath)) {
182
+ problems.push("basePath must be a path like /auth, without a trailing slash");
183
+ }
184
+ const afterSignIn = path(options.afterSignIn, "afterSignIn", "/", problems);
185
+ const afterSignOut = path(options.afterSignOut, "afterSignOut", "/", problems);
186
+ const errorPath = path(options.errorPath, "errorPath", "/", problems);
187
+ const sessionMaxAge = options.sessionMaxAge ?? SEVEN_DAYS;
188
+ if (!Number.isInteger(sessionMaxAge) || sessionMaxAge < 60) {
189
+ problems.push("sessionMaxAge must be a whole number of seconds, at least 60");
190
+ }
191
+ const prefix = options.cookiePrefix ?? "nextidp";
192
+ if (!/^[A-Za-z0-9._-]{1,32}$/.test(prefix)) {
193
+ problems.push("cookiePrefix may hold letters, digits, dots, dashes and underscores only");
194
+ }
195
+ const store = options.store;
196
+ if (store !== void 0 && (typeof store?.get !== "function" || typeof store.set !== "function" || typeof store.delete !== "function")) {
197
+ problems.push("store must have get, set and delete functions");
198
+ }
199
+ if (problems.length > 0 || !issuer || !app || !clientId) throw misconfigured(problems);
200
+ const appUrl = app.origin;
201
+ const secure = app.protocol === "https:";
202
+ const name = (purpose) => `${secure ? "__Host-" : ""}${prefix}.${purpose}`;
203
+ return {
204
+ // Kept exactly as written, without a trailing slash: it's compared with the discovery
205
+ // document's issuer and every token's `iss`.
206
+ issuer: issuer.href.replace(/\/+$/, ""),
207
+ clientId,
208
+ clientSecret,
209
+ appUrl,
210
+ secrets,
211
+ scope,
212
+ resource,
213
+ basePath,
214
+ redirectUri: `${appUrl}${basePath}/callback`,
215
+ afterSignIn,
216
+ afterSignOut,
217
+ postLogoutRedirectUri: `${appUrl}${afterSignOut}`,
218
+ errorPath,
219
+ signOutOfIdp: options.signOutOfIdp ?? false,
220
+ sessionMaxAge,
221
+ secure,
222
+ cookies: { session: name("session"), flow: name("flow") },
223
+ store,
224
+ backchannelLogoutUri: `${appUrl}${basePath}/backchannel-logout`
225
+ };
226
+ }
227
+ // Annotate the CommonJS export names for ESM import in node:
228
+ 0 && (module.exports = {
229
+ DEFAULT_SCOPES,
230
+ resolveApiConfig,
231
+ resolveConfig,
232
+ resolveServiceConfig
233
+ });
@@ -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;