@profullstack/chat-plugins 0.0.0-stage → 0.2.0
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/LICENSE +3 -0
- package/README.md +126 -2
- package/index.d.ts +360 -0
- package/package.json +53 -4
- package/src/catalog.js +79 -0
- package/src/discover.js +180 -0
- package/src/index.js +41 -0
- package/src/loop.js +403 -0
- package/src/mcp.js +323 -0
- package/src/money.js +372 -0
- package/src/net.js +299 -0
- package/src/oauth.js +280 -0
- package/src/seal.js +69 -0
- package/src/tools.js +114 -0
package/src/net.js
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// Network guard: every request this package makes goes through safeFetch.
|
|
2
|
+
//
|
|
3
|
+
// - https only (http allowed for localhost when `allowHttpLocalhost`, or anywhere
|
|
4
|
+
// when `allowPrivate` is set, which tests and local dev use).
|
|
5
|
+
// - SSRF: the hostname is resolved (node:dns when available) and every address
|
|
6
|
+
// must be public. Private, loopback, link-local, CGNAT, multicast and
|
|
7
|
+
// reserved ranges are refused unless `allowPrivate`.
|
|
8
|
+
// - Redirects are followed by hand, re-checked at every hop, and a request that
|
|
9
|
+
// carries a bearer token is never forwarded to a different origin.
|
|
10
|
+
// - Response bodies are read with a byte cap.
|
|
11
|
+
|
|
12
|
+
export class PluginError extends Error {
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} message
|
|
15
|
+
* @param {{ code?: string, status?: number, cause?: unknown }} [info]
|
|
16
|
+
*/
|
|
17
|
+
constructor(message, info = {}) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "PluginError";
|
|
20
|
+
this.code = info.code || "plugin_error";
|
|
21
|
+
if (info.status !== undefined) this.status = info.status;
|
|
22
|
+
if (info.cause !== undefined) this.cause = info.cause;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const LOCAL_NAMES = new Set(["localhost", "localhost.localdomain", "ip6-localhost", "ip6-loopback"]);
|
|
27
|
+
|
|
28
|
+
/** @param {string} host */
|
|
29
|
+
function stripBrackets(host) {
|
|
30
|
+
return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {string} ip */
|
|
34
|
+
function parseV4(ip) {
|
|
35
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
|
|
36
|
+
if (!m) return null;
|
|
37
|
+
const parts = m.slice(1).map(Number);
|
|
38
|
+
if (parts.some((p) => p > 255)) return null;
|
|
39
|
+
return parts;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* True when an IP literal is not a public unicast address.
|
|
44
|
+
* @param {string} ip
|
|
45
|
+
*/
|
|
46
|
+
export function isPrivateAddress(ip) {
|
|
47
|
+
ip = stripBrackets(String(ip).trim()).toLowerCase();
|
|
48
|
+
const v4 = parseV4(ip);
|
|
49
|
+
if (v4) {
|
|
50
|
+
const [a, b, c] = v4;
|
|
51
|
+
if (a === 0 || a === 10 || a === 127) return true;
|
|
52
|
+
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
|
|
53
|
+
if (a === 169 && b === 254) return true; // link-local, cloud metadata
|
|
54
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
55
|
+
if (a === 192 && b === 168) return true;
|
|
56
|
+
if (a === 192 && b === 0 && (c === 0 || c === 2)) return true;
|
|
57
|
+
if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking
|
|
58
|
+
if (a === 198 && b === 51 && c === 100) return true;
|
|
59
|
+
if (a === 203 && b === 0 && c === 113) return true;
|
|
60
|
+
if (a >= 224) return true; // multicast, reserved, broadcast
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
if (!ip.includes(":")) return false; // not an IP literal
|
|
64
|
+
if (ip === "::" || ip === "::1") return true;
|
|
65
|
+
const mapped = /^::(?:ffff:)?(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
|
|
66
|
+
if (mapped) return isPrivateAddress(mapped[1]);
|
|
67
|
+
const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(ip);
|
|
68
|
+
if (mappedHex) {
|
|
69
|
+
const hi = parseInt(mappedHex[1], 16);
|
|
70
|
+
const lo = parseInt(mappedHex[2], 16);
|
|
71
|
+
return isPrivateAddress(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
|
|
72
|
+
}
|
|
73
|
+
const groups = ip.split(":");
|
|
74
|
+
const first = parseInt(groups[0] || "0", 16);
|
|
75
|
+
if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local
|
|
76
|
+
if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local
|
|
77
|
+
if ((first & 0xffc0) === 0xfec0) return true; // site-local (deprecated)
|
|
78
|
+
if ((first & 0xff00) === 0xff00) return true; // multicast
|
|
79
|
+
if (first === 0x2001 && groups[1] === "db8") return true; // documentation
|
|
80
|
+
if (first === 0x64 && groups[1] === "ff9b") return true; // NAT64 reaches v4 private
|
|
81
|
+
if (first === 0x2002) return true; // 6to4 embeds an arbitrary v4
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** @param {string} host */
|
|
86
|
+
function isIpLiteral(host) {
|
|
87
|
+
host = stripBrackets(host);
|
|
88
|
+
return !!parseV4(host) || host.includes(":");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** @param {string} host */
|
|
92
|
+
export function isLocalHostname(host) {
|
|
93
|
+
host = stripBrackets(host).toLowerCase().replace(/\.$/, "");
|
|
94
|
+
if (LOCAL_NAMES.has(host) || host.endsWith(".localhost")) return true;
|
|
95
|
+
if (isIpLiteral(host)) {
|
|
96
|
+
const v4 = parseV4(host);
|
|
97
|
+
return (v4 && v4[0] === 127) || host === "::1";
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @type {any} */
|
|
103
|
+
let dnsLookup;
|
|
104
|
+
async function getLookup() {
|
|
105
|
+
if (dnsLookup !== undefined) return dnsLookup;
|
|
106
|
+
try {
|
|
107
|
+
const dns = await import("node:dns/promises");
|
|
108
|
+
dnsLookup = dns.lookup;
|
|
109
|
+
} catch {
|
|
110
|
+
dnsLookup = null; // browser / edge: literal checks only
|
|
111
|
+
}
|
|
112
|
+
return dnsLookup;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Throws a PluginError unless `url` is safe to fetch from a server.
|
|
117
|
+
* @param {string | URL} input
|
|
118
|
+
* @param {import("../index.js").NetOptions} [opts]
|
|
119
|
+
* @returns {Promise<URL>}
|
|
120
|
+
*/
|
|
121
|
+
export async function assertSafeUrl(input, opts = {}) {
|
|
122
|
+
let url;
|
|
123
|
+
try {
|
|
124
|
+
url = new URL(String(input));
|
|
125
|
+
} catch {
|
|
126
|
+
throw new PluginError(`Not a valid URL: ${String(input).slice(0, 200)}`, { code: "bad_url" });
|
|
127
|
+
}
|
|
128
|
+
if (url.username || url.password) {
|
|
129
|
+
throw new PluginError("Plugin URLs cannot carry credentials", { code: "bad_url" });
|
|
130
|
+
}
|
|
131
|
+
const host = url.hostname;
|
|
132
|
+
const local = isLocalHostname(host);
|
|
133
|
+
if (url.protocol === "http:") {
|
|
134
|
+
if (!(opts.allowPrivate || (opts.allowHttpLocalhost && local))) {
|
|
135
|
+
throw new PluginError("Plugin URLs must use https", { code: "insecure_url" });
|
|
136
|
+
}
|
|
137
|
+
} else if (url.protocol !== "https:") {
|
|
138
|
+
throw new PluginError(`Unsupported URL scheme ${url.protocol}`, { code: "bad_url" });
|
|
139
|
+
}
|
|
140
|
+
if (!opts.allowPrivate && !(opts.allowHttpLocalhost && local)) {
|
|
141
|
+
if (local) throw new PluginError("Plugin URL points at this machine", { code: "private_address" });
|
|
142
|
+
if (isIpLiteral(host)) {
|
|
143
|
+
if (isPrivateAddress(host)) {
|
|
144
|
+
throw new PluginError("Plugin URL points at a private address", { code: "private_address" });
|
|
145
|
+
}
|
|
146
|
+
} else {
|
|
147
|
+
const lookup = await getLookup();
|
|
148
|
+
if (lookup) {
|
|
149
|
+
let addrs;
|
|
150
|
+
try {
|
|
151
|
+
addrs = await lookup(host, { all: true, verbatim: true });
|
|
152
|
+
} catch (err) {
|
|
153
|
+
throw new PluginError(`Cannot resolve ${host}`, { code: "dns_failed", cause: err });
|
|
154
|
+
}
|
|
155
|
+
if (!addrs.length) throw new PluginError(`Cannot resolve ${host}`, { code: "dns_failed" });
|
|
156
|
+
for (const a of addrs) {
|
|
157
|
+
if (isPrivateAddress(a.address)) {
|
|
158
|
+
throw new PluginError(`${host} resolves to a private address`, { code: "private_address" });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (opts.guard) await opts.guard(url);
|
|
165
|
+
return url;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Read a response body as text with a byte cap.
|
|
170
|
+
* @param {Response} res
|
|
171
|
+
* @param {number} maxBytes
|
|
172
|
+
*/
|
|
173
|
+
export async function readCapped(res, maxBytes) {
|
|
174
|
+
if (!res.body) return "";
|
|
175
|
+
const reader = res.body.getReader();
|
|
176
|
+
const decoder = new TextDecoder();
|
|
177
|
+
let total = 0;
|
|
178
|
+
let out = "";
|
|
179
|
+
for (;;) {
|
|
180
|
+
const { done, value } = await reader.read();
|
|
181
|
+
if (done) break;
|
|
182
|
+
total += value.byteLength;
|
|
183
|
+
if (total > maxBytes) {
|
|
184
|
+
try {
|
|
185
|
+
await reader.cancel();
|
|
186
|
+
} catch {}
|
|
187
|
+
throw new PluginError(`Response larger than ${maxBytes} bytes`, { code: "too_large" });
|
|
188
|
+
}
|
|
189
|
+
out += decoder.decode(value, { stream: true });
|
|
190
|
+
}
|
|
191
|
+
return out + decoder.decode();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* fetch with the guard, a timeout, and hand-followed redirects (each hop re-checked;
|
|
196
|
+
* an authenticated request never leaves its origin). The caller must call done().
|
|
197
|
+
* @param {string | URL} input
|
|
198
|
+
* @param {RequestInit & { headers?: Record<string,string> }} init
|
|
199
|
+
* @param {import("../index.js").NetOptions} [opts]
|
|
200
|
+
* @returns {Promise<{ res: Response, url: URL, done: () => void }>}
|
|
201
|
+
*/
|
|
202
|
+
export async function safeFetch(input, init = {}, opts = {}) {
|
|
203
|
+
const f = opts.fetch || globalThis.fetch;
|
|
204
|
+
if (!f) throw new PluginError("No fetch implementation available");
|
|
205
|
+
const ctrl = new AbortController();
|
|
206
|
+
const timeoutMs = opts.timeoutMs ?? 30_000;
|
|
207
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
208
|
+
const done = () => clearTimeout(timer);
|
|
209
|
+
try {
|
|
210
|
+
let url = await assertSafeUrl(input, opts);
|
|
211
|
+
const origin0 = url.origin;
|
|
212
|
+
const headers = { ...(init.headers || {}) };
|
|
213
|
+
const hasAuth = Object.keys(headers).some((k) => k.toLowerCase() === "authorization");
|
|
214
|
+
let method = init.method || "GET";
|
|
215
|
+
let body = init.body;
|
|
216
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
217
|
+
let res;
|
|
218
|
+
try {
|
|
219
|
+
res = await f(url.toString(), { ...init, method, body, headers, redirect: "manual", signal: ctrl.signal });
|
|
220
|
+
} catch (err) {
|
|
221
|
+
if (ctrl.signal.aborted) {
|
|
222
|
+
throw new PluginError(`Request to ${url.host} timed out after ${timeoutMs} ms`, { code: "timeout" });
|
|
223
|
+
}
|
|
224
|
+
throw new PluginError(`Could not reach ${url.host}: ${/** @type {any} */ (err)?.message || err}`, {
|
|
225
|
+
code: "network",
|
|
226
|
+
cause: err,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
const loc = res.headers.get("location");
|
|
230
|
+
if (res.status >= 300 && res.status < 400 && loc) {
|
|
231
|
+
const next = new URL(loc, url);
|
|
232
|
+
try {
|
|
233
|
+
await res.body?.cancel();
|
|
234
|
+
} catch {}
|
|
235
|
+
if (hasAuth && next.origin !== origin0) {
|
|
236
|
+
throw new PluginError("Plugin redirected an authenticated request to another host", {
|
|
237
|
+
code: "cross_origin_redirect",
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
url = await assertSafeUrl(next, opts);
|
|
241
|
+
if (res.status === 303) {
|
|
242
|
+
method = "GET";
|
|
243
|
+
body = undefined;
|
|
244
|
+
}
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
return { res, url, done };
|
|
248
|
+
}
|
|
249
|
+
throw new PluginError("Too many redirects", { code: "redirect_loop" });
|
|
250
|
+
} catch (err) {
|
|
251
|
+
done();
|
|
252
|
+
throw err;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Fetch and parse JSON. With `soft`, returns null instead of throwing on a
|
|
258
|
+
* non-2xx status or a body that is not a JSON object (an HTML 200 included).
|
|
259
|
+
* @param {string | URL} url
|
|
260
|
+
* @param {RequestInit & { headers?: Record<string,string> }} init
|
|
261
|
+
* @param {import("../index.js").NetOptions & { soft?: boolean }} [opts]
|
|
262
|
+
* @returns {Promise<any>}
|
|
263
|
+
*/
|
|
264
|
+
export async function fetchJson(url, init = {}, opts = {}) {
|
|
265
|
+
let r;
|
|
266
|
+
try {
|
|
267
|
+
r = await safeFetch(url, init, opts);
|
|
268
|
+
} catch (err) {
|
|
269
|
+
if (opts.soft && /** @type {any} */ (err)?.code !== "private_address" && /** @type {any} */ (err)?.code !== "insecure_url") {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
const { res, done } = r;
|
|
275
|
+
try {
|
|
276
|
+
const text = await readCapped(res, opts.maxBytes ?? 1_000_000);
|
|
277
|
+
let json = null;
|
|
278
|
+
if (/^\s*[{[]/.test(text)) {
|
|
279
|
+
try {
|
|
280
|
+
json = JSON.parse(text);
|
|
281
|
+
} catch {
|
|
282
|
+
json = null;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (!res.ok || json === null || typeof json !== "object" || Array.isArray(json)) {
|
|
286
|
+
if (opts.soft) return null;
|
|
287
|
+
const msg =
|
|
288
|
+
(json && (json.error_description || json.error?.message || json.error || json.message)) ||
|
|
289
|
+
`HTTP ${res.status}`;
|
|
290
|
+
throw new PluginError(`${new URL(String(url)).host}: ${typeof msg === "string" ? msg : JSON.stringify(msg)}`, {
|
|
291
|
+
code: "http_error",
|
|
292
|
+
status: res.status,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return json;
|
|
296
|
+
} finally {
|
|
297
|
+
done();
|
|
298
|
+
}
|
|
299
|
+
}
|
package/src/oauth.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// OAuth 2.1 for remote MCP servers: dynamic client registration (RFC 7591, public
|
|
2
|
+
// client), PKCE S256, state, code exchange and refresh. No forms for the person:
|
|
3
|
+
// the client registers itself and the person only sees the provider's sign-in page.
|
|
4
|
+
|
|
5
|
+
import { fetchJson, PluginError } from "./net.js";
|
|
6
|
+
|
|
7
|
+
/** @param {Uint8Array} bytes */
|
|
8
|
+
export function base64url(bytes) {
|
|
9
|
+
let s = "";
|
|
10
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
11
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param {number} n */
|
|
15
|
+
export function randomToken(n = 32) {
|
|
16
|
+
const b = new Uint8Array(n);
|
|
17
|
+
crypto.getRandomValues(b);
|
|
18
|
+
return base64url(b);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param {string} verifier */
|
|
22
|
+
export async function pkceChallenge(verifier) {
|
|
23
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
24
|
+
return base64url(new Uint8Array(digest));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** In-memory PluginStore (tests, CLIs that keep their own file). */
|
|
28
|
+
export function memoryStore() {
|
|
29
|
+
const clients = new Map();
|
|
30
|
+
const tokens = new Map();
|
|
31
|
+
return {
|
|
32
|
+
/** @param {string} key */
|
|
33
|
+
getClient: async (key) => clients.get(key) || null,
|
|
34
|
+
/** @param {string} key @param {any} c */
|
|
35
|
+
setClient: async (key, c) => void clients.set(key, c),
|
|
36
|
+
/** @param {string} key */
|
|
37
|
+
deleteClient: async (key) => void clients.delete(key),
|
|
38
|
+
/** @param {string} slug */
|
|
39
|
+
getTokens: async (slug) => tokens.get(slug) || null,
|
|
40
|
+
/** @param {string} slug @param {any} t */
|
|
41
|
+
setTokens: async (slug, t) => void tokens.set(slug, t),
|
|
42
|
+
/** @param {string} slug */
|
|
43
|
+
deleteTokens: async (slug) => void tokens.delete(slug),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {string} issuer @param {string} redirectUri */
|
|
48
|
+
export function clientKey(issuer, redirectUri) {
|
|
49
|
+
return `${issuer}|${redirectUri}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {import("../index.js").DiscoveredServer} server
|
|
54
|
+
*/
|
|
55
|
+
function requireAuth(server) {
|
|
56
|
+
if (!server || typeof server.auth !== "object" || !server.auth) {
|
|
57
|
+
throw new PluginError("This plugin does not use sign-in", { code: "no_auth" });
|
|
58
|
+
}
|
|
59
|
+
return server.auth;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Register (or reuse) a public client and build the authorize URL.
|
|
64
|
+
* @param {import("../index.js").StartAuthOptions} opts
|
|
65
|
+
* @returns {Promise<{ authorizeUrl: string, pending: import("../index.js").PendingAuth }>}
|
|
66
|
+
*/
|
|
67
|
+
export async function startAuth(opts) {
|
|
68
|
+
const { server, redirectUri, clientName = "Chat plugins", store } = opts;
|
|
69
|
+
const auth = requireAuth(server);
|
|
70
|
+
if (!redirectUri) throw new PluginError("redirectUri is required", { code: "bad_request" });
|
|
71
|
+
if (!store || typeof store.getClient !== "function" || typeof store.setClient !== "function") {
|
|
72
|
+
throw new PluginError("store with getClient/setClient is required", { code: "bad_request" });
|
|
73
|
+
}
|
|
74
|
+
const key = clientKey(auth.issuer, redirectUri);
|
|
75
|
+
/** @type {any} */
|
|
76
|
+
let client = await store.getClient(key);
|
|
77
|
+
if (!client?.client_id) {
|
|
78
|
+
if (opts.clientId) {
|
|
79
|
+
client = { client_id: opts.clientId };
|
|
80
|
+
} else if (auth.registration_endpoint) {
|
|
81
|
+
const body = {
|
|
82
|
+
client_name: clientName,
|
|
83
|
+
redirect_uris: [redirectUri],
|
|
84
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
85
|
+
response_types: ["code"],
|
|
86
|
+
token_endpoint_auth_method: "none",
|
|
87
|
+
...(opts.clientUri ? { client_uri: opts.clientUri } : {}),
|
|
88
|
+
...(opts.logoUri ? { logo_uri: opts.logoUri } : {}),
|
|
89
|
+
...(auth.scopes?.length ? { scope: auth.scopes.join(" ") } : {}),
|
|
90
|
+
};
|
|
91
|
+
const reg = await fetchJson(
|
|
92
|
+
auth.registration_endpoint,
|
|
93
|
+
{ method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body) },
|
|
94
|
+
{ timeoutMs: 15_000, ...opts },
|
|
95
|
+
);
|
|
96
|
+
if (!reg.client_id) throw new PluginError("Client registration returned no client_id", { code: "registration_failed" });
|
|
97
|
+
client = {
|
|
98
|
+
client_id: String(reg.client_id),
|
|
99
|
+
...(reg.client_secret ? { client_secret: String(reg.client_secret) } : {}),
|
|
100
|
+
registered_at: Date.now(),
|
|
101
|
+
};
|
|
102
|
+
} else {
|
|
103
|
+
throw new PluginError(
|
|
104
|
+
"This plugin's sign-in server does not allow automatic registration (no registration_endpoint)",
|
|
105
|
+
{ code: "no_registration" },
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
await store.setClient(key, client);
|
|
109
|
+
}
|
|
110
|
+
const verifier = randomToken(48);
|
|
111
|
+
const state = randomToken(24);
|
|
112
|
+
const scopes = opts.scopes || auth.scopes;
|
|
113
|
+
const u = new URL(auth.authorization_endpoint);
|
|
114
|
+
u.searchParams.set("response_type", "code");
|
|
115
|
+
u.searchParams.set("client_id", client.client_id);
|
|
116
|
+
u.searchParams.set("redirect_uri", redirectUri);
|
|
117
|
+
u.searchParams.set("code_challenge", await pkceChallenge(verifier));
|
|
118
|
+
u.searchParams.set("code_challenge_method", "S256");
|
|
119
|
+
u.searchParams.set("state", state);
|
|
120
|
+
if (scopes?.length) u.searchParams.set("scope", scopes.join(" "));
|
|
121
|
+
if (auth.resource) u.searchParams.set("resource", auth.resource);
|
|
122
|
+
return {
|
|
123
|
+
authorizeUrl: u.toString(),
|
|
124
|
+
pending: {
|
|
125
|
+
v: 1,
|
|
126
|
+
state,
|
|
127
|
+
verifier,
|
|
128
|
+
client_id: client.client_id,
|
|
129
|
+
...(client.client_secret ? { client_secret: client.client_secret } : {}),
|
|
130
|
+
url: server.url,
|
|
131
|
+
issuer: auth.issuer,
|
|
132
|
+
token_endpoint: auth.token_endpoint,
|
|
133
|
+
resource: auth.resource,
|
|
134
|
+
redirect_uri: redirectUri,
|
|
135
|
+
created_at: Date.now(),
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** @param {string} a @param {string} b */
|
|
141
|
+
function safeEqual(a, b) {
|
|
142
|
+
if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
|
|
143
|
+
let r = 0;
|
|
144
|
+
for (let i = 0; i < a.length; i++) r |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
145
|
+
return r === 0;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* @param {any} json
|
|
150
|
+
* @param {{ client_id: string, client_secret?: string, token_endpoint: string, resource?: string }} ctx
|
|
151
|
+
* @param {string} [previousRefresh]
|
|
152
|
+
* @returns {import("../index.js").Tokens}
|
|
153
|
+
*/
|
|
154
|
+
function toTokens(json, ctx, previousRefresh) {
|
|
155
|
+
if (!json || typeof json.access_token !== "string" || !json.access_token) {
|
|
156
|
+
throw new PluginError("Sign-in server returned no access_token", { code: "token_failed" });
|
|
157
|
+
}
|
|
158
|
+
const expiresIn = Number(json.expires_in);
|
|
159
|
+
return {
|
|
160
|
+
access_token: json.access_token,
|
|
161
|
+
...(json.refresh_token || previousRefresh ? { refresh_token: json.refresh_token || previousRefresh } : {}),
|
|
162
|
+
...(Number.isFinite(expiresIn) && expiresIn > 0 ? { expires_at: Date.now() + expiresIn * 1000 } : {}),
|
|
163
|
+
token_type: json.token_type || "Bearer",
|
|
164
|
+
...(json.scope ? { scope: String(json.scope) } : {}),
|
|
165
|
+
client_id: ctx.client_id,
|
|
166
|
+
...(ctx.client_secret ? { client_secret: ctx.client_secret } : {}),
|
|
167
|
+
token_endpoint: ctx.token_endpoint,
|
|
168
|
+
...(ctx.resource ? { resource: ctx.resource } : {}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* @param {string} endpoint
|
|
174
|
+
* @param {Record<string,string|undefined>} form
|
|
175
|
+
* @param {import("../index.js").NetOptions} opts
|
|
176
|
+
*/
|
|
177
|
+
async function postForm(endpoint, form, opts) {
|
|
178
|
+
const body = new URLSearchParams();
|
|
179
|
+
for (const [k, v] of Object.entries(form)) if (v !== undefined && v !== "") body.set(k, v);
|
|
180
|
+
try {
|
|
181
|
+
return await fetchJson(
|
|
182
|
+
endpoint,
|
|
183
|
+
{
|
|
184
|
+
method: "POST",
|
|
185
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
186
|
+
body: body.toString(),
|
|
187
|
+
},
|
|
188
|
+
{ timeoutMs: 15_000, ...opts },
|
|
189
|
+
);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
const e = /** @type {any} */ (err);
|
|
192
|
+
throw new PluginError(`Sign-in failed: ${e.message}`, { code: "token_failed", status: e.status, cause: err });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Max age of a pending sign-in. */
|
|
197
|
+
export const PENDING_TTL_MS = 30 * 60 * 1000;
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Exchange the callback code for tokens.
|
|
201
|
+
* @param {import("../index.js").FinishAuthOptions} opts
|
|
202
|
+
* @returns {Promise<import("../index.js").Tokens>}
|
|
203
|
+
*/
|
|
204
|
+
export async function finishAuth(opts) {
|
|
205
|
+
const { pending, code, state } = opts;
|
|
206
|
+
if (!pending || !pending.verifier || !pending.token_endpoint) {
|
|
207
|
+
throw new PluginError("Unknown or expired sign-in", { code: "bad_state" });
|
|
208
|
+
}
|
|
209
|
+
if (!safeEqual(String(state || ""), pending.state)) {
|
|
210
|
+
throw new PluginError("Sign-in state did not match (open the link again)", { code: "bad_state" });
|
|
211
|
+
}
|
|
212
|
+
if (pending.created_at && Date.now() - pending.created_at > PENDING_TTL_MS) {
|
|
213
|
+
throw new PluginError("Sign-in took too long, start again", { code: "expired" });
|
|
214
|
+
}
|
|
215
|
+
if (!code) throw new PluginError("No authorization code in callback", { code: "bad_request" });
|
|
216
|
+
const redirectUri = opts.redirectUri || pending.redirect_uri;
|
|
217
|
+
const json = await postForm(
|
|
218
|
+
pending.token_endpoint,
|
|
219
|
+
{
|
|
220
|
+
grant_type: "authorization_code",
|
|
221
|
+
code,
|
|
222
|
+
redirect_uri: redirectUri,
|
|
223
|
+
client_id: pending.client_id,
|
|
224
|
+
client_secret: pending.client_secret,
|
|
225
|
+
code_verifier: pending.verifier,
|
|
226
|
+
resource: pending.resource,
|
|
227
|
+
},
|
|
228
|
+
opts,
|
|
229
|
+
);
|
|
230
|
+
return toTokens(json, pending);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* True when the access token is expired or about to be.
|
|
235
|
+
* @param {import("../index.js").Tokens | null | undefined} tokens
|
|
236
|
+
* @param {number} [skewMs]
|
|
237
|
+
*/
|
|
238
|
+
export function isExpired(tokens, skewMs = 60_000) {
|
|
239
|
+
return !!tokens?.expires_at && Date.now() + skewMs >= tokens.expires_at;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Use the refresh token. Keeps the old refresh token when the server does not rotate it.
|
|
244
|
+
* @param {import("../index.js").Tokens} tokens
|
|
245
|
+
* @param {import("../index.js").NetOptions} [opts]
|
|
246
|
+
* @returns {Promise<import("../index.js").Tokens>}
|
|
247
|
+
*/
|
|
248
|
+
export async function refresh(tokens, opts = {}) {
|
|
249
|
+
if (!tokens?.refresh_token) throw new PluginError("No refresh token; sign in again", { code: "reauth_required" });
|
|
250
|
+
if (!tokens.token_endpoint || !tokens.client_id) {
|
|
251
|
+
throw new PluginError("Token record lacks token_endpoint/client_id; sign in again", { code: "reauth_required" });
|
|
252
|
+
}
|
|
253
|
+
const json = await postForm(
|
|
254
|
+
tokens.token_endpoint,
|
|
255
|
+
{
|
|
256
|
+
grant_type: "refresh_token",
|
|
257
|
+
refresh_token: tokens.refresh_token,
|
|
258
|
+
client_id: tokens.client_id,
|
|
259
|
+
client_secret: tokens.client_secret,
|
|
260
|
+
resource: tokens.resource,
|
|
261
|
+
},
|
|
262
|
+
opts,
|
|
263
|
+
);
|
|
264
|
+
return toTokens(
|
|
265
|
+
json,
|
|
266
|
+
{ client_id: tokens.client_id, client_secret: tokens.client_secret, token_endpoint: tokens.token_endpoint, resource: tokens.resource },
|
|
267
|
+
tokens.refresh_token,
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Refresh when expired. Returns the (possibly new) tokens and whether they changed,
|
|
273
|
+
* so the caller can persist them.
|
|
274
|
+
* @param {import("../index.js").Tokens} tokens
|
|
275
|
+
* @param {import("../index.js").NetOptions} [opts]
|
|
276
|
+
*/
|
|
277
|
+
export async function ensureFresh(tokens, opts = {}) {
|
|
278
|
+
if (!isExpired(tokens) || !tokens.refresh_token) return { tokens, refreshed: false };
|
|
279
|
+
return { tokens: await refresh(tokens, opts), refreshed: true };
|
|
280
|
+
}
|
package/src/seal.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// AES-256-GCM sealing for tokens at rest. WebCrypto only, so it runs on Node 20+,
|
|
2
|
+
// Bun, Deno, Workers and browsers.
|
|
3
|
+
//
|
|
4
|
+
// Format: "v1.<iv base64url>.<ciphertext+tag base64url>"
|
|
5
|
+
// Key: 32 raw bytes, a 64-char hex string, a base64/base64url string of 32 bytes,
|
|
6
|
+
// or any other string (hashed with SHA-256; use a long random secret).
|
|
7
|
+
|
|
8
|
+
import { base64url } from "./oauth.js";
|
|
9
|
+
|
|
10
|
+
/** @param {string} s */
|
|
11
|
+
function fromBase64url(s) {
|
|
12
|
+
const b64 = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
|
|
13
|
+
const bin = atob(b64);
|
|
14
|
+
const out = new Uint8Array(bin.length);
|
|
15
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param {string | Uint8Array} key */
|
|
20
|
+
async function importKey(key) {
|
|
21
|
+
let raw;
|
|
22
|
+
if (key instanceof Uint8Array) raw = key;
|
|
23
|
+
else if (typeof key === "string" && /^[0-9a-f]{64}$/i.test(key)) {
|
|
24
|
+
raw = new Uint8Array(32);
|
|
25
|
+
for (let i = 0; i < 32; i++) raw[i] = parseInt(key.slice(i * 2, i * 2 + 2), 16);
|
|
26
|
+
} else if (typeof key === "string" && /^[A-Za-z0-9+/_-]{43}=?$/.test(key)) {
|
|
27
|
+
raw = fromBase64url(key.replace(/=$/, ""));
|
|
28
|
+
} else if (typeof key === "string" && key.length >= 16) {
|
|
29
|
+
raw = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)));
|
|
30
|
+
} else {
|
|
31
|
+
throw new Error("sealToken: key must be 32 bytes or a secret string of at least 16 characters");
|
|
32
|
+
}
|
|
33
|
+
if (raw.length !== 32) throw new Error("sealToken: key must be 32 bytes");
|
|
34
|
+
return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Encrypt a token (string or JSON-able object).
|
|
39
|
+
* @param {string | object} secret
|
|
40
|
+
* @param {string | Uint8Array} key
|
|
41
|
+
* @returns {Promise<string>}
|
|
42
|
+
*/
|
|
43
|
+
export async function sealToken(secret, key) {
|
|
44
|
+
const plain = typeof secret === "string" ? `s:${secret}` : `j:${JSON.stringify(secret)}`;
|
|
45
|
+
const iv = new Uint8Array(12);
|
|
46
|
+
crypto.getRandomValues(iv);
|
|
47
|
+
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await importKey(key), new TextEncoder().encode(plain));
|
|
48
|
+
return `v1.${base64url(iv)}.${base64url(new Uint8Array(ct))}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Decrypt a value from sealToken. Throws when the key is wrong or the value was altered.
|
|
53
|
+
* @param {string} sealed
|
|
54
|
+
* @param {string | Uint8Array} key
|
|
55
|
+
* @returns {Promise<any>}
|
|
56
|
+
*/
|
|
57
|
+
export async function openToken(sealed, key) {
|
|
58
|
+
const parts = String(sealed || "").split(".");
|
|
59
|
+
if (parts.length !== 3 || parts[0] !== "v1") throw new Error("openToken: not a sealed value");
|
|
60
|
+
const pt = await crypto.subtle.decrypt(
|
|
61
|
+
{ name: "AES-GCM", iv: fromBase64url(parts[1]) },
|
|
62
|
+
await importKey(key),
|
|
63
|
+
fromBase64url(parts[2]),
|
|
64
|
+
);
|
|
65
|
+
const s = new TextDecoder().decode(pt);
|
|
66
|
+
if (s.startsWith("s:")) return s.slice(2);
|
|
67
|
+
if (s.startsWith("j:")) return JSON.parse(s.slice(2));
|
|
68
|
+
throw new Error("openToken: unknown payload");
|
|
69
|
+
}
|