editlet 0.0.0-stage → 0.1.0-alpha.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 +21 -0
- package/README.md +113 -2
- package/dist/admin/config.d.ts +22 -0
- package/dist/admin/config.js +75 -0
- package/dist/admin/dist/assets/RichEditor-BlaCRrEX.css +1 -0
- package/dist/admin/dist/assets/RichEditor-IZKdt6MK.js +42 -0
- package/dist/admin/dist/assets/blank-line-CbGzlqBI.js +1 -0
- package/dist/admin/dist/assets/channel-CljeMIwA.js +1 -0
- package/dist/admin/dist/assets/db-CCMyPgQa.js +1 -0
- package/dist/admin/dist/assets/index-CWoJh4H8.js +257 -0
- package/dist/admin/dist/assets/index-DkRMnD_M.css +1 -0
- package/dist/admin/dist/assets/mdast-util-from-markdown-C79q1_d8.js +3 -0
- package/dist/admin/dist/assets/mdast-util-gfm-cM-_xFJE.js +19 -0
- package/dist/admin/dist/assets/micromark-extension-gfm-Wz6-oszS.js +1 -0
- package/dist/admin/dist/assets/micromark-util-classify-character-BgXaGAja.js +1 -0
- package/dist/admin/dist/assets/micromark-util-html-tag-name-B61T18yC.js +1 -0
- package/dist/admin/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/admin/dist/index.html +16 -0
- package/dist/admin/dist/preview.js +1 -0
- package/dist/admin/dist/window.js +1 -0
- package/dist/astro/content.d.ts +21 -0
- package/dist/astro/content.js +235 -0
- package/dist/astro/devServer.js +89 -0
- package/dist/astro/index.d.ts +15 -0
- package/dist/astro/index.js +98 -0
- package/dist/astro/nodeBridge.js +36 -0
- package/dist/astro/shared.js +10 -0
- package/dist/astro/stub/index.html +71 -0
- package/dist/auth/client.d.ts +24 -0
- package/dist/auth/client.js +120 -0
- package/dist/auth/handler.d.ts +16 -0
- package/dist/auth/handler.js +281 -0
- package/dist/auth/protocol.d.ts +25 -0
- package/dist/auth/protocol.js +3 -0
- package/dist/core/assets.d.ts +73 -0
- package/dist/core/assets.js +405 -0
- package/dist/core/devApi.d.ts +28 -0
- package/dist/core/devApi.js +3 -0
- package/dist/core/entryFile.d.ts +13 -0
- package/dist/core/entryFile.js +81 -0
- package/dist/core/fields.js +147 -0
- package/dist/core/generate.d.ts +3 -0
- package/dist/core/generate.js +70 -0
- package/dist/core/gitStyle.d.ts +92 -0
- package/dist/core/gitStyle.js +206 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/issues.d.ts +10 -0
- package/dist/core/issues.js +10 -0
- package/dist/core/paths.d.ts +31 -0
- package/dist/core/paths.js +114 -0
- package/dist/core/project.js +56 -0
- package/dist/core/references.d.ts +68 -0
- package/dist/core/references.js +103 -0
- package/dist/core/rename.d.ts +60 -0
- package/dist/core/rename.js +133 -0
- package/dist/core/schema.d.ts +117 -0
- package/dist/core/schema.js +299 -0
- package/dist/core/sha.d.ts +2 -0
- package/dist/core/sha.js +13 -0
- package/dist/core/source.d.ts +48 -0
- package/dist/core/source.js +57 -0
- package/dist/core/validate.d.ts +22 -0
- package/dist/core/validate.js +148 -0
- package/dist/core/walk.d.ts +23 -0
- package/dist/core/walk.js +94 -0
- package/dist/core/writes.d.ts +37 -0
- package/dist/core/writes.js +166 -0
- package/dist/github/base64.js +16 -0
- package/dist/github/cache.d.ts +34 -0
- package/dist/github/cache.js +126 -0
- package/dist/github/client.d.ts +38 -0
- package/dist/github/client.js +228 -0
- package/dist/github/codeowners.d.ts +23 -0
- package/dist/github/codeowners.js +96 -0
- package/dist/github/commitReader.d.ts +25 -0
- package/dist/github/commitReader.js +38 -0
- package/dist/github/deploy.d.ts +15 -0
- package/dist/github/deploy.js +33 -0
- package/dist/github/index.d.ts +9 -0
- package/dist/github/index.js +8 -0
- package/dist/github/repo.d.ts +95 -0
- package/dist/github/repo.js +375 -0
- package/dist/github/source.d.ts +115 -0
- package/dist/github/source.js +558 -0
- package/dist/loader/index.d.ts +27 -0
- package/dist/loader/index.js +151 -0
- package/dist/loader/protocol.d.ts +95 -0
- package/dist/loader/protocol.js +120 -0
- package/dist/loader/window/geometry.js +9 -0
- package/dist/next/EditletLoader.d.ts +5 -0
- package/dist/next/EditletLoader.js +33 -0
- package/dist/next/assetUrl.d.ts +9 -0
- package/dist/next/assetUrl.js +13 -0
- package/dist/next/buildGuard.js +26 -0
- package/dist/next/config.d.ts +18 -0
- package/dist/next/config.js +255 -0
- package/dist/next/devServer.js +70 -0
- package/dist/next/editletField.d.ts +7 -0
- package/dist/next/editletField.js +7 -0
- package/dist/next/index.d.ts +8 -0
- package/dist/next/index.js +6 -0
- package/dist/next/preview.d.ts +18 -0
- package/dist/next/preview.js +100 -0
- package/dist/next/previewCookie.d.ts +5 -0
- package/dist/next/previewCookie.js +72 -0
- package/dist/next/previewEnv.js +25 -0
- package/dist/next/previewRef.d.ts +8 -0
- package/dist/next/previewRef.js +17 -0
- package/dist/next/publicDir.js +65 -0
- package/dist/next/reader.d.ts +49 -0
- package/dist/next/reader.js +161 -0
- package/dist/next/stub/index.html +56 -0
- package/dist/node/devHandler.d.ts +6 -0
- package/dist/node/devHandler.js +430 -0
- package/dist/node/fs.js +37 -0
- package/dist/node/index.d.ts +3 -0
- package/dist/node/index.js +3 -0
- package/dist/node/project.d.ts +12 -0
- package/dist/node/project.js +43 -0
- package/package.json +187 -4
- package/skills/README.md +84 -0
- package/skills/editlet/SKILL.md +119 -0
- package/skills/editlet/references/content-format.md +191 -0
- package/skills/editlet/references/preview.md +75 -0
- package/skills/editlet/references/publishing.md +137 -0
- package/skills/editlet/references/schema-changes.md +127 -0
- package/skills/editlet/scripts/guard.mjs +1061 -0
- package/skills/editlet/scripts/link.mjs +193 -0
- package/skills/editlet/scripts/refs.mjs +1480 -0
- package/skills/editlet/scripts/schema.mjs +1340 -0
- package/skills/editlet/scripts/style.mjs +657 -0
- package/skills/editlet/scripts/types.mjs +525 -0
- package/skills/editlet/scripts/validate.mjs +724 -0
- package/skills/editlet-migrate/SKILL.md +92 -0
- package/skills/editlet-migrate/references/mapping.md +73 -0
- package/skills/editlet-migrate/references/sources.md +70 -0
- package/skills/editlet-setup/SKILL.md +108 -0
- package/skills/editlet-setup/references/astro.md +83 -0
- package/skills/editlet-setup/references/doctor.md +89 -0
- package/skills/editlet-setup/references/next.md +140 -0
- package/skills/editlet-setup/references/preview.md +54 -0
- package/skills/editlet-setup/references/production.md +153 -0
- package/skills/editlet-setup/references/roles.md +238 -0
- package/skills/editlet-setup/references/skills.md +99 -0
- package/skills/editlet-setup/scripts/doctor.mjs +1378 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import "./protocol.js";
|
|
2
|
+
// auth/client.ts
|
|
3
|
+
var AuthError = class extends Error {
|
|
4
|
+
code;
|
|
5
|
+
description;
|
|
6
|
+
constructor(code, description) {
|
|
7
|
+
super(description ?? code);
|
|
8
|
+
this.name = "AuthError";
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.description = description;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
const POLL_MS = 500;
|
|
14
|
+
const DEFAULT_TIMEOUT_MS = 3e5;
|
|
15
|
+
const REFRESH_SKEW_MS = 3e5;
|
|
16
|
+
function toSession(token, now) {
|
|
17
|
+
if (typeof token !== "object" || token === null || typeof token.access_token !== "string" || !token.access_token) throw new TypeError("invalid token");
|
|
18
|
+
return {
|
|
19
|
+
accessToken: token.access_token,
|
|
20
|
+
tokenType: token.token_type,
|
|
21
|
+
expiresAt: token.expires_in ? now + token.expires_in * 1e3 : null,
|
|
22
|
+
refreshToken: token.refresh_token ?? null,
|
|
23
|
+
refreshTokenExpiresAt: token.refresh_token_expires_in ? now + token.refresh_token_expires_in * 1e3 : null
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function isAuthMessage(data) {
|
|
27
|
+
return typeof data === "object" && data !== null && data.source === "editlet-auth";
|
|
28
|
+
}
|
|
29
|
+
/** `<workerUrl>/<route>`, keeping any path on `workerUrl` (the handler may be mounted under a route). */
|
|
30
|
+
function endpoint(workerUrl, route) {
|
|
31
|
+
const base = new URL(workerUrl);
|
|
32
|
+
base.pathname = `${base.pathname.replace(/\/+$/, "")}/${route}`;
|
|
33
|
+
base.search = "";
|
|
34
|
+
base.hash = "";
|
|
35
|
+
return base;
|
|
36
|
+
}
|
|
37
|
+
/** Call synchronously from a click handler, before any `await`, or popup blockers will stop it. */
|
|
38
|
+
function startLogin(options) {
|
|
39
|
+
let workerOrigin;
|
|
40
|
+
let url;
|
|
41
|
+
try {
|
|
42
|
+
workerOrigin = new URL(options.workerUrl).origin;
|
|
43
|
+
url = endpoint(options.workerUrl, "auth");
|
|
44
|
+
} catch {
|
|
45
|
+
return Promise.reject(new AuthError("invalid_worker_url"));
|
|
46
|
+
}
|
|
47
|
+
url.searchParams.set("origin", location.origin);
|
|
48
|
+
const popup = window.open(url.toString(), "editlet-auth", "popup,width=600,height=720");
|
|
49
|
+
if (!popup) return Promise.reject(new AuthError("popup_blocked"));
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
let settled = false;
|
|
52
|
+
let poll;
|
|
53
|
+
let timer;
|
|
54
|
+
const settle = (finish) => {
|
|
55
|
+
if (settled) return;
|
|
56
|
+
settled = true;
|
|
57
|
+
clearInterval(poll);
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
window.removeEventListener("message", onMessage);
|
|
60
|
+
finish();
|
|
61
|
+
};
|
|
62
|
+
function onMessage(event) {
|
|
63
|
+
if (event.origin !== workerOrigin || event.source !== popup || !isAuthMessage(event.data)) return;
|
|
64
|
+
const message = event.data;
|
|
65
|
+
if (message.ok) {
|
|
66
|
+
let session;
|
|
67
|
+
try {
|
|
68
|
+
session = toSession(message.token, Date.now());
|
|
69
|
+
} catch {
|
|
70
|
+
settle(() => reject(new AuthError("token_request_failed")));
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
settle(() => resolve(session));
|
|
74
|
+
} else settle(() => reject(new AuthError(message.error, message.description)));
|
|
75
|
+
}
|
|
76
|
+
window.addEventListener("message", onMessage);
|
|
77
|
+
poll = setInterval(() => {
|
|
78
|
+
if (popup.closed) settle(() => reject(new AuthError("popup_closed")));
|
|
79
|
+
}, POLL_MS);
|
|
80
|
+
timer = setTimeout(() => settle(() => {
|
|
81
|
+
try {
|
|
82
|
+
popup.close();
|
|
83
|
+
} catch {}
|
|
84
|
+
reject(new AuthError("timeout"));
|
|
85
|
+
}), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** Refresh tokens are single-use: store the returned session, including its new refresh token. */
|
|
89
|
+
async function refresh(options) {
|
|
90
|
+
let refreshUrl;
|
|
91
|
+
try {
|
|
92
|
+
refreshUrl = endpoint(options.workerUrl, "refresh").toString();
|
|
93
|
+
} catch {
|
|
94
|
+
throw new AuthError("invalid_worker_url");
|
|
95
|
+
}
|
|
96
|
+
let response;
|
|
97
|
+
try {
|
|
98
|
+
response = await fetch(refreshUrl, {
|
|
99
|
+
method: "POST",
|
|
100
|
+
headers: { "Content-Type": "application/json" },
|
|
101
|
+
body: JSON.stringify({ refresh_token: options.refreshToken })
|
|
102
|
+
});
|
|
103
|
+
} catch {
|
|
104
|
+
throw new AuthError("network_error");
|
|
105
|
+
}
|
|
106
|
+
let body;
|
|
107
|
+
try {
|
|
108
|
+
body = await response.json();
|
|
109
|
+
} catch {
|
|
110
|
+
throw new AuthError("token_request_failed");
|
|
111
|
+
}
|
|
112
|
+
const data = body ?? {};
|
|
113
|
+
if (typeof data.error === "string") throw new AuthError(data.error, typeof data.error_description === "string" ? data.error_description : void 0);
|
|
114
|
+
if (!response.ok || typeof data.access_token !== "string") throw new AuthError("token_request_failed");
|
|
115
|
+
return toSession(data, Date.now());
|
|
116
|
+
}
|
|
117
|
+
function needsRefresh(session, now = Date.now()) {
|
|
118
|
+
return session.expiresAt !== null && now >= session.expiresAt - REFRESH_SKEW_MS;
|
|
119
|
+
}
|
|
120
|
+
export { AuthError, needsRefresh, refresh, startLogin };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Configuration. Cloudflare passes it as bindings; Node, Bun, Deno and Next pass `process.env`. */
|
|
2
|
+
export interface Env {
|
|
3
|
+
GITHUB_CLIENT_ID?: string;
|
|
4
|
+
GITHUB_CLIENT_SECRET?: string;
|
|
5
|
+
ALLOWED_ORIGINS?: string;
|
|
6
|
+
/** Public URL of this handler, e.g. `https://example.com/api/editlet/oauth`. Needed behind a proxy or under a path. */
|
|
7
|
+
PUBLIC_URL?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Matches a canonical origin against a comma/whitespace-separated allowlist.
|
|
11
|
+
* `*` matches one or more of `[a-z0-9-]` (never a dot) and is valid only in the host. Entries with a path, query,
|
|
12
|
+
* or a wildcard outside the host never match. Fails closed on empty input.
|
|
13
|
+
*/
|
|
14
|
+
export declare function isAllowedOrigin(origin: string, allowed: string | undefined): boolean;
|
|
15
|
+
/** The whole auth service as one Web-standard handler. Runs on any `fetch(Request) → Response` runtime. */
|
|
16
|
+
export declare function handleRequest(request: Request, env: Env): Promise<Response>;
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { AUTH_MESSAGE_SOURCE } from "./protocol.js";
|
|
2
|
+
// auth/handler.ts
|
|
3
|
+
function escapeRegex(value) {
|
|
4
|
+
return value.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
5
|
+
}
|
|
6
|
+
const WILDCARD_PROBE = "wildcard0";
|
|
7
|
+
/**
|
|
8
|
+
* Turns one allowlist entry into a regex, or `null` when the entry is malformed (fails closed).
|
|
9
|
+
* An entry must be a bare origin (`scheme://host[:port]`, trailing `/` tolerated); `*` is only valid in the host.
|
|
10
|
+
*/
|
|
11
|
+
function entryToRegex(raw) {
|
|
12
|
+
const entry = raw.toLowerCase().replace(/\/+$/, "");
|
|
13
|
+
const probe = entry.replace(/\*/g, WILDCARD_PROBE);
|
|
14
|
+
let parsed;
|
|
15
|
+
try {
|
|
16
|
+
parsed = new URL(probe);
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
if (parsed.origin !== probe) return null;
|
|
21
|
+
const count = (text) => text.split(WILDCARD_PROBE).length - 1;
|
|
22
|
+
if (count(probe) !== count(parsed.hostname)) return null;
|
|
23
|
+
return new RegExp(`^${escapeRegex(entry).replace(/\*/g, "[a-z0-9-]+")}$`);
|
|
24
|
+
}
|
|
25
|
+
function allowlistEntries(allowed) {
|
|
26
|
+
return (allowed ?? "").split(/[\s,]+/).filter(Boolean);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Matches a canonical origin against a comma/whitespace-separated allowlist.
|
|
30
|
+
* `*` matches one or more of `[a-z0-9-]` (never a dot) and is valid only in the host. Entries with a path, query,
|
|
31
|
+
* or a wildcard outside the host never match. Fails closed on empty input.
|
|
32
|
+
*/
|
|
33
|
+
function isAllowedOrigin(origin, allowed) {
|
|
34
|
+
return allowlistEntries(allowed).some((entry) => entryToRegex(entry)?.test(origin) ?? false);
|
|
35
|
+
}
|
|
36
|
+
const COOKIE_NAME = "__Host-editlet-oauth";
|
|
37
|
+
const GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
|
|
38
|
+
const GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
|
|
39
|
+
function notFound() {
|
|
40
|
+
return new Response("Not found", {
|
|
41
|
+
status: 404,
|
|
42
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function base64url(bytes) {
|
|
46
|
+
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
47
|
+
}
|
|
48
|
+
function randomToken() {
|
|
49
|
+
return base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
|
|
50
|
+
}
|
|
51
|
+
async function pkceChallenge(verifier) {
|
|
52
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
53
|
+
return base64url(new Uint8Array(digest));
|
|
54
|
+
}
|
|
55
|
+
function isCanonicalAllowedOrigin(origin, env) {
|
|
56
|
+
if (!origin) return false;
|
|
57
|
+
try {
|
|
58
|
+
return new URL(origin).origin === origin && isAllowedOrigin(origin, env.ALLOWED_ORIGINS);
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function readCookie(request) {
|
|
64
|
+
const header = request.headers.get("Cookie") ?? "";
|
|
65
|
+
for (const part of header.split(";")) {
|
|
66
|
+
const index = part.indexOf("=");
|
|
67
|
+
if (index === -1 || part.slice(0, index).trim() !== COOKIE_NAME) continue;
|
|
68
|
+
try {
|
|
69
|
+
const raw = part.slice(index + 1).trim().replace(/-/g, "+").replace(/_/g, "/");
|
|
70
|
+
const data = JSON.parse(atob(raw + "=".repeat((4 - raw.length % 4) % 4)));
|
|
71
|
+
if (typeof data !== "object" || data === null) return null;
|
|
72
|
+
const { state, verifier, origin } = data;
|
|
73
|
+
if (typeof state !== "string" || typeof verifier !== "string" || typeof origin !== "string") return null;
|
|
74
|
+
return {
|
|
75
|
+
state,
|
|
76
|
+
verifier,
|
|
77
|
+
origin
|
|
78
|
+
};
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
function escapeHtml(value) {
|
|
86
|
+
return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
87
|
+
}
|
|
88
|
+
function safeJson(value) {
|
|
89
|
+
return JSON.stringify(value).replace(/</g, "\\u003c");
|
|
90
|
+
}
|
|
91
|
+
function callbackPage(message, target, status, headers = new Headers()) {
|
|
92
|
+
const nonce = base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)));
|
|
93
|
+
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Editlet sign-in</title></head><body><p>${message.ok ? "Signed in. You can close this window." : `Sign-in failed: ${escapeHtml(message.error)}. Close this window and try again.`}</p><script nonce="${nonce}">${`const m = ${safeJson(message)}; const t = ${safeJson(target)}; if (window.opener) { window.opener.postMessage(m, t); window.close(); }`}<\/script></body></html>`;
|
|
94
|
+
headers.set("Content-Type", "text/html; charset=utf-8");
|
|
95
|
+
headers.set("Cache-Control", "no-store");
|
|
96
|
+
headers.set("Referrer-Policy", "no-referrer");
|
|
97
|
+
headers.set("X-Content-Type-Options", "nosniff");
|
|
98
|
+
headers.set("Content-Security-Policy", `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'`);
|
|
99
|
+
return new Response(html, {
|
|
100
|
+
status,
|
|
101
|
+
headers
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
function failure(error, status, description, headers) {
|
|
105
|
+
const message = {
|
|
106
|
+
source: AUTH_MESSAGE_SOURCE,
|
|
107
|
+
ok: false,
|
|
108
|
+
error
|
|
109
|
+
};
|
|
110
|
+
if (description) message.description = description;
|
|
111
|
+
return callbackPage(message, "*", status, headers);
|
|
112
|
+
}
|
|
113
|
+
/** Posts a grant to GitHub's token endpoint. `params` are the grant-specific fields. */
|
|
114
|
+
async function exchangeToken(env, params) {
|
|
115
|
+
let data;
|
|
116
|
+
try {
|
|
117
|
+
data = await (await fetch(GITHUB_TOKEN_URL, {
|
|
118
|
+
method: "POST",
|
|
119
|
+
headers: {
|
|
120
|
+
Accept: "application/json",
|
|
121
|
+
"Content-Type": "application/json"
|
|
122
|
+
},
|
|
123
|
+
body: JSON.stringify({
|
|
124
|
+
client_id: env.GITHUB_CLIENT_ID,
|
|
125
|
+
client_secret: env.GITHUB_CLIENT_SECRET,
|
|
126
|
+
...params
|
|
127
|
+
})
|
|
128
|
+
})).json();
|
|
129
|
+
} catch {
|
|
130
|
+
return { error: "token_request_failed" };
|
|
131
|
+
}
|
|
132
|
+
if (typeof data !== "object" || data === null) return { error: "token_request_failed" };
|
|
133
|
+
const body = data;
|
|
134
|
+
if (typeof body.error === "string") {
|
|
135
|
+
const failed = { error: body.error };
|
|
136
|
+
if (typeof body.error_description === "string") failed.description = body.error_description;
|
|
137
|
+
return failed;
|
|
138
|
+
}
|
|
139
|
+
if (typeof body.access_token !== "string") return { error: "token_request_failed" };
|
|
140
|
+
const token = {
|
|
141
|
+
access_token: body.access_token,
|
|
142
|
+
token_type: typeof body.token_type === "string" ? body.token_type : "bearer",
|
|
143
|
+
scope: typeof body.scope === "string" ? body.scope : ""
|
|
144
|
+
};
|
|
145
|
+
if (typeof body.expires_in === "number") token.expires_in = body.expires_in;
|
|
146
|
+
if (typeof body.refresh_token === "string") token.refresh_token = body.refresh_token;
|
|
147
|
+
if (typeof body.refresh_token_expires_in === "number") token.refresh_token_expires_in = body.refresh_token_expires_in;
|
|
148
|
+
return token;
|
|
149
|
+
}
|
|
150
|
+
async function handleAuth(url, base, env) {
|
|
151
|
+
if (allowlistEntries(env.ALLOWED_ORIGINS).length === 0 || !env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET) return failure("server_misconfigured", 500);
|
|
152
|
+
const origin = url.searchParams.get("origin");
|
|
153
|
+
if (!isCanonicalAllowedOrigin(origin, env)) return failure("origin_not_allowed", 400);
|
|
154
|
+
const state = randomToken();
|
|
155
|
+
const verifier = randomToken();
|
|
156
|
+
const authorize = new URL(GITHUB_AUTHORIZE_URL);
|
|
157
|
+
authorize.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
|
|
158
|
+
authorize.searchParams.set("redirect_uri", `${base}/callback`);
|
|
159
|
+
authorize.searchParams.set("state", state);
|
|
160
|
+
authorize.searchParams.set("code_challenge", await pkceChallenge(verifier));
|
|
161
|
+
authorize.searchParams.set("code_challenge_method", "S256");
|
|
162
|
+
const payload = base64url(new TextEncoder().encode(JSON.stringify({
|
|
163
|
+
state,
|
|
164
|
+
verifier,
|
|
165
|
+
origin
|
|
166
|
+
})));
|
|
167
|
+
return new Response(null, {
|
|
168
|
+
status: 302,
|
|
169
|
+
headers: {
|
|
170
|
+
Location: authorize.toString(),
|
|
171
|
+
"Set-Cookie": `${COOKIE_NAME}=${payload}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`,
|
|
172
|
+
"Cache-Control": "no-store"
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
async function handleCallback(request, url, base, env) {
|
|
177
|
+
const clear = new Headers({ "Set-Cookie": `${COOKIE_NAME}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0` });
|
|
178
|
+
const fail = (error, status = 200, description) => failure(error, status, description, new Headers(clear));
|
|
179
|
+
const githubError = url.searchParams.get("error");
|
|
180
|
+
if (githubError) return fail(/^[a-z0-9_]{1,64}$/.test(githubError) ? githubError : "unknown_error", 200, url.searchParams.get("error_description") ?? void 0);
|
|
181
|
+
const cookie = readCookie(request);
|
|
182
|
+
const code = url.searchParams.get("code");
|
|
183
|
+
const state = url.searchParams.get("state");
|
|
184
|
+
if (!cookie || !code || !state || state !== cookie.state) return fail("state_mismatch");
|
|
185
|
+
if (!isCanonicalAllowedOrigin(cookie.origin, env)) return fail("origin_not_allowed");
|
|
186
|
+
if (!env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET) return fail("server_misconfigured", 500);
|
|
187
|
+
const result = await exchangeToken(env, {
|
|
188
|
+
code,
|
|
189
|
+
redirect_uri: `${base}/callback`,
|
|
190
|
+
code_verifier: cookie.verifier
|
|
191
|
+
});
|
|
192
|
+
if ("error" in result) return fail(result.error, 200, result.description);
|
|
193
|
+
return callbackPage({
|
|
194
|
+
source: AUTH_MESSAGE_SOURCE,
|
|
195
|
+
ok: true,
|
|
196
|
+
token: result
|
|
197
|
+
}, cookie.origin, 200, new Headers(clear));
|
|
198
|
+
}
|
|
199
|
+
function json(body, status, origin) {
|
|
200
|
+
return new Response(JSON.stringify(body), {
|
|
201
|
+
status,
|
|
202
|
+
headers: {
|
|
203
|
+
"Content-Type": "application/json",
|
|
204
|
+
"Cache-Control": "no-store",
|
|
205
|
+
"Access-Control-Allow-Origin": origin,
|
|
206
|
+
Vary: "Origin"
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
async function handleRefresh(request, env) {
|
|
211
|
+
const origin = request.headers.get("Origin");
|
|
212
|
+
if (!isCanonicalAllowedOrigin(origin, env)) return new Response("Forbidden", { status: 403 });
|
|
213
|
+
if (request.method === "OPTIONS") return new Response(null, {
|
|
214
|
+
status: 204,
|
|
215
|
+
headers: {
|
|
216
|
+
"Access-Control-Allow-Origin": origin,
|
|
217
|
+
"Access-Control-Allow-Methods": "POST",
|
|
218
|
+
"Access-Control-Allow-Headers": "Content-Type",
|
|
219
|
+
"Access-Control-Max-Age": "86400",
|
|
220
|
+
Vary: "Origin"
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
let refreshToken;
|
|
224
|
+
try {
|
|
225
|
+
const body = await request.json();
|
|
226
|
+
refreshToken = typeof body === "object" && body !== null ? body.refresh_token : null;
|
|
227
|
+
} catch {
|
|
228
|
+
refreshToken = null;
|
|
229
|
+
}
|
|
230
|
+
if (typeof refreshToken !== "string" || !refreshToken) return json({ error: "invalid_request" }, 400, origin);
|
|
231
|
+
if (!env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET) return json({ error: "server_misconfigured" }, 500, origin);
|
|
232
|
+
const result = await exchangeToken(env, {
|
|
233
|
+
grant_type: "refresh_token",
|
|
234
|
+
refresh_token: refreshToken
|
|
235
|
+
});
|
|
236
|
+
if (!("error" in result)) return json(result, 200, origin);
|
|
237
|
+
if (result.error === "token_request_failed") return json({ error: result.error }, 502, origin);
|
|
238
|
+
const body = { error: result.error };
|
|
239
|
+
if (result.description) body.error_description = result.description;
|
|
240
|
+
return json(body, 400, origin);
|
|
241
|
+
}
|
|
242
|
+
const LOCAL_HOSTS = /* @__PURE__ */ new Set([
|
|
243
|
+
"localhost",
|
|
244
|
+
"127.0.0.1",
|
|
245
|
+
"[::1]"
|
|
246
|
+
]);
|
|
247
|
+
/**
|
|
248
|
+
* Public base URL without a trailing `/`: `PUBLIC_URL` when set, else the request origin.
|
|
249
|
+
* `null` when `PUBLIC_URL` is unparsable or not HTTPS (plain HTTP only on localhost): the state cookie is `Secure`.
|
|
250
|
+
*/
|
|
251
|
+
function publicBase(request, env) {
|
|
252
|
+
if (!env.PUBLIC_URL) return new URL(request.url).origin;
|
|
253
|
+
let url;
|
|
254
|
+
try {
|
|
255
|
+
url = new URL(env.PUBLIC_URL);
|
|
256
|
+
} catch {
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
return url.protocol === "https:" || url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname) ? `${url.origin}${url.pathname}`.replace(/\/+$/, "") : null;
|
|
260
|
+
}
|
|
261
|
+
/** The whole auth service as one Web-standard handler. Runs on any `fetch(Request) → Response` runtime. */
|
|
262
|
+
async function handleRequest(request, env) {
|
|
263
|
+
const base = publicBase(request, env);
|
|
264
|
+
if (base === null) return failure("server_misconfigured", 500);
|
|
265
|
+
const url = new URL(request.url);
|
|
266
|
+
const basePath = new URL(base).pathname.replace(/\/$/, "");
|
|
267
|
+
if (basePath && !url.pathname.startsWith(`${basePath}/`)) return notFound();
|
|
268
|
+
const route = url.pathname.slice(basePath.length).replace(/(.)\/$/, "$1");
|
|
269
|
+
switch (`${request.method} ${route}`) {
|
|
270
|
+
case "GET /health": return new Response(null, {
|
|
271
|
+
status: 204,
|
|
272
|
+
headers: { "Cache-Control": "no-store" }
|
|
273
|
+
});
|
|
274
|
+
case "GET /auth": return handleAuth(url, base, env);
|
|
275
|
+
case "GET /callback": return handleCallback(request, url, base, env);
|
|
276
|
+
case "OPTIONS /refresh":
|
|
277
|
+
case "POST /refresh": return handleRefresh(request, env);
|
|
278
|
+
default: return notFound();
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
export { handleRequest, isAllowedOrigin };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare const AUTH_MESSAGE_SOURCE: 'editlet-auth';
|
|
2
|
+
export interface TokenResponse {
|
|
3
|
+
/** `ghu_…` */
|
|
4
|
+
access_token: string;
|
|
5
|
+
/** `"bearer"` */
|
|
6
|
+
token_type: string;
|
|
7
|
+
/** `""` for GitHub Apps */
|
|
8
|
+
scope: string;
|
|
9
|
+
/** Seconds, 28800. Absent when the app has expiring tokens off. */
|
|
10
|
+
expires_in?: number;
|
|
11
|
+
/** `ghr_…` */
|
|
12
|
+
refresh_token?: string;
|
|
13
|
+
/** Seconds, 15897600 */
|
|
14
|
+
refresh_token_expires_in?: number;
|
|
15
|
+
}
|
|
16
|
+
export type AuthMessage = {
|
|
17
|
+
source: typeof AUTH_MESSAGE_SOURCE;
|
|
18
|
+
ok: true;
|
|
19
|
+
token: TokenResponse;
|
|
20
|
+
} | {
|
|
21
|
+
source: typeof AUTH_MESSAGE_SOURCE;
|
|
22
|
+
ok: false;
|
|
23
|
+
error: string;
|
|
24
|
+
description?: string;
|
|
25
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { Collection, Schema } from "./schema.js";
|
|
2
|
+
/** `[start, end)` offsets into the body text. */
|
|
3
|
+
export type TextRange = readonly [number, number];
|
|
4
|
+
/**
|
|
5
|
+
* One image in a markdown body, with the offsets needed to change its alt or src without touching the rest:
|
|
6
|
+
* - `inline`: ``;
|
|
7
|
+
* - `reference`: `![alt][label]`, `![alt][]` or `![alt]` plus a `[label]: src` definition (`srcRange` points into
|
|
8
|
+
* the definition, so images sharing one definition share it);
|
|
9
|
+
* - `html`: `<img src="…" alt="…">`.
|
|
10
|
+
*/
|
|
11
|
+
export type BodyImage = {
|
|
12
|
+
kind: 'inline' | 'reference' | 'html';
|
|
13
|
+
src: string;
|
|
14
|
+
/** Alt text, unescaped (markdown backslash escapes, HTML entities). */
|
|
15
|
+
alt: string;
|
|
16
|
+
/** The whole image (``, `![…][…]` or the `<img …>` tag). */
|
|
17
|
+
range: TextRange;
|
|
18
|
+
/** The alt text between the brackets, or the HTML attribute value; `null` for an `<img>` without `alt`. */
|
|
19
|
+
altRange: TextRange | null;
|
|
20
|
+
srcRange: TextRange;
|
|
21
|
+
/** Reference images: the label, and whether it was written out (`full`) or taken from the alt text. */
|
|
22
|
+
label?: {
|
|
23
|
+
text: string;
|
|
24
|
+
form: 'full' | 'collapsed' | 'shortcut';
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
/** One place an entry uses an image file. */
|
|
28
|
+
export type ImageUse = {
|
|
29
|
+
/**
|
|
30
|
+
* The field key: an `image` field, or the `markdown` field for body images (`body` when there is none). Inside an
|
|
31
|
+
* `object` or a block it is the dot path (`content.2.image`), and `at` holds the same path as parts.
|
|
32
|
+
*/
|
|
33
|
+
field: string;
|
|
34
|
+
/** Path of a nested value: the `image` field, or the Markdown string the image is in. Unset at the top level. */
|
|
35
|
+
at?: (string | number)[];
|
|
36
|
+
/** Label of a nested field with its place (`Image (content.2)`); unset at the top level. */
|
|
37
|
+
label?: string;
|
|
38
|
+
src: string;
|
|
39
|
+
alt: string;
|
|
40
|
+
/** Repo path `src` resolves to (`resolveAssetPath`), `null` for URLs, absolute paths and paths outside contentDir. */
|
|
41
|
+
path: string | null;
|
|
42
|
+
/** Set for images in the body, or in a nested Markdown string (with `at`). Ranges are inside that text. */
|
|
43
|
+
body?: BodyImage;
|
|
44
|
+
};
|
|
45
|
+
/** Every image in a markdown body (code blocks, inline code and HTML comments skipped), in document order. */
|
|
46
|
+
export declare function findBodyImages(body: string): BodyImage[];
|
|
47
|
+
/** Images an entry uses: its `image` fields (with a `src`), then the images in its body. */
|
|
48
|
+
export declare function findImageRefs(schema: Schema, collection: Collection, entryPath: string, data: Record<string, unknown>, body: string): ImageUse[];
|
|
49
|
+
export type BodyImageEdit = {
|
|
50
|
+
image: BodyImage;
|
|
51
|
+
alt?: string;
|
|
52
|
+
src?: string;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* The body with the given images' alt and/or src replaced; every other byte stays. Edits that hit the same range
|
|
56
|
+
* (several images sharing one reference definition) are applied once. Ranges come from `findBodyImages(body)`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function editBodyImages(body: string, edits: BodyImageEdit[]): string;
|
|
59
|
+
/** A change to one image use (`findImageRefs`): a new `alt` and/or `src`. */
|
|
60
|
+
export type ImageUseEdit = {
|
|
61
|
+
use: ImageUse;
|
|
62
|
+
alt?: string;
|
|
63
|
+
src?: string;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* One entry's data and body with `edits` applied (all uses of the same entry): image fields get the new `alt`/`src`
|
|
67
|
+
* at any depth, images in the body or in a nested Markdown string are changed in place (`editBodyImages`, every other
|
|
68
|
+
* byte kept). The inputs are not changed.
|
|
69
|
+
*/
|
|
70
|
+
export declare function applyImageEdits(data: Record<string, unknown>, body: string, edits: ImageUseEdit[]): {
|
|
71
|
+
data: Record<string, unknown>;
|
|
72
|
+
body: string;
|
|
73
|
+
};
|