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,145 @@
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 store_exports = {};
20
+ __export(store_exports, {
21
+ cookieBackend: () => cookieBackend,
22
+ memoryStore: () => memoryStore,
23
+ storeBackend: () => storeBackend
24
+ });
25
+ module.exports = __toCommonJS(store_exports);
26
+ var import_cookies = require("./cookies.js");
27
+ var import_pkce = require("./pkce.js");
28
+ var import_session = require("./session.js");
29
+ function memoryStore() {
30
+ const values = /* @__PURE__ */ new Map();
31
+ const sweep = (now) => {
32
+ for (const [key, entry] of values) if (entry.until <= now) values.delete(key);
33
+ };
34
+ return {
35
+ async get(key) {
36
+ const entry = values.get(key);
37
+ if (!entry) return void 0;
38
+ if (entry.until > Date.now()) return entry.value;
39
+ values.delete(key);
40
+ return void 0;
41
+ },
42
+ async set(key, value, ttlSeconds) {
43
+ const now = Date.now();
44
+ if (values.size >= 1e4) sweep(now);
45
+ values.set(key, { value, until: now + ttlSeconds * 1e3 });
46
+ },
47
+ async delete(key) {
48
+ values.delete(key);
49
+ }
50
+ };
51
+ }
52
+ function cookieBackend(settings) {
53
+ const { sealer, cookie, secure, maxAge } = settings;
54
+ const write = async (jar, stored) => (0, import_cookies.writeCookie)(jar, cookie, await sealer.seal(stored, import_session.SESSION_PURPOSE, maxAge), {
55
+ secure,
56
+ maxAge
57
+ });
58
+ return {
59
+ async load(jar) {
60
+ const stored = (0, import_session.parseStoredSession)(
61
+ await sealer.unseal((0, import_cookies.readCookie)(jar, cookie), import_session.SESSION_PURPOSE)
62
+ );
63
+ return stored ? { stored } : void 0;
64
+ },
65
+ create: write,
66
+ update: (jar, _loaded, stored) => write(jar, stored),
67
+ async remove(jar) {
68
+ return (0, import_cookies.clearCookie)(jar, cookie, secure);
69
+ }
70
+ };
71
+ }
72
+ const REFERENCE_PURPOSE = "nextidp:session-reference";
73
+ const RECORD_PURPOSE = "nextidp:stored-session";
74
+ function nowSeconds() {
75
+ return Math.floor(Date.now() / 1e3);
76
+ }
77
+ function storeBackend(store, settings) {
78
+ const { sealer, cookie, secure, maxAge } = settings;
79
+ const prefix = `nextidp:${encodeURIComponent(settings.clientId)}`;
80
+ const sessionKey = (id) => `${prefix}:session:${id}`;
81
+ const sidKey = (sid) => `${prefix}:ended-sid:${encodeURIComponent(sid)}`;
82
+ const subKey = (sub) => `${prefix}:ended-sub:${encodeURIComponent(sub)}`;
83
+ const referenced = async (jar) => {
84
+ const reference = await sealer.unseal((0, import_cookies.readCookie)(jar, cookie), REFERENCE_PURPOSE);
85
+ return typeof reference?.id === "string" ? reference.id : void 0;
86
+ };
87
+ const save = async (jar, id, stored, createdAt) => {
88
+ await store.set(
89
+ sessionKey(id),
90
+ await sealer.seal({ ...stored, createdAt }, RECORD_PURPOSE, maxAge),
91
+ maxAge
92
+ );
93
+ return (0, import_cookies.writeCookie)(jar, cookie, await sealer.seal({ id }, REFERENCE_PURPOSE, maxAge), {
94
+ secure,
95
+ maxAge
96
+ });
97
+ };
98
+ const ended = async (stored, createdAt) => {
99
+ const { sid, sub } = stored.claims;
100
+ if (typeof sid === "string" && sid && await store.get(sidKey(sid))) return true;
101
+ if (typeof sub !== "string" || !sub) return false;
102
+ const since = Number(await store.get(subKey(sub)));
103
+ return Number.isFinite(since) && since >= createdAt;
104
+ };
105
+ return {
106
+ async load(jar) {
107
+ const id = await referenced(jar);
108
+ if (!id) return void 0;
109
+ const sealed = await store.get(sessionKey(id));
110
+ if (!sealed) return void 0;
111
+ const payload = await sealer.unseal(sealed, RECORD_PURPOSE);
112
+ const stored = (0, import_session.parseStoredSession)(payload);
113
+ const createdAt = typeof payload?.createdAt === "number" ? payload.createdAt : 0;
114
+ if (!stored) return void 0;
115
+ if (await ended(stored, createdAt)) {
116
+ await store.delete(sessionKey(id));
117
+ return void 0;
118
+ }
119
+ return { stored, id, createdAt };
120
+ },
121
+ async create(jar, stored) {
122
+ const previous = await referenced(jar);
123
+ if (previous) await store.delete(sessionKey(previous));
124
+ return save(jar, (0, import_pkce.randomToken)(), stored, nowSeconds());
125
+ },
126
+ update(jar, loaded, stored) {
127
+ return save(jar, loaded.id ?? (0, import_pkce.randomToken)(), stored, loaded.createdAt ?? nowSeconds());
128
+ },
129
+ async remove(jar) {
130
+ const id = await referenced(jar);
131
+ if (id) await store.delete(sessionKey(id));
132
+ return (0, import_cookies.clearCookie)(jar, cookie, secure);
133
+ },
134
+ async endIdpSession({ sid, sub }) {
135
+ if (sid) await store.set(sidKey(sid), "1", maxAge);
136
+ else if (sub) await store.set(subKey(sub), String(nowSeconds()), maxAge);
137
+ }
138
+ };
139
+ }
140
+ // Annotate the CommonJS export names for ESM import in node:
141
+ 0 && (module.exports = {
142
+ cookieBackend,
143
+ memoryStore,
144
+ storeBackend
145
+ });
@@ -0,0 +1,38 @@
1
+ import * as v from "valibot";
2
+ import type { Discovery } from "./discovery.js";
3
+ import type { Http } from "./http.js";
4
+ declare const TokenResponseSchema: v.ObjectSchema<{
5
+ readonly access_token: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>]>;
6
+ readonly token_type: v.StringSchema<undefined>;
7
+ readonly expires_in: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
8
+ readonly id_token: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
9
+ readonly refresh_token: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
10
+ readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
11
+ }, undefined>;
12
+ export type TokenResponse = v.InferOutput<typeof TokenResponseSchema>;
13
+ export type Client = {
14
+ clientId: string;
15
+ clientSecret: string | undefined;
16
+ };
17
+ /** Redeems an authorization code, proving with the PKCE verifier that this app asked for it. */
18
+ export declare function exchangeCode(http: Http, discovery: Discovery, client: Client, input: {
19
+ code: string;
20
+ verifier: string;
21
+ redirectUri: string;
22
+ resource: string | undefined;
23
+ }): Promise<TokenResponse>;
24
+ /** New tokens for a refresh token. The server rotates it: the old one stops working. */
25
+ export declare function refreshTokens(http: Http, discovery: Discovery, client: Client, input: {
26
+ refreshToken: string;
27
+ resource: string | undefined;
28
+ }): Promise<TokenResponse>;
29
+ /** A service's own access token (RFC 6749 4.4): no person, the client's own credentials. */
30
+ export declare function clientCredentials(http: Http, discovery: Discovery, client: Client, input: {
31
+ scope: string | undefined;
32
+ resource: string | undefined;
33
+ }): Promise<TokenResponse>;
34
+ /** Revokes a refresh token at sign-out, when the server offers revocation. Never throws. */
35
+ export declare function revokeRefreshToken(http: Http, discovery: Discovery, client: Client, refreshToken: string): Promise<void>;
36
+ /** The userinfo endpoint's claims for an access token. */
37
+ export declare function fetchUserInfo(http: Http, discovery: Discovery, accessToken: string): Promise<Record<string, unknown>>;
38
+ export {};
@@ -0,0 +1,138 @@
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 tokens_exports = {};
30
+ __export(tokens_exports, {
31
+ clientCredentials: () => clientCredentials,
32
+ exchangeCode: () => exchangeCode,
33
+ fetchUserInfo: () => fetchUserInfo,
34
+ refreshTokens: () => refreshTokens,
35
+ revokeRefreshToken: () => revokeRefreshToken
36
+ });
37
+ module.exports = __toCommonJS(tokens_exports);
38
+ var v = __toESM(require("valibot"), 1);
39
+ var import_errors = require("./errors.js");
40
+ const TokenResponseSchema = v.object({
41
+ access_token: v.pipe(v.string(), v.nonEmpty()),
42
+ token_type: v.string(),
43
+ expires_in: v.optional(v.number()),
44
+ id_token: v.optional(v.string()),
45
+ refresh_token: v.optional(v.string()),
46
+ scope: v.optional(v.string())
47
+ });
48
+ function authenticate(client, form) {
49
+ if (!client.clientSecret) {
50
+ form.set("client_id", client.clientId);
51
+ return {};
52
+ }
53
+ const pair = `${encodeURIComponent(client.clientId)}:${encodeURIComponent(client.clientSecret)}`;
54
+ return { authorization: `Basic ${btoa(pair)}` };
55
+ }
56
+ function oauthError(data) {
57
+ const error = data?.error;
58
+ return typeof error === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(error) ? error : void 0;
59
+ }
60
+ async function tokenRequest(http, discovery, client, form, code) {
61
+ const headers = authenticate(client, form);
62
+ let answer;
63
+ try {
64
+ answer = await http.postForm(discovery.token_endpoint, form, headers);
65
+ } catch (cause) {
66
+ throw new import_errors.IdpError(code, "The token endpoint didn't answer.", { cause });
67
+ }
68
+ if (!answer.ok) {
69
+ throw new import_errors.IdpError(
70
+ code,
71
+ `The token endpoint refused: ${oauthError(answer.data) ?? answer.status}.`,
72
+ { status: answer.status }
73
+ );
74
+ }
75
+ const parsed = v.safeParse(TokenResponseSchema, answer.data);
76
+ if (!parsed.success) throw new import_errors.IdpError(code, "The token endpoint's answer isn't valid.");
77
+ return parsed.output;
78
+ }
79
+ function exchangeCode(http, discovery, client, input) {
80
+ const form = new URLSearchParams({
81
+ grant_type: "authorization_code",
82
+ code: input.code,
83
+ code_verifier: input.verifier,
84
+ redirect_uri: input.redirectUri
85
+ });
86
+ if (input.resource) form.set("resource", input.resource);
87
+ return tokenRequest(http, discovery, client, form, "token_failed");
88
+ }
89
+ function refreshTokens(http, discovery, client, input) {
90
+ const form = new URLSearchParams({
91
+ grant_type: "refresh_token",
92
+ refresh_token: input.refreshToken
93
+ });
94
+ if (input.resource) form.set("resource", input.resource);
95
+ return tokenRequest(http, discovery, client, form, "refresh_failed");
96
+ }
97
+ function clientCredentials(http, discovery, client, input) {
98
+ const form = new URLSearchParams({ grant_type: "client_credentials" });
99
+ if (input.scope) form.set("scope", input.scope);
100
+ if (input.resource) form.set("resource", input.resource);
101
+ return tokenRequest(http, discovery, client, form, "service_token_failed");
102
+ }
103
+ async function revokeRefreshToken(http, discovery, client, refreshToken) {
104
+ if (!discovery.revocation_endpoint) return;
105
+ const form = new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token" });
106
+ const headers = authenticate(client, form);
107
+ await http.postForm(discovery.revocation_endpoint, form, headers).catch(() => void 0);
108
+ }
109
+ async function fetchUserInfo(http, discovery, accessToken) {
110
+ if (!discovery.userinfo_endpoint) {
111
+ throw new import_errors.IdpError("userinfo_failed", "The auth server has no userinfo endpoint.");
112
+ }
113
+ let answer;
114
+ try {
115
+ answer = await http.get(discovery.userinfo_endpoint, {
116
+ authorization: `Bearer ${accessToken}`
117
+ });
118
+ } catch (cause) {
119
+ throw new import_errors.IdpError("userinfo_failed", "The userinfo endpoint didn't answer.", { cause });
120
+ }
121
+ if (!answer.ok) {
122
+ throw new import_errors.IdpError("userinfo_failed", `The userinfo endpoint answered ${answer.status}.`, {
123
+ status: answer.status
124
+ });
125
+ }
126
+ if (!answer.data || typeof answer.data !== "object" || Array.isArray(answer.data)) {
127
+ throw new import_errors.IdpError("userinfo_failed", "The userinfo answer isn't an object.");
128
+ }
129
+ return answer.data;
130
+ }
131
+ // Annotate the CommonJS export names for ESM import in node:
132
+ 0 && (module.exports = {
133
+ clientCredentials,
134
+ exchangeCode,
135
+ fetchUserInfo,
136
+ refreshTokens,
137
+ revokeRefreshToken
138
+ });
@@ -0,0 +1,56 @@
1
+ import { type JWTVerifyGetKey } from "jose";
2
+ import type { ApiConfig } from "./config.js";
3
+ import type { Discovery } from "./discovery.js";
4
+ import { IdpError } from "./errors.js";
5
+ import type { Http } from "./http.js";
6
+ /** An access token that checked out. */
7
+ export type AccessToken = {
8
+ /** `sub`: the person, or for a service calling as itself, its client ID. */
9
+ subject: string | undefined;
10
+ /** The app the token was issued to. */
11
+ clientId: string | undefined;
12
+ /** A service calling as itself (client credentials), not on a person's behalf. */
13
+ isService: boolean;
14
+ scopes: string[];
15
+ audience: string[];
16
+ /** Seconds since the epoch. */
17
+ expiresAt: number | undefined;
18
+ /** Every claim, or every field of the introspection answer. */
19
+ claims: Record<string, unknown>;
20
+ };
21
+ export type TokenRequirements = {
22
+ /** Every one of these scopes must be granted. */
23
+ scopes?: readonly string[] | undefined;
24
+ };
25
+ /** The token in an `Authorization: Bearer …` header, or undefined. */
26
+ export declare function bearerToken(authorization: string | null | undefined): string | undefined;
27
+ /** Throws insufficient_scope (403) unless every required scope was granted. */
28
+ export declare function requireScopes(token: AccessToken, required?: readonly string[]): AccessToken;
29
+ /** Whether a token is a JWT (three parts, a header that decodes) rather than opaque. */
30
+ export declare function isJwt(token: string): boolean;
31
+ /**
32
+ * A JWT access token (RFC 9068): `typ` at+jwt, so no other kind of JWT (an ID token, a logout
33
+ * token) passes for one; a signature by one of the issuer's keys (asymmetric algorithms
34
+ * only); `iss`; `aud` naming this API; and not expired (60 seconds of clock skew).
35
+ */
36
+ export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<AccessToken>;
37
+ /**
38
+ * Asks the auth server whether an opaque token is active, with this API's client
39
+ * credentials. The auth server answers only for tokens this client issued, or tokens for an
40
+ * API this client is linked to; to anything else it answers inactive.
41
+ */
42
+ export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<AccessToken>;
43
+ /**
44
+ * The WWW-Authenticate challenge for a refused request (RFC 6750 3): no error code when
45
+ * there was no token at all, else invalid_token or insufficient_scope with the scopes needed.
46
+ */
47
+ export declare function bearerChallenge(error: IdpError): string;
48
+ /** The status, challenge and JSON body to answer a refused request with. */
49
+ export declare function tokenRefusal(error: IdpError): {
50
+ status: 401 | 403;
51
+ headers: Record<string, string>;
52
+ body: {
53
+ error: string;
54
+ error_description: string;
55
+ };
56
+ };
@@ -0,0 +1,156 @@
1
+ import { decodeProtectedHeader, jwtVerify } from "jose";
2
+ import * as v from "valibot";
3
+ import { IdpError } from "./errors.js";
4
+ const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
5
+ const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
6
+ const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
7
+ const invalid = (message, cause) => new IdpError("invalid_token", message, { status: 401, cause });
8
+ function bearerToken(authorization) {
9
+ return authorization ? BEARER.exec(authorization)?.[1] : void 0;
10
+ }
11
+ function list(value) {
12
+ if (typeof value === "string") return value.split(" ").filter(Boolean);
13
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
14
+ }
15
+ function toAccessToken(claims) {
16
+ const subject = typeof claims.sub === "string" ? claims.sub : void 0;
17
+ const clientId = typeof claims.client_id === "string" ? claims.client_id : typeof claims.azp === "string" ? claims.azp : void 0;
18
+ return {
19
+ subject,
20
+ clientId,
21
+ isService: subject !== void 0 && subject === clientId,
22
+ scopes: list(claims.scope),
23
+ audience: list(claims.aud),
24
+ expiresAt: typeof claims.exp === "number" ? claims.exp : void 0,
25
+ claims
26
+ };
27
+ }
28
+ function requireScopes(token, required = []) {
29
+ const missing = required.filter((scope) => !token.scopes.includes(scope));
30
+ if (missing.length > 0) {
31
+ throw new IdpError("insufficient_scope", `The access token lacks: ${missing.join(" ")}.`, {
32
+ status: 403,
33
+ scopes: required
34
+ });
35
+ }
36
+ return token;
37
+ }
38
+ function isJwt(token) {
39
+ if (token.split(".").length !== 3) return false;
40
+ try {
41
+ decodeProtectedHeader(token);
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+ async function verifyJwtAccessToken(token, keys, config) {
48
+ const { typ } = decodeProtectedHeader(token);
49
+ if (typ === void 0 || !ACCESS_TOKEN_TYPES.has(typ.toLowerCase())) {
50
+ throw invalid("The token isn't a JWT access token (its typ isn't at+jwt).");
51
+ }
52
+ try {
53
+ const { payload } = await jwtVerify(token, keys, {
54
+ algorithms: ALGORITHMS,
55
+ issuer: config.issuer,
56
+ audience: config.audience,
57
+ requiredClaims: ["exp"],
58
+ clockTolerance: 60
59
+ });
60
+ return toAccessToken(payload);
61
+ } catch (cause) {
62
+ throw invalid(
63
+ "The access token didn't verify: expired, for another API, or not signed by the issuer.",
64
+ cause
65
+ );
66
+ }
67
+ }
68
+ const IntrospectionSchema = v.looseObject({
69
+ active: v.boolean(),
70
+ scope: v.optional(v.string()),
71
+ client_id: v.optional(v.string()),
72
+ sub: v.optional(v.string()),
73
+ exp: v.optional(v.number()),
74
+ aud: v.optional(v.union([v.string(), v.array(v.string())])),
75
+ iss: v.optional(v.string())
76
+ });
77
+ async function introspect(http, discovery, config, token) {
78
+ if (!discovery.introspection_endpoint) {
79
+ throw invalid("The auth server has no introspection endpoint, and the token isn't a JWT.");
80
+ }
81
+ if (!config.clientId || !config.clientSecret) {
82
+ throw invalid(
83
+ "An opaque access token can only be checked by introspection, which needs clientId and clientSecret. Ask for tokens with `resource` to get JWTs instead."
84
+ );
85
+ }
86
+ const pair = `${encodeURIComponent(config.clientId)}:${encodeURIComponent(config.clientSecret)}`;
87
+ let answer;
88
+ try {
89
+ answer = await http.postForm(
90
+ discovery.introspection_endpoint,
91
+ new URLSearchParams({ token, token_type_hint: "access_token" }),
92
+ { authorization: `Basic ${btoa(pair)}` }
93
+ );
94
+ } catch (cause) {
95
+ throw new IdpError("discovery_failed", "The introspection endpoint didn't answer.", { cause });
96
+ }
97
+ if (!answer.ok) {
98
+ throw new IdpError(
99
+ "misconfigured",
100
+ `Introspection answered ${answer.status}: check clientId and clientSecret.`,
101
+ {
102
+ status: answer.status
103
+ }
104
+ );
105
+ }
106
+ const parsed = v.safeParse(IntrospectionSchema, answer.data);
107
+ if (!parsed.success) throw invalid("The introspection answer isn't valid.");
108
+ if (!parsed.output.active) throw invalid("The access token isn't active.");
109
+ if (parsed.output.iss !== void 0 && parsed.output.iss.replace(/\/+$/, "") !== config.issuer) {
110
+ throw invalid("The access token is from another issuer.");
111
+ }
112
+ const checked = toAccessToken(parsed.output);
113
+ const own = config.acceptOwnTokens && checked.clientId === config.clientId;
114
+ if (!checked.audience.includes(config.audience) && !own) {
115
+ throw invalid("The access token is for another API.");
116
+ }
117
+ if (checked.expiresAt !== void 0 && checked.expiresAt <= Math.floor(Date.now() / 1e3)) {
118
+ throw invalid("The access token has expired.");
119
+ }
120
+ return checked;
121
+ }
122
+ function quoted(value) {
123
+ return `"${value.replace(/[\\"]/g, "\\$&")}"`;
124
+ }
125
+ function bearerChallenge(error) {
126
+ if (error.code === "missing_token") return "Bearer";
127
+ const parts = [
128
+ `error=${quoted(error.code === "insufficient_scope" ? "insufficient_scope" : "invalid_token")}`
129
+ ];
130
+ parts.push(`error_description=${quoted(error.message)}`);
131
+ if (error.code === "insufficient_scope" && error.scopes?.length) {
132
+ parts.push(`scope=${quoted(error.scopes.join(" "))}`);
133
+ }
134
+ return `Bearer ${parts.join(", ")}`;
135
+ }
136
+ function tokenRefusal(error) {
137
+ const status = error.code === "insufficient_scope" ? 403 : 401;
138
+ return {
139
+ status,
140
+ headers: {
141
+ "www-authenticate": bearerChallenge(error),
142
+ "content-type": "application/json",
143
+ "cache-control": "no-store"
144
+ },
145
+ body: { error: error.code, error_description: error.message }
146
+ };
147
+ }
148
+ export {
149
+ bearerChallenge,
150
+ bearerToken,
151
+ introspect,
152
+ isJwt,
153
+ requireScopes,
154
+ tokenRefusal,
155
+ verifyJwtAccessToken
156
+ };
@@ -0,0 +1,128 @@
1
+ import { IdpError } from "./errors.js";
2
+ import type { SessionStore } from "./store.js";
3
+ /** What `idp()` takes. Every setting can also come from the environment (in brackets). */
4
+ export type IdpOptions = {
5
+ /** The auth server, also the OIDC issuer: `https://auth.example.com` (IDP_ISSUER). */
6
+ issuer?: string | undefined;
7
+ /** This app's client ID, from the auth server's admin screen (IDP_CLIENT_ID). */
8
+ clientId?: string | undefined;
9
+ /** A confidential client's secret. Leave it out for a public one (IDP_CLIENT_SECRET). */
10
+ clientSecret?: string | undefined;
11
+ /** This app's own origin: `https://app.example.com` (IDP_APP_URL). */
12
+ appUrl?: string | undefined;
13
+ /**
14
+ * At least 32 characters: encrypts this app's cookies (IDP_SECRET). A list rotates it: the
15
+ * first encrypts, every one decrypts (IDP_SECRET, comma-separated).
16
+ */
17
+ secret?: string | readonly string[] | undefined;
18
+ /** What to ask for. Default `openid profile email offline_access` (IDP_SCOPES). */
19
+ scopes?: string | readonly string[] | undefined;
20
+ /** An API's URI (RFC 8707): the access token is then a JWT for that API (IDP_RESOURCE). */
21
+ resource?: string | undefined;
22
+ /**
23
+ * For an API that checks tokens: its own URI, as the auth server lists it in
24
+ * OAUTH_RESOURCES. Every access token must name it in `aud` (IDP_AUDIENCE). Never taken
25
+ * from `resource`: that's the API an app asks tokens *for*, and accepting those here would
26
+ * let an app take tokens meant for the API it calls.
27
+ */
28
+ audience?: string | undefined;
29
+ /**
30
+ * Also accept an opaque token, by introspection, that doesn't name `audience` but was
31
+ * issued to this very client (`clientId`): an app checking its own tokens. Off by default,
32
+ * so only tokens for this API pass.
33
+ */
34
+ acceptOwnTokens?: boolean | undefined;
35
+ /** Where nextidp's routes live. Default `/auth`: the redirect URI is `<appUrl>/auth/callback`. */
36
+ basePath?: string | undefined;
37
+ /** Where a sign-in lands when it wasn't asked to return somewhere. Default `/`. */
38
+ afterSignIn?: string | undefined;
39
+ /** Where sign-out lands, and the post-logout redirect URI on the auth server. Default `/`. */
40
+ afterSignOut?: string | undefined;
41
+ /** Where a failed sign-in lands, with `?error=<code>`. Default `/`. */
42
+ errorPath?: string | undefined;
43
+ /** Sign out of the auth server too, by default. A form field can still choose. Default false. */
44
+ signOutOfIdp?: boolean | undefined;
45
+ /** How long the session cookie lasts, in seconds, renewed at every refresh. Default 7 days. */
46
+ sessionMaxAge?: number | undefined;
47
+ /** The start of this app's cookie names. Default `nextidp`. */
48
+ cookiePrefix?: string | undefined;
49
+ /**
50
+ * Keep sessions here instead of in the cookie, which then holds only a sealed reference.
51
+ * Needed for back-channel logout (`<basePath>/backchannel-logout`): the auth server can
52
+ * then end this app's sessions. Default: none, sessions live in the cookie.
53
+ */
54
+ store?: SessionStore | undefined;
55
+ /**
56
+ * Where the IDP_* settings are read from, when an option isn't passed. Default
57
+ * `process.env`.
58
+ */
59
+ env?: Readonly<Record<string, string | undefined>> | undefined;
60
+ /**
61
+ * Told about every sign-in, refresh or setting that failed. Default: one `console.error`
62
+ * line with the code and message, which never hold a token or a claim.
63
+ */
64
+ onError?: ((error: IdpError) => void) | undefined;
65
+ };
66
+ /** What checking access tokens needs: an API has no sign-in of its own. */
67
+ export type ApiConfig = {
68
+ issuer: string;
69
+ audience: string;
70
+ /** For introspecting opaque tokens; a JWT needs neither. */
71
+ clientId: string | undefined;
72
+ clientSecret: string | undefined;
73
+ /** See IdpOptions.acceptOwnTokens. */
74
+ acceptOwnTokens: boolean;
75
+ };
76
+ /** What a service needs to get tokens of its own: a confidential client. */
77
+ export type ServiceConfig = {
78
+ issuer: string;
79
+ clientId: string;
80
+ clientSecret: string;
81
+ /** The API to ask tokens for when a call names none (IDP_RESOURCE). */
82
+ resource: string | undefined;
83
+ };
84
+ /** The settings once checked, as nextidp uses them. */
85
+ export type IdpConfig = {
86
+ issuer: string;
87
+ clientId: string;
88
+ clientSecret: string | undefined;
89
+ /** This app's origin. */
90
+ appUrl: string;
91
+ /** The first one encrypts. */
92
+ secrets: readonly string[];
93
+ scope: string;
94
+ resource: string | undefined;
95
+ basePath: string;
96
+ redirectUri: string;
97
+ afterSignIn: string;
98
+ afterSignOut: string;
99
+ postLogoutRedirectUri: string;
100
+ errorPath: string;
101
+ signOutOfIdp: boolean;
102
+ sessionMaxAge: number;
103
+ /** https: cookies are Secure, with `__Host-` names. */
104
+ secure: boolean;
105
+ cookies: {
106
+ session: string;
107
+ flow: string;
108
+ };
109
+ store: SessionStore | undefined;
110
+ /** Where the auth server sends logout tokens, with a store. */
111
+ backchannelLogoutUri: string;
112
+ };
113
+ export declare const DEFAULT_SCOPES: readonly ["openid", "profile", "email", "offline_access"];
114
+ /**
115
+ * What checking access tokens needs: the issuer and this API's audience. The client ID and
116
+ * secret are optional: only introspection (an opaque token) uses them.
117
+ */
118
+ export declare function resolveApiConfig(options: IdpOptions): ApiConfig;
119
+ /**
120
+ * What getting a service's own tokens (client credentials) needs: the issuer, and a
121
+ * confidential client's ID and secret. Sign-in's `appUrl` and `secret` aren't needed.
122
+ */
123
+ export declare function resolveServiceConfig(options: IdpOptions): ServiceConfig;
124
+ /**
125
+ * The checked settings for signing people in. Throws an IdpError("misconfigured") that
126
+ * names every setting that's missing or wrong, and never repeats a value.
127
+ */
128
+ export declare function resolveConfig(options: IdpOptions): IdpConfig;