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.
- package/CHANGELOG.md +85 -0
- package/README.md +434 -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/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/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 +130 -5
|
@@ -0,0 +1,127 @@
|
|
|
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 node_http_exports = {};
|
|
20
|
+
__export(node_http_exports, {
|
|
21
|
+
BodyTooLarge: () => BodyTooLarge,
|
|
22
|
+
MAX_FORM_BYTES: () => MAX_FORM_BYTES,
|
|
23
|
+
appendSetCookies: () => appendSetCookies,
|
|
24
|
+
pathOf: () => pathOf,
|
|
25
|
+
sendText: () => sendText,
|
|
26
|
+
sendWebResponse: () => sendWebResponse,
|
|
27
|
+
toWebRequest: () => toWebRequest,
|
|
28
|
+
urlOf: () => urlOf
|
|
29
|
+
});
|
|
30
|
+
module.exports = __toCommonJS(node_http_exports);
|
|
31
|
+
const MAX_FORM_BYTES = 64 * 1024;
|
|
32
|
+
class BodyTooLarge extends Error {
|
|
33
|
+
constructor() {
|
|
34
|
+
super("The request body is too large.");
|
|
35
|
+
this.name = "BodyTooLarge";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function pathOf(req) {
|
|
39
|
+
const original = req.originalUrl;
|
|
40
|
+
const path = typeof original === "string" ? original : req.url ?? "/";
|
|
41
|
+
return path.startsWith("/") ? path : `/${path}`;
|
|
42
|
+
}
|
|
43
|
+
function urlOf(req, appUrl) {
|
|
44
|
+
return new URL(`${appUrl}${pathOf(req)}`);
|
|
45
|
+
}
|
|
46
|
+
function headersOf(req) {
|
|
47
|
+
const headers = new Headers();
|
|
48
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
49
|
+
if (value === void 0 || name.startsWith(":")) continue;
|
|
50
|
+
if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
51
|
+
else headers.set(name, value);
|
|
52
|
+
}
|
|
53
|
+
return headers;
|
|
54
|
+
}
|
|
55
|
+
function parsedBody(body) {
|
|
56
|
+
if (typeof body === "string") return body;
|
|
57
|
+
if (body instanceof Uint8Array) return new Uint8Array(body);
|
|
58
|
+
if (!body || typeof body !== "object") return void 0;
|
|
59
|
+
const form = new URLSearchParams();
|
|
60
|
+
for (const [name, value] of Object.entries(body)) {
|
|
61
|
+
if (typeof value === "string") form.append(name, value);
|
|
62
|
+
else if (Array.isArray(value)) {
|
|
63
|
+
for (const item of value) if (typeof item === "string") form.append(name, item);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return form.toString();
|
|
67
|
+
}
|
|
68
|
+
async function readBody(req) {
|
|
69
|
+
const declared = Number(req.headers["content-length"]);
|
|
70
|
+
if (declared > MAX_FORM_BYTES) throw new BodyTooLarge();
|
|
71
|
+
const chunks = [];
|
|
72
|
+
let size = 0;
|
|
73
|
+
for await (const chunk of req) {
|
|
74
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
75
|
+
size += bytes.length;
|
|
76
|
+
if (size > MAX_FORM_BYTES) throw new BodyTooLarge();
|
|
77
|
+
chunks.push(bytes);
|
|
78
|
+
}
|
|
79
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
80
|
+
}
|
|
81
|
+
async function toWebRequest(req, appUrl) {
|
|
82
|
+
const url = urlOf(req, appUrl);
|
|
83
|
+
const headers = headersOf(req);
|
|
84
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
85
|
+
if (method === "GET" || method === "HEAD") return new Request(url, { method, headers });
|
|
86
|
+
let body;
|
|
87
|
+
if (req.readableEnded) {
|
|
88
|
+
body = parsedBody(req.body);
|
|
89
|
+
if (typeof body === "string") headers.set("content-type", "application/x-www-form-urlencoded");
|
|
90
|
+
} else {
|
|
91
|
+
body = await readBody(req);
|
|
92
|
+
}
|
|
93
|
+
headers.delete("content-length");
|
|
94
|
+
headers.delete("transfer-encoding");
|
|
95
|
+
return new Request(url, { method, headers, ...body === void 0 ? {} : { body } });
|
|
96
|
+
}
|
|
97
|
+
function appendSetCookies(res, cookies) {
|
|
98
|
+
if (cookies.length === 0) return;
|
|
99
|
+
const existing = res.getHeader("set-cookie");
|
|
100
|
+
const list = existing === void 0 ? [] : Array.isArray(existing) ? existing : [String(existing)];
|
|
101
|
+
res.setHeader("set-cookie", [...list, ...cookies]);
|
|
102
|
+
}
|
|
103
|
+
async function sendWebResponse(res, response) {
|
|
104
|
+
res.statusCode = response.status;
|
|
105
|
+
response.headers.forEach((value, name) => {
|
|
106
|
+
if (name !== "set-cookie") res.setHeader(name, value);
|
|
107
|
+
});
|
|
108
|
+
appendSetCookies(res, response.headers.getSetCookie());
|
|
109
|
+
res.end(response.body ? Buffer.from(await response.arrayBuffer()) : void 0);
|
|
110
|
+
}
|
|
111
|
+
function sendText(res, status, text) {
|
|
112
|
+
res.statusCode = status;
|
|
113
|
+
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
114
|
+
res.setHeader("cache-control", "no-store");
|
|
115
|
+
res.end(text);
|
|
116
|
+
}
|
|
117
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
118
|
+
0 && (module.exports = {
|
|
119
|
+
BodyTooLarge,
|
|
120
|
+
MAX_FORM_BYTES,
|
|
121
|
+
appendSetCookies,
|
|
122
|
+
pathOf,
|
|
123
|
+
sendText,
|
|
124
|
+
sendWebResponse,
|
|
125
|
+
toWebRequest,
|
|
126
|
+
urlOf
|
|
127
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { IdpOptions } from "./config.js";
|
|
3
|
+
import { type Idp } from "./idp.js";
|
|
4
|
+
import { type SessionOptions } from "./node-adapter.js";
|
|
5
|
+
import type { Session } from "./session.js";
|
|
6
|
+
export type NodeIdp = Idp & {
|
|
7
|
+
/**
|
|
8
|
+
* Answers nextidp's routes (`<basePath>/login`, `/callback`, `/logout`, `/refresh`) and
|
|
9
|
+
* returns true; any other path is left to you, and it returns false.
|
|
10
|
+
*/
|
|
11
|
+
handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
|
|
12
|
+
/**
|
|
13
|
+
* The signed-in session, or null. Refreshes the access token first when it's about to
|
|
14
|
+
* expire, setting the new cookie on `res`, so call it before you start the response. Read
|
|
15
|
+
* twice in one request, it answers the same.
|
|
16
|
+
*/
|
|
17
|
+
session(req: IncomingMessage, res: ServerResponse, options?: SessionOptions): Promise<Session | null>;
|
|
18
|
+
/**
|
|
19
|
+
* The session; or, signed out, a redirect to sign in that comes back to `returnTo` (default:
|
|
20
|
+
* this request's path) for GET and HEAD, or 401 for anything else. Then it's null and the
|
|
21
|
+
* response is sent.
|
|
22
|
+
*/
|
|
23
|
+
requireSession(req: IncomingMessage, res: ServerResponse, returnTo?: string): Promise<Session | null>;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The client for an app on Node's own HTTP server:
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* import { createServer } from "node:http";
|
|
30
|
+
* import { idp } from "nextidp/node";
|
|
31
|
+
*
|
|
32
|
+
* const auth = idp(); // the IDP_* environment variables, read on first use
|
|
33
|
+
*
|
|
34
|
+
* createServer(async (req, res) => {
|
|
35
|
+
* if (await auth.handle(req, res)) return;
|
|
36
|
+
* const session = await auth.requireSession(req, res);
|
|
37
|
+
* if (!session) return;
|
|
38
|
+
* res.end(`Hello, ${session.user.name}`);
|
|
39
|
+
* }).listen(3000);
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function idp(options?: IdpOptions | (() => IdpOptions)): NodeIdp;
|
|
43
|
+
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
44
|
+
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
45
|
+
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
46
|
+
export type { Idp, Refreshed } from "./idp.js";
|
|
47
|
+
export type { SessionOptions } from "./node-adapter.js";
|
|
48
|
+
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
49
|
+
export type { IdpUser, Session } from "./session.js";
|
|
50
|
+
export { memoryStore, type SessionStore } from "./store.js";
|
package/dist/cjs/node.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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 node_exports = {};
|
|
20
|
+
__export(node_exports, {
|
|
21
|
+
IdpError: () => import_errors.IdpError,
|
|
22
|
+
SIGN_IN_ERROR_CODES: () => import_errors.SIGN_IN_ERROR_CODES,
|
|
23
|
+
idp: () => idp,
|
|
24
|
+
isIdpError: () => import_errors.isIdpError,
|
|
25
|
+
isSignInErrorCode: () => import_errors.isSignInErrorCode,
|
|
26
|
+
isTokenError: () => import_errors.isTokenError,
|
|
27
|
+
memoryStore: () => import_store.memoryStore
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(node_exports);
|
|
30
|
+
var import_idp = require("./idp.js");
|
|
31
|
+
var import_node_adapter = require("./node-adapter.js");
|
|
32
|
+
var import_errors = require("./errors.js");
|
|
33
|
+
var import_store = require("./store.js");
|
|
34
|
+
function idp(options) {
|
|
35
|
+
const core = (0, import_idp.createIdp)(options);
|
|
36
|
+
const node = (0, import_node_adapter.nodeAdapter)(core);
|
|
37
|
+
return {
|
|
38
|
+
...core,
|
|
39
|
+
handle: node.handle,
|
|
40
|
+
session: node.session,
|
|
41
|
+
async requireSession(req, res, returnTo) {
|
|
42
|
+
const session = await node.session(req, res);
|
|
43
|
+
if (!session) node.turnAway(req, res, returnTo);
|
|
44
|
+
return session;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
49
|
+
0 && (module.exports = {
|
|
50
|
+
IdpError,
|
|
51
|
+
SIGN_IN_ERROR_CODES,
|
|
52
|
+
idp,
|
|
53
|
+
isIdpError,
|
|
54
|
+
isSignInErrorCode,
|
|
55
|
+
isTokenError,
|
|
56
|
+
memoryStore
|
|
57
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** 256 random bits, base64url: a PKCE verifier (RFC 7636 4.1), a state or a nonce. */
|
|
2
|
+
export declare function randomToken(): string;
|
|
3
|
+
/** The S256 code challenge for a verifier: base64url(SHA-256(verifier)). */
|
|
4
|
+
export declare function challengeFor(verifier: string): Promise<string>;
|
|
5
|
+
/** Compares two strings without leaking where they differ through timing. */
|
|
6
|
+
export declare function sameString(a: string, b: string): boolean;
|
package/dist/cjs/pkce.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
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 pkce_exports = {};
|
|
20
|
+
__export(pkce_exports, {
|
|
21
|
+
challengeFor: () => challengeFor,
|
|
22
|
+
randomToken: () => randomToken,
|
|
23
|
+
sameString: () => sameString
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(pkce_exports);
|
|
26
|
+
var import_jose = require("jose");
|
|
27
|
+
function randomToken() {
|
|
28
|
+
return import_jose.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));
|
|
29
|
+
}
|
|
30
|
+
async function challengeFor(verifier) {
|
|
31
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
32
|
+
return import_jose.base64url.encode(new Uint8Array(digest));
|
|
33
|
+
}
|
|
34
|
+
function sameString(a, b) {
|
|
35
|
+
const left = new TextEncoder().encode(a);
|
|
36
|
+
const right = new TextEncoder().encode(b);
|
|
37
|
+
if (left.length !== right.length) return false;
|
|
38
|
+
let difference = 0;
|
|
39
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
40
|
+
difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
|
|
41
|
+
}
|
|
42
|
+
return difference === 0;
|
|
43
|
+
}
|
|
44
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
45
|
+
0 && (module.exports = {
|
|
46
|
+
challengeFor,
|
|
47
|
+
randomToken,
|
|
48
|
+
sameString
|
|
49
|
+
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A path of this app, or undefined. Where a sign-in returns to comes from the browser
|
|
3
|
+
* (`?returnTo=`, a form field), so anything that could lead to another site is refused:
|
|
4
|
+
* `//evil.example`, `/\evil.example`, `https://…`, `javascript:…`, and control characters.
|
|
5
|
+
*/
|
|
6
|
+
export declare function safePath(value: unknown): string | undefined;
|
|
@@ -0,0 +1,41 @@
|
|
|
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 return_path_exports = {};
|
|
20
|
+
__export(return_path_exports, {
|
|
21
|
+
safePath: () => safePath
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(return_path_exports);
|
|
24
|
+
const PLACEHOLDER = "http://nextidp.invalid";
|
|
25
|
+
function safePath(value) {
|
|
26
|
+
if (typeof value !== "string" || !value.startsWith("/")) return void 0;
|
|
27
|
+
if (value.startsWith("//") || value.includes("\\") || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
28
|
+
return void 0;
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const url = new URL(value, PLACEHOLDER);
|
|
32
|
+
if (url.origin !== PLACEHOLDER) return void 0;
|
|
33
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
34
|
+
} catch {
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
39
|
+
0 && (module.exports = {
|
|
40
|
+
safePath
|
|
41
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Seals and opens values for one `idp()` instance; derived keys are kept, not recomputed. */
|
|
2
|
+
export declare class Sealer {
|
|
3
|
+
#private;
|
|
4
|
+
constructor(secrets: readonly string[]);
|
|
5
|
+
/** Encrypts with the first secret. */
|
|
6
|
+
seal(payload: Record<string, unknown>, purpose: string, maxAgeSeconds: number): Promise<string>;
|
|
7
|
+
/**
|
|
8
|
+
* The payload, or undefined if the value is missing, altered, sealed for another purpose,
|
|
9
|
+
* expired, or sealed with a secret no longer in the list. Tries every secret, in order.
|
|
10
|
+
*/
|
|
11
|
+
unseal(value: string | undefined, purpose: string): Promise<Record<string, unknown> | undefined>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
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 sealed_exports = {};
|
|
20
|
+
__export(sealed_exports, {
|
|
21
|
+
Sealer: () => Sealer
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(sealed_exports);
|
|
24
|
+
var import_jose = require("jose");
|
|
25
|
+
const encoder = new TextEncoder();
|
|
26
|
+
const SALT = encoder.encode("nextidp sealed cookie");
|
|
27
|
+
async function deriveKey(secret, purpose) {
|
|
28
|
+
const material = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, [
|
|
29
|
+
"deriveBits"
|
|
30
|
+
]);
|
|
31
|
+
const bits = await crypto.subtle.deriveBits(
|
|
32
|
+
{ name: "HKDF", hash: "SHA-256", salt: SALT, info: encoder.encode(purpose) },
|
|
33
|
+
material,
|
|
34
|
+
256
|
|
35
|
+
);
|
|
36
|
+
return new Uint8Array(bits);
|
|
37
|
+
}
|
|
38
|
+
class Sealer {
|
|
39
|
+
#secrets;
|
|
40
|
+
#keys = /* @__PURE__ */ new Map();
|
|
41
|
+
constructor(secrets) {
|
|
42
|
+
this.#secrets = secrets;
|
|
43
|
+
}
|
|
44
|
+
#key(secret, purpose) {
|
|
45
|
+
const id = `${purpose}\0${secret}`;
|
|
46
|
+
let key = this.#keys.get(id);
|
|
47
|
+
if (!key) {
|
|
48
|
+
key = deriveKey(secret, purpose);
|
|
49
|
+
this.#keys.set(id, key);
|
|
50
|
+
}
|
|
51
|
+
return key;
|
|
52
|
+
}
|
|
53
|
+
/** Encrypts with the first secret. */
|
|
54
|
+
async seal(payload, purpose, maxAgeSeconds) {
|
|
55
|
+
const [secret] = this.#secrets;
|
|
56
|
+
if (secret === void 0) throw new Error("No secret to seal with.");
|
|
57
|
+
return new import_jose.EncryptJWT(payload).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).setIssuedAt().setExpirationTime(`${maxAgeSeconds}s`).encrypt(await this.#key(secret, purpose));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The payload, or undefined if the value is missing, altered, sealed for another purpose,
|
|
61
|
+
* expired, or sealed with a secret no longer in the list. Tries every secret, in order.
|
|
62
|
+
*/
|
|
63
|
+
async unseal(value, purpose) {
|
|
64
|
+
if (!value) return void 0;
|
|
65
|
+
for (const secret of this.#secrets) {
|
|
66
|
+
try {
|
|
67
|
+
const { payload } = await (0, import_jose.jwtDecrypt)(value, await this.#key(secret, purpose));
|
|
68
|
+
return payload;
|
|
69
|
+
} catch {
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return void 0;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
76
|
+
0 && (module.exports = {
|
|
77
|
+
Sealer
|
|
78
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ServiceConfig } from "./config.js";
|
|
2
|
+
import type { Discovery } from "./discovery.js";
|
|
3
|
+
import type { Http } from "./http.js";
|
|
4
|
+
export type ServiceTokenOptions = {
|
|
5
|
+
/** The scopes to ask for (default: none, so the auth server decides). */
|
|
6
|
+
scopes?: readonly string[] | undefined;
|
|
7
|
+
/** The API the token is for (RFC 8707). Default `resource` (IDP_RESOURCE), if set. */
|
|
8
|
+
resource?: string | undefined;
|
|
9
|
+
/** Ask for a new token even if one is kept. */
|
|
10
|
+
fresh?: boolean | undefined;
|
|
11
|
+
};
|
|
12
|
+
export type UseServiceTokenOptions = Omit<ServiceTokenOptions, "fresh"> & {
|
|
13
|
+
/**
|
|
14
|
+
* The origins the token may be sent to, like `https://orders.example.com`. Default: the
|
|
15
|
+
* origin of `resource` (or IDP_RESOURCE). A request anywhere else goes out untouched, with
|
|
16
|
+
* no token: a URL from elsewhere must never carry this service's token away.
|
|
17
|
+
*/
|
|
18
|
+
origins?: readonly string[] | undefined;
|
|
19
|
+
};
|
|
20
|
+
type RequestConfigLike = {
|
|
21
|
+
url: string;
|
|
22
|
+
baseUrl?: string;
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
retried?: boolean;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* What `useServiceToken` needs of an HTTP client: fast-http-client's `createHttp()` has it.
|
|
28
|
+
* Written out rather than imported, so a client from another version of it fits too.
|
|
29
|
+
*/
|
|
30
|
+
export type InterceptableClient = {
|
|
31
|
+
request(config: RequestConfigLike): Promise<unknown>;
|
|
32
|
+
interceptors: {
|
|
33
|
+
request: {
|
|
34
|
+
use(fn: (config: RequestConfigLike) => Promise<RequestConfigLike>): () => void;
|
|
35
|
+
};
|
|
36
|
+
response: {
|
|
37
|
+
use(handlers: {
|
|
38
|
+
onRejected?: (error: unknown) => unknown;
|
|
39
|
+
}): () => void;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
export type ServiceTokens = {
|
|
44
|
+
get(options?: ServiceTokenOptions): Promise<string>;
|
|
45
|
+
drop(token: string): void;
|
|
46
|
+
/** The API a token is for when a call names none (IDP_RESOURCE). */
|
|
47
|
+
defaultResource: string | undefined;
|
|
48
|
+
};
|
|
49
|
+
export declare function createServiceTokens(deps: {
|
|
50
|
+
http: Http;
|
|
51
|
+
discovery: () => Promise<Discovery>;
|
|
52
|
+
config: ServiceConfig;
|
|
53
|
+
}): ServiceTokens;
|
|
54
|
+
/**
|
|
55
|
+
* Puts a service token on every request of `client` to the allowed origins, and nowhere else.
|
|
56
|
+
* When the API answers 401, the token is dropped and the request sent once more with a new
|
|
57
|
+
* one (a token revoked early); a second 401 is the caller's. Returns a function that takes
|
|
58
|
+
* both hooks off.
|
|
59
|
+
*/
|
|
60
|
+
export declare function useServiceToken(tokens: ServiceTokens, client: InterceptableClient, options?: UseServiceTokenOptions): () => void;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,173 @@
|
|
|
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 service_exports = {};
|
|
20
|
+
__export(service_exports, {
|
|
21
|
+
createServiceTokens: () => createServiceTokens,
|
|
22
|
+
useServiceToken: () => useServiceToken
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(service_exports);
|
|
25
|
+
var import_access_token = require("./access-token.js");
|
|
26
|
+
var import_errors = require("./errors.js");
|
|
27
|
+
var import_tokens = require("./tokens.js");
|
|
28
|
+
const RENEW_BEFORE_S = 60;
|
|
29
|
+
const MAX_KEPT = 100;
|
|
30
|
+
function misconfigured(problem) {
|
|
31
|
+
return new import_errors.IdpError("misconfigured", `nextidp is misconfigured: ${problem}.`);
|
|
32
|
+
}
|
|
33
|
+
function scopeOf(scopes) {
|
|
34
|
+
const list = [...new Set((scopes ?? []).map((scope) => scope.trim()).filter(Boolean))];
|
|
35
|
+
if (list.some((scope) => /\s/.test(scope))) throw misconfigured("a scope can't hold spaces");
|
|
36
|
+
return list.length > 0 ? list.sort().join(" ") : void 0;
|
|
37
|
+
}
|
|
38
|
+
function resourceOf(resource) {
|
|
39
|
+
if (resource === void 0) return void 0;
|
|
40
|
+
if (!URL.canParse(resource) || /\s/.test(resource)) {
|
|
41
|
+
throw misconfigured("resource must be an absolute URI");
|
|
42
|
+
}
|
|
43
|
+
return resource;
|
|
44
|
+
}
|
|
45
|
+
function createServiceTokens(deps) {
|
|
46
|
+
const kept = /* @__PURE__ */ new Map();
|
|
47
|
+
const client = { clientId: deps.config.clientId, clientSecret: deps.config.clientSecret };
|
|
48
|
+
const issue = async (scope, resource) => {
|
|
49
|
+
const tokens = await (0, import_tokens.clientCredentials)(deps.http, await deps.discovery(), client, {
|
|
50
|
+
scope,
|
|
51
|
+
resource
|
|
52
|
+
});
|
|
53
|
+
const lifetime = tokens.expires_in ?? 0;
|
|
54
|
+
const renewIn = lifetime - Math.min(RENEW_BEFORE_S, lifetime / 2);
|
|
55
|
+
return { token: tokens.access_token, until: Date.now() + Math.max(0, renewIn) * 1e3 };
|
|
56
|
+
};
|
|
57
|
+
const prune = (now) => {
|
|
58
|
+
for (const [key, entry] of kept) {
|
|
59
|
+
if (entry.issued && entry.issued.until <= now) kept.delete(key);
|
|
60
|
+
}
|
|
61
|
+
const oldest = kept.keys().next();
|
|
62
|
+
if (kept.size >= MAX_KEPT && !oldest.done) kept.delete(oldest.value);
|
|
63
|
+
};
|
|
64
|
+
return {
|
|
65
|
+
async get(options = {}) {
|
|
66
|
+
const scope = scopeOf(options.scopes);
|
|
67
|
+
const resource = resourceOf(options.resource ?? deps.config.resource);
|
|
68
|
+
const key = JSON.stringify([resource ?? null, scope ?? null]);
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const known = kept.get(key);
|
|
71
|
+
if (known && !options.fresh) {
|
|
72
|
+
if (!known.issued) return (await known.pending).token;
|
|
73
|
+
if (known.issued.until > now) return known.issued.token;
|
|
74
|
+
}
|
|
75
|
+
if (kept.size >= MAX_KEPT) prune(now);
|
|
76
|
+
const entry = { pending: issue(scope, resource) };
|
|
77
|
+
entry.pending.then(
|
|
78
|
+
(issued) => {
|
|
79
|
+
entry.issued = issued;
|
|
80
|
+
},
|
|
81
|
+
() => void 0
|
|
82
|
+
);
|
|
83
|
+
kept.set(key, entry);
|
|
84
|
+
try {
|
|
85
|
+
return (await entry.pending).token;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (kept.get(key) === entry) kept.delete(key);
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
drop(token) {
|
|
92
|
+
for (const [key, entry] of kept) if (entry.issued?.token === token) kept.delete(key);
|
|
93
|
+
},
|
|
94
|
+
defaultResource: deps.config.resource
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function statusOf(error) {
|
|
98
|
+
const status = error?.status;
|
|
99
|
+
return typeof status === "number" ? status : void 0;
|
|
100
|
+
}
|
|
101
|
+
function configOf(error) {
|
|
102
|
+
const config = error?.config;
|
|
103
|
+
return config && typeof config === "object" && typeof config.url === "string" ? config : void 0;
|
|
104
|
+
}
|
|
105
|
+
function originOf(config) {
|
|
106
|
+
try {
|
|
107
|
+
return new URL(config.url, config.baseUrl).origin;
|
|
108
|
+
} catch {
|
|
109
|
+
return void 0;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function allowedOrigins(tokens, options) {
|
|
113
|
+
const resource = options.resource ?? tokens.defaultResource;
|
|
114
|
+
const listed = options.origins ?? (resource && /^https?:\/\//i.test(resource) ? [resource] : []);
|
|
115
|
+
const origins = /* @__PURE__ */ new Set();
|
|
116
|
+
for (const value of listed) {
|
|
117
|
+
const url = URL.canParse(value) ? new URL(value) : void 0;
|
|
118
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:") {
|
|
119
|
+
throw misconfigured("useServiceToken's origins must be http(s) URLs");
|
|
120
|
+
}
|
|
121
|
+
origins.add(url.origin);
|
|
122
|
+
}
|
|
123
|
+
if (origins.size === 0) {
|
|
124
|
+
throw misconfigured(
|
|
125
|
+
"useServiceToken needs origins, or an http(s) resource, to know where the token may go"
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
return origins;
|
|
129
|
+
}
|
|
130
|
+
function withoutAuthorization(headers) {
|
|
131
|
+
return Object.fromEntries(
|
|
132
|
+
Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization")
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
function useServiceToken(tokens, client, options = {}) {
|
|
136
|
+
const origins = allowedOrigins(tokens, options);
|
|
137
|
+
const { origins: _listed, ...tokenOptions } = options;
|
|
138
|
+
const allowed = (config) => {
|
|
139
|
+
const origin = originOf(config);
|
|
140
|
+
return origin !== void 0 && origins.has(origin);
|
|
141
|
+
};
|
|
142
|
+
const stopRequest = client.interceptors.request.use(
|
|
143
|
+
async (config) => allowed(config) ? {
|
|
144
|
+
...config,
|
|
145
|
+
headers: {
|
|
146
|
+
...withoutAuthorization(config.headers),
|
|
147
|
+
authorization: `Bearer ${await tokens.get(tokenOptions)}`
|
|
148
|
+
}
|
|
149
|
+
} : config
|
|
150
|
+
);
|
|
151
|
+
const stopResponse = client.interceptors.response.use({
|
|
152
|
+
async onRejected(error) {
|
|
153
|
+
const config = configOf(error);
|
|
154
|
+
if (statusOf(error) !== 401 || !config || config.retried || !allowed(config)) throw error;
|
|
155
|
+
const refused = (0, import_access_token.bearerToken)(
|
|
156
|
+
Object.entries(config.headers ?? {}).find(
|
|
157
|
+
([name]) => name.toLowerCase() === "authorization"
|
|
158
|
+
)?.[1]
|
|
159
|
+
);
|
|
160
|
+
if (refused) tokens.drop(refused);
|
|
161
|
+
return client.request({ ...config, retried: true });
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
return () => {
|
|
165
|
+
stopRequest();
|
|
166
|
+
stopResponse();
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
170
|
+
0 && (module.exports = {
|
|
171
|
+
createServiceTokens,
|
|
172
|
+
useServiceToken
|
|
173
|
+
});
|