nextidp 0.0.1 → 0.1.3

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 (101) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +502 -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/hono.d.ts +65 -0
  16. package/dist/cjs/hono.js +130 -0
  17. package/dist/cjs/http.d.ts +10 -0
  18. package/dist/cjs/http.js +68 -0
  19. package/dist/cjs/id-token.d.ts +19 -0
  20. package/dist/cjs/id-token.js +77 -0
  21. package/dist/cjs/idp.d.ts +81 -0
  22. package/dist/cjs/idp.js +482 -0
  23. package/dist/cjs/index.d.ts +9 -0
  24. package/dist/cjs/index.js +53 -0
  25. package/dist/cjs/logout-token.d.ts +13 -0
  26. package/dist/cjs/logout-token.js +63 -0
  27. package/dist/cjs/nestjs.d.ts +53 -0
  28. package/dist/cjs/nestjs.js +142 -0
  29. package/dist/cjs/next.d.ts +61 -0
  30. package/dist/cjs/next.js +118 -0
  31. package/dist/cjs/node-adapter.d.ts +16 -0
  32. package/dist/cjs/node-adapter.js +76 -0
  33. package/dist/cjs/node-http.d.ts +22 -0
  34. package/dist/cjs/node-http.js +127 -0
  35. package/dist/cjs/node.d.ts +50 -0
  36. package/dist/cjs/node.js +57 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/pkce.d.ts +6 -0
  39. package/dist/cjs/pkce.js +49 -0
  40. package/dist/cjs/return-path.d.ts +6 -0
  41. package/dist/cjs/return-path.js +41 -0
  42. package/dist/cjs/sealed.d.ts +12 -0
  43. package/dist/cjs/sealed.js +78 -0
  44. package/dist/cjs/service.d.ts +61 -0
  45. package/dist/cjs/service.js +173 -0
  46. package/dist/cjs/session.d.ts +51 -0
  47. package/dist/cjs/session.js +97 -0
  48. package/dist/cjs/store.d.ts +58 -0
  49. package/dist/cjs/store.js +145 -0
  50. package/dist/cjs/tokens.d.ts +38 -0
  51. package/dist/cjs/tokens.js +138 -0
  52. package/dist/esm/access-token.d.ts +56 -0
  53. package/dist/esm/access-token.js +156 -0
  54. package/dist/esm/config.d.ts +128 -0
  55. package/dist/esm/config.js +206 -0
  56. package/dist/esm/cookies.d.ts +23 -0
  57. package/dist/esm/cookies.js +89 -0
  58. package/dist/esm/discovery.d.ts +24 -0
  59. package/dist/esm/discovery.js +56 -0
  60. package/dist/esm/errors.d.ts +63 -0
  61. package/dist/esm/errors.js +41 -0
  62. package/dist/esm/express.d.ts +71 -0
  63. package/dist/esm/express.js +90 -0
  64. package/dist/esm/hono.d.ts +65 -0
  65. package/dist/esm/hono.js +106 -0
  66. package/dist/esm/http.d.ts +10 -0
  67. package/dist/esm/http.js +44 -0
  68. package/dist/esm/id-token.d.ts +19 -0
  69. package/dist/esm/id-token.js +51 -0
  70. package/dist/esm/idp.d.ts +81 -0
  71. package/dist/esm/idp.js +488 -0
  72. package/dist/esm/index.d.ts +9 -0
  73. package/dist/esm/index.js +30 -0
  74. package/dist/esm/logout-token.d.ts +13 -0
  75. package/dist/esm/logout-token.js +39 -0
  76. package/dist/esm/nestjs.d.ts +53 -0
  77. package/dist/esm/nestjs.js +118 -0
  78. package/dist/esm/next.d.ts +61 -0
  79. package/dist/esm/next.js +94 -0
  80. package/dist/esm/node-adapter.d.ts +16 -0
  81. package/dist/esm/node-adapter.js +60 -0
  82. package/dist/esm/node-http.d.ts +22 -0
  83. package/dist/esm/node-http.js +96 -0
  84. package/dist/esm/node.d.ts +50 -0
  85. package/dist/esm/node.js +33 -0
  86. package/dist/esm/package.json +1 -0
  87. package/dist/esm/pkce.d.ts +6 -0
  88. package/dist/esm/pkce.js +23 -0
  89. package/dist/esm/return-path.d.ts +6 -0
  90. package/dist/esm/return-path.js +17 -0
  91. package/dist/esm/sealed.d.ts +12 -0
  92. package/dist/esm/sealed.js +54 -0
  93. package/dist/esm/service.d.ts +61 -0
  94. package/dist/esm/service.js +148 -0
  95. package/dist/esm/session.d.ts +51 -0
  96. package/dist/esm/session.js +58 -0
  97. package/dist/esm/store.d.ts +58 -0
  98. package/dist/esm/store.js +119 -0
  99. package/dist/esm/tokens.d.ts +38 -0
  100. package/dist/esm/tokens.js +100 -0
  101. package/package.json +152 -5
