ownledger 0.0.1 → 1.1.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.
Files changed (94) hide show
  1. package/AGENTS.md +94 -0
  2. package/CHANGELOG.md +30 -0
  3. package/LICENSE +21 -0
  4. package/README.md +101 -1
  5. package/assets/_headers +5 -0
  6. package/assets/app.css +61 -0
  7. package/assets/app.js +369 -0
  8. package/assets/icon.svg +1 -0
  9. package/assets/index.html +30 -0
  10. package/assets/manifest.webmanifest +1 -0
  11. package/dist/cli/check.d.ts +3 -0
  12. package/dist/cli/check.js +21 -0
  13. package/dist/cli/deploy.d.ts +1 -0
  14. package/dist/cli/deploy.js +258 -0
  15. package/dist/cli/dev.d.ts +3 -0
  16. package/dist/cli/dev.js +107 -0
  17. package/dist/cli/import.d.ts +3 -0
  18. package/dist/cli/import.js +151 -0
  19. package/dist/cli/index.d.ts +2 -0
  20. package/dist/cli/index.js +47 -0
  21. package/dist/cli/init.d.ts +1 -0
  22. package/dist/cli/init.js +73 -0
  23. package/dist/cli/jsonc.d.ts +2 -0
  24. package/dist/cli/jsonc.js +39 -0
  25. package/dist/engine/actions.d.ts +61 -0
  26. package/dist/engine/actions.js +227 -0
  27. package/dist/engine/balances.d.ts +30 -0
  28. package/dist/engine/balances.js +75 -0
  29. package/dist/engine/categories.d.ts +17 -0
  30. package/dist/engine/categories.js +35 -0
  31. package/dist/engine/check.d.ts +11 -0
  32. package/dist/engine/check.js +229 -0
  33. package/dist/engine/dates.d.ts +15 -0
  34. package/dist/engine/dates.js +56 -0
  35. package/dist/engine/defaults.d.ts +2 -0
  36. package/dist/engine/defaults.js +61 -0
  37. package/dist/engine/index.d.ts +13 -0
  38. package/dist/engine/index.js +13 -0
  39. package/dist/engine/load.d.ts +23 -0
  40. package/dist/engine/load.js +129 -0
  41. package/dist/engine/networth.d.ts +12 -0
  42. package/dist/engine/networth.js +73 -0
  43. package/dist/engine/registry.d.ts +24 -0
  44. package/dist/engine/registry.js +41 -0
  45. package/dist/engine/reports.d.ts +68 -0
  46. package/dist/engine/reports.js +149 -0
  47. package/dist/engine/schedules.d.ts +75 -0
  48. package/dist/engine/schedules.js +208 -0
  49. package/dist/engine/types.d.ts +132 -0
  50. package/dist/engine/types.js +2 -0
  51. package/dist/engine/write.d.ts +30 -0
  52. package/dist/engine/write.js +105 -0
  53. package/dist/import/hash.d.ts +1 -0
  54. package/dist/import/hash.js +17 -0
  55. package/dist/import/index.d.ts +6 -0
  56. package/dist/import/index.js +6 -0
  57. package/dist/import/mapping.d.ts +96 -0
  58. package/dist/import/mapping.js +54 -0
  59. package/dist/import/profile.d.ts +39 -0
  60. package/dist/import/profile.js +125 -0
  61. package/dist/import/run.d.ts +101 -0
  62. package/dist/import/run.js +416 -0
  63. package/dist/import/workbook.d.ts +13 -0
  64. package/dist/import/workbook.js +168 -0
  65. package/dist/import/xlsx-write.d.ts +6 -0
  66. package/dist/import/xlsx-write.js +38 -0
  67. package/dist/node/files.d.ts +3 -0
  68. package/dist/node/files.js +26 -0
  69. package/dist/node/scaffold.d.ts +14 -0
  70. package/dist/node/scaffold.js +45 -0
  71. package/dist/worker/api.d.ts +3 -0
  72. package/dist/worker/api.js +139 -0
  73. package/dist/worker/auth.d.ts +11 -0
  74. package/dist/worker/auth.js +182 -0
  75. package/dist/worker/env.d.ts +27 -0
  76. package/dist/worker/env.js +6 -0
  77. package/dist/worker/github.d.ts +29 -0
  78. package/dist/worker/github.js +154 -0
  79. package/dist/worker/index.d.ts +5 -0
  80. package/dist/worker/index.js +64 -0
  81. package/dist/worker/mcp.d.ts +4 -0
  82. package/dist/worker/mcp.js +301 -0
  83. package/dist/worker/store.d.ts +42 -0
  84. package/dist/worker/store.js +92 -0
  85. package/dist/worker/tar.d.ts +2 -0
  86. package/dist/worker/tar.js +62 -0
  87. package/dist/worker/version.d.ts +1 -0
  88. package/dist/worker/version.js +2 -0
  89. package/package.json +66 -4
  90. package/presets/misa.mapping.yaml +48 -0
  91. package/templates/repo/.github/dependabot.yml +11 -0
  92. package/templates/repo/.github/workflows/check.yml +15 -0
  93. package/templates/repo/.github/workflows/deploy.yml +21 -0
  94. package/templates/repo/README.md +10 -0
