@posissue/server 0.0.0-stage → 1.3.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/dist/index.js ADDED
@@ -0,0 +1,455 @@
1
+ // 仕様: docs/spec/04-http-api.html, 05-data-model.html, 07-spam-security.html
2
+ import { assertForms, buildIssue, DEFAULT_FORMS, parseReportRequest, reportUrls, } from "@posissue/core";
3
+ import { mount } from "posissue"; // ウィジェット本体。/widget.js として配信する(先に npm run build -w posissue が必要)
4
+ import { createIssue, isOurUserToken, userInstallationRepos, userInstallations, userToken, verifyWebhook } from "./github";
5
+ import { formPage, ICON_SVG, keysPage, landingPage, messagePage } from "./pages";
6
+ import { normalizeDailyLimit, normalizeOrigins, signSession, verifySession } from "./session";
7
+ export { DEFAULT_FORMS } from "@posissue/core";
8
+ const PENDING_TTL_SEC = 14 * 86400;
9
+ const MAX_BODY = 20_000;
10
+ const STATUS = {
11
+ invalid_input: 400, captcha_failed: 403, forbidden_origin: 403, unknown_project: 404,
12
+ duplicate: 409, spam: 422, rate_limited: 429, upstream_error: 502,
13
+ };
14
+ const WIDGET_JS =
15
+ // wrangler(esbuild) の keepNames が関数本体に __name(...) を差し込むので、toString した先でも動くよう同名の素通し関数を置く
16
+ `(function(){var __name=function(f){return f};var s=document.currentScript;if(!s)return;var mount=${mount.toString()};` +
17
+ `var go=function(){mount({projectKey:s.dataset.key,endpoint:new URL(s.src).origin,position:s.dataset.position,label:s.dataset.label,lang:s.dataset.lang,` +
18
+ `kinds:s.dataset.kinds?s.dataset.kinds.split(","):undefined})};document.body?go():addEventListener("DOMContentLoaded",go)})();`;
19
+ // スクリプトのない案内ページ用の既定 CSP。フォームとトップページは自分の CSP で上書きする
20
+ const STATIC_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'";
21
+ const html = (body, headers = {}, status = 200) => new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": STATIC_CSP, ...headers } });
22
+ const newKey = () => {
23
+ const a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
24
+ return "pk_" + Array.from(crypto.getRandomValues(new Uint8Array(24)), (b) => a[b % a.length]).join("");
25
+ };
26
+ const sha256 = async (s) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))]
27
+ .map((b) => b.toString(16).padStart(2, "0")).join("");
28
+ /** 表示言語:?lang= → クッキー pi_lang → ブラウザの言語(日本語以外は英語) */
29
+ function pickLang(req, url) {
30
+ const q = url.searchParams.get("lang");
31
+ if (q === "ja" || q === "en")
32
+ return q;
33
+ const c = /(?:^|;\s*)pi_lang=(ja|en)/.exec(req.headers.get("cookie") ?? "")?.[1];
34
+ if (c === "ja" || c === "en")
35
+ return c;
36
+ return /^ja\b/i.test(req.headers.get("accept-language") ?? "") ? "ja" : "en";
37
+ }
38
+ const langCookie = (lang) => `pi_lang=${lang}; Path=/; Max-Age=31536000; Secure; SameSite=Lax`;
39
+ const splitOrigins = (s) => s.split(",").map((x) => x.trim()).filter(Boolean);
40
+ const origins = (p) => splitOrigins(p.allowed_origins);
41
+ export function createHandler(config = {}) {
42
+ const forms = config.forms ?? DEFAULT_FORMS;
43
+ assertForms(forms);
44
+ const minElapsed = config.minElapsedMs ?? 3000;
45
+ const maxUrls = config.maxUrls ?? 2;
46
+ const perDay = config.limits?.projectPerDay ?? 50;
47
+ const getProject = (env, key) => env.DB.prepare("SELECT * FROM projects WHERE key = ? AND active = 1 AND banned = 0").bind(key).first();
48
+ async function report(req, env, cors) {
49
+ const fail = (error, key = "-") => {
50
+ console.log(JSON.stringify({ rejected: error, key }));
51
+ const r = Response.json({ ok: false, error }, { status: STATUS[error] });
52
+ cors(r.headers);
53
+ return r;
54
+ };
55
+ // 7.1 の順序どおり。安い検査から。
56
+ // 7.1 #0: 巨大な本文は読む前に断る(正規の報告は最大でも 20KB に収まる)
57
+ if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY)
58
+ return fail("invalid_input");
59
+ const text = await req.text();
60
+ if (text.length > MAX_BODY)
61
+ return fail("invalid_input");
62
+ let json = null;
63
+ try {
64
+ json = JSON.parse(text);
65
+ }
66
+ catch { /* 下で invalid_input */ }
67
+ const r = parseReportRequest(json, forms);
68
+ if (!r)
69
+ return fail("invalid_input");
70
+ if (r.hp)
71
+ return fail("spam", r.projectKey);
72
+ if (r.elapsedMs < minElapsed)
73
+ return fail("spam", r.projectKey);
74
+ if (reportUrls(r) > maxUrls)
75
+ return fail("spam", r.projectKey);
76
+ const p = await getProject(env, r.projectKey);
77
+ if (!p)
78
+ return fail("unknown_project", r.projectKey);
79
+ const origin = req.headers.get("origin");
80
+ const self = new URL(req.url).origin;
81
+ const allowed = origins(p);
82
+ if (origin && origin !== self && allowed.length && !allowed.includes(origin))
83
+ return fail("forbidden_origin", p.key);
84
+ const ip = req.headers.get("cf-connecting-ip") ?? "unknown";
85
+ if (!(await env.RL_IP.limit({ key: ip })).success)
86
+ return fail("rate_limited", p.key);
87
+ const form = new FormData();
88
+ form.append("secret", env.TURNSTILE_SECRET);
89
+ form.append("response", r.turnstileToken);
90
+ form.append("remoteip", ip);
91
+ const ts = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", { method: "POST", body: form })
92
+ .then((x) => x.json()).catch(() => ({ success: false, hostname: undefined }));
93
+ if (!ts.success)
94
+ return fail("captcha_failed", p.key);
95
+ // 7.1 #8: 自分のフォームで取った認証か確かめる(Cloudflare のテスト用秘密キーは hostname が固定なので除く)
96
+ if (!env.TURNSTILE_SECRET.startsWith("1x0000") && ts.hostname !== new URL(req.url).hostname)
97
+ return fail("captcha_failed", p.key);
98
+ const day = new Date().toISOString().slice(0, 10);
99
+ const used = await env.DB.prepare("INSERT INTO usage (key, day, count) VALUES (?, ?, 1) ON CONFLICT (key, day) DO UPDATE SET count = count + 1 RETURNING count").bind(p.key, day).first("count");
100
+ if ((used ?? 0) > (p.daily_limit ?? perDay))
101
+ return fail("rate_limited", p.key);
102
+ const now = Math.floor(Date.now() / 1000);
103
+ const hash = await sha256(JSON.stringify([p.key, r.kind, r.title, r.fields]));
104
+ await env.DB.prepare("DELETE FROM recent_hashes WHERE created_at < ?").bind(now - 86400).run();
105
+ const fresh = await env.DB.prepare("INSERT INTO recent_hashes (hash, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")
106
+ .bind(hash, now).run();
107
+ if (!fresh.meta.changes)
108
+ return fail("duplicate", p.key);
109
+ const built = buildIssue(r, forms, config.labels);
110
+ if (p.approval) {
111
+ // 承認モード(4.7):起票せずに保存し、作者の承認を待つ
112
+ await env.DB.prepare("DELETE FROM pending WHERE created_at < ?").bind(now - PENDING_TTL_SEC).run();
113
+ await env.DB.prepare("INSERT INTO pending (id, key, issue, created_at) VALUES (?, ?, ?, ?)")
114
+ .bind(crypto.randomUUID(), p.key, JSON.stringify(built), now).run();
115
+ const res = Response.json({ ok: true, pending: true }, { status: 202 });
116
+ cors(res.headers);
117
+ return res;
118
+ }
119
+ try {
120
+ const issue = await createIssue(creds(env), p.installation_id, p.repo, built);
121
+ const res = Response.json({ ok: true, issueNumber: issue.number, issueUrl: issue.html_url }, { status: 201 });
122
+ cors(res.headers);
123
+ return res;
124
+ }
125
+ catch (e) {
126
+ console.log(String(e));
127
+ await env.DB.prepare("DELETE FROM recent_hashes WHERE hash = ?").bind(hash).run(); // 失敗時は再送できるように
128
+ return fail("upstream_error", p.key);
129
+ }
130
+ }
131
+ // Origin の可否は report() 内で判定する(7.1 #6)。ここでは応答を読めるようにするだけ
132
+ const corsFor = (req) => (h) => {
133
+ const origin = req.headers.get("origin");
134
+ if (origin) {
135
+ h.set("access-control-allow-origin", origin);
136
+ h.set("vary", "origin");
137
+ }
138
+ };
139
+ /**
140
+ * /setup(App のインストール直後)と /keys(あとから確認)の共通処理。
141
+ * GitHub でログインしてもらい、本人がアクセスできるリポジトリのキーだけを表示する(4.3)。
142
+ * state は "keys"(全インストール)か installation_id(そのインストールだけ)。
143
+ */
144
+ async function setup(req, url, env) {
145
+ // 4.3: OAuth の state は、こちらが発行してクッキーにも入れたものと一致したときだけ信じる(ログイン CSRF 対策)。
146
+ // 一致しなければ code は使わず、認可からやり直す(インストール直後に GitHub から来た場合もここを通る。認可済みなら一瞬で戻ってくる)
147
+ const state = url.searchParams.get("state");
148
+ const code = url.searchParams.get("code");
149
+ const cookie = /(?:^|;\s*)pi_state=([^;]+)/.exec(req.headers.get("cookie") ?? "")?.[1];
150
+ const verified = !!(code && state && cookie && state === cookie);
151
+ const target = verified ? state.slice(state.indexOf(".") + 1) : (url.searchParams.get("installation_id") ?? "keys");
152
+ const one = Number(target);
153
+ if (target !== "keys" && (!Number.isInteger(one) || one <= 0)) {
154
+ return html(messagePage("Error", "<p>installation_id がありません。</p>"), {}, 400);
155
+ }
156
+ // GitHub から戻ってきたのにクッキーがない=ブロックされている。やり直すと行き来が止まらないので案内を出す
157
+ if (!verified && code && state && !cookie) {
158
+ return html(messagePage("Cookie が必要です", `<p>ログインの確認に Cookie を使います。このサイト(posissue.2nj.lol)の Cookie を許可してから、<a href="/keys">もう一度お試しください</a>。</p>`), {}, 400);
159
+ }
160
+ if (!verified)
161
+ return startAuth(env, target);
162
+ // 7.3: GitHub API を呼ぶのはここからなので、ここで IP ごとに絞る(認可画面へのリダイレクトは数えない)
163
+ const ip = req.headers.get("cf-connecting-ip") ?? "unknown";
164
+ if (!(await env.RL_ADMIN.limit({ key: `setup:${ip}` })).success) {
165
+ return html(messagePage("Too many requests", "<p>少し待ってからもう一度お試しください。</p>"), {}, 429);
166
+ }
167
+ const forbidden = () => html(messagePage("Forbidden", "<p>確認できませんでした。インストールしたアカウントでもう一度お試しください。</p>"), {}, 403);
168
+ const rows = [];
169
+ try {
170
+ const token = await userToken(env.GITHUB_CLIENT_ID, env.GITHUB_CLIENT_SECRET, code);
171
+ if (!token)
172
+ return forbidden();
173
+ const ids = target === "keys" ? await userInstallations(token) : [one];
174
+ for (const id of ids) {
175
+ const repos = await userInstallationRepos(token, id);
176
+ if (!repos) {
177
+ if (target !== "keys")
178
+ return forbidden();
179
+ continue;
180
+ }
181
+ for (const repo of repos) {
182
+ const row = { ...(await ensureProject(env, id, repo.name, repo.isPrivate)), canEdit: repo.canAdmin, installationId: id };
183
+ if (row.key && row.canEdit)
184
+ row.pending = await listPending(env, row.key);
185
+ rows.push(row);
186
+ }
187
+ }
188
+ }
189
+ catch (e) {
190
+ console.log(String(e));
191
+ return html(messagePage("Error", "<p>GitHub との通信に失敗しました。時間をおいてお試しください。</p>"), {}, 502);
192
+ }
193
+ const nonce = crypto.randomUUID().replace(/-/g, "");
194
+ const session = await signSession(env.SESSION_SECRET, rows.filter((r) => r.key && r.canEdit).map((r) => [r.repo, r.installationId]));
195
+ return html(keysPage({ origin: url.origin, appSlug: env.GITHUB_APP_SLUG, rows, nonce, session, defaultDailyLimit: perDay, justInstalled: target !== "keys", lang: pickLang(req, url) }), {
196
+ "content-security-policy": `default-src 'none'; script-src 'nonce-${nonce}'; connect-src 'self'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'`,
197
+ "cache-control": "no-store",
198
+ "set-cookie": "pi_state=; Path=/setup; Max-Age=0; HttpOnly; Secure; SameSite=Lax", // 使い捨て
199
+ });
200
+ }
201
+ /**
202
+ * CLI 用(4.5)。GitHub のデバイスフローで作者自身がログインして得たユーザートークンを受け取り、
203
+ * そのユーザーがアクセスできるリポジトリのキーを JSON で返す。トークンは保存しない。
204
+ */
205
+ async function apiKeys(req, env) {
206
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
207
+ const ip = req.headers.get("cf-connecting-ip") ?? "unknown";
208
+ if (!(await env.RL_ADMIN.limit({ key: `keys:${ip}` })).success)
209
+ return json({ ok: false, error: "rate_limited" }, 429);
210
+ const token = /^Bearer\s+(\S+)$/i.exec(req.headers.get("authorization") ?? "")?.[1];
211
+ if (!token)
212
+ return json({ ok: false, error: "unauthorized" }, 401);
213
+ try {
214
+ if (!(await isOurUserToken(env.GITHUB_CLIENT_ID, env.GITHUB_CLIENT_SECRET, token)))
215
+ return json({ ok: false, error: "unauthorized" }, 401);
216
+ const rows = [];
217
+ for (const id of await userInstallations(token)) {
218
+ for (const repo of (await userInstallationRepos(token, id)) ?? [])
219
+ rows.push(await ensureProject(env, id, repo.name, repo.isPrivate));
220
+ }
221
+ return json({ ok: true, endpoint: new URL(req.url).origin, keys: rows.map((r) => ({ repo: r.repo, key: r.key, stopped: r.key === null, allowedOrigins: r.origins, dailyLimit: r.dailyLimit, approval: r.approval })) });
222
+ }
223
+ catch (e) {
224
+ console.log(String(e));
225
+ return json({ ok: false, error: "upstream_error" }, 502);
226
+ }
227
+ }
228
+ /**
229
+ * 4.6: キー確認画面からの設定変更。本文の session(署名付き・30 分)に含まれるリポジトリだけ変えられる。
230
+ * クッキーを使わないので CSRF の心配がない。同じオリジンからだけ受け付ける。
231
+ */
232
+ async function apiSettings(req, env) {
233
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
234
+ if (req.headers.get("origin") !== new URL(req.url).origin)
235
+ return json({ ok: false, error: "forbidden" }, 403);
236
+ const ip = req.headers.get("cf-connecting-ip") ?? "unknown";
237
+ if (!(await env.RL_ADMIN.limit({ key: `settings:${ip}` })).success)
238
+ return json({ ok: false, error: "rate_limited" }, 429);
239
+ const text = await req.text();
240
+ if (text.length > 4000)
241
+ return json({ ok: false, error: "invalid_input" }, 400);
242
+ let b;
243
+ try {
244
+ b = JSON.parse(text);
245
+ }
246
+ catch {
247
+ return json({ ok: false, error: "invalid_input" }, 400);
248
+ }
249
+ const grants = await verifySession(env.SESSION_SECRET, b.session);
250
+ if (!grants)
251
+ return json({ ok: false, error: "session_expired" }, 401);
252
+ const grant = grants.find(([repo]) => repo === b.repo);
253
+ if (!grant)
254
+ return json({ ok: false, error: "forbidden" }, 403);
255
+ const allowed = normalizeOrigins(b.allowedOrigins);
256
+ const limit = normalizeDailyLimit(b.dailyLimit);
257
+ if (!allowed || limit === undefined || typeof b.approval !== "boolean")
258
+ return json({ ok: false, error: "invalid_input" }, 400);
259
+ // 署名後にアンインストール・付け替えされていたら変えない
260
+ const r = await env.DB.prepare("UPDATE projects SET allowed_origins = ?, daily_limit = ?, approval = ? WHERE repo = ? AND installation_id = ? AND active = 1 AND banned = 0")
261
+ .bind(allowed.join(","), limit, b.approval ? 1 : 0, grant[0], grant[1]).run();
262
+ if (!r.meta.changes)
263
+ return json({ ok: false, error: "forbidden" }, 403);
264
+ return json({ ok: true, allowedOrigins: allowed, dailyLimit: limit, approval: b.approval });
265
+ }
266
+ /** 4.7: 承認待ちの報告を起票する・捨てる。認可は設定と同じ署名付きトークン。 */
267
+ async function apiPending(req, env) {
268
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
269
+ if (req.headers.get("origin") !== new URL(req.url).origin)
270
+ return json({ ok: false, error: "forbidden" }, 403);
271
+ const ip = req.headers.get("cf-connecting-ip") ?? "unknown";
272
+ if (!(await env.RL_ADMIN.limit({ key: `pending:${ip}` })).success)
273
+ return json({ ok: false, error: "rate_limited" }, 429);
274
+ const text = await req.text();
275
+ if (text.length > 4000)
276
+ return json({ ok: false, error: "invalid_input" }, 400);
277
+ let b;
278
+ try {
279
+ b = JSON.parse(text);
280
+ }
281
+ catch {
282
+ return json({ ok: false, error: "invalid_input" }, 400);
283
+ }
284
+ if (typeof b.id !== "string" || (b.action !== "approve" && b.action !== "reject"))
285
+ return json({ ok: false, error: "invalid_input" }, 400);
286
+ const grants = await verifySession(env.SESSION_SECRET, b.session);
287
+ if (!grants)
288
+ return json({ ok: false, error: "session_expired" }, 401);
289
+ const grant = grants.find(([repo]) => repo === b.repo);
290
+ if (!grant)
291
+ return json({ ok: false, error: "forbidden" }, 403);
292
+ // 署名にあるリポジトリ・インストールの、有効なプロジェクトの承認待ちだけを対象にする
293
+ const row = await env.DB.prepare("SELECT pending.issue AS issue FROM pending JOIN projects ON projects.key = pending.key WHERE pending.id = ? AND projects.repo = ? AND projects.installation_id = ? AND projects.active = 1 AND projects.banned = 0").bind(b.id, grant[0], grant[1]).first();
294
+ if (!row)
295
+ return json({ ok: false, error: "not_found" }, 404);
296
+ // 先に消して、二重に起票されないようにする(起票に失敗したら戻す)
297
+ const del = await env.DB.prepare("DELETE FROM pending WHERE id = ?").bind(b.id).run();
298
+ if (!del.meta.changes)
299
+ return json({ ok: false, error: "not_found" }, 404);
300
+ if (b.action === "reject")
301
+ return json({ ok: true });
302
+ try {
303
+ const issue = await createIssue(creds(env), grant[1], grant[0], JSON.parse(row.issue));
304
+ return json({ ok: true, issueNumber: issue.number, issueUrl: issue.html_url });
305
+ }
306
+ catch (e) {
307
+ console.log(String(e));
308
+ await env.DB.prepare("INSERT INTO pending (id, key, issue, created_at) SELECT ?, key, ?, ? FROM projects WHERE repo = ?")
309
+ .bind(b.id, row.issue, Math.floor(Date.now() / 1000), grant[0]).run();
310
+ return json({ ok: false, error: "upstream_error" }, 502);
311
+ }
312
+ }
313
+ /** GitHub の認可画面へ送る。state = ランダム値.対象 を、同じ値の短命クッキーと組にする。 */
314
+ function startAuth(env, target) {
315
+ const state = `${crypto.randomUUID().replace(/-/g, "")}.${target}`;
316
+ const auth = new URL("https://github.com/login/oauth/authorize");
317
+ auth.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
318
+ auth.searchParams.set("state", state);
319
+ return new Response(null, {
320
+ status: 302,
321
+ headers: {
322
+ location: auth.toString(),
323
+ "set-cookie": `pi_state=${state}; Path=/setup; Max-Age=600; HttpOnly; Secure; SameSite=Lax`,
324
+ "cache-control": "no-store",
325
+ },
326
+ });
327
+ }
328
+ /** 7.4: 有効なキーがあれば再利用、停止中なら新しいキーに置き換える。運営が止めたものは復活させない。 */
329
+ async function ensureProject(env, id, repo, isPrivate) {
330
+ const cur = await env.DB.prepare("SELECT key, active, banned, allowed_origins, daily_limit, approval FROM projects WHERE repo = ?").bind(repo)
331
+ .first();
332
+ if (cur?.banned)
333
+ return { repo, key: null, origins: [], dailyLimit: null, approval: false };
334
+ if (!cur || !cur.active) {
335
+ const key = newKey();
336
+ await env.DB.prepare(
337
+ // 4.7: 新規は公開リポジトリなら承認モード、非公開なら即時起票。再有効化では作者が選んだ値を残す
338
+ "INSERT INTO projects (key, installation_id, repo, approval) VALUES (?, ?, ?, ?) ON CONFLICT (repo) DO UPDATE SET key = excluded.key, installation_id = excluded.installation_id, active = 1").bind(key, id, repo, isPrivate ? 0 : 1).run();
339
+ return { repo, key, origins: cur ? splitOrigins(cur.allowed_origins) : [], dailyLimit: cur?.daily_limit ?? null, approval: cur ? !!cur.approval : !isPrivate };
340
+ }
341
+ await env.DB.prepare("UPDATE projects SET installation_id = ? WHERE repo = ?").bind(id, repo).run();
342
+ return { repo, key: cur.key, origins: splitOrigins(cur.allowed_origins), dailyLimit: cur.daily_limit, approval: !!cur.approval };
343
+ }
344
+ async function listPending(env, key) {
345
+ const now = Math.floor(Date.now() / 1000);
346
+ await env.DB.prepare("DELETE FROM pending WHERE created_at < ?").bind(now - PENDING_TTL_SEC).run();
347
+ const r = await env.DB.prepare("SELECT id, issue, created_at FROM pending WHERE key = ? ORDER BY created_at DESC LIMIT 50").bind(key)
348
+ .all();
349
+ return r.results.map((x) => {
350
+ const i = JSON.parse(x.issue);
351
+ return { id: x.id, title: i.title, body: i.body, createdAt: x.created_at };
352
+ });
353
+ }
354
+ async function webhook(req, env) {
355
+ const body = await req.text();
356
+ if (!(await verifyWebhook(env.GITHUB_WEBHOOK_SECRET, body, req.headers.get("x-hub-signature-256")))) {
357
+ return new Response("bad signature", { status: 401 });
358
+ }
359
+ const ev = req.headers.get("x-github-event");
360
+ const p = JSON.parse(body);
361
+ if (ev === "installation" && p.action === "deleted") {
362
+ await env.DB.prepare("UPDATE projects SET active = 0 WHERE installation_id = ?").bind(p.installation.id).run();
363
+ }
364
+ else if (ev === "installation_repositories" && p.action === "removed") {
365
+ for (const r of p.repositories_removed ?? []) {
366
+ await env.DB.prepare("UPDATE projects SET active = 0 WHERE repo = ?").bind(r.full_name).run();
367
+ }
368
+ }
369
+ return new Response("ok");
370
+ }
371
+ const creds = (env) => ({ appId: env.GITHUB_APP_ID, privateKey: env.GITHUB_APP_PRIVATE_KEY });
372
+ return {
373
+ async fetch(req, env) {
374
+ const url = new URL(req.url);
375
+ const path = url.pathname;
376
+ if (path === "/api/report") {
377
+ const cors = corsFor(req);
378
+ if (req.method === "OPTIONS") {
379
+ const h = new Headers({ "access-control-allow-methods": "POST", "access-control-allow-headers": "content-type", "access-control-max-age": "86400" });
380
+ cors(h);
381
+ return new Response(null, { status: 204, headers: h });
382
+ }
383
+ if (req.method === "POST")
384
+ return report(req, env, cors);
385
+ }
386
+ if (req.method === "GET" && (path === "/icon.svg" || path === "/favicon.ico")) {
387
+ return new Response(ICON_SVG, { headers: { "content-type": "image/svg+xml", "cache-control": "public, max-age=3600" } });
388
+ }
389
+ if (req.method === "GET" && path === "/widget.js") {
390
+ return new Response(WIDGET_JS, { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300" } });
391
+ }
392
+ const m = path.match(/^\/r\/(pk_[A-Za-z0-9]{24})$/);
393
+ if (req.method === "GET" && m) {
394
+ const p = await getProject(env, m[1]);
395
+ if (!p)
396
+ return html(messagePage("Not found", "<p>Unknown project.</p>"), {}, 404);
397
+ const meta = {};
398
+ let shown = forms;
399
+ let lang;
400
+ for (const [k, v] of url.searchParams) {
401
+ if (k === "lang") {
402
+ if (v === "ja" || v === "en")
403
+ lang = v;
404
+ }
405
+ else if (k === "kinds") {
406
+ const ks = v.split(",");
407
+ const picked = forms.filter((t) => ks.includes(t.kind));
408
+ if (picked.length)
409
+ shown = picked;
410
+ }
411
+ else if (Object.keys(meta).length < 18 && /^[A-Za-z0-9_-]{1,50}$/.test(k))
412
+ meta[k] = v.slice(0, 200); // 18 + userAgent/language = 20
413
+ }
414
+ const nonce = crypto.randomUUID().replace(/-/g, "");
415
+ const allowed = origins(p);
416
+ const csp = [
417
+ "default-src 'none'", `script-src 'nonce-${nonce}' https://challenges.cloudflare.com`,
418
+ "frame-src https://challenges.cloudflare.com", "connect-src 'self'", "style-src 'unsafe-inline'",
419
+ // 許可リストがあれば、埋め込めるサイトをそこに限る(Origin チェックの実体)
420
+ `frame-ancestors ${allowed.length ? allowed.join(" ") : "*"}`,
421
+ ].join("; ");
422
+ return html(formPage({ projectKey: p.key, repo: p.repo, siteKey: env.TURNSTILE_SITE_KEY, forms: shown, meta, nonce, lang }), {
423
+ "content-security-policy": csp, "referrer-policy": "no-referrer",
424
+ });
425
+ }
426
+ if (req.method === "GET" && path === "/setup")
427
+ return setup(req, url, env);
428
+ // あとからキーを確認するページ。GitHub の認可画面へ送り、戻り先の /setup で一覧を出す
429
+ // 管理画面。/keys は以前の URL として残す
430
+ if (req.method === "GET" && (path === "/admin" || path === "/keys"))
431
+ return startAuth(env, "keys");
432
+ if (req.method === "GET" && path === "/api/keys")
433
+ return apiKeys(req, env);
434
+ if (req.method === "POST" && path === "/api/settings")
435
+ return apiSettings(req, env);
436
+ if (req.method === "POST" && path === "/api/pending")
437
+ return apiPending(req, env);
438
+ if (req.method === "POST" && path === "/webhook")
439
+ return webhook(req, env);
440
+ if (req.method === "GET" && path === "/") {
441
+ const nonce = crypto.randomUUID().replace(/-/g, "");
442
+ const lang = pickLang(req, url);
443
+ return html(landingPage({
444
+ origin: url.origin, appSlug: env.GITHUB_APP_SLUG, demoKey: env.DEMO_KEY, nonce, lang,
445
+ repoUrl: "https://github.com/ninjin0802/posissue",
446
+ }), {
447
+ ...(url.searchParams.has("lang") ? { "set-cookie": langCookie(lang) } : {}),
448
+ vary: "accept-language, cookie",
449
+ "content-security-policy": `default-src 'none'; script-src 'self' 'nonce-${nonce}'; style-src 'unsafe-inline'; frame-src 'self'; connect-src 'self'; img-src 'self'`,
450
+ });
451
+ }
452
+ return new Response("Not found", { status: 404 });
453
+ },
454
+ };
455
+ }
@@ -0,0 +1,56 @@
1
+ import type { FormTemplate } from "@posissue/core";
2
+ export declare const esc: (s: string) => string;
3
+ /** フォームの見た目はフォームの型(FormTemplate[])から組み立てる。値は textContent で入れるので HTML 注入されない。 */
4
+ export declare function formPage(o: {
5
+ projectKey: string;
6
+ repo: string;
7
+ siteKey: string;
8
+ forms: FormTemplate[];
9
+ meta: Record<string, string>;
10
+ nonce: string;
11
+ lang?: "ja" | "en";
12
+ }): string;
13
+ export declare function messagePage(title: string, bodyHtml: string): string;
14
+ /** 公式ホストのトップページ。demoKey があればフォームの実物を埋め込み、ウィジェットも置く(自分自身への報告になる)。 */
15
+ export type Lang = "ja" | "en";
16
+ /** 日英の切り替え。t("日本語", "English") */
17
+ export declare const tr: (lang: Lang) => (ja: string, en: string) => string;
18
+ /** プライバシーポリシーなど静的ページの言語別 URL(英語は /en/ の下) */
19
+ export declare const docPath: (lang: Lang, page: "privacy" | "terms" | "changelog") => string;
20
+ export declare function landingPage(o: {
21
+ origin: string;
22
+ appSlug: string;
23
+ demoKey?: string;
24
+ repoUrl: string;
25
+ nonce: string;
26
+ lang: Lang;
27
+ }): string;
28
+ export declare const ICON_SVG = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\" role=\"img\" aria-label=\"PosIssue\">\n <defs>\n <mask id=\"eyes\" maskUnits=\"userSpaceOnUse\" x=\"0\" y=\"0\" width=\"512\" height=\"512\">\n <rect width=\"512\" height=\"512\" fill=\"#fff\"/>\n <path d=\"M164 262c22-24 52-30 78-14-18 26-48 34-78 14z\"/>\n <path d=\"M348 262c-22-24-52-30-78-14 18 26 48 34 78 14z\"/>\n </mask>\n </defs>\n <rect x=\"4\" y=\"4\" width=\"504\" height=\"504\" rx=\"114\" fill=\"#0d1117\" stroke=\"#30363d\" stroke-width=\"8\"/>\n <g transform=\"translate(64 64) scale(.75)\" fill=\"#f0f6fc\" mask=\"url(#eyes)\">\n <path d=\"M96 268c0-92 68-150 160-150s160 58 160 150-68 152-160 152S96 360 96 268z\"/>\n <path d=\"M110 222 126 74c1-12 13-17 22-10l92 70z\"/>\n <path d=\"M402 222 386 74c-1-12-13-17-22-10l-92 70z\"/>\n </g>\n</svg>";
29
+ /** key=null は運営が停止中。origins は埋め込みを許すサイト(空なら制限なし)、dailyLimit は 1 日の上限(null は既定値) */
30
+ export interface PendingItem {
31
+ id: string;
32
+ title: string;
33
+ body: string;
34
+ createdAt: number;
35
+ }
36
+ export interface KeyRow {
37
+ repo: string;
38
+ key: string | null;
39
+ origins: string[];
40
+ dailyLimit: number | null;
41
+ approval: boolean;
42
+ canEdit?: boolean;
43
+ installationId?: number;
44
+ pending?: PendingItem[];
45
+ }
46
+ /** ログインした作者向けの管理画面(/admin・/setup)。キーの確認、設定、承認待ちの処理。 */
47
+ export declare function keysPage(o: {
48
+ origin: string;
49
+ appSlug: string;
50
+ rows: KeyRow[];
51
+ nonce: string;
52
+ session: string;
53
+ defaultDailyLimit: number;
54
+ justInstalled: boolean;
55
+ lang: Lang;
56
+ }): string;