zero-debt 0.0.0-stage → 2.2.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 +249 -3
- package/lib/claude.js +148 -0
- package/package.json +18 -6
- package/public/css/zero.css +341 -0
- package/public/fonts/OFL-hanken-grotesk.txt +93 -0
- package/public/fonts/OFL-jetbrains-mono.txt +93 -0
- package/public/fonts/hanken-grotesk.woff2 +0 -0
- package/public/fonts/jetbrains-mono.woff2 +0 -0
- package/public/index.html +245 -0
- package/public/js/analysis.js +62 -0
- package/public/js/api.js +88 -0
- package/public/js/categorize.js +69 -0
- package/public/js/charts.js +173 -0
- package/public/js/demo.js +84 -0
- package/public/js/format.js +38 -0
- package/public/js/importers.js +251 -0
- package/public/js/insights.js +137 -0
- package/public/js/keys.js +50 -0
- package/public/js/main.js +946 -0
- package/public/js/palette.js +67 -0
- package/public/js/payoff.js +143 -0
- package/public/js/progress.js +91 -0
- package/public/js/settings.js +112 -0
- package/public/js/state.js +130 -0
- package/public/og.png +0 -0
- package/server.js +314 -0
package/server.js
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// server.js — zero's local server. No dependencies: just Node 22+.
|
|
3
|
+
//
|
|
4
|
+
// npx zero-debt → http://localhost:4321 (or: npm start in a clone)
|
|
5
|
+
// npx zero-debt --help flags and environment variables
|
|
6
|
+
//
|
|
7
|
+
// What it does:
|
|
8
|
+
// • serves the app from ./public
|
|
9
|
+
// • keeps your data as plain JSON files in ./data (state.json, settings.json)
|
|
10
|
+
// • keeps your Anthropic API key in ./data/secrets.json (owner-only permissions),
|
|
11
|
+
// and never sends it back to the browser
|
|
12
|
+
// • calls Claude for the two jobs in lib/claude.js
|
|
13
|
+
//
|
|
14
|
+
// It only listens on 127.0.0.1, and every /api request must come from this app's own
|
|
15
|
+
// page (Host, Origin and a custom header are checked), so other websites you visit
|
|
16
|
+
// can't read your data or spend your key.
|
|
17
|
+
//
|
|
18
|
+
// Flags and environment (all optional; flags win):
|
|
19
|
+
// --port, ZERO_PORT default 4321
|
|
20
|
+
// --data, ZERO_DATA_DIR default ./data in a clone, ~/.zero when run with npx
|
|
21
|
+
// ANTHROPIC_API_KEY use this key instead of the one saved from the app
|
|
22
|
+
// ZERO_MODEL override the model chosen in settings
|
|
23
|
+
|
|
24
|
+
import http from 'node:http';
|
|
25
|
+
import { readFile, writeFile, rename, mkdir, unlink, chmod, stat, copyFile } from 'node:fs/promises';
|
|
26
|
+
import { realpathSync } from 'node:fs';
|
|
27
|
+
import { createHash } from 'node:crypto';
|
|
28
|
+
import { join, normalize, extname, dirname, relative, isAbsolute } from 'node:path';
|
|
29
|
+
import { homedir } from 'node:os';
|
|
30
|
+
import { fileURLToPath } from 'node:url';
|
|
31
|
+
import { runJob, verifyKey, checkPayload, DEFAULT_MODEL } from './lib/claude.js';
|
|
32
|
+
|
|
33
|
+
const ROOT = dirname(fileURLToPath(import.meta.url));
|
|
34
|
+
const PUBLIC = join(ROOT, 'public');
|
|
35
|
+
|
|
36
|
+
/** --name value or --name=value from the command line. */
|
|
37
|
+
function flag(name) {
|
|
38
|
+
const args = process.argv.slice(2);
|
|
39
|
+
const i = args.findIndex((a) => a === `--${name}` || a.startsWith(`--${name}=`));
|
|
40
|
+
if (i === -1) return undefined;
|
|
41
|
+
return args[i].includes('=') ? args[i].split('=').slice(1).join('=') : args[i + 1];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Run from a clone, data lives next to the code in ./data. Run through npx or a global
|
|
45
|
+
// install, the code sits in npm's cache, which can be wiped at any time, so data goes to
|
|
46
|
+
// ~/.zero instead.
|
|
47
|
+
const installedByNpm = /[\\/](node_modules|_npx)[\\/]/.test(ROOT);
|
|
48
|
+
const DATA = flag('data') || process.env.ZERO_DATA_DIR || (installedByNpm ? join(homedir(), '.zero') : join(ROOT, 'data'));
|
|
49
|
+
const PORT = Number(flag('port') || process.env.ZERO_PORT) || 4321;
|
|
50
|
+
const HOST = '127.0.0.1';
|
|
51
|
+
const VERSION = '2.2.0';
|
|
52
|
+
|
|
53
|
+
const DATA_FILES = { state: 'state.json', settings: 'settings.json' };
|
|
54
|
+
const SECRETS = 'secrets.json';
|
|
55
|
+
const MAX_JSON = 2 * 1024 * 1024; // state / settings
|
|
56
|
+
const MAX_UPLOAD = 12 * 1024 * 1024; // a ~9 MB statement once base64'd
|
|
57
|
+
|
|
58
|
+
const MIME = {
|
|
59
|
+
'.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
60
|
+
'.json': 'application/json', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.txt': 'text/plain; charset=utf-8',
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const SECURITY_HEADERS = {
|
|
64
|
+
'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
|
|
65
|
+
'x-content-type-options': 'nosniff',
|
|
66
|
+
'referrer-policy': 'no-referrer',
|
|
67
|
+
'cross-origin-opener-policy': 'same-origin',
|
|
68
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
69
|
+
'permissions-policy': 'camera=(), microphone=(), geolocation=(), payment=()',
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/* ---------- small helpers ---------- */
|
|
73
|
+
|
|
74
|
+
function send(res, status, body, type = 'application/json') {
|
|
75
|
+
const isJson = type === 'application/json';
|
|
76
|
+
res.writeHead(status, { ...SECURITY_HEADERS, 'content-type': type, 'cache-control': 'no-store' });
|
|
77
|
+
res.end(isJson ? JSON.stringify(body) : body);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function readBody(req, limit) {
|
|
81
|
+
const chunks = [];
|
|
82
|
+
let size = 0;
|
|
83
|
+
for await (const chunk of req) {
|
|
84
|
+
size += chunk.length;
|
|
85
|
+
if (size > limit) throw Object.assign(new Error('too large'), { status: 413 });
|
|
86
|
+
chunks.push(chunk);
|
|
87
|
+
}
|
|
88
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Reads a data file. Resolves to { value, rev }: value is null when the file doesn't exist,
|
|
93
|
+
* rev is a short hash of its bytes (or 'none'), used to catch writes from a stale tab.
|
|
94
|
+
* Throws { invalid: true } when the file exists but isn't valid JSON, so nothing overwrites it.
|
|
95
|
+
*/
|
|
96
|
+
async function readData(name) {
|
|
97
|
+
let text;
|
|
98
|
+
try { text = await readFile(join(DATA, name), 'utf8'); } catch (e) {
|
|
99
|
+
if (e.code === 'ENOENT') return { value: null, rev: 'none' };
|
|
100
|
+
throw e;
|
|
101
|
+
}
|
|
102
|
+
const rev = createHash('sha256').update(text).digest('hex').slice(0, 16);
|
|
103
|
+
try { return { value: JSON.parse(text), rev }; } catch (e) {
|
|
104
|
+
throw Object.assign(new Error(`${name} isn’t valid JSON (${e.message}). zero won’t overwrite it: fix it, or move it out of the data folder, then reload.`), { invalid: true });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function readJSON(name) {
|
|
109
|
+
try { return (await readData(name)).value; } catch { return null; }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** rename() can briefly fail on Windows while antivirus or sync tools hold the file. */
|
|
113
|
+
async function renameWithRetry(from, to) {
|
|
114
|
+
for (let i = 0; ; i++) {
|
|
115
|
+
try { return await rename(from, to); } catch (e) {
|
|
116
|
+
if (i >= 4 || !['EPERM', 'EBUSY', 'EACCES'].includes(e.code)) throw e;
|
|
117
|
+
await new Promise((r) => setTimeout(r, 60 * (i + 1)));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Write-then-rename, so a crash mid-write never leaves a half-written file. The previous
|
|
124
|
+
* version is kept as <name>.bak, one step of undo for a bad import or a bad edit.
|
|
125
|
+
*/
|
|
126
|
+
async function writeJSON(name, value, mode = 0o600) {
|
|
127
|
+
await mkdir(DATA, { recursive: true, mode: 0o700 });
|
|
128
|
+
const file = join(DATA, name);
|
|
129
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
130
|
+
await writeFile(tmp, JSON.stringify(value, null, 2) + '\n', { mode });
|
|
131
|
+
if (name !== SECRETS) { try { await copyFile(file, `${file}.bak`); await chmod(`${file}.bak`, mode); } catch { /* first write */ } }
|
|
132
|
+
await renameWithRetry(tmp, file);
|
|
133
|
+
await chmod(file, mode);
|
|
134
|
+
return createHash('sha256').update(JSON.stringify(value, null, 2) + '\n').digest('hex').slice(0, 16);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function apiKey() {
|
|
138
|
+
if (process.env.ANTHROPIC_API_KEY) return { key: process.env.ANTHROPIC_API_KEY, source: 'env' };
|
|
139
|
+
const s = await readJSON(SECRETS);
|
|
140
|
+
return s?.anthropicKey ? { key: s.anthropicKey, source: 'file', status: s.status } : { key: null };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const hint = (key) => (key ? `…${key.slice(-4)}` : null);
|
|
144
|
+
|
|
145
|
+
/** How the data folder is shown in the app: "data" inside the repo, "~/…" elsewhere. */
|
|
146
|
+
function displayDir() {
|
|
147
|
+
const rel = relative(ROOT, DATA);
|
|
148
|
+
if (rel && !rel.startsWith('..')) return rel;
|
|
149
|
+
const home = homedir();
|
|
150
|
+
return DATA.startsWith(home) ? `~${DATA.slice(home.length)}` : DATA;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/* ---------- request guard ---------- */
|
|
154
|
+
|
|
155
|
+
const ALLOWED_HOSTS = new Set([`localhost:${PORT}`, `127.0.0.1:${PORT}`]);
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Blocks DNS-rebinding (Host must be ours) and cross-site requests (Origin, if sent,
|
|
159
|
+
* must be ours, and /api calls need the x-zero header, which browsers only allow
|
|
160
|
+
* cross-origin after a CORS preflight this server never approves).
|
|
161
|
+
*/
|
|
162
|
+
function allowed(req, isApi) {
|
|
163
|
+
if (!ALLOWED_HOSTS.has(req.headers.host)) return false;
|
|
164
|
+
const origin = req.headers.origin;
|
|
165
|
+
if (origin && !ALLOWED_HOSTS.has(origin.replace(/^http:\/\//, ''))) return false;
|
|
166
|
+
if (isApi && req.headers['x-zero'] !== '1') return false;
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/* ---------- api ---------- */
|
|
171
|
+
|
|
172
|
+
async function api(req, res, path) {
|
|
173
|
+
const method = req.method;
|
|
174
|
+
|
|
175
|
+
if (path === '/api/health' && method === 'GET') {
|
|
176
|
+
const { key, source, status } = await apiKey();
|
|
177
|
+
const settings = await readJSON(DATA_FILES.settings);
|
|
178
|
+
return send(res, 200, {
|
|
179
|
+
ok: true, version: VERSION, dataDir: displayDir(),
|
|
180
|
+
key: { set: Boolean(key), hint: hint(key), source: source || null, status: status || null },
|
|
181
|
+
model: process.env.ZERO_MODEL || settings?.model || DEFAULT_MODEL,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const file = path.match(/^\/api\/data\/(state|settings)$/)?.[1];
|
|
186
|
+
if (file && method === 'GET') {
|
|
187
|
+
try { return send(res, 200, await readData(DATA_FILES[file])); } catch (e) {
|
|
188
|
+
if (e.invalid) return send(res, 422, { error: e.message });
|
|
189
|
+
throw e;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (file && method === 'PUT') {
|
|
193
|
+
let value;
|
|
194
|
+
try { value = JSON.parse(await readBody(req, MAX_JSON)); } catch (e) { return send(res, e.status || 400, { error: e.status ? 'too large' : 'not valid JSON' }); }
|
|
195
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return send(res, 400, { error: 'expected a JSON object' });
|
|
196
|
+
// refuse to overwrite a file that changed since this tab read it (another tab, or a hand edit)
|
|
197
|
+
const expected = req.headers['x-zero-rev'];
|
|
198
|
+
if (expected) {
|
|
199
|
+
let current;
|
|
200
|
+
try { current = (await readData(DATA_FILES[file])).rev; } catch (e) { if (e.invalid) return send(res, 422, { error: e.message }); throw e; }
|
|
201
|
+
if (current !== expected) return send(res, 409, { error: `${DATA_FILES[file]} changed since this tab loaded it (another tab, or an edit by hand). reload to get the latest.` });
|
|
202
|
+
}
|
|
203
|
+
const rev = await writeJSON(DATA_FILES[file], value);
|
|
204
|
+
return send(res, 200, { ok: true, rev, savedAt: new Date().toISOString() });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (path === '/api/key' && method === 'POST') {
|
|
208
|
+
let key;
|
|
209
|
+
try { key = String(JSON.parse(await readBody(req, 4096)).key || '').trim(); } catch { return send(res, 400, { error: 'not valid JSON' }); }
|
|
210
|
+
if (!/^sk-ant-[A-Za-z0-9_-]{20,200}$/.test(key)) return send(res, 400, { error: 'that doesn’t look like an anthropic api key (sk-ant-…)' });
|
|
211
|
+
const status = await verifyKey(key);
|
|
212
|
+
if (status === 'invalid') return send(res, 400, { error: 'anthropic rejected that key' });
|
|
213
|
+
await writeJSON(SECRETS, { anthropicKey: key, status, savedAt: new Date().toISOString() });
|
|
214
|
+
return send(res, 200, { ok: true, hint: hint(key), status });
|
|
215
|
+
}
|
|
216
|
+
if (path === '/api/key' && method === 'DELETE') {
|
|
217
|
+
try { await unlink(join(DATA, SECRETS)); } catch { /* already gone */ }
|
|
218
|
+
return send(res, 200, { ok: true });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (path === '/api/claude' && method === 'POST') {
|
|
222
|
+
let body;
|
|
223
|
+
try { body = JSON.parse(await readBody(req, MAX_UPLOAD)); } catch (e) { return send(res, e.status || 400, { error: e.status ? 'that file is too big (max ~9 MB)' : 'not valid JSON' }); }
|
|
224
|
+
const problem = checkPayload(body?.task, body?.payload);
|
|
225
|
+
if (problem) return send(res, 400, { error: problem });
|
|
226
|
+
const { key } = await apiKey();
|
|
227
|
+
if (!key) return send(res, 409, { error: 'add your anthropic api key in settings first' });
|
|
228
|
+
const settings = await readJSON(DATA_FILES.settings);
|
|
229
|
+
const out = await runJob(key, process.env.ZERO_MODEL || settings?.model, body.task, body.payload);
|
|
230
|
+
return out.error ? send(res, out.status, { error: out.error }) : send(res, 200, { result: out.result });
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return send(res, 404, { error: 'not found' });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/* ---------- static files ---------- */
|
|
237
|
+
|
|
238
|
+
async function serveStatic(req, res, path) {
|
|
239
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'method not allowed' });
|
|
240
|
+
const rel = normalize(decodeURIComponent(path === '/' ? '/index.html' : path)).replace(/^([/\\])+/, '');
|
|
241
|
+
const file = join(PUBLIC, rel);
|
|
242
|
+
const inside = relative(PUBLIC, file);
|
|
243
|
+
if (!inside || inside.startsWith('..') || isAbsolute(inside)) return send(res, 403, { error: 'forbidden' });
|
|
244
|
+
try {
|
|
245
|
+
if (!(await stat(file)).isFile()) throw new Error('not a file');
|
|
246
|
+
const body = await readFile(file);
|
|
247
|
+
res.writeHead(200, { ...SECURITY_HEADERS, 'content-type': MIME[extname(file)] || 'application/octet-stream', 'cache-control': 'no-cache' });
|
|
248
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
249
|
+
} catch {
|
|
250
|
+
send(res, 404, 'not found', 'text/plain; charset=utf-8');
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/* ---------- boot ---------- */
|
|
255
|
+
|
|
256
|
+
export function createServer() {
|
|
257
|
+
return http.createServer(async (req, res) => {
|
|
258
|
+
const path = new URL(req.url, 'http://localhost').pathname;
|
|
259
|
+
const isApi = path.startsWith('/api/');
|
|
260
|
+
if (!allowed(req, isApi)) return send(res, 403, { error: 'forbidden' });
|
|
261
|
+
try {
|
|
262
|
+
return isApi ? await api(req, res, path) : await serveStatic(req, res, path);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
console.error(err);
|
|
265
|
+
return send(res, 500, { error: 'something went wrong on the server' });
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** True when this file was started directly (node server.js, npm start, or a bin symlink). */
|
|
271
|
+
function isMain() {
|
|
272
|
+
try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const HELP = `zero: a local, private debt payoff planner
|
|
276
|
+
|
|
277
|
+
usage
|
|
278
|
+
npx zero-debt [--port 4321] [--data ~/.zero]
|
|
279
|
+
|
|
280
|
+
flags and environment variables (flags win)
|
|
281
|
+
--port, ZERO_PORT port on 127.0.0.1 (default 4321)
|
|
282
|
+
--data, ZERO_DATA_DIR folder for state.json, settings.json, secrets.json
|
|
283
|
+
ANTHROPIC_API_KEY use this key instead of one saved in the app
|
|
284
|
+
ZERO_MODEL force a claude model for every call
|
|
285
|
+
|
|
286
|
+
https://github.com/aposoloam/zero`;
|
|
287
|
+
|
|
288
|
+
if (isMain() && (process.argv.includes('--help') || process.argv.includes('-h'))) {
|
|
289
|
+
console.log(HELP);
|
|
290
|
+
process.exit(0);
|
|
291
|
+
}
|
|
292
|
+
if (isMain() && (process.argv.includes('--version') || process.argv.includes('-v'))) {
|
|
293
|
+
console.log(VERSION);
|
|
294
|
+
process.exit(0);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (isMain()) {
|
|
298
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
299
|
+
if (major < 22) console.warn(` note: zero is tested on node 22 and newer. you have ${process.versions.node}.`);
|
|
300
|
+
await mkdir(DATA, { recursive: true, mode: 0o700 });
|
|
301
|
+
try { await chmod(DATA, 0o700); } catch { /* not supported on this file system */ }
|
|
302
|
+
const server = createServer();
|
|
303
|
+
server.on('error', (err) => {
|
|
304
|
+
if (err.code === 'EADDRINUSE') {
|
|
305
|
+
console.error(`\n port ${PORT} is already in use. zero may already be running: try http://localhost:${PORT}\n or pick another port: ZERO_PORT=4322 npm start\n`);
|
|
306
|
+
} else {
|
|
307
|
+
console.error(`\n zero couldn’t start: ${err.message}\n`);
|
|
308
|
+
}
|
|
309
|
+
process.exit(1);
|
|
310
|
+
});
|
|
311
|
+
server.listen(PORT, HOST, () => {
|
|
312
|
+
console.log(`\n zero ${VERSION}\n → http://localhost:${PORT}\n data: ${DATA}\n\n ctrl+c to stop\n`);
|
|
313
|
+
});
|
|
314
|
+
}
|