@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ninjin0802
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @posissue/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Self-host [PosIssue](https://posissue.2nj.lol) on **Cloudflare Workers**: a beautiful feedback form, a spam-protected API, a maintainer dashboard and approval mode — reports become GitHub issues, and reporters don’t need a GitHub account.
4
+
5
+ > Prefer not to run anything? Use the free hosted service at https://posissue.2nj.lol.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm i @posissue/server
11
+ ```
12
+
13
+ ```ts
14
+ // src/index.ts
15
+ import { createHandler, type FormTemplate } from "@posissue/server";
16
+
17
+ const forms: FormTemplate[] = [
18
+ {
19
+ kind: "bug",
20
+ label: { en: "Bug", ja: "バグ報告" },
21
+ fields: [
22
+ { id: "steps", type: "textarea", required: true, label: { en: "Steps to reproduce", ja: "再現手順" } },
23
+ { id: "actual", type: "textarea", required: true, label: { en: "What happened", ja: "実際に起きたこと" } },
24
+ ],
25
+ },
26
+ ];
27
+
28
+ export default createHandler({ forms, labels: ["from-widget"], limits: { projectPerDay: 50 } });
29
+ ```
30
+
31
+ Omit `forms` to use the built-in Bug / Feature request / Other forms. Mistakes in the form type throw at startup.
32
+
33
+ ## Bindings and secrets (wrangler)
34
+
35
+ | Name | Kind | Purpose |
36
+ |---|---|---|
37
+ | `DB` | D1 | Projects, pending reports, counters (apply the migrations from the repo’s `apps/hosted/migrations`) |
38
+ | `RL_IP` | Rate limit | Reports per IP (e.g. 2 / 60s) |
39
+ | `RL_ADMIN` | Rate limit | Maintainer actions per IP (e.g. 30 / 60s) |
40
+ | `GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY` | Secret | Your GitHub App (PKCS#8 key) |
41
+ | `GITHUB_APP_SLUG`, `GITHUB_CLIENT_ID` | Var | App slug and OAuth client ID |
42
+ | `GITHUB_CLIENT_SECRET`, `GITHUB_WEBHOOK_SECRET` | Secret | OAuth and webhook |
43
+ | `TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET` | Var / Secret | Cloudflare Turnstile |
44
+ | `SESSION_SECRET` | Secret | Signs dashboard actions |
45
+
46
+ A complete example lives in [`apps/hosted`](https://github.com/ninjin0802/posissue/tree/main/apps/hosted), and the full spec in [`docs/spec`](https://github.com/ninjin0802/posissue/tree/main/docs/spec).
47
+
48
+ This package ships ES modules for bundlers (wrangler/esbuild); it is not meant to run directly in Node.js.
49
+
50
+ MIT · https://github.com/ninjin0802/posissue
@@ -0,0 +1,34 @@
1
+ export declare function appJwt(appId: string, pem: string, now?: number): Promise<string>;
2
+ export interface GitHubCreds {
3
+ appId: string;
4
+ privateKey: string;
5
+ }
6
+ /** OAuth の code をユーザートークンに換える。失敗なら null。 */
7
+ export declare function userToken(clientId: string, clientSecret: string, code: string): Promise<string | null>;
8
+ /**
9
+ * トークンが「この App のために発行されたユーザートークン」か GitHub に確かめる(CLI の /api/keys 用)。
10
+ * 他の App のトークンや PAT を受け付けると、別アプリのインストール ID でプロジェクトを作ってしまうため。
11
+ */
12
+ export declare function isOurUserToken(clientId: string, clientSecret: string, token: string): Promise<boolean>;
13
+ /** そのユーザーがアクセスできる、この App のインストール ID の一覧。 */
14
+ export declare function userInstallations(token: string): Promise<number[]>;
15
+ /**
16
+ * インストールのうち「そのユーザー自身が見られるリポジトリ」だけを返す。
17
+ * Organization のメンバーが、自分に権限のないリポジトリ名やキーを見られないようにするため。
18
+ * アクセスできなければ null。
19
+ */
20
+ export interface UserRepo {
21
+ name: string;
22
+ canAdmin: boolean;
23
+ isPrivate: boolean;
24
+ }
25
+ export declare function userInstallationRepos(token: string, id: number): Promise<UserRepo[] | null>;
26
+ export declare function createIssue(c: GitHubCreds, id: number, repo: string, issue: {
27
+ title: string;
28
+ body: string;
29
+ labels: string[];
30
+ }): Promise<{
31
+ number: number;
32
+ html_url: string;
33
+ }>;
34
+ export declare function verifyWebhook(secret: string, body: string, sigHeader: string | null): Promise<boolean>;
package/dist/github.js ADDED
@@ -0,0 +1,96 @@
1
+ // 仕様: docs/spec/06-github-app.html
2
+ const API = "https://api.github.com";
3
+ const enc = new TextEncoder();
4
+ const b64url = (b) => btoa(String.fromCharCode(...new Uint8Array(b))).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
5
+ let keyCache;
6
+ async function signingKey(pem) {
7
+ if (keyCache?.pem === pem)
8
+ return keyCache.key;
9
+ if (pem.includes("BEGIN RSA PRIVATE KEY"))
10
+ throw new Error("GITHUB_APP_PRIVATE_KEY must be PKCS#8 (see spec 6.2)");
11
+ const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s/g, "")), (c) => c.charCodeAt(0));
12
+ const key = await crypto.subtle.importKey("pkcs8", der, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);
13
+ keyCache = { pem, key };
14
+ return key;
15
+ }
16
+ export async function appJwt(appId, pem, now = Math.floor(Date.now() / 1000)) {
17
+ const head = b64url(enc.encode(JSON.stringify({ alg: "RS256", typ: "JWT" })));
18
+ const body = b64url(enc.encode(JSON.stringify({ iat: now - 60, exp: now + 540, iss: appId })));
19
+ const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", await signingKey(pem), enc.encode(`${head}.${body}`));
20
+ return `${head}.${body}.${b64url(sig)}`;
21
+ }
22
+ async function gh(path, token, init = {}) {
23
+ const res = await fetch(API + path, {
24
+ ...init,
25
+ headers: {
26
+ authorization: `Bearer ${token}`, accept: "application/vnd.github+json",
27
+ "x-github-api-version": "2022-11-28", "user-agent": "posissue", "content-type": "application/json",
28
+ },
29
+ });
30
+ if (!res.ok)
31
+ throw new Error(`GitHub ${init.method ?? "GET"} ${path}: ${res.status}`);
32
+ return res.json();
33
+ }
34
+ const tokens = new Map();
35
+ async function installationToken(c, id) {
36
+ const hit = tokens.get(id);
37
+ if (hit && hit.exp - Date.now() > 5 * 60_000)
38
+ return hit.token;
39
+ const r = await gh(`/app/installations/${id}/access_tokens`, await appJwt(c.appId, c.privateKey), { method: "POST" });
40
+ tokens.set(id, { token: r.token, exp: Date.parse(r.expires_at) });
41
+ return r.token;
42
+ }
43
+ /** OAuth の code をユーザートークンに換える。失敗なら null。 */
44
+ export async function userToken(clientId, clientSecret, code) {
45
+ const res = await fetch("https://github.com/login/oauth/access_token", {
46
+ method: "POST",
47
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": "posissue" },
48
+ body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, code }),
49
+ });
50
+ return (await res.json()).access_token ?? null;
51
+ }
52
+ /**
53
+ * トークンが「この App のために発行されたユーザートークン」か GitHub に確かめる(CLI の /api/keys 用)。
54
+ * 他の App のトークンや PAT を受け付けると、別アプリのインストール ID でプロジェクトを作ってしまうため。
55
+ */
56
+ export async function isOurUserToken(clientId, clientSecret, token) {
57
+ const res = await fetch(`${API}/applications/${clientId}/token`, {
58
+ method: "POST",
59
+ headers: {
60
+ authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`, accept: "application/vnd.github+json",
61
+ "content-type": "application/json", "user-agent": "posissue", "x-github-api-version": "2022-11-28",
62
+ },
63
+ body: JSON.stringify({ access_token: token }),
64
+ });
65
+ return res.ok;
66
+ }
67
+ /** そのユーザーがアクセスできる、この App のインストール ID の一覧。 */
68
+ export async function userInstallations(token) {
69
+ // shortcut: 先頭 100 件のみ。1 ユーザーが 100 を超えるインストールを持つならページングを足す
70
+ const r = await gh(`/user/installations?per_page=100`, token);
71
+ return r.installations.map((x) => x.id);
72
+ }
73
+ export async function userInstallationRepos(token, id) {
74
+ // shortcut: 先頭 100 件のみ。100 リポジトリを超えたらページングを足す
75
+ const res = await fetch(`${API}/user/installations/${id}/repositories?per_page=100`, {
76
+ headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "user-agent": "posissue" },
77
+ });
78
+ if (!res.ok)
79
+ return null; // 404 = そのユーザーはこのインストールにアクセスできない
80
+ const r = (await res.json());
81
+ // 設定を変えられるのは、そのリポジトリの管理者(admin / maintain)だけ(4.6)
82
+ return r.repositories.map((x) => ({ name: x.full_name, canAdmin: !!(x.permissions?.admin || x.permissions?.maintain), isPrivate: x.private !== false }));
83
+ }
84
+ export async function createIssue(c, id, repo, issue) {
85
+ return gh(`/repos/${repo}/issues`, await installationToken(c, id), { method: "POST", body: JSON.stringify(issue) });
86
+ }
87
+ export async function verifyWebhook(secret, body, sigHeader) {
88
+ if (!sigHeader?.startsWith("sha256="))
89
+ return false;
90
+ const hex = sigHeader.slice(7);
91
+ if (!/^[0-9a-f]{64}$/.test(hex))
92
+ return false;
93
+ const sig = Uint8Array.from(hex.match(/../g), (h) => parseInt(h, 16));
94
+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
95
+ return crypto.subtle.verify("HMAC", key, sig, enc.encode(body)); // 時間一定の比較
96
+ }
@@ -0,0 +1,33 @@
1
+ import { type FormTemplate } from "@posissue/core";
2
+ export type { ReportRequest, ReportResponse, ErrorCode, FormTemplate, FormField } from "@posissue/core";
3
+ export { DEFAULT_FORMS } from "@posissue/core";
4
+ export interface Env {
5
+ DB: D1Database;
6
+ RL_IP: RateLimit;
7
+ /** 作者向けの操作(/setup・/api/keys・/api/settings・/api/pending)用。報告より緩い制限 */
8
+ RL_ADMIN: RateLimit;
9
+ GITHUB_APP_ID: string;
10
+ GITHUB_APP_PRIVATE_KEY: string;
11
+ GITHUB_APP_SLUG: string;
12
+ /** App の OAuth(/setup で持ち主を確かめる)。client id は公開してよい値 */
13
+ GITHUB_CLIENT_ID: string;
14
+ GITHUB_CLIENT_SECRET: string;
15
+ /** キー確認画面から設定を変えるときの署名用(4.6)。ランダムな長い文字列 */
16
+ SESSION_SECRET: string;
17
+ GITHUB_WEBHOOK_SECRET: string;
18
+ TURNSTILE_SITE_KEY: string;
19
+ TURNSTILE_SECRET: string;
20
+ /** トップページのデモに使う projectKey(任意)。PosIssue 自身のリポジトリのキーを入れる */
21
+ DEMO_KEY?: string;
22
+ }
23
+ export interface ServerConfig {
24
+ /** 種別ごとのフォームの型。省略時は DEFAULT_FORMS。並び順がタブの順になる */
25
+ forms?: FormTemplate[];
26
+ labels?: string[];
27
+ limits?: {
28
+ projectPerDay?: number;
29
+ };
30
+ minElapsedMs?: number;
31
+ maxUrls?: number;
32
+ }
33
+ export declare function createHandler(config?: ServerConfig): ExportedHandler<Env>;