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,118 @@
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 cookies_exports = {};
20
+ __export(cookies_exports, {
21
+ CHUNK_SIZE: () => CHUNK_SIZE,
22
+ applySetCookies: () => applySetCookies,
23
+ clearCookie: () => clearCookie,
24
+ parseCookies: () => parseCookies,
25
+ readCookie: () => readCookie,
26
+ writeCookie: () => writeCookie
27
+ });
28
+ module.exports = __toCommonJS(cookies_exports);
29
+ const CHUNK_SIZE = 3800;
30
+ const MAX_CHUNKS = 10;
31
+ function parseCookies(header) {
32
+ const jar = /* @__PURE__ */ new Map();
33
+ for (const pair of (header ?? "").split(";")) {
34
+ const index = pair.indexOf("=");
35
+ if (index <= 0) continue;
36
+ const name = pair.slice(0, index).trim();
37
+ if (!name || jar.has(name)) continue;
38
+ let value = pair.slice(index + 1).trim();
39
+ if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
40
+ jar.set(name, value);
41
+ }
42
+ return jar;
43
+ }
44
+ function serialize(name, value, { secure, maxAge }) {
45
+ return [
46
+ `${name}=${value}`,
47
+ "Path=/",
48
+ `Max-Age=${maxAge}`,
49
+ "HttpOnly",
50
+ "SameSite=Lax",
51
+ ...secure ? ["Secure"] : []
52
+ ].join("; ");
53
+ }
54
+ function chunkNames(jar, name) {
55
+ return [...jar.keys()].filter(
56
+ (key) => key.startsWith(`${name}.`) && /^\d+$/.test(key.slice(name.length + 1))
57
+ );
58
+ }
59
+ function readCookie(jar, name) {
60
+ const whole = jar.get(name);
61
+ if (whole) return whole;
62
+ const parts = [];
63
+ for (let index = 0; index < MAX_CHUNKS; index += 1) {
64
+ const part = jar.get(`${name}.${index}`);
65
+ if (part === void 0) break;
66
+ parts.push(part);
67
+ }
68
+ return parts.length > 0 ? parts.join("") : void 0;
69
+ }
70
+ function writeCookie(jar, name, value, attributes) {
71
+ const headers = [];
72
+ const written = /* @__PURE__ */ new Set();
73
+ if (value.length <= CHUNK_SIZE) {
74
+ headers.push(serialize(name, value, attributes));
75
+ written.add(name);
76
+ } else {
77
+ const count = Math.ceil(value.length / CHUNK_SIZE);
78
+ if (count > MAX_CHUNKS) throw new Error("The session is too big to keep in cookies.");
79
+ for (let index = 0; index < count; index += 1) {
80
+ const chunk = `${name}.${index}`;
81
+ headers.push(
82
+ serialize(chunk, value.slice(index * CHUNK_SIZE, (index + 1) * CHUNK_SIZE), attributes)
83
+ );
84
+ written.add(chunk);
85
+ }
86
+ }
87
+ for (const stale of [name, ...chunkNames(jar, name)]) {
88
+ if (!written.has(stale) && jar.has(stale))
89
+ headers.push(serialize(stale, "", { ...attributes, maxAge: 0 }));
90
+ }
91
+ return headers;
92
+ }
93
+ function clearCookie(jar, name, secure) {
94
+ const names = /* @__PURE__ */ new Set([name, ...chunkNames(jar, name)]);
95
+ return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0 }));
96
+ }
97
+ function applySetCookies(header, setCookies) {
98
+ const jar = new Map(parseCookies(header));
99
+ for (const line of setCookies) {
100
+ const [pair = ""] = line.split(";");
101
+ const index = pair.indexOf("=");
102
+ if (index <= 0) continue;
103
+ const name = pair.slice(0, index);
104
+ const value = pair.slice(index + 1);
105
+ if (/;\s*Max-Age=0(?:;|$)/i.test(line)) jar.delete(name);
106
+ else jar.set(name, value);
107
+ }
108
+ return [...jar].map(([name, value]) => `${name}=${value}`).join("; ");
109
+ }
110
+ // Annotate the CommonJS export names for ESM import in node:
111
+ 0 && (module.exports = {
112
+ CHUNK_SIZE,
113
+ applySetCookies,
114
+ clearCookie,
115
+ parseCookies,
116
+ readCookie,
117
+ writeCookie
118
+ });
@@ -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,91 @@
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 discovery_exports = {};
30
+ __export(discovery_exports, {
31
+ createDiscovery: () => createDiscovery,
32
+ parseDiscovery: () => parseDiscovery
33
+ });
34
+ module.exports = __toCommonJS(discovery_exports);
35
+ var v = __toESM(require("valibot"), 1);
36
+ var import_errors = require("./errors.js");
37
+ const Url = v.pipe(v.string(), v.url());
38
+ const DiscoverySchema = v.object({
39
+ issuer: v.string(),
40
+ authorization_endpoint: Url,
41
+ token_endpoint: Url,
42
+ jwks_uri: Url,
43
+ userinfo_endpoint: v.optional(Url),
44
+ revocation_endpoint: v.optional(Url),
45
+ /** RFC 7662: whether an opaque access token is active, asked with a client's credentials. */
46
+ introspection_endpoint: v.optional(Url),
47
+ /** RP-initiated logout: where to send someone to sign out of the auth server too. */
48
+ end_session_endpoint: v.optional(Url),
49
+ id_token_signing_alg_values_supported: v.optional(v.array(v.string()))
50
+ });
51
+ const ONE_HOUR = 60 * 60 * 1e3;
52
+ function parseDiscovery(document, expectedIssuer) {
53
+ const parsed = v.safeParse(DiscoverySchema, document);
54
+ if (!parsed.success) {
55
+ throw new import_errors.IdpError("discovery_failed", "The discovery document is missing endpoints.");
56
+ }
57
+ if (parsed.output.issuer.replace(/\/+$/, "") !== expectedIssuer) {
58
+ throw new import_errors.IdpError("discovery_failed", "The discovery document names a different issuer.");
59
+ }
60
+ return parsed.output;
61
+ }
62
+ function createDiscovery(http, issuer) {
63
+ let cached;
64
+ return () => {
65
+ if (cached && cached.until > Date.now()) return cached.value;
66
+ const value = (async () => {
67
+ let answer;
68
+ try {
69
+ answer = await http.get(`${issuer}/.well-known/openid-configuration`);
70
+ } catch (cause) {
71
+ throw new import_errors.IdpError("discovery_failed", "The auth server didn't answer.", { cause });
72
+ }
73
+ if (!answer.ok) {
74
+ throw new import_errors.IdpError("discovery_failed", `Discovery answered ${answer.status}.`, {
75
+ status: answer.status
76
+ });
77
+ }
78
+ return parseDiscovery(answer.data, issuer);
79
+ })();
80
+ cached = { value, until: Date.now() + ONE_HOUR };
81
+ value.catch(() => {
82
+ if (cached?.value === value) cached = void 0;
83
+ });
84
+ return value;
85
+ };
86
+ }
87
+ // Annotate the CommonJS export names for ESM import in node:
88
+ 0 && (module.exports = {
89
+ createDiscovery,
90
+ parseDiscovery
91
+ });
@@ -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,69 @@
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 errors_exports = {};
20
+ __export(errors_exports, {
21
+ IdpError: () => IdpError,
22
+ SIGN_IN_ERROR_CODES: () => SIGN_IN_ERROR_CODES,
23
+ isIdpError: () => isIdpError,
24
+ isSignInErrorCode: () => isSignInErrorCode,
25
+ isTokenError: () => isTokenError
26
+ });
27
+ module.exports = __toCommonJS(errors_exports);
28
+ const SIGN_IN_ERROR_CODES = [
29
+ "access_denied",
30
+ "expired",
31
+ "state_mismatch",
32
+ "token_failed",
33
+ "invalid_id_token",
34
+ "refresh_failed"
35
+ ];
36
+ function isSignInErrorCode(value) {
37
+ return typeof value === "string" && SIGN_IN_ERROR_CODES.includes(value);
38
+ }
39
+ function isTokenError(error) {
40
+ return isIdpError(error) && (error.code === "missing_token" || error.code === "invalid_token" || error.code === "insufficient_scope");
41
+ }
42
+ class IdpError extends Error {
43
+ name = "IdpError";
44
+ code;
45
+ /**
46
+ * The HTTP status the auth server answered with, when there was one; for a token error,
47
+ * the status to answer the caller with (401 or 403).
48
+ */
49
+ status;
50
+ /** For insufficient_scope: the scopes the route needs, for the WWW-Authenticate challenge. */
51
+ scopes;
52
+ constructor(code, message, options) {
53
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
54
+ this.code = code;
55
+ this.status = options?.status;
56
+ this.scopes = options?.scopes;
57
+ }
58
+ }
59
+ function isIdpError(error) {
60
+ return error instanceof Error && error.name === "IdpError" && typeof error.code === "string";
61
+ }
62
+ // Annotate the CommonJS export names for ESM import in node:
63
+ 0 && (module.exports = {
64
+ IdpError,
65
+ SIGN_IN_ERROR_CODES,
66
+ isIdpError,
67
+ isSignInErrorCode,
68
+ isTokenError
69
+ });
@@ -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,114 @@
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 express_exports = {};
20
+ __export(express_exports, {
21
+ IdpError: () => import_errors2.IdpError,
22
+ SIGN_IN_ERROR_CODES: () => import_errors2.SIGN_IN_ERROR_CODES,
23
+ idp: () => idp,
24
+ isIdpError: () => import_errors2.isIdpError,
25
+ isSignInErrorCode: () => import_errors2.isSignInErrorCode,
26
+ isTokenError: () => import_errors2.isTokenError,
27
+ memoryStore: () => import_store.memoryStore
28
+ });
29
+ module.exports = __toCommonJS(express_exports);
30
+ var import_access_token = require("./access-token.js");
31
+ var import_errors = require("./errors.js");
32
+ var import_idp = require("./idp.js");
33
+ var import_node_adapter = require("./node-adapter.js");
34
+ var import_errors2 = require("./errors.js");
35
+ var import_store = require("./store.js");
36
+ function authorizationOf(req) {
37
+ const value = req.headers.authorization;
38
+ return Array.isArray(value) ? void 0 : value;
39
+ }
40
+ function remember(req, found) {
41
+ const request = req;
42
+ request.idp = { ...request.idp, ...found };
43
+ }
44
+ function idp(options) {
45
+ const core = (0, import_idp.createIdp)(options);
46
+ const node = (0, import_node_adapter.nodeAdapter)(core);
47
+ return {
48
+ ...core,
49
+ express(sessionOptions = {}) {
50
+ return (req, res, next) => {
51
+ const run = async () => {
52
+ if (await node.handle(req, res)) return true;
53
+ remember(req, { session: await node.session(req, res, sessionOptions) });
54
+ return false;
55
+ };
56
+ run().then((answered) => {
57
+ if (!answered) next();
58
+ }, next);
59
+ };
60
+ },
61
+ requireSession() {
62
+ return (req, res, next) => {
63
+ node.session(req, res).then((session) => {
64
+ if (!session) {
65
+ node.turnAway(req, res);
66
+ return;
67
+ }
68
+ remember(req, { session });
69
+ next();
70
+ }, next);
71
+ };
72
+ },
73
+ sessionOf(req) {
74
+ const session = req.idp?.session;
75
+ if (session === void 0) {
76
+ throw new Error(
77
+ "nextidp: no session was read for this request. Mount auth.express() first."
78
+ );
79
+ }
80
+ return session;
81
+ },
82
+ requireToken(requirements = {}) {
83
+ return (req, res, next) => {
84
+ core.verifyBearer(authorizationOf(req), requirements).then(
85
+ (token) => {
86
+ remember(req, { token });
87
+ next();
88
+ },
89
+ (error) => {
90
+ if (!(0, import_errors.isTokenError)(error)) {
91
+ next(error);
92
+ return;
93
+ }
94
+ const refusal = (0, import_access_token.tokenRefusal)(error);
95
+ res.statusCode = refusal.status;
96
+ for (const [name, value] of Object.entries(refusal.headers)) res.setHeader(name, value);
97
+ res.end(JSON.stringify(refusal.body));
98
+ }
99
+ );
100
+ };
101
+ },
102
+ tokenOf: (req) => req.idp?.token
103
+ };
104
+ }
105
+ // Annotate the CommonJS export names for ESM import in node:
106
+ 0 && (module.exports = {
107
+ IdpError,
108
+ SIGN_IN_ERROR_CODES,
109
+ idp,
110
+ isIdpError,
111
+ isSignInErrorCode,
112
+ isTokenError,
113
+ memoryStore
114
+ });
@@ -0,0 +1,10 @@
1
+ export type Answer = {
2
+ ok: boolean;
3
+ status: number;
4
+ data: unknown;
5
+ };
6
+ export type Http = {
7
+ get(url: string, headers?: Record<string, string>): Promise<Answer>;
8
+ postForm(url: string, form: URLSearchParams, headers?: Record<string, string>): Promise<Answer>;
9
+ };
10
+ export declare function createIdpHttp(): Http;
@@ -0,0 +1,68 @@
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 http_exports = {};
20
+ __export(http_exports, {
21
+ createIdpHttp: () => createIdpHttp
22
+ });
23
+ module.exports = __toCommonJS(http_exports);
24
+ var import_fast_http_client = require("fast-http-client");
25
+ function bare(error) {
26
+ return new Error(error instanceof Error ? error.message : "The request failed.");
27
+ }
28
+ function refusal(error) {
29
+ if (typeof error !== "object" || error === null) return void 0;
30
+ const { status, data } = error;
31
+ return typeof status === "number" ? { ok: false, status, data } : void 0;
32
+ }
33
+ function createIdpHttp() {
34
+ const client = (0, import_fast_http_client.createHttp)({
35
+ timeoutMs: 1e4,
36
+ headers: { accept: "application/json" },
37
+ circuitBreaker: false
38
+ });
39
+ return {
40
+ async get(url, headers) {
41
+ try {
42
+ const response = await client.get(url, headers ? { headers } : {});
43
+ return { ok: true, status: response.status, data: response.data };
44
+ } catch (error) {
45
+ const answer = refusal(error);
46
+ if (answer) return answer;
47
+ throw bare(error);
48
+ }
49
+ },
50
+ async postForm(url, form, headers) {
51
+ try {
52
+ const response = await client.post(url, form, {
53
+ retry: false,
54
+ headers: { "content-type": "application/x-www-form-urlencoded", ...headers }
55
+ });
56
+ return { ok: true, status: response.status, data: response.data };
57
+ } catch (error) {
58
+ const answer = refusal(error);
59
+ if (answer) return answer;
60
+ throw bare(error);
61
+ }
62
+ }
63
+ };
64
+ }
65
+ // Annotate the CommonJS export names for ESM import in node:
66
+ 0 && (module.exports = {
67
+ createIdpHttp
68
+ });
@@ -0,0 +1,19 @@
1
+ import { type JWTPayload, type JWTVerifyGetKey } from "jose";
2
+ export type IdTokenCheck = {
3
+ issuer: string;
4
+ clientId: string;
5
+ /** The nonce the authorization request sent. Absent for a token from a refresh. */
6
+ nonce?: string | undefined;
7
+ /** What discovery lists, if anything; narrowed to ALLOWED_ALGORITHMS. */
8
+ algorithms?: readonly string[] | undefined;
9
+ };
10
+ /** What discovery lists, narrowed to ALLOWED_ALGORITHMS; RS256 when it lists none of them. */
11
+ export declare function signingAlgorithms(listed: readonly string[] | undefined): string[];
12
+ /** The issuer's public keys from its jwks_uri: fetched once, again for a new `kid`. */
13
+ export declare function createKeys(): (jwksUri: string) => JWTVerifyGetKey;
14
+ /**
15
+ * Verifies an ID token (OIDC Core 3.1.3.7): a signature by one of the issuer's keys, `iss`
16
+ * the issuer, `aud` this client (and `azp` too when there are several audiences), `sub`,
17
+ * `iat`, not expired, and the nonce this sign-in sent.
18
+ */
19
+ export declare function verifyIdToken(idToken: string, keys: JWTVerifyGetKey, check: IdTokenCheck): Promise<JWTPayload>;