@@ -0,0 +1,26 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join, relative, sep } from "node:path";
3
+ /** Reads a data repo's data/ folder into a FileMap (paths relative to the repo root, "/" separators). */
4
+ export function readDataDir(root) {
5
+ const out = {};
6
+ const walk = (dir) => {
7
+ let names;
8
+ try {
9
+ names = readdirSync(dir);
10
+ }
11
+ catch {
12
+ return;
13
+ }
14
+ for (const n of names) {
15
+ if (n.startsWith("."))
16
+ continue;
17
+ const p = join(dir, n);
18
+ if (statSync(p).isDirectory())
19
+ walk(p);
20
+ else
21
+ out[relative(root, p).split(sep).join("/")] = readFileSync(p, "utf8");
22
+ }
23
+ };
24
+ walk(join(root, "data"));
25
+ return out;
26
+ }
@@ -0,0 +1,14 @@
1
+ import type { FileMap } from "../engine/load.js";
2
+ export interface ScaffoldOpts {
3
+ name: string;
4
+ base: string;
5
+ lang: "vi" | "en";
6
+ owner?: string;
7
+ version: string;
8
+ }
9
+ /** Absolute path of a file in the installed ownledger package (works from src/ and dist/). */
10
+ export declare function pkgPath(rel: string): string;
11
+ export declare function readPkgFile(rel: string): string;
12
+ export declare function pkgVersion(): string;
13
+ /** The files `init` writes into a new data repo. */
14
+ export declare function scaffold(o: ScaffoldOpts): FileMap;
@@ -0,0 +1,45 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { stringify } from "yaml";
5
+ import { defaultCategories } from "../engine/defaults.js";
6
+ import { FORMAT } from "../engine/types.js";
7
+ const CURRENCY_NAMES = { VND: "Việt Nam đồng", USD: "US dollar", EUR: "Euro" };
8
+ const DECIMALS = { VND: 0, JPY: 0, KRW: 0 };
9
+ /** Absolute path of a file in the installed ownledger package (works from src/ and dist/). */
10
+ export function pkgPath(rel) {
11
+ return join(dirname(fileURLToPath(import.meta.url)), "..", "..", rel);
12
+ }
13
+ export function readPkgFile(rel) {
14
+ return readFileSync(pkgPath(rel), "utf8");
15
+ }
16
+ export function pkgVersion() {
17
+ return JSON.parse(readPkgFile("package.json")).version;
18
+ }
19
+ /** The files `init` writes into a new data repo. */
20
+ export function scaffold(o) {
21
+ const y = (v) => stringify(v, { lineWidth: 0 });
22
+ const files = {
23
+ "data/meta.yaml": y({ format: FORMAT, base: o.base, locale: o.lang, owner: o.owner ?? null, name: o.name }),
24
+ "data/assets.yaml": y([{ id: o.base, name: CURRENCY_NAMES[o.base] ?? o.base, kind: "currency", decimals: DECIMALS[o.base] ?? 2 }]),
25
+ "data/accounts.yaml": "[]\n",
26
+ "data/categories.yaml": y(defaultCategories(o.lang)),
27
+ "data/plans.yaml": "[]\n",
28
+ "data/budgets.yaml": "[]\n",
29
+ "data/prices.csv": "date,asset,price\n",
30
+ "imports/raw/.gitkeep": "",
31
+ "package.json": JSON.stringify({
32
+ name: o.name,
33
+ private: true,
34
+ type: "module",
35
+ scripts: { check: "ownledger check", import: "ownledger import", deploy: "ownledger deploy", dev: "ownledger dev" },
36
+ dependencies: { ownledger: `^${o.version}` },
37
+ devDependencies: { wrangler: "^4.166.0" },
38
+ }, null, 2) + "\n",
39
+ ".gitignore": "node_modules/\n.wrangler/\n.dev.vars\n.env*\n.DS_Store\n",
40
+ };
41
+ for (const t of ["README.md", ".github/workflows/check.yml", ".github/dependabot.yml"])
42
+ files[t] = readPkgFile(`templates/repo/${t}`).replaceAll("{{name}}", o.name);
43
+ files["AGENTS.md"] = readPkgFile("AGENTS.md");
44
+ return files;
45
+ }
@@ -0,0 +1,3 @@
1
+ import type { Env } from "./env.js";
2
+ /** JSON for the dashboard. Same sign-in allowlist as the connector; read-only except import (Phase 6). */
3
+ export declare function api(req: Request, env: Env): Promise<Response>;
@@ -0,0 +1,139 @@
1
+ import { accountValues } from "../engine/balances.js";
2
+ import { flattenCategories } from "../engine/categories.js";
3
+ import { addMonths, todayIn } from "../engine/dates.js";
4
+ import { netWorth, netWorthSeries } from "../engine/networth.js";
5
+ import { TYPES } from "../engine/registry.js";
6
+ import { queryTransactions, report } from "../engine/reports.js";
7
+ import { budgets, cards, deposits, planStatus, plansDue, today } from "../engine/schedules.js";
8
+ import { checkFiles } from "../engine/check.js";
9
+ import { applyChange } from "../engine/write.js";
10
+ import { parseMapping } from "../import/mapping.js";
11
+ import { runImport } from "../import/run.js";
12
+ import { readWorkbook } from "../import/workbook.js";
13
+ import { sessionLogin } from "./auth.js";
14
+ import { applyPending, savePending, snapshot, sourceFor } from "./store.js";
15
+ import { VERSION } from "./version.js";
16
+ const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
17
+ /** JSON for the dashboard. Same sign-in allowlist as the connector; read-only except import (Phase 6). */
18
+ export async function api(req, env) {
19
+ const login = await sessionLogin(req, env);
20
+ if (!login)
21
+ return json({ error: "sign in", login: "/auth/login" }, 401);
22
+ // same-origin only for anything that changes state
23
+ if (req.method !== "GET" && req.headers.get("Origin") !== new URL(req.url).origin)
24
+ return json({ error: "bad origin" }, 403);
25
+ const url = new URL(req.url);
26
+ const q = url.searchParams;
27
+ const path = url.pathname.slice(5);
28
+ const src = sourceFor(env);
29
+ const s = await snapshot(env, src);
30
+ const L = s.ledger;
31
+ const asOf = q.get("date") ?? todayIn(env.TIMEZONE || "Asia/Ho_Chi_Minh");
32
+ try {
33
+ switch (path) {
34
+ case "me":
35
+ return json({ login, version: VERSION, data: src.label, commit: s.sha, base: L.meta.base, locale: L.meta.locale ?? "en", name: L.meta.name, today: asOf, check: { errors: s.errors, warnings: s.warnings } });
36
+ case "meta": {
37
+ const { map } = flattenCategories(L.categories);
38
+ return json({
39
+ base: L.meta.base,
40
+ locale: L.meta.locale,
41
+ types: Object.fromEntries(Object.entries(TYPES).map(([k, v]) => [k, v.label])),
42
+ categories: [...map.values()],
43
+ accounts: L.accounts.map((a) => ({ id: a.id, name: a.name, type: a.type, closed: a.closed ?? null, group: a.group ?? null })),
44
+ assets: L.assets,
45
+ });
46
+ }
47
+ case "overview": {
48
+ const m = report(L, asOf.slice(0, 7));
49
+ return json({ today: today(L, asOf), month: { income: m.income, expense: m.expense, net: m.net, previous: m.previous, top: m.rows.filter((r) => r.expense).slice(0, 8) }, netWorth: netWorth(L, asOf), series: netWorthSeries(L, addMonths(asOf.slice(0, 7) + "-01", -11), asOf) });
50
+ }
51
+ case "accounts":
52
+ return json(accountValues(L, asOf).map((v) => ({ ...v.account, value: v.value, cost: v.cost, qty: v.qty, asset: v.asset, priced: v.priced, price: v.price })));
53
+ case "transactions": {
54
+ const n = (k) => (q.get(k) ? Number(q.get(k)) : undefined);
55
+ const r = queryTransactions(L, {
56
+ from: q.get("from") ?? undefined,
57
+ to: q.get("to") ?? undefined,
58
+ account: q.get("account") ?? undefined,
59
+ category: q.get("category") ?? undefined,
60
+ text: q.get("text") ?? undefined,
61
+ min: n("min"),
62
+ max: n("max"),
63
+ includeVoid: q.get("void") === "1",
64
+ offset: n("offset"),
65
+ limit: n("limit") ?? 100,
66
+ });
67
+ return json(r);
68
+ }
69
+ case "report": {
70
+ const period = q.get("from") && q.get("to") ? { from: q.get("from"), to: q.get("to") } : (q.get("period") ?? asOf.slice(0, 7));
71
+ return json(report(L, period, { by: (q.get("by") ?? "top"), kind: q.get("kind") ?? undefined, category: q.get("category") ?? undefined }));
72
+ }
73
+ case "networth":
74
+ return json(netWorthSeries(L, q.get("from") ?? addMonths(asOf.slice(0, 7) + "-01", -23), asOf));
75
+ case "plans":
76
+ return json({ status: planStatus(L, asOf), due: plansDue(L, asOf, Number(q.get("days") ?? 60)), plans: L.plans });
77
+ case "cards":
78
+ return json(cards(L, asOf));
79
+ case "deposits":
80
+ return json(deposits(L, asOf));
81
+ case "budgets":
82
+ return json(budgets(L, asOf));
83
+ case "import/mappings":
84
+ return json(Object.keys(s.files).filter((p) => /^imports\/[^/]+\.mapping\.yaml$/.test(p)));
85
+ case "import/preview": {
86
+ if (req.method !== "POST")
87
+ return json({ error: "POST" }, 405);
88
+ const body = (await req.json());
89
+ const maps = Object.keys(s.files).filter((p) => /^imports\/[^/]+\.mapping\.yaml$/.test(p));
90
+ const mp = body.mapping ?? (maps.length === 1 ? maps[0] : undefined);
91
+ if (!mp || !s.files[mp])
92
+ return json({ error: maps.length ? "choose a mapping" : "no mapping in imports/: do the first import of a new app with the CLI and your AI (see AGENTS.md)", mappings: maps }, 400);
93
+ const bytes = Uint8Array.from(atob(body.base64), (c) => c.charCodeAt(0));
94
+ const r = runImport(readWorkbook(body.file_name, bytes), parseMapping(s.files[mp]), L);
95
+ const report = {
96
+ ok: r.ok, source: r.source, rows: r.rows, new: r.transactions.length, skipped: r.skipped, accounts: r.accounts.map((a) => `${a.id} (${a.type})`),
97
+ reconcile: r.reconcile, rounding: r.rounding, zeroed: r.zeroed, unpaired: r.unpaired.map((u) => ({ sheet: u.sheet, row: u.row, date: u.date, amount: u.amount, note: u.note })),
98
+ unresolvedCategories: r.unresolvedCategories, unresolvedRows: r.unresolvedRows.slice(0, 50).map((u) => ({ sheet: u.sheet, row: u.row, date: u.date, amount: u.amount, note: u.note })),
99
+ changed: r.changed, gone: r.gone, replace: r.replace.length, errors: r.errors,
100
+ sample: r.transactions.slice(0, 20),
101
+ };
102
+ if (!r.ok || (!r.transactions.length && !r.accounts.length && !r.replace.length))
103
+ return json({ report });
104
+ const changed = applyChange(s.files, { addAccounts: r.accounts, addTransactions: r.transactions, replaceTransactions: r.replace });
105
+ const c = checkFiles({ ...s.files, ...changed });
106
+ if (!c.ok)
107
+ return json({ report: { ...report, ok: false, errors: c.errors.slice(0, 20).map((e) => e.message) } });
108
+ const stamp = asOf.replace(/-/g, "");
109
+ const safe = body.file_name.replace(/[^A-Za-z0-9._-]/g, "_").slice(-80);
110
+ const message = `Import ${r.source}: ${r.transactions.length} transaction(s)${r.accounts.length ? `, ${r.accounts.length} account(s)` : ""} (dashboard)`;
111
+ const id = await savePending(env, { baseSha: s.sha, files: changed, binary: [{ path: `imports/raw/${stamp}-${safe}`, base64: body.base64 }], message, summary: [message], created: new Date().toISOString() });
112
+ return json({ report, preview_id: id, message });
113
+ }
114
+ case "import/apply": {
115
+ if (req.method !== "POST")
116
+ return json({ error: "POST" }, 405);
117
+ const { preview_id } = (await req.json());
118
+ return json(await applyPending(env, src, preview_id));
119
+ }
120
+ case "grants": {
121
+ if (req.method === "DELETE") {
122
+ const id = q.get("id");
123
+ if (!id)
124
+ return json({ error: "id" }, 400);
125
+ await env.OAUTH_PROVIDER.revokeGrant(id, login);
126
+ return json({ revoked: id });
127
+ }
128
+ const g = await env.OAUTH_PROVIDER.listUserGrants(login);
129
+ const clients = await Promise.all(g.items.map((x) => env.OAUTH_PROVIDER.lookupClient(x.clientId).catch(() => null)));
130
+ return json(g.items.map((x, i) => ({ id: x.id, client: clients[i]?.clientName ?? x.clientId, scope: x.scope, created: x.createdAt })));
131
+ }
132
+ default:
133
+ return json({ error: "not found" }, 404);
134
+ }
135
+ }
136
+ catch (e) {
137
+ return json({ error: e.message }, 400);
138
+ }
139
+ }
@@ -0,0 +1,11 @@
1
+ import { type Env } from "./env.js";
2
+ export declare function esc(s: string): string;
3
+ export declare function page(title: string, body: string, status?: number, headers?: Headers): Response;
4
+ /** The dashboard's signed-in login, or null. */
5
+ export declare function sessionLogin(req: Request, env: Env): Promise<string | null>;
6
+ export declare function authorizeGet(req: Request, env: Env): Promise<Response>;
7
+ export declare function authorizePost(req: Request, env: Env): Promise<Response>;
8
+ export declare function oauthCallback(req: Request, env: Env): Promise<Response>;
9
+ export declare function dashboardLogin(req: Request, env: Env): Promise<Response>;
10
+ export declare function dashboardCallback(req: Request, env: Env): Promise<Response>;
11
+ export declare function dashboardLogout(): Response;
@@ -0,0 +1,182 @@
1
+ import { AuthorizationError, authorizationErrorRedirect } from "@cloudflare/workers-oauth-provider";
2
+ import { allowed } from "./env.js";
3
+ import { githubAuthorizeUrl, githubLogin, randomToken, s256 } from "./github.js";
4
+ /* ------------------------------------------------------------------ html */
5
+ const CSP = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self' https://github.com";
6
+ export function esc(s) {
7
+ return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
8
+ }
9
+ export function page(title, body, status = 200, headers = new Headers()) {
10
+ headers.set("Content-Type", "text/html; charset=utf-8");
11
+ headers.set("Content-Security-Policy", CSP);
12
+ headers.set("X-Frame-Options", "DENY");
13
+ headers.set("Cache-Control", "no-store");
14
+ headers.set("Referrer-Policy", "no-referrer");
15
+ return new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title>
16
+ <style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:10vh auto;padding:0 1rem;color:#1a1a1a;background:#fafafa}h1{font-size:1.3rem}
17
+ .card{background:#fff;border:1px solid #e5e5e5;border-radius:12px;padding:1.5rem}button{font:inherit;padding:.6rem 1.1rem;border-radius:8px;border:1px solid #ccc;background:#fff;cursor:pointer}
18
+ button.primary{background:#1a1a1a;color:#fff;border-color:#1a1a1a}.muted{color:#666;font-size:.9rem}code{background:#f0f0f0;padding:0 .3rem;border-radius:4px}</style></head>
19
+ <body><div class="card">${body}</div></body></html>`, { status, headers });
20
+ }
21
+ /* ------------------------------------------------------------------ signed cookies */
22
+ async function hmac(secret, data) {
23
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
24
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data)));
25
+ return btoa(String.fromCharCode(...sig)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
26
+ }
27
+ async function seal(secret, value) {
28
+ const body = btoa(unescape(encodeURIComponent(JSON.stringify(value)))).replace(/=+$/, "");
29
+ return `${body}.${await hmac(secret, body)}`;
30
+ }
31
+ async function unseal(secret, token) {
32
+ if (!token)
33
+ return null;
34
+ const [body, sig] = token.split(".");
35
+ if (!body || !sig)
36
+ return null;
37
+ const want = await hmac(secret, body);
38
+ if (want.length !== sig.length)
39
+ return null;
40
+ let diff = 0;
41
+ for (let i = 0; i < want.length; i++)
42
+ diff |= want.charCodeAt(i) ^ sig.charCodeAt(i);
43
+ if (diff)
44
+ return null;
45
+ try {
46
+ const v = JSON.parse(decodeURIComponent(escape(atob(body))));
47
+ if (v.exp && v.exp < Date.now() / 1000)
48
+ return null;
49
+ return v;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ function cookie(req, name) {
56
+ const c = req.headers.get("Cookie") ?? "";
57
+ for (const part of c.split(/;\s*/)) {
58
+ const i = part.indexOf("=");
59
+ if (i > 0 && part.slice(0, i) === name)
60
+ return part.slice(i + 1);
61
+ }
62
+ return undefined;
63
+ }
64
+ const SESSION = "__Host-ol_session";
65
+ const LOGIN_STATE = "__Host-ol_login";
66
+ const SESSION_DAYS = 14;
67
+ function setCookie(name, value, maxAge) {
68
+ return `${name}=${value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
69
+ }
70
+ /** The dashboard's signed-in login, or null. */
71
+ export async function sessionLogin(req, env) {
72
+ if (env.DEV_LOGIN)
73
+ return env.DEV_LOGIN;
74
+ const s = await unseal(env.COOKIE_SECRET, cookie(req, SESSION));
75
+ return s && allowed(env, s.login) ? s.login : null;
76
+ }
77
+ /* ------------------------------------------------------------------ MCP client authorization (/authorize) */
78
+ /** The registered app's name, kept in the token props so writes can say which app made them. */
79
+ async function clientName(oauth, clientId) {
80
+ const c = await oauth.lookupClient(clientId).catch(() => null);
81
+ const name = (c?.clientName || clientId || "").slice(0, 60);
82
+ return name ? { client: name } : {};
83
+ }
84
+ export async function authorizeGet(req, env) {
85
+ const oauth = env.OAUTH_PROVIDER;
86
+ let request;
87
+ try {
88
+ request = await oauth.parseAuthRequest(req);
89
+ }
90
+ catch (e) {
91
+ if (e instanceof AuthorizationError && e.redirectUri && e.redirectTo)
92
+ return Response.redirect(e.redirectTo, 302);
93
+ return page("Can't connect", `<h1>Can't connect</h1><p>${esc(e.message)}</p>`, 400);
94
+ }
95
+ const d = await oauth.describeConsent(request);
96
+ const consent = await oauth.beginConsent(request);
97
+ return page("Connect to your ledger", `<h1>Connect <b>${esc(d.clientName || d.clientId)}</b> to your ledger?</h1>
98
+ <p>It will be able to <b>read</b> your finances and <b>propose changes</b>; every change still needs your go in the chat before it is committed.</p>
99
+ <p class="muted">Sends you back to <code>${esc(d.redirectHost)}</code>. You'll sign in with GitHub${env.DEV_LOGIN ? " (dev: skipped)" : ""}; only ${esc(env.ALLOWED_LOGINS)} can.</p>
100
+ <form method="post" action="/authorize"><input type="hidden" name="handle" value="${esc(consent.handle)}">
101
+ <button class="primary" name="decision" value="approve">Allow</button> <button name="decision" value="deny">Deny</button></form>`, 200, consent.headers);
102
+ }
103
+ export async function authorizePost(req, env) {
104
+ const oauth = env.OAUTH_PROVIDER;
105
+ const form = await req.formData();
106
+ const handle = String(form.get("handle") ?? "");
107
+ try {
108
+ if (form.get("decision") !== "approve") {
109
+ const denied = await oauth.denyConsent(req, handle);
110
+ return new Response(null, { status: 302, headers: denied.headers });
111
+ }
112
+ const approved = await oauth.approveConsent(req, handle);
113
+ if (env.DEV_LOGIN) {
114
+ const { redirectTo } = await oauth.completeAuthorization({ request: approved.request, userId: env.DEV_LOGIN, metadata: { login: env.DEV_LOGIN }, scope: approved.request.scope, props: { login: env.DEV_LOGIN, ...(await clientName(oauth, approved.request.clientId)) } });
115
+ approved.headers.set("Location", redirectTo);
116
+ return new Response(null, { status: 302, headers: approved.headers });
117
+ }
118
+ const verifier = randomToken(32);
119
+ const { state, headers } = await oauth.beginUpstream(approved.request, { data: { verifier }, headers: approved.headers });
120
+ headers.set("Location", githubAuthorizeUrl(env.GITHUB_CLIENT_ID, new URL("/oauth/callback", req.url).toString(), state, await s256(verifier)));
121
+ return new Response(null, { status: 302, headers });
122
+ }
123
+ catch (e) {
124
+ if (e instanceof AuthorizationError)
125
+ return page("Expired", `<h1>This page expired</h1><p>${esc(e.message)}</p><p>Start again from your AI app.</p>`, 400);
126
+ throw e;
127
+ }
128
+ }
129
+ export async function oauthCallback(req, env) {
130
+ const oauth = env.OAUTH_PROVIDER;
131
+ let resumed;
132
+ try {
133
+ resumed = await oauth.finishUpstream(req);
134
+ }
135
+ catch (e) {
136
+ if (e instanceof AuthorizationError)
137
+ return page("Expired", `<h1>Sign-in expired</h1><p>${esc(e.message)}</p><p>Start again from your AI app.</p>`, 400);
138
+ throw e;
139
+ }
140
+ const url = new URL(req.url);
141
+ const deny = (why) => {
142
+ resumed.headers.set("Location", authorizationErrorRedirect(resumed.request, "access_denied", why));
143
+ return new Response(null, { status: 302, headers: resumed.headers });
144
+ };
145
+ if (url.searchParams.get("error"))
146
+ return deny("GitHub sign-in was declined");
147
+ const login = await githubLogin(env.GITHUB_CLIENT_ID, env.GITHUB_CLIENT_SECRET, url.searchParams.get("code") ?? "", resumed.data.verifier, new URL("/oauth/callback", req.url).toString());
148
+ if (!allowed(env, login))
149
+ return deny(`${login} is not allowed on this ledger`);
150
+ const { redirectTo } = await oauth.completeAuthorization({ request: resumed.request, userId: login, metadata: { login }, scope: resumed.request.scope, props: { login, ...(await clientName(oauth, resumed.request.clientId)) } });
151
+ resumed.headers.set("Location", redirectTo);
152
+ return new Response(null, { status: 302, headers: resumed.headers });
153
+ }
154
+ /* ------------------------------------------------------------------ dashboard sign-in */
155
+ export async function dashboardLogin(req, env) {
156
+ if (env.DEV_LOGIN)
157
+ return Response.redirect(new URL("/", req.url).toString(), 302);
158
+ const state = randomToken(16);
159
+ const verifier = randomToken(32);
160
+ const sealed = await seal(env.COOKIE_SECRET, { state, verifier, exp: Math.floor(Date.now() / 1000) + 600 });
161
+ const headers = new Headers({ Location: githubAuthorizeUrl(env.GITHUB_CLIENT_ID, new URL("/auth/callback", req.url).toString(), state, await s256(verifier)) });
162
+ headers.append("Set-Cookie", setCookie(LOGIN_STATE, sealed, 600));
163
+ return new Response(null, { status: 302, headers });
164
+ }
165
+ export async function dashboardCallback(req, env) {
166
+ const url = new URL(req.url);
167
+ const st = await unseal(env.COOKIE_SECRET, cookie(req, LOGIN_STATE));
168
+ if (!st || st.state !== url.searchParams.get("state"))
169
+ return page("Sign-in expired", `<h1>Sign-in expired</h1><p><a href="/auth/login">Try again</a></p>`, 400);
170
+ const login = await githubLogin(env.GITHUB_CLIENT_ID, env.GITHUB_CLIENT_SECRET, url.searchParams.get("code") ?? "", st.verifier, new URL("/auth/callback", req.url).toString());
171
+ if (!allowed(env, login))
172
+ return page("Not allowed", `<h1>Not allowed</h1><p><code>${esc(login)}</code> can't open this ledger.</p>`, 403);
173
+ const headers = new Headers({ Location: "/" });
174
+ headers.append("Set-Cookie", setCookie(SESSION, await seal(env.COOKIE_SECRET, { login, exp: Math.floor(Date.now() / 1000) + SESSION_DAYS * 86400 }), SESSION_DAYS * 86400));
175
+ headers.append("Set-Cookie", setCookie(LOGIN_STATE, "", 0));
176
+ return new Response(null, { status: 302, headers });
177
+ }
178
+ export function dashboardLogout() {
179
+ const headers = new Headers({ Location: "/" });
180
+ headers.append("Set-Cookie", setCookie(SESSION, "", 0));
181
+ return new Response(null, { status: 302, headers });
182
+ }
@@ -0,0 +1,27 @@
1
+ import type { OAuthHelpers } from "@cloudflare/workers-oauth-provider";
2
+ export interface Env {
3
+ OAUTH_KV: KVNamespace;
4
+ OAUTH_PROVIDER: OAuthHelpers;
5
+ ASSETS?: Fetcher;
6
+ /** https://<worker>.<subdomain>.workers.dev (or the custom domain), no trailing slash */
7
+ PUBLIC_URL: string;
8
+ /** owner/name of the private data repo */
9
+ DATA_REPO: string;
10
+ DATA_BRANCH?: string;
11
+ /** GitHub logins allowed to sign in, comma-separated */
12
+ ALLOWED_LOGINS: string;
13
+ TIMEZONE?: string;
14
+ GITHUB_APP_ID: string;
15
+ GITHUB_APP_PRIVATE_KEY: string;
16
+ GITHUB_CLIENT_ID: string;
17
+ GITHUB_CLIENT_SECRET: string;
18
+ COOKIE_SECRET: string;
19
+ DEV_DATA_URL?: string;
20
+ DEV_LOGIN?: string;
21
+ }
22
+ export interface Props {
23
+ login: string;
24
+ /** The connected app's name (from its OAuth registration), recorded on writes. Missing on tokens issued before 1.1.0. */
25
+ client?: string;
26
+ }
27
+ export declare function allowed(env: Env, login: string): boolean;
@@ -0,0 +1,6 @@
1
+ export function allowed(env, login) {
2
+ return env.ALLOWED_LOGINS.split(",")
3
+ .map((s) => s.trim().toLowerCase())
4
+ .filter(Boolean)
5
+ .includes(login.toLowerCase());
6
+ }
@@ -0,0 +1,29 @@
1
+ export declare class MainMovedError extends Error {
2
+ constructor();
3
+ }
4
+ /** GitHub hands out PKCS#1 ("BEGIN RSA PRIVATE KEY"); WebCrypto wants PKCS#8. Wrap it. */
5
+ export declare function pemToPkcs8(pem: string): Uint8Array;
6
+ export declare function appJwt(appId: string, pem: string, now?: number): Promise<string>;
7
+ export interface GitHubAppConfig {
8
+ appId: string;
9
+ privateKey: string;
10
+ repo: string;
11
+ branch: string;
12
+ }
13
+ export declare function installationToken(c: GitHubAppConfig): Promise<string>;
14
+ export declare function headSha(c: GitHubAppConfig): Promise<string>;
15
+ /** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball. */
16
+ export declare function filesAt(c: GitHubAppConfig, sha: string): Promise<Record<string, string>>;
17
+ export interface CommitFile {
18
+ path: string;
19
+ content?: string;
20
+ base64?: string;
21
+ delete?: boolean;
22
+ }
23
+ /** One atomic commit on top of `baseSha`; refused (MainMovedError) if the branch moved. */
24
+ export declare function commit(c: GitHubAppConfig, baseSha: string, files: CommitFile[], message: string): Promise<string>;
25
+ export declare function githubAuthorizeUrl(clientId: string, redirectUri: string, state: string, codeChallenge: string): string;
26
+ /** Exchanges the code, reads the login, then revokes the user token: it is never kept. */
27
+ export declare function githubLogin(clientId: string, clientSecret: string, code: string, verifier: string, redirectUri: string): Promise<string>;
28
+ export declare function s256(verifier: string): Promise<string>;
29
+ export declare function randomToken(bytes?: number): string;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The Worker's only network peer: GitHub's API, through the user's own GitHub App.
3
+ * Installation tokens are short-lived and limited to the one data repo.
4
+ */
5
+ const API = "https://api.github.com";
6
+ const UA = "ownledger-worker";
7
+ export class MainMovedError extends Error {
8
+ constructor() {
9
+ super("main moved since the preview (someone else committed). Preview again.");
10
+ }
11
+ }
12
+ /* ------------------------------------------------------------------ keys and JWT */
13
+ const b64url = (b) => btoa(String.fromCharCode(...new Uint8Array(b instanceof Uint8Array ? b : new Uint8Array(b)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
14
+ const b64urlStr = (s) => b64url(new TextEncoder().encode(s));
15
+ function derLen(n) {
16
+ if (n < 0x80)
17
+ return [n];
18
+ const out = [];
19
+ while (n > 0) {
20
+ out.unshift(n & 0xff);
21
+ n >>= 8;
22
+ }
23
+ return [0x80 | out.length, ...out];
24
+ }
25
+ /** GitHub hands out PKCS#1 ("BEGIN RSA PRIVATE KEY"); WebCrypto wants PKCS#8. Wrap it. */
26
+ export function pemToPkcs8(pem) {
27
+ const body = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
28
+ const der = Uint8Array.from(atob(body), (c) => c.charCodeAt(0));
29
+ if (!/BEGIN RSA PRIVATE KEY/.test(pem))
30
+ return der;
31
+ const algo = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00];
32
+ const octet = [0x04, ...derLen(der.length), ...der];
33
+ const inner = [0x02, 0x01, 0x00, ...algo, ...octet];
34
+ return new Uint8Array([0x30, ...derLen(inner.length), ...inner]);
35
+ }
36
+ let keyCache = null;
37
+ export async function appJwt(appId, pem, now = Math.floor(Date.now() / 1000)) {
38
+ if (!keyCache || keyCache.pem !== pem) {
39
+ const key = await crypto.subtle.importKey("pkcs8", pemToPkcs8(pem), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);
40
+ keyCache = { pem, key };
41
+ }
42
+ const head = b64urlStr(JSON.stringify({ alg: "RS256", typ: "JWT" }));
43
+ const body = b64urlStr(JSON.stringify({ iat: now - 60, exp: now + 540, iss: appId }));
44
+ const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", keyCache.key, new TextEncoder().encode(`${head}.${body}`));
45
+ return `${head}.${body}.${b64url(sig)}`;
46
+ }
47
+ let tokenCache = null;
48
+ async function gh(path, token, init = {}) {
49
+ const res = await fetch(path.startsWith("http") ? path : `${API}${path}`, {
50
+ ...init,
51
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": UA, "X-GitHub-Api-Version": "2022-11-28", ...(init.headers ?? {}) },
52
+ });
53
+ return res;
54
+ }
55
+ async function ok(res, what) {
56
+ if (!res.ok)
57
+ throw new Error(`GitHub ${what}: ${res.status} ${(await res.text()).slice(0, 300)}`);
58
+ return (await res.json());
59
+ }
60
+ export async function installationToken(c) {
61
+ const now = Date.now();
62
+ if (tokenCache && tokenCache.repo === c.repo && tokenCache.exp - now > 5 * 60_000)
63
+ return tokenCache.token;
64
+ const jwt = await appJwt(c.appId, c.privateKey);
65
+ const inst = await ok(await gh(`/repos/${c.repo}/installation`, jwt), "find the app's installation on the data repo");
66
+ const name = c.repo.split("/")[1];
67
+ const t = await ok(await gh(`/app/installations/${inst.id}/access_tokens`, jwt, { method: "POST", body: JSON.stringify({ repositories: [name] }) }), "create an installation token");
68
+ tokenCache = { repo: c.repo, token: t.token, exp: Date.parse(t.expires_at) };
69
+ return t.token;
70
+ }
71
+ export async function headSha(c) {
72
+ const token = await installationToken(c);
73
+ const res = await gh(`/repos/${c.repo}/commits/${encodeURIComponent(c.branch)}`, token, { headers: { Accept: "application/vnd.github.sha" } });
74
+ if (!res.ok)
75
+ throw new Error(`GitHub head of ${c.branch}: ${res.status}`);
76
+ return (await res.text()).trim();
77
+ }
78
+ /** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball. */
79
+ export async function filesAt(c, sha) {
80
+ const token = await installationToken(c);
81
+ const res = await gh(`/repos/${c.repo}/tarball/${sha}`, token);
82
+ if (!res.ok || !res.body)
83
+ throw new Error(`GitHub tarball: ${res.status}`);
84
+ const { untar } = await import("./tar.js");
85
+ return untar(res.body.pipeThrough(new DecompressionStream("gzip")), (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p));
86
+ }
87
+ /** One atomic commit on top of `baseSha`; refused (MainMovedError) if the branch moved. */
88
+ export async function commit(c, baseSha, files, message) {
89
+ const token = await installationToken(c);
90
+ const base = await ok(await gh(`/repos/${c.repo}/git/commits/${baseSha}`, token), "read the base commit");
91
+ const tree = [];
92
+ for (const f of files) {
93
+ if (f.delete)
94
+ tree.push({ path: f.path, mode: "100644", type: "blob", sha: null });
95
+ else if (f.base64 !== undefined) {
96
+ const blob = await ok(await gh(`/repos/${c.repo}/git/blobs`, token, { method: "POST", body: JSON.stringify({ content: f.base64, encoding: "base64" }) }), "upload a file");
97
+ tree.push({ path: f.path, mode: "100644", type: "blob", sha: blob.sha });
98
+ }
99
+ else
100
+ tree.push({ path: f.path, mode: "100644", type: "blob", content: f.content ?? "" });
101
+ }
102
+ const t = await ok(await gh(`/repos/${c.repo}/git/trees`, token, { method: "POST", body: JSON.stringify({ base_tree: base.tree.sha, tree }) }), "write the tree");
103
+ const cm = await ok(await gh(`/repos/${c.repo}/git/commits`, token, { method: "POST", body: JSON.stringify({ message, tree: t.sha, parents: [baseSha] }) }), "write the commit");
104
+ const ref = await gh(`/repos/${c.repo}/git/refs/heads/${encodeURIComponent(c.branch)}`, token, {
105
+ method: "PATCH",
106
+ body: JSON.stringify({ sha: cm.sha, force: false }),
107
+ });
108
+ if (ref.status === 422 || ref.status === 409)
109
+ throw new MainMovedError();
110
+ if (!ref.ok)
111
+ throw new Error(`GitHub update ${c.branch}: ${ref.status} ${(await ref.text()).slice(0, 200)}`);
112
+ return cm.sha;
113
+ }
114
+ /* ------------------------------------------------------------------ user sign-in (GitHub App user auth) */
115
+ export function githubAuthorizeUrl(clientId, redirectUri, state, codeChallenge) {
116
+ const u = new URL("https://github.com/login/oauth/authorize");
117
+ u.searchParams.set("client_id", clientId);
118
+ u.searchParams.set("redirect_uri", redirectUri);
119
+ u.searchParams.set("state", state);
120
+ u.searchParams.set("code_challenge", codeChallenge);
121
+ u.searchParams.set("code_challenge_method", "S256");
122
+ u.searchParams.set("allow_signup", "false");
123
+ return u.toString();
124
+ }
125
+ /** Exchanges the code, reads the login, then revokes the user token: it is never kept. */
126
+ export async function githubLogin(clientId, clientSecret, code, verifier, redirectUri) {
127
+ const res = await fetch("https://github.com/login/oauth/access_token", {
128
+ method: "POST",
129
+ headers: { Accept: "application/json", "Content-Type": "application/json", "User-Agent": UA },
130
+ body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, code, code_verifier: verifier, redirect_uri: redirectUri }),
131
+ });
132
+ const t = (await res.json());
133
+ if (!t.access_token)
134
+ throw new Error(`GitHub sign-in failed: ${t.error_description ?? t.error ?? res.status}`);
135
+ try {
136
+ const u = await ok(await gh("/user", t.access_token), "read the signed-in user");
137
+ return u.login;
138
+ }
139
+ finally {
140
+ await fetch(`${API}/applications/${clientId}/token`, {
141
+ method: "DELETE",
142
+ headers: { Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`, Accept: "application/vnd.github+json", "User-Agent": UA },
143
+ body: JSON.stringify({ access_token: t.access_token }),
144
+ }).catch(() => undefined);
145
+ }
146
+ }
147
+ export async function s256(verifier) {
148
+ return b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
149
+ }
150
+ export function randomToken(bytes = 32) {
151
+ const b = new Uint8Array(bytes);
152
+ crypto.getRandomValues(b);
153
+ return b64url(b);
154
+ }