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.
- package/CHANGELOG.md +98 -0
- package/README.md +502 -4
- package/dist/cjs/access-token.d.ts +56 -0
- package/dist/cjs/access-token.js +196 -0
- package/dist/cjs/config.d.ts +128 -0
- package/dist/cjs/config.js +233 -0
- package/dist/cjs/cookies.d.ts +23 -0
- package/dist/cjs/cookies.js +118 -0
- package/dist/cjs/discovery.d.ts +24 -0
- package/dist/cjs/discovery.js +91 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +69 -0
- package/dist/cjs/express.d.ts +71 -0
- package/dist/cjs/express.js +114 -0
- package/dist/cjs/hono.d.ts +65 -0
- package/dist/cjs/hono.js +130 -0
- package/dist/cjs/http.d.ts +10 -0
- package/dist/cjs/http.js +68 -0
- package/dist/cjs/id-token.d.ts +19 -0
- package/dist/cjs/id-token.js +77 -0
- package/dist/cjs/idp.d.ts +81 -0
- package/dist/cjs/idp.js +482 -0
- package/dist/cjs/index.d.ts +9 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/logout-token.d.ts +13 -0
- package/dist/cjs/logout-token.js +63 -0
- package/dist/cjs/nestjs.d.ts +53 -0
- package/dist/cjs/nestjs.js +142 -0
- package/dist/cjs/next.d.ts +61 -0
- package/dist/cjs/next.js +118 -0
- package/dist/cjs/node-adapter.d.ts +16 -0
- package/dist/cjs/node-adapter.js +76 -0
- package/dist/cjs/node-http.d.ts +22 -0
- package/dist/cjs/node-http.js +127 -0
- package/dist/cjs/node.d.ts +50 -0
- package/dist/cjs/node.js +57 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pkce.d.ts +6 -0
- package/dist/cjs/pkce.js +49 -0
- package/dist/cjs/return-path.d.ts +6 -0
- package/dist/cjs/return-path.js +41 -0
- package/dist/cjs/sealed.d.ts +12 -0
- package/dist/cjs/sealed.js +78 -0
- package/dist/cjs/service.d.ts +61 -0
- package/dist/cjs/service.js +173 -0
- package/dist/cjs/session.d.ts +51 -0
- package/dist/cjs/session.js +97 -0
- package/dist/cjs/store.d.ts +58 -0
- package/dist/cjs/store.js +145 -0
- package/dist/cjs/tokens.d.ts +38 -0
- package/dist/cjs/tokens.js +138 -0
- package/dist/esm/access-token.d.ts +56 -0
- package/dist/esm/access-token.js +156 -0
- package/dist/esm/config.d.ts +128 -0
- package/dist/esm/config.js +206 -0
- package/dist/esm/cookies.d.ts +23 -0
- package/dist/esm/cookies.js +89 -0
- package/dist/esm/discovery.d.ts +24 -0
- package/dist/esm/discovery.js +56 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +41 -0
- package/dist/esm/express.d.ts +71 -0
- package/dist/esm/express.js +90 -0
- package/dist/esm/hono.d.ts +65 -0
- package/dist/esm/hono.js +106 -0
- package/dist/esm/http.d.ts +10 -0
- package/dist/esm/http.js +44 -0
- package/dist/esm/id-token.d.ts +19 -0
- package/dist/esm/id-token.js +51 -0
- package/dist/esm/idp.d.ts +81 -0
- package/dist/esm/idp.js +488 -0
- package/dist/esm/index.d.ts +9 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/logout-token.d.ts +13 -0
- package/dist/esm/logout-token.js +39 -0
- package/dist/esm/nestjs.d.ts +53 -0
- package/dist/esm/nestjs.js +118 -0
- package/dist/esm/next.d.ts +61 -0
- package/dist/esm/next.js +94 -0
- package/dist/esm/node-adapter.d.ts +16 -0
- package/dist/esm/node-adapter.js +60 -0
- package/dist/esm/node-http.d.ts +22 -0
- package/dist/esm/node-http.js +96 -0
- package/dist/esm/node.d.ts +50 -0
- package/dist/esm/node.js +33 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pkce.d.ts +6 -0
- package/dist/esm/pkce.js +23 -0
- package/dist/esm/return-path.d.ts +6 -0
- package/dist/esm/return-path.js +17 -0
- package/dist/esm/sealed.d.ts +12 -0
- package/dist/esm/sealed.js +54 -0
- package/dist/esm/service.d.ts +61 -0
- package/dist/esm/service.js +148 -0
- package/dist/esm/session.d.ts +51 -0
- package/dist/esm/session.js +58 -0
- package/dist/esm/store.d.ts +58 -0
- package/dist/esm/store.js +119 -0
- package/dist/esm/tokens.d.ts +38 -0
- package/dist/esm/tokens.js +100 -0
- package/package.json +152 -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,65 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
3
|
+
import type { IdpOptions } from "./config.js";
|
|
4
|
+
import { type Idp } from "./idp.js";
|
|
5
|
+
import type { Session } from "./session.js";
|
|
6
|
+
/**
|
|
7
|
+
* The context variables nextidp sets: `session` (by `middleware()`, null when signed out) and
|
|
8
|
+
* `token` (by `requireToken()`). Give it to your app: `new Hono<IdpEnv>()`.
|
|
9
|
+
*/
|
|
10
|
+
export type IdpEnv = {
|
|
11
|
+
Variables: {
|
|
12
|
+
session: Session | null;
|
|
13
|
+
token: AccessToken;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
export type HonoSessionOptions = {
|
|
17
|
+
/** Refresh the access token when it expires within a minute (default true). */
|
|
18
|
+
refresh?: boolean;
|
|
19
|
+
};
|
|
20
|
+
export type HonoIdp = Idp & {
|
|
21
|
+
/** nextidp's routes, for `app.all("/auth/*", auth.routes())` (under `basePath`). */
|
|
22
|
+
routes(): (c: Context) => Promise<Response>;
|
|
23
|
+
/**
|
|
24
|
+
* Reads the session for every request (refreshing the access token when it's about to
|
|
25
|
+
* expire, with the new cookie on the response) and puts it on the context:
|
|
26
|
+
* `c.get("session")`, null when signed out. `app.use(auth.middleware())`.
|
|
27
|
+
*/
|
|
28
|
+
middleware(options?: HonoSessionOptions): MiddlewareHandler<IdpEnv>;
|
|
29
|
+
/**
|
|
30
|
+
* Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
|
|
31
|
+
* comes back after; anything else gets 401.
|
|
32
|
+
*/
|
|
33
|
+
requireSession(): MiddlewareHandler<IdpEnv>;
|
|
34
|
+
/**
|
|
35
|
+
* Lets a request through only with a valid access token that has every scope in
|
|
36
|
+
* `requirements`, put on the context as `c.get("token")`. A refused one gets 401 or 403 with
|
|
37
|
+
* WWW-Authenticate (RFC 6750); one that can't be checked now (the auth server is down) 503.
|
|
38
|
+
*/
|
|
39
|
+
requireToken(requirements?: TokenRequirements): MiddlewareHandler<IdpEnv>;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The client for a Hono app or API:
|
|
43
|
+
*
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { Hono } from "hono";
|
|
46
|
+
* import { idp, type IdpEnv } from "nextidp/hono";
|
|
47
|
+
*
|
|
48
|
+
* const auth = idp({ issuer: "https://auth.example.com", clientId: "…", appUrl: "…", secret: "…" });
|
|
49
|
+
* const app = new Hono<IdpEnv>();
|
|
50
|
+
* app.all("/auth/*", auth.routes());
|
|
51
|
+
* app.use(auth.middleware());
|
|
52
|
+
* app.get("/dashboard", auth.requireSession(), (c) => c.text(`Hello, ${c.get("session")?.user.name}`));
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* On a runtime without `process.env` (Cloudflare Workers), pass the settings, or `env`:
|
|
56
|
+
* `idp(() => ({ env: workerEnv }))`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function idp(options?: IdpOptions | (() => IdpOptions)): HonoIdp;
|
|
59
|
+
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
60
|
+
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
61
|
+
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
62
|
+
export type { Idp, Refreshed } from "./idp.js";
|
|
63
|
+
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
64
|
+
export type { IdpUser, Session } from "./session.js";
|
|
65
|
+
export { memoryStore, type SessionStore } from "./store.js";
|