@@ -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
+ };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Why a sign-in didn't finish. The app is sent to its `errorPath` with `?error=<code>`, so it
3
+ * can say what happened; these are the only codes it ever gets there.
4
+ */
5
+ export type SignInErrorCode =
6
+ /** The person chose Deny on the auth server. */
7
+ "access_denied"
8
+ /** The sign-in took longer than 10 minutes, or its cookie was lost. */
9
+ | "expired"
10
+ /** The answer wasn't for a sign-in this browser started. */
11
+ | "state_mismatch"
12
+ /** The auth server refused the code, or answered with an error. */
13
+ | "token_failed"
14
+ /** The ID token's signature, issuer, audience, expiry or nonce was wrong. */
15
+ | "invalid_id_token"
16
+ /** The refresh token was refused: used, revoked or expired. */
17
+ | "refresh_failed";
18
+ export declare const SIGN_IN_ERROR_CODES: readonly SignInErrorCode[];
19
+ export declare function isSignInErrorCode(value: unknown): value is SignInErrorCode;
20
+ export type IdpErrorCode = SignInErrorCode
21
+ /** A setting is missing or wrong: the message names it. */
22
+ | "misconfigured"
23
+ /** The auth server's discovery document couldn't be fetched or isn't valid. */
24
+ | "discovery_failed"
25
+ /** The userinfo endpoint refused the access token or didn't answer. */
26
+ | "userinfo_failed"
27
+ /** An API was called without an access token (401, no error code in the challenge). */
28
+ | "missing_token"
29
+ /** The access token is expired, revoked, for another API, or not valid at all (401). */
30
+ | "invalid_token"
31
+ /** The access token is valid but lacks a scope this route needs (403). */
32
+ | "insufficient_scope"
33
+ /** The token endpoint refused this service's client credentials, or didn't answer. */
34
+ | "service_token_failed"
35
+ /** A back-channel logout request's token didn't verify, or isn't a logout token. */
36
+ | "invalid_logout_token";
37
+ /** The three codes an API answers a caller with; see `tokenErrorResponse`. */
38
+ export type TokenErrorCode = "missing_token" | "invalid_token" | "insufficient_scope";
39
+ export declare function isTokenError(error: unknown): error is IdpError & {
40
+ code: TokenErrorCode;
41
+ };
42
+ /**
43
+ * Every error nextidp throws. Its message never holds a token, a secret or a claim.
44
+ * Check it with `isIdpError`: `instanceof` can fail when an app loads both the ES module and
45
+ * the CommonJS build.
46
+ */
47
+ export declare class IdpError extends Error {
48
+ readonly name = "IdpError";
49
+ readonly code: IdpErrorCode;
50
+ /**
51
+ * The HTTP status the auth server answered with, when there was one; for a token error,
52
+ * the status to answer the caller with (401 or 403).
53
+ */
54
+ readonly status: number | undefined;
55
+ /** For insufficient_scope: the scopes the route needs, for the WWW-Authenticate challenge. */
56
+ readonly scopes: readonly string[] | undefined;
57
+ constructor(code: IdpErrorCode, message: string, options?: {
58
+ status?: number;
59
+ cause?: unknown;
60
+ scopes?: readonly string[];
61
+ });
62
+ }
63
+ export declare function isIdpError(error: unknown): error is IdpError;
@@ -0,0 +1,41 @@
1
+ const SIGN_IN_ERROR_CODES = [
2
+ "access_denied",
3
+ "expired",
4
+ "state_mismatch",
5
+ "token_failed",
6
+ "invalid_id_token",
7
+ "refresh_failed"
8
+ ];
9
+ function isSignInErrorCode(value) {
10
+ return typeof value === "string" && SIGN_IN_ERROR_CODES.includes(value);
11
+ }
12
+ function isTokenError(error) {
13
+ return isIdpError(error) && (error.code === "missing_token" || error.code === "invalid_token" || error.code === "insufficient_scope");
14
+ }
15
+ class IdpError extends Error {
16
+ name = "IdpError";
17
+ code;
18
+ /**
19
+ * The HTTP status the auth server answered with, when there was one; for a token error,
20
+ * the status to answer the caller with (401 or 403).
21
+ */
22
+ status;
23
+ /** For insufficient_scope: the scopes the route needs, for the WWW-Authenticate challenge. */
24
+ scopes;
25
+ constructor(code, message, options) {
26
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
27
+ this.code = code;
28
+ this.status = options?.status;
29
+ this.scopes = options?.scopes;
30
+ }
31
+ }
32
+ function isIdpError(error) {
33
+ return error instanceof Error && error.name === "IdpError" && typeof error.code === "string";
34
+ }
35
+ export {
36
+ IdpError,
37
+ SIGN_IN_ERROR_CODES,
38
+ isIdpError,
39
+ isSignInErrorCode,
40
+ isTokenError
41
+ };
@@ -0,0 +1,71 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type AccessToken, type TokenRequirements } from "./access-token.js";
3
+ import type { IdpOptions } from "./config.js";
4
+ import { type Idp } from "./idp.js";
5
+ import { type SessionOptions } from "./node-adapter.js";
6
+ import type { Session } from "./session.js";
7
+ /**
8
+ * A request nextidp's middleware saw: `req.idp.session` after `auth.express()` (null when
9
+ * signed out), `req.idp.token` after `requireToken`.
10
+ */
11
+ export type IdpRequest = IncomingMessage & {
12
+ idp?: {
13
+ session?: Session | null;
14
+ token?: AccessToken;
15
+ };
16
+ };
17
+ export type Middleware = (req: IncomingMessage, res: ServerResponse, next: (error?: unknown) => void) => void;
18
+ export type ExpressIdp = Idp & {
19
+ /**
20
+ * The sign-in middleware, once, before your routes: `app.use(auth.express())`. It answers
21
+ * nextidp's routes under `basePath`, and for every other request reads the session
22
+ * (refreshing the access token when it's about to expire) for `sessionOf(req)`.
23
+ */
24
+ express(options?: SessionOptions): Middleware;
25
+ /**
26
+ * Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
27
+ * comes back after; anything else gets 401.
28
+ *
29
+ * ```ts
30
+ * app.get("/dashboard", auth.requireSession(), (req, res) => {
31
+ * res.render("dashboard", { user: auth.sessionOf(req)?.user });
32
+ * });
33
+ * ```
34
+ */
35
+ requireSession(): Middleware;
36
+ /** The session `express()` read for this request, or null when signed out. */
37
+ sessionOf(req: IncomingMessage): Session | null;
38
+ /**
39
+ * Middleware that lets a request through only with a valid access token that has every
40
+ * scope in `requirements`. A refused one gets 401 or 403 with WWW-Authenticate (RFC 6750);
41
+ * a token that can't be checked now (the auth server is down) goes to `next(error)`.
42
+ *
43
+ * ```ts
44
+ * app.get("/orders", auth.requireToken({ scopes: ["orders:read"] }), (req, res) => {
45
+ * res.json(ordersOf(auth.tokenOf(req)?.subject));
46
+ * });
47
+ * ```
48
+ */
49
+ requireToken(requirements?: TokenRequirements): Middleware;
50
+ /** The access token `requireToken` checked for this request. */
51
+ tokenOf(req: IncomingMessage): AccessToken | undefined;
52
+ };
53
+ /**
54
+ * The client for an Express app or API. An app that signs people in needs the sign-in
55
+ * settings (`IDP_ISSUER`, `IDP_CLIENT_ID`, `IDP_APP_URL`, `IDP_SECRET`); an API only `issuer`
56
+ * and `audience`:
57
+ *
58
+ * ```ts
59
+ * import { idp } from "nextidp/express";
60
+ * export const auth = idp(); // the IDP_* environment variables, read on first use
61
+ * ```
62
+ */
63
+ export declare function idp(options?: IdpOptions | (() => IdpOptions)): ExpressIdp;
64
+ export type { AccessToken, TokenRequirements } from "./access-token.js";
65
+ export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
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";
68
+ export type { SessionOptions } from "./node-adapter.js";
69
+ export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
70
+ export type { IdpUser, Session } from "./session.js";
71
+ export { memoryStore, type SessionStore } from "./store.js";
@@ -0,0 +1,90 @@
1
+ import { tokenRefusal } from "./access-token.js";
2
+ import { isTokenError } from "./errors.js";
3
+ import { createIdp } from "./idp.js";
4
+ import { nodeAdapter } from "./node-adapter.js";
5
+ function authorizationOf(req) {
6
+ const value = req.headers.authorization;
7
+ return Array.isArray(value) ? void 0 : value;
8
+ }
9
+ function remember(req, found) {
10
+ const request = req;
11
+ request.idp = { ...request.idp, ...found };
12
+ }
13
+ function idp(options) {
14
+ const core = createIdp(options);
15
+ const node = nodeAdapter(core);
16
+ return {
17
+ ...core,
18
+ express(sessionOptions = {}) {
19
+ return (req, res, next) => {
20
+ const run = async () => {
21
+ if (await node.handle(req, res)) return true;
22
+ remember(req, { session: await node.session(req, res, sessionOptions) });
23
+ return false;
24
+ };
25
+ run().then((answered) => {
26
+ if (!answered) next();
27
+ }, next);
28
+ };
29
+ },
30
+ requireSession() {
31
+ return (req, res, next) => {
32
+ node.session(req, res).then((session) => {
33
+ if (!session) {
34
+ node.turnAway(req, res);
35
+ return;
36
+ }
37
+ remember(req, { session });
38
+ next();
39
+ }, next);
40
+ };
41
+ },
42
+ sessionOf(req) {
43
+ const session = req.idp?.session;
44
+ if (session === void 0) {
45
+ throw new Error(
46
+ "nextidp: no session was read for this request. Mount auth.express() first."
47
+ );
48
+ }
49
+ return session;
50
+ },
51
+ requireToken(requirements = {}) {
52
+ return (req, res, next) => {
53
+ core.verifyBearer(authorizationOf(req), requirements).then(
54
+ (token) => {
55
+ remember(req, { token });
56
+ next();
57
+ },
58
+ (error) => {
59
+ if (!isTokenError(error)) {
60
+ next(error);
61
+ return;
62
+ }
63
+ const refusal = tokenRefusal(error);
64
+ res.statusCode = refusal.status;
65
+ for (const [name, value] of Object.entries(refusal.headers)) res.setHeader(name, value);
66
+ res.end(JSON.stringify(refusal.body));
67
+ }
68
+ );
69
+ };
70
+ },
71
+ tokenOf: (req) => req.idp?.token
72
+ };
73
+ }
74
+ import {
75
+ IdpError,
76
+ isIdpError,
77
+ isSignInErrorCode,
78
+ isTokenError as isTokenError2,
79
+ SIGN_IN_ERROR_CODES
80
+ } from "./errors.js";
81
+ import { memoryStore } from "./store.js";
82
+ export {
83
+ IdpError,
84
+ SIGN_IN_ERROR_CODES,
85
+ idp,
86
+ isIdpError,
87
+ isSignInErrorCode,
88
+ isTokenError2 as isTokenError,
89
+ memoryStore
90
+ };