bearminion 1.15.0 → 1.16.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.
@@ -0,0 +1,343 @@
1
+ import { r as isSameOriginRequest } from "./request-guards-BcSUj8Gc.js";
2
+ //#region src/hosted-auth.ts
3
+ const AUTH_PREFIX = "/__bearminion/auth";
4
+ const encoder = new TextEncoder();
5
+ const decoder = new TextDecoder();
6
+ const STATE_MINUTES = 10;
7
+ const REFRESH_MARGIN_MS = 6e4;
8
+ function toBase64Url(bytes) {
9
+ let text = "";
10
+ for (const byte of bytes) text += String.fromCharCode(byte);
11
+ return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12
+ }
13
+ function fromBase64Url(text) {
14
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
15
+ const bytes = new Uint8Array(binary.length);
16
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
17
+ return bytes;
18
+ }
19
+ function randomToken(size) {
20
+ return toBase64Url(crypto.getRandomValues(new Uint8Array(size)));
21
+ }
22
+ async function deriveKey(secret) {
23
+ const raw = await crypto.subtle.digest("SHA-256", encoder.encode(`bearminion-hosted-auth:${secret}`));
24
+ return crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
25
+ }
26
+ /** Encrypts and authenticates `value`. `purpose` is bound in, so a login-state cookie can never pass as a session. */
27
+ async function seal(key, purpose, value) {
28
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
29
+ const data = encoder.encode(JSON.stringify(value));
30
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({
31
+ name: "AES-GCM",
32
+ iv,
33
+ additionalData: encoder.encode(purpose)
34
+ }, key, data));
35
+ const out = new Uint8Array(iv.length + sealed.length);
36
+ out.set(iv);
37
+ out.set(sealed, iv.length);
38
+ return toBase64Url(out);
39
+ }
40
+ async function open(key, purpose, text) {
41
+ if (!text) return null;
42
+ try {
43
+ const bytes = fromBase64Url(text);
44
+ if (bytes.length < 13) return null;
45
+ const plain = await crypto.subtle.decrypt({
46
+ name: "AES-GCM",
47
+ iv: bytes.slice(0, 12),
48
+ additionalData: encoder.encode(purpose)
49
+ }, key, bytes.slice(12));
50
+ return JSON.parse(decoder.decode(plain));
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ function readCookies(header) {
56
+ const cookies = /* @__PURE__ */ new Map();
57
+ for (const part of (header ?? "").split(";")) {
58
+ const at = part.indexOf("=");
59
+ if (at > 0) cookies.set(part.slice(0, at).trim(), part.slice(at + 1).trim());
60
+ }
61
+ return cookies;
62
+ }
63
+ function escapeHtml(text) {
64
+ return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
65
+ }
66
+ /** Only a path on this site: no other origin, no protocol-relative `//host`, no backslash tricks. */
67
+ function safeReturnTo(value) {
68
+ if (value === null || !/^\/(?![/\\])[^\s\\]*$/.test(value)) return "/";
69
+ return value;
70
+ }
71
+ function page(status, title, message, extra) {
72
+ const body = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title><body style="font:16px system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1 style="font-size:1.25rem">${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`;
73
+ return new Response(body, {
74
+ status,
75
+ headers: {
76
+ "content-type": "text/html; charset=utf-8",
77
+ "cache-control": "no-store",
78
+ "x-content-type-options": "nosniff",
79
+ ...extra
80
+ }
81
+ });
82
+ }
83
+ function jsonResponse(status, body, headers = {}) {
84
+ return new Response(JSON.stringify(body), {
85
+ status,
86
+ headers: {
87
+ "content-type": "application/json; charset=utf-8",
88
+ "cache-control": "no-store",
89
+ "x-content-type-options": "nosniff",
90
+ ...headers
91
+ }
92
+ });
93
+ }
94
+ function createHostedAuth(options) {
95
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(options.repo)) throw new Error(`createHostedAuth(): repo must be "owner/name", got "${options.repo}".`);
96
+ if (!options.clientId || !options.clientSecret) throw new Error("createHostedAuth(): clientId and clientSecret are required.");
97
+ if (typeof options.secret !== "string" || options.secret.length < 32) throw new Error("createHostedAuth(): secret must be at least 32 characters. Generate one with `openssl rand -base64 32`.");
98
+ const githubUrl = (options.githubUrl ?? "https://github.com").replace(/\/+$/, "");
99
+ const apiUrl = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
100
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
101
+ const now = options.now ?? Date.now;
102
+ const sessionMs = (options.sessionDays ?? 7) * 864e5;
103
+ const keyPromise = deriveKey(options.secret);
104
+ const originOf = (request) => (options.origin ?? new URL(request.url).origin).replace(/\/+$/, "");
105
+ const secure = (request) => originOf(request).startsWith("https://");
106
+ const names = (request) => secure(request) ? {
107
+ session: "__Host-bm-session",
108
+ state: "__Host-bm-state"
109
+ } : {
110
+ session: "bm-session",
111
+ state: "bm-state"
112
+ };
113
+ function cookie(request, name, value, maxAgeSeconds) {
114
+ return `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${secure(request) ? "; Secure" : ""}`;
115
+ }
116
+ async function tokenRequest(body) {
117
+ try {
118
+ const response = await doFetch(`${githubUrl}/login/oauth/access_token`, {
119
+ method: "POST",
120
+ headers: {
121
+ accept: "application/json",
122
+ "content-type": "application/json",
123
+ "user-agent": "bearminion"
124
+ },
125
+ body: JSON.stringify({
126
+ client_id: options.clientId,
127
+ client_secret: options.clientSecret,
128
+ ...body
129
+ })
130
+ });
131
+ const reply = await response.json();
132
+ if (!response.ok || reply.error || typeof reply.access_token !== "string") return null;
133
+ return reply;
134
+ } catch {
135
+ return null;
136
+ }
137
+ }
138
+ async function githubGet(token, route) {
139
+ try {
140
+ return await doFetch(`${apiUrl}${route}`, { headers: {
141
+ accept: "application/vnd.github+json",
142
+ authorization: `Bearer ${token}`,
143
+ "x-github-api-version": "2022-11-28",
144
+ "user-agent": "bearminion"
145
+ } });
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ async function hasPushAccess(token) {
151
+ const response = await githubGet(token, `/repos/${options.repo}`);
152
+ if (!response?.ok) return false;
153
+ return (await response.json()).permissions?.push === true;
154
+ }
155
+ function sessionFrom(reply, who, issuedAt) {
156
+ const at = now();
157
+ return {
158
+ login: who.login,
159
+ id: who.id,
160
+ token: reply.access_token,
161
+ expiresAt: at + (reply.expires_in ?? 28800) * 1e3,
162
+ ...reply.refresh_token ? { refreshToken: reply.refresh_token } : {},
163
+ ...reply.refresh_token ? { refreshExpiresAt: at + (reply.refresh_token_expires_in ?? 15552e3) * 1e3 } : {},
164
+ issuedAt
165
+ };
166
+ }
167
+ async function sessionCookie(request, session) {
168
+ const maxAge = Math.max(1, Math.floor((session.issuedAt + sessionMs - now()) / 1e3));
169
+ return cookie(request, names(request).session, await seal(await keyPromise, "session", session), maxAge);
170
+ }
171
+ async function authenticate(request) {
172
+ const stored = await open(await keyPromise, "session", readCookies(request.headers.get("cookie")).get(names(request).session));
173
+ if (!stored || typeof stored.token !== "string" || typeof stored.login !== "string") return null;
174
+ const at = now();
175
+ if (at >= stored.issuedAt + sessionMs) return null;
176
+ if (at < stored.expiresAt - REFRESH_MARGIN_MS) return { session: stored };
177
+ if (!stored.refreshToken || !stored.refreshExpiresAt || at >= stored.refreshExpiresAt) return null;
178
+ const reply = await tokenRequest({
179
+ grant_type: "refresh_token",
180
+ refresh_token: stored.refreshToken
181
+ });
182
+ if (!reply || !await hasPushAccess(reply.access_token)) return null;
183
+ const session = sessionFrom(reply, stored, stored.issuedAt);
184
+ return {
185
+ session,
186
+ cookie: await sessionCookie(request, session)
187
+ };
188
+ }
189
+ async function login(request) {
190
+ const url = new URL(request.url);
191
+ const state = randomToken(16);
192
+ const verifier = randomToken(32);
193
+ const challenge = toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier))));
194
+ const returnTo = safeReturnTo(url.searchParams.get("returnTo"));
195
+ const sealed = await seal(await keyPromise, "state", {
196
+ state,
197
+ verifier,
198
+ returnTo,
199
+ expires: now() + STATE_MINUTES * 6e4
200
+ });
201
+ const authorize = new URL(`${githubUrl}/login/oauth/authorize`);
202
+ authorize.searchParams.set("client_id", options.clientId);
203
+ authorize.searchParams.set("redirect_uri", `${originOf(request)}${AUTH_PREFIX}/callback`);
204
+ authorize.searchParams.set("state", state);
205
+ authorize.searchParams.set("code_challenge", challenge);
206
+ authorize.searchParams.set("code_challenge_method", "S256");
207
+ return new Response(null, {
208
+ status: 302,
209
+ headers: {
210
+ location: authorize.href,
211
+ "cache-control": "no-store",
212
+ "set-cookie": cookie(request, names(request).state, sealed, 600)
213
+ }
214
+ });
215
+ }
216
+ async function callback(request) {
217
+ const url = new URL(request.url);
218
+ const clearState = cookie(request, names(request).state, "", 0);
219
+ const saved = await open(await keyPromise, "state", readCookies(request.headers.get("cookie")).get(names(request).state));
220
+ const code = url.searchParams.get("code");
221
+ if (!saved || saved.expires < now() || !code || url.searchParams.get("state") !== saved.state) return page(400, "Sign-in could not be completed", "The sign-in link expired or was not started here. Start again.", { "set-cookie": clearState });
222
+ const reply = await tokenRequest({
223
+ code,
224
+ redirect_uri: `${originOf(request)}${AUTH_PREFIX}/callback`,
225
+ code_verifier: saved.verifier
226
+ });
227
+ if (!reply) return page(502, "Sign-in failed", "GitHub did not accept the sign-in. Start again.", { "set-cookie": clearState });
228
+ const userReply = await githubGet(reply.access_token, "/user");
229
+ if (!userReply?.ok) return page(502, "Sign-in failed", "GitHub did not say who you are. Start again.", { "set-cookie": clearState });
230
+ const who = await userReply.json();
231
+ if (typeof who.login !== "string" || typeof who.id !== "number") return page(502, "Sign-in failed", "GitHub sent an unexpected answer. Start again.", { "set-cookie": clearState });
232
+ if (!await hasPushAccess(reply.access_token)) return page(403, "No access", `${who.login} cannot write to ${options.repo}. Ask the owner for write access, and check that the GitHub App is installed on the repository.`, { "set-cookie": clearState });
233
+ const headers = new Headers({
234
+ location: saved.returnTo,
235
+ "cache-control": "no-store"
236
+ });
237
+ headers.append("set-cookie", clearState);
238
+ headers.append("set-cookie", await sessionCookie(request, sessionFrom(reply, {
239
+ login: who.login,
240
+ id: who.id
241
+ }, now())));
242
+ return new Response(null, {
243
+ status: 302,
244
+ headers
245
+ });
246
+ }
247
+ async function handle(request) {
248
+ const pathname = new URL(request.url).pathname.replace(/\/+$/, "");
249
+ if (pathname !== "/__bearminion/auth" && !pathname.startsWith(`/__bearminion/auth/`)) return null;
250
+ const method = request.method.toUpperCase();
251
+ const route = pathname.slice(18);
252
+ if (route === "/login") return method === "GET" ? login(request) : jsonResponse(405, {
253
+ error: "method_not_allowed",
254
+ message: "Allowed: GET."
255
+ }, { allow: "GET" });
256
+ if (route === "/callback") return method === "GET" ? callback(request) : jsonResponse(405, {
257
+ error: "method_not_allowed",
258
+ message: "Allowed: GET."
259
+ }, { allow: "GET" });
260
+ if (route === "/session") {
261
+ if (method !== "GET") return jsonResponse(405, {
262
+ error: "method_not_allowed",
263
+ message: "Allowed: GET."
264
+ }, { allow: "GET" });
265
+ const found = await authenticate(request);
266
+ if (!found) return jsonResponse(401, {
267
+ error: "unauthenticated",
268
+ login: `${AUTH_PREFIX}/login`
269
+ });
270
+ return jsonResponse(200, {
271
+ login: found.session.login,
272
+ id: found.session.id
273
+ }, found.cookie ? { "set-cookie": found.cookie } : {});
274
+ }
275
+ if (route === "/logout") {
276
+ if (method !== "POST") return jsonResponse(405, {
277
+ error: "method_not_allowed",
278
+ message: "Allowed: POST."
279
+ }, { allow: "POST" });
280
+ if (!isSameOriginRequest(request.headers, request.url)) return jsonResponse(403, {
281
+ error: "forbidden",
282
+ message: "Cross-site request refused."
283
+ });
284
+ return new Response(null, {
285
+ status: 204,
286
+ headers: {
287
+ "set-cookie": cookie(request, names(request).session, "", 0),
288
+ "cache-control": "no-store"
289
+ }
290
+ });
291
+ }
292
+ return jsonResponse(404, {
293
+ error: "not_found",
294
+ message: "Unknown sign-in route."
295
+ });
296
+ }
297
+ return {
298
+ handle,
299
+ authenticate
300
+ };
301
+ }
302
+ //#endregion
303
+ //#region src/hosted-middleware.ts
304
+ function isPageLoad(request) {
305
+ if (request.method !== "GET" && request.method !== "HEAD") return false;
306
+ const fetchDest = request.headers.get("sec-fetch-dest");
307
+ if (fetchDest) return fetchDest === "document" || fetchDest === "iframe";
308
+ return (request.headers.get("accept") ?? "").includes("text/html");
309
+ }
310
+ function redirectToSignIn(request) {
311
+ const url = new URL(request.url);
312
+ const returnTo = `${url.pathname}${url.search}`;
313
+ return new Response(null, {
314
+ status: 302,
315
+ headers: {
316
+ location: `${AUTH_PREFIX}/login?returnTo=${encodeURIComponent(returnTo)}`,
317
+ "cache-control": "no-store"
318
+ }
319
+ });
320
+ }
321
+ function createHostedMiddleware(editor, options = {}) {
322
+ const required = options.signIn !== "optional";
323
+ return async ({ request, locals }, next) => {
324
+ const handled = await editor.handle(request);
325
+ if (handled) return handled;
326
+ const scope = await editor.scope(request);
327
+ if (!scope) {
328
+ if (!required) return next();
329
+ if (isPageLoad(request)) return redirectToSignIn(request);
330
+ return new Response("Sign in to continue.", {
331
+ status: 401,
332
+ headers: {
333
+ "cache-control": "no-store",
334
+ "content-type": "text/plain; charset=utf-8"
335
+ }
336
+ });
337
+ }
338
+ locals.bearminion = scope;
339
+ return editor.inject(request, await next());
340
+ };
341
+ }
342
+ //#endregion
343
+ export { AUTH_PREFIX as n, createHostedAuth as r, createHostedMiddleware as t };
@@ -0,0 +1,2 @@
1
+ /** The editor overlay as one self-contained browser script (an ES module that mounts itself). */
2
+ export declare const overlaySource: string