create-heresay 0.2.43 → 0.2.45

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.43",
3
+ "version": "0.2.45",
4
4
  "description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.43
1
+ 0.2.45
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.43';
2
+ export const VERSION = '0.2.45';
3
3
  //# sourceMappingURL=version.js.map
@@ -0,0 +1,322 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ const T = 'hs_entity';
3
+ const C = 'hs_chunk';
4
+ const BODY_MAX = 8000; // base64 characters per row, under the 10,000 of a text column
5
+ const PAGE = 300; // ZCQL returns at most 300 rows
6
+ const RETRIES = 8;
7
+ const SAFE = /^[A-Za-z0-9_:.@+=/ -]*$/;
8
+ /** The only way a value gets into a statement. */
9
+ function lit(v) {
10
+ if (typeof v === 'number') {
11
+ if (!Number.isFinite(v))
12
+ throw new Error('bad number');
13
+ return String(Math.trunc(v));
14
+ }
15
+ if (!SAFE.test(v))
16
+ throw new Error(`unsafe value in statement: ${JSON.stringify(v.slice(0, 40))}`);
17
+ return `'${v}'`;
18
+ }
19
+ /** ROWID is a bigint that can pass 2^53: keep it as the digits it came as. */
20
+ function rowid(v) {
21
+ if (!/^\d+$/.test(v))
22
+ throw new Error('bad ROWID');
23
+ return v;
24
+ }
25
+ const enc = (v) => Buffer.from(JSON.stringify(v), 'utf8').toString('base64');
26
+ const dec = (s) => JSON.parse(Buffer.from(s, 'base64').toString('utf8'));
27
+ const nonce = () => randomBytes(9).toString('base64url');
28
+ const num = (v) => Number(v ?? 0);
29
+ const str = (v) => (v == null ? '' : String(v));
30
+ function head(r) {
31
+ return {
32
+ ROWID: str(r.ROWID), ekey: str(r.ekey), etype: str(r.etype), rev: num(r.rev), nonce: str(r.nonce), claimed: str(r.claimed),
33
+ gen: str(r.gen), nparts: num(r.nparts), body: str(r.body),
34
+ ix: { ix1: str(r.ix1), ix2: str(r.ix2), ix3: str(r.ix3), ix4: str(r.ix4) },
35
+ };
36
+ }
37
+ const ixSet = (ix) => `ix1=${lit(ix.ix1 ?? '')}, ix2=${lit(ix.ix2 ?? '')}, ix3=${lit(ix.ix3 ?? '')}, ix4=${lit(ix.ix4 ?? '')}`;
38
+ export class CatalystStore {
39
+ z;
40
+ constructor(z) {
41
+ this.z = z;
42
+ }
43
+ // ---- primitives ----------------------------------------------------------------------
44
+ /**
45
+ * Pages through a SELECT, since one statement returns at most 300 rows. ZCQL's `LIMIT start, count`
46
+ * counts rows from 1 (0 and 1 both mean the first row), unlike SQL's offset: checked on a real project.
47
+ */
48
+ async select(table, where, order = '', limit = Infinity) {
49
+ const out = [];
50
+ while (out.length < limit) {
51
+ const n = Math.min(PAGE, limit - out.length);
52
+ const rows = await this.z.query(`SELECT * FROM ${table} WHERE ${where}${order ? ' ORDER BY ' + order : ''} LIMIT ${out.length + 1}, ${n}`);
53
+ out.push(...rows);
54
+ if (rows.length < n)
55
+ break;
56
+ }
57
+ return out;
58
+ }
59
+ async load(h) {
60
+ if (h.nparts === 0)
61
+ return h.body;
62
+ const rows = await this.select(C, `ekey=${lit(h.ekey)} AND gen=${lit(h.gen)}`, 'part');
63
+ if (rows.length !== h.nparts)
64
+ throw new Error(`incomplete document ${h.ekey}`);
65
+ return rows.sort((a, b) => num(a.part) - num(b.part)).map((r) => str(r.body)).join('');
66
+ }
67
+ async readHead(ekey) {
68
+ const rows = await this.z.query(`SELECT * FROM ${T} WHERE ekey=${lit(ekey)} LIMIT 0, 1`);
69
+ return rows[0] ? head(rows[0]) : null;
70
+ }
71
+ async read(ekey) {
72
+ const h = await this.readHead(ekey);
73
+ return h ? { h, doc: dec(await this.load(h)) } : null;
74
+ }
75
+ async readMany(rows) {
76
+ const out = [];
77
+ for (const r of rows) {
78
+ const h = head(r);
79
+ out.push(dec(await this.load(h)));
80
+ }
81
+ return out;
82
+ }
83
+ /** Writes the body: inline if it fits, else as a new generation of chunk rows. Returns the columns for the head. */
84
+ async stage(ekey, ix1, doc) {
85
+ const b64 = enc(doc);
86
+ if (b64.length <= BODY_MAX)
87
+ return { gen: '', nparts: 0, body: b64, undo: async () => { } };
88
+ const gen = nonce();
89
+ const parts = [];
90
+ for (let i = 0; i < b64.length; i += BODY_MAX)
91
+ parts.push(b64.slice(i, i + BODY_MAX));
92
+ const undo = () => this.z.query(`DELETE FROM ${C} WHERE ekey=${lit(ekey)} AND gen=${lit(gen)}`).then(() => { });
93
+ try {
94
+ for (let i = 0; i < parts.length; i++) {
95
+ await this.z.query(`INSERT INTO ${C} (ekey, gen, part, ix1, body) VALUES (${lit(ekey)}, ${lit(gen)}, ${i}, ${lit(ix1)}, ${lit(parts[i])})`);
96
+ }
97
+ }
98
+ catch (e) {
99
+ await undo().catch(() => { });
100
+ throw e;
101
+ }
102
+ return { gen, nparts: parts.length, body: '', undo };
103
+ }
104
+ async dropOldChunks(ekey, keepGen) {
105
+ await this.z.query(`DELETE FROM ${C} WHERE ekey=${lit(ekey)} AND gen<>${lit(keepGen)}`).catch(() => { });
106
+ }
107
+ /** Creates the row. Throws if it exists (the unique ekey is the real guard; this is the early, clear error). */
108
+ async insert(ekey, etype, ix, doc) {
109
+ if (await this.readHead(ekey))
110
+ throw new Error(`already exists: ${ekey}`);
111
+ const s = await this.stage(ekey, ix.ix1 ?? '', doc);
112
+ try {
113
+ await this.z.query(`INSERT INTO ${T} (ekey, etype, ix1, ix2, ix3, ix4, rev, nonce, claimed, gen, nparts, body) VALUES `
114
+ + `(${lit(ekey)}, ${lit(etype)}, ${lit(ix.ix1 ?? '')}, ${lit(ix.ix2 ?? '')}, ${lit(ix.ix3 ?? '')}, ${lit(ix.ix4 ?? '')}, 1, ${lit(nonce())}, '', ${lit(s.gen)}, ${s.nparts}, ${lit(s.body)})`);
115
+ }
116
+ catch (e) {
117
+ await s.undo().catch(() => { });
118
+ throw e;
119
+ }
120
+ }
121
+ /** Compare-and-swap: replace the document only if nobody has since. */
122
+ async swap(h, doc, ix = h.ix) {
123
+ const s = await this.stage(h.ekey, ix.ix1 ?? h.ix.ix1, doc);
124
+ const mine = nonce();
125
+ await this.z.query(`UPDATE ${T} SET ${ixSet({ ...h.ix, ...ix })}, rev=${h.rev + 1}, nonce=${lit(mine)}, gen=${lit(s.gen)}, nparts=${s.nparts}, body=${lit(s.body)} `
126
+ + `WHERE ROWID=${rowid(h.ROWID)} AND rev=${h.rev}`);
127
+ const now = await this.readHead(h.ekey);
128
+ const won = !!now && now.nonce === mine;
129
+ if (won)
130
+ await this.dropOldChunks(h.ekey, s.gen);
131
+ else
132
+ await s.undo().catch(() => { });
133
+ return won;
134
+ }
135
+ /** Read, change, swap; again from the top if someone got in between. `fn` returns null to leave it alone. */
136
+ async modify(ekey, fn, ix) {
137
+ for (let i = 0; i < RETRIES; i++) {
138
+ const cur = await this.read(ekey);
139
+ if (!cur)
140
+ return null;
141
+ const next = fn(cur.doc);
142
+ if (next === null)
143
+ return cur.doc;
144
+ if (await this.swap(cur.h, next, ix?.(next)))
145
+ return next;
146
+ }
147
+ throw new Error(`too much contention on ${ekey}`);
148
+ }
149
+ async remove(ekey) {
150
+ await this.z.query(`DELETE FROM ${C} WHERE ekey=${lit(ekey)}`);
151
+ await this.z.query(`DELETE FROM ${T} WHERE ekey=${lit(ekey)}`);
152
+ }
153
+ // ---- keys and indexes ------------------------------------------------------------------
154
+ reportIx = (r) => ({ ix1: r.project_id, ix2: r.device_id, ix3: r.created_at, ix4: r.updated_at });
155
+ rk = (p, id) => `report:${p}:${id}`;
156
+ tk = (p, id) => `task:${p}:${id}`;
157
+ // ---- Store ---------------------------------------------------------------------------
158
+ async getInstance() { return (await this.read('instance'))?.doc ?? null; }
159
+ async updateInstance(fn) {
160
+ for (let i = 0; i < RETRIES; i++) {
161
+ const cur = await this.read('instance');
162
+ const next = fn(cur ? structuredClone(cur.doc) : null);
163
+ if (!cur) {
164
+ try {
165
+ await this.insert('instance', 'instance', {}, next);
166
+ return next;
167
+ }
168
+ catch (e) {
169
+ if (!/exists|unique|duplicate/i.test(String(e)))
170
+ throw e;
171
+ continue;
172
+ }
173
+ }
174
+ if (await this.swap(cur.h, next))
175
+ return next;
176
+ }
177
+ throw new Error('too much contention on the instance');
178
+ }
179
+ async createProject(p) { await this.insert(`project:${p.id}`, 'project', { ix1: p.key }, p); }
180
+ async getProject(id) { return (await this.read(`project:${id}`))?.doc ?? null; }
181
+ async getProjectByKey(key) {
182
+ const rows = await this.z.query(`SELECT * FROM ${T} WHERE etype='project' AND ix1=${lit(key)} LIMIT 0, 1`);
183
+ return rows[0] ? (await this.readMany(rows))[0] : null;
184
+ }
185
+ async listProjects() { return this.readMany(await this.select(T, `etype='project'`, 'ROWID')); }
186
+ async updateProject(id, patch) {
187
+ const { id: _ignored, ...rest } = patch;
188
+ await this.modify(`project:${id}`, (p) => ({ ...p, ...rest }), (p) => ({ ix1: p.key }));
189
+ }
190
+ async deleteProject(id) {
191
+ await this.z.query(`DELETE FROM ${C} WHERE ix1=${lit(id)}`);
192
+ await this.z.query(`DELETE FROM ${T} WHERE ix1=${lit(id)} AND etype IN ('report', 'task')`);
193
+ await this.remove(`project:${id}`);
194
+ }
195
+ async createReport(r) { await this.insert(this.rk(r.project_id, r.id), 'report', this.reportIx(r), r); }
196
+ async getReport(project_id, id) { return (await this.read(this.rk(project_id, id)))?.doc ?? null; }
197
+ async listReports(project_id) {
198
+ return this.readMany(await this.select(T, `etype='report' AND ix1=${lit(project_id)}`, 'ix3 DESC', 500));
199
+ }
200
+ async listReportsSince(project_id, since) {
201
+ const rows = await this.select(T, `etype='report' AND ix1=${lit(project_id)} AND ix4>${lit(since)}`, 'ix4', 500);
202
+ return (await this.readMany(rows)).filter((r) => r.updated_at > since);
203
+ }
204
+ async listReportsForDevice(project_id, device_id) {
205
+ return this.readMany(await this.select(T, `etype='report' AND ix1=${lit(project_id)} AND ix2=${lit(device_id)}`, 'ix3 DESC', 50));
206
+ }
207
+ async updateReport(project_id, id, patch) {
208
+ const { id: _i, project_id: _p, status: _s, ...rest } = patch;
209
+ await this.modify(this.rk(project_id, id), (r) => ({ ...r, ...rest }), this.reportIx);
210
+ }
211
+ async accept(project_id, report_id, task, at) {
212
+ const t = await this.moveWith(project_id, report_id, 'open', (r) => ({ ...r, status: 'accepted', triaged_by: task.accepted_by, updated_at: at }));
213
+ if (!t.ok)
214
+ return t;
215
+ // The claim above is what makes this the one accept. A crash before this line leaves an
216
+ // accepted report with no task, which fails closed: nothing reaches an agent without a task.
217
+ await this.insert(this.tk(project_id, report_id), 'task', { ix1: project_id }, task).catch((e) => { if (!/exists|unique|duplicate/i.test(String(e)))
218
+ throw e; });
219
+ return t;
220
+ }
221
+ async move(project_id, report_id, from, to, patch) {
222
+ return this.moveWith(project_id, report_id, from, (r) => ({
223
+ ...r, status: to, triaged_by: patch.triaged_by, updated_at: patch.updated_at,
224
+ decline_reason: patch.decline_reason ?? r.decline_reason,
225
+ fix_note: patch.fix_note !== undefined ? patch.fix_note : (r.fix_note ?? null),
226
+ }));
227
+ }
228
+ /** The status change, once: only from `from`, and only the writer whose swap lands gets `ok`. */
229
+ async moveWith(project_id, report_id, from, next) {
230
+ const ekey = this.rk(project_id, report_id);
231
+ for (let i = 0; i < RETRIES; i++) {
232
+ const cur = await this.read(ekey);
233
+ if (!cur)
234
+ return { ok: false, reason: 'not_found' };
235
+ if (cur.doc.status !== from)
236
+ return { ok: false, reason: 'wrong_status', status: cur.doc.status };
237
+ const r = next(cur.doc);
238
+ if (await this.swap(cur.h, r, this.reportIx(r)))
239
+ return { ok: true, report: r };
240
+ }
241
+ throw new Error(`too much contention on ${ekey}`);
242
+ }
243
+ async getTask(project_id, report_id) { return (await this.read(this.tk(project_id, report_id)))?.doc ?? null; }
244
+ async listTasks(project_id) { return this.readMany(await this.select(T, `etype='task' AND ix1=${lit(project_id)}`, 'ROWID', 500)); }
245
+ async updateTask(project_id, report_id, fn) {
246
+ return this.modify(this.tk(project_id, report_id), (t) => fn(structuredClone(t)));
247
+ }
248
+ async createAgentToken(t) { await this.insert(`token:${t.id}`, 'token', {}, t); }
249
+ async getAgentToken(id) { return (await this.read(`token:${id}`))?.doc ?? null; }
250
+ async listAgentTokens() { return this.readMany(await this.select(T, `etype='token'`, 'ROWID')); }
251
+ async updateAgentToken(id, patch) {
252
+ const { id: _ignored, ...rest } = patch;
253
+ await this.modify(`token:${id}`, (t) => ({ ...t, ...rest }));
254
+ }
255
+ ak = (kind, id) => `auth:${kind}:${id}`;
256
+ async putAuth(r) {
257
+ const ix = { ix1: r.kind, ix2: r.expires_at ?? '' };
258
+ for (let i = 0; i < RETRIES; i++) {
259
+ const cur = await this.readHead(this.ak(r.kind, r.id));
260
+ if (!cur) {
261
+ try {
262
+ await this.insert(this.ak(r.kind, r.id), 'auth', ix, r);
263
+ return;
264
+ }
265
+ catch (e) {
266
+ if (!/exists|unique|duplicate/i.test(String(e)))
267
+ throw e;
268
+ continue;
269
+ }
270
+ }
271
+ if (await this.swap(cur, r, ix))
272
+ return;
273
+ }
274
+ throw new Error('too much contention on an auth record');
275
+ }
276
+ async getAuth(kind, id) { return (await this.read(this.ak(kind, id)))?.doc ?? null; }
277
+ /** One claimer wins: `claimed` can only go from empty to a nonce once. Whoever loses gets null for good. */
278
+ async takeAuth(kind, id) {
279
+ const ekey = this.ak(kind, id);
280
+ const cur = await this.read(ekey);
281
+ if (!cur || cur.h.claimed)
282
+ return null;
283
+ const mine = nonce();
284
+ await this.z.query(`UPDATE ${T} SET claimed=${lit(mine)} WHERE ROWID=${rowid(cur.h.ROWID)} AND claimed=''`);
285
+ const now = await this.readHead(ekey);
286
+ if (!now || now.claimed !== mine)
287
+ return null;
288
+ await this.remove(ekey);
289
+ return cur.doc;
290
+ }
291
+ async deleteAuth(kind, id) { await this.remove(this.ak(kind, id)); }
292
+ async listAuth(kind) { return this.readMany(await this.select(T, `etype='auth' AND ix1=${lit(kind)}`, 'ROWID')); }
293
+ /**
294
+ * Rate counters. Correct, but every hit is a SELECT and an UPDATE against a small monthly Data
295
+ * Store quota: the Catalyst adapter should count in memory (see LiteStore) and keep this for
296
+ * the contract only.
297
+ */
298
+ async hit(bucket, limit, expires_at) {
299
+ const ekey = `rate:${bucket}`;
300
+ const ix = { ix2: String(expires_at) };
301
+ for (let i = 0; i < RETRIES; i++) {
302
+ const cur = await this.read(ekey);
303
+ if (!cur) {
304
+ try {
305
+ await this.insert(ekey, 'rate', ix, { n: 1 });
306
+ return true;
307
+ }
308
+ catch (e) {
309
+ if (!/exists|unique|duplicate/i.test(String(e)))
310
+ throw e;
311
+ continue;
312
+ }
313
+ }
314
+ if (cur.doc.n >= limit)
315
+ return false;
316
+ if (await this.swap(cur.h, { n: cur.doc.n + 1 }, ix))
317
+ return true;
318
+ }
319
+ throw new Error('too much contention on a rate counter');
320
+ }
321
+ }
322
+ //# sourceMappingURL=catalyst-store.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Wraps `catalystApp.zcql()` (use the admin scope: App Users are read-only by default). ZCQL
3
+ * answers each row under its table's name, `[{ hs_entity: {...} }]`; the store wants the row.
4
+ * Statements that return nothing (INSERT, UPDATE, DELETE) come back as whatever the SDK gives.
5
+ */
6
+ export function catalystZcql(zcql) {
7
+ return {
8
+ async query(sql) {
9
+ const out = await zcql.executeZCQLQuery(sql);
10
+ if (!Array.isArray(out) || !/^\s*select/i.test(sql))
11
+ return [];
12
+ return out.map((r) => {
13
+ const only = r && typeof r === 'object' ? Object.values(r) : [];
14
+ return (only.length === 1 && only[0] && typeof only[0] === 'object' ? only[0] : r);
15
+ });
16
+ },
17
+ };
18
+ }
19
+ //# sourceMappingURL=zcql.js.map
@@ -30,11 +30,18 @@ const deps = {
30
30
  telegramPhoto: telegramPhoto(),
31
31
  telegramApi: telegramApi(),
32
32
  };
33
+ /**
34
+ * The addresses this Heresay's dashboard is served from. A named Hosting site (HERESAY_SITE,
35
+ * written to functions/.env by the deploy) comes first: it is the one people use, so OAuth
36
+ * discovery and alert links name it, not the project's default site.
37
+ */
33
38
  function selfOrigins() {
34
39
  const id = process.env.GCLOUD_PROJECT;
35
40
  if (process.env.FUNCTIONS_EMULATOR === 'true')
36
41
  return ['http://127.0.0.1:5055', 'http://localhost:5055'];
37
- return id ? [`https://${id}.web.app`, `https://${id}.firebaseapp.com`] : [];
42
+ const site = process.env.HERESAY_SITE;
43
+ const named = site && site !== id ? [`https://${site}.web.app`, `https://${site}.firebaseapp.com`] : [];
44
+ return id ? [...named, `https://${id}.web.app`, `https://${id}.firebaseapp.com`] : named;
38
45
  }
39
46
  /** Hosting rewrites /v1/** and /.well-known/** here, so the SDK, the API and the dashboard share one origin. */
40
47
  // create-heresay writes HERESAY_REGION to functions/.env; it is read when the deploy loads this file.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Imported first by node-server.ts, so it runs before firebase-admin starts. Hosts that hand
3
+ * secrets over as environment variables (not files) pass the service-account key as
4
+ * GOOGLE_APPLICATION_CREDENTIALS_JSON; firebase-admin only reads a path, so write it to one.
5
+ */
6
+ import { writeFileSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ const json = process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON;
10
+ if (json && !process.env.GOOGLE_APPLICATION_CREDENTIALS) {
11
+ JSON.parse(json); // fail at start with a clear error, not on the first request
12
+ const path = join(tmpdir(), 'heresay-service-account.json');
13
+ writeFileSync(path, json, { mode: 0o600 });
14
+ process.env.GOOGLE_APPLICATION_CREDENTIALS = path;
15
+ }
16
+ //# sourceMappingURL=lite-env.js.map
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Lite hosting: the same core handler and Firestore store as api.ts, as a plain Node server, so
3
+ * the API can run anywhere that runs Node while Firestore and Auth stay on the free Spark plan
4
+ * (Cloud Functions needs Blaze). It also serves public/ and the few Firebase Hosting URLs the
5
+ * dashboard relies on, so one origin still serves the SDK, the API and the dashboard.
6
+ *
7
+ * Nothing here is imported by the Cloud Functions deploy; run it with `npm run serve:lite`.
8
+ * Needs HERESAY_ORIGIN, HERESAY_FIREBASE_CONFIG (the web app config as JSON), GCLOUD_PROJECT
9
+ * and credentials for firebase-admin (GOOGLE_APPLICATION_CREDENTIALS). Set HERESAY_TRUST_PROXY=1
10
+ * behind a proxy that sets x-forwarded-for. HERESAY_RATE_STORE=firestore shares rate limits
11
+ * across instances at the cost of Firestore reads and writes.
12
+ */
13
+ import './lite-env.js'; // first: it must run before firebase-admin starts
14
+ import { createServer } from 'node:http';
15
+ import { readFile } from 'node:fs/promises';
16
+ import { extname, join, normalize, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { auth, db } from './admin.js';
19
+ import { FirestoreStore } from './firestore-store.js';
20
+ import { handle } from '../../core/handler.js';
21
+ import { VERSION } from '../../core/version.js';
22
+ import { notificationSender, telegramLookup, telegramPhoto } from '../../core/notifications.js';
23
+ import { telegramApi } from '../../core/telegram.js';
24
+ const PUBLIC_DIR = resolve(fileURLToPath(new URL('../../../../public', import.meta.url)));
25
+ const FIREBASE_JS = '10.14.1';
26
+ const MAX_BODY = 256 * 1024;
27
+ const TYPES = {
28
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
29
+ '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml',
30
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.ico': 'image/x-icon', '.md': 'text/markdown; charset=utf-8',
31
+ '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8',
32
+ };
33
+ const origin = process.env.HERESAY_ORIGIN?.replace(/\/$/, '') ?? '';
34
+ const trustProxy = process.env.HERESAY_TRUST_PROXY === '1';
35
+ /**
36
+ * Rate-limit counters are the biggest Firestore cost per request (a read and a write each), and
37
+ * on the free Spark plan reads and writes are the budget. A single Lite process can count in
38
+ * memory instead; the counts reset when it restarts, which only ever lets a few extra requests
39
+ * through. Run more than one instance, or set HERESAY_RATE_STORE=firestore, to share counters.
40
+ */
41
+ class LiteStore extends FirestoreStore {
42
+ counts = new Map();
43
+ async hit(bucket, limit, expires_at) {
44
+ const now = Date.now();
45
+ if (this.counts.size > 20_000)
46
+ for (const [k, v] of this.counts)
47
+ if (v.expires <= now)
48
+ this.counts.delete(k);
49
+ const c = this.counts.get(bucket);
50
+ const n = c && c.expires > now ? c.n : 0;
51
+ if (n >= limit)
52
+ return false;
53
+ this.counts.set(bucket, { n: n + 1, expires: expires_at });
54
+ return true;
55
+ }
56
+ }
57
+ const deps = {
58
+ store: process.env.HERESAY_RATE_STORE === 'firestore' ? new FirestoreStore(db) : new LiteStore(db),
59
+ async verifyIdToken(token) {
60
+ try {
61
+ const t = await auth.verifyIdToken(token);
62
+ return { uid: t.uid, email: t.email ?? null, emailVerified: t.email_verified === true };
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ },
68
+ now: () => Date.now(),
69
+ log: (event, fields) => console.log(JSON.stringify({ severity: 'INFO', event, ...fields })),
70
+ version: VERSION,
71
+ selfOrigins: origin ? [origin] : [],
72
+ sendNotification: notificationSender(),
73
+ telegramLookup: telegramLookup(),
74
+ telegramPhoto: telegramPhoto(),
75
+ telegramApi: telegramApi(),
76
+ };
77
+ function readBody(req) {
78
+ return new Promise((ok, fail) => {
79
+ const chunks = [];
80
+ let size = 0;
81
+ req.on('data', (c) => {
82
+ size += c.length;
83
+ if (size > MAX_BODY) {
84
+ fail(new Error('too large'));
85
+ req.destroy();
86
+ return;
87
+ }
88
+ chunks.push(c);
89
+ });
90
+ req.on('end', () => {
91
+ const text = Buffer.concat(chunks).toString('utf8');
92
+ if (!text)
93
+ return ok(undefined);
94
+ const type = req.headers['content-type'] ?? '';
95
+ if (type.includes('application/x-www-form-urlencoded'))
96
+ return ok(Object.fromEntries(new URLSearchParams(text)));
97
+ try {
98
+ ok(JSON.parse(text));
99
+ }
100
+ catch {
101
+ ok(text);
102
+ }
103
+ });
104
+ req.on('error', fail);
105
+ });
106
+ }
107
+ function clientIp(req) {
108
+ const fwd = req.headers['x-forwarded-for'];
109
+ if (trustProxy && typeof fwd === 'string')
110
+ return fwd.split(',')[0].trim();
111
+ return req.socket.remoteAddress ?? '';
112
+ }
113
+ async function api(req, res, url) {
114
+ const headers = {};
115
+ for (const [k, v] of Object.entries(req.headers))
116
+ headers[k] = Array.isArray(v) ? v[0] : v;
117
+ const query = {};
118
+ for (const [k, v] of url.searchParams)
119
+ query[k] = v;
120
+ let body;
121
+ try {
122
+ body = await readBody(req);
123
+ }
124
+ catch {
125
+ res.writeHead(413).end();
126
+ return;
127
+ }
128
+ const out = await handle({ method: req.method ?? 'GET', path: url.pathname, query, headers, ip: clientIp(req), body }, deps);
129
+ for (const [k, v] of Object.entries(out.headers ?? {}))
130
+ res.setHeader(k, v);
131
+ if (out.status === 204 || out.body === null) {
132
+ res.writeHead(out.status).end();
133
+ return;
134
+ }
135
+ res.setHeader('content-type', 'application/json; charset=utf-8');
136
+ res.writeHead(out.status).end(JSON.stringify(out.body));
137
+ }
138
+ /** The URLs Firebase Hosting reserves and the dashboard loads: the web config and the SDK files. */
139
+ function reserved(res, path) {
140
+ if (path === '/__/firebase/init.js') {
141
+ const config = process.env.HERESAY_FIREBASE_CONFIG ?? '{}';
142
+ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
143
+ // Hosting wires the Auth emulator itself; here the same variable the admin SDK reads does it.
144
+ const emu = process.env.FIREBASE_AUTH_EMULATOR_HOST;
145
+ const emulator = emu ? `firebase.auth().useEmulator(${JSON.stringify(`http://${emu}`)}, { disableWarnings: true });\n` : '';
146
+ res.end(`if (typeof firebase === 'undefined') throw new Error('firebase not loaded');\nfirebase.initializeApp(${config});\n${emulator}`);
147
+ return true;
148
+ }
149
+ const m = /^\/__\/firebase\/(\d+\.\d+\.\d+)\/([\w.-]+\.js)$/.exec(path);
150
+ if (m) {
151
+ res.writeHead(302, { location: `https://www.gstatic.com/firebasejs/${m[1]}/${m[2]}`, 'cache-control': 'public, max-age=86400' });
152
+ res.end();
153
+ return true;
154
+ }
155
+ return false;
156
+ }
157
+ async function file(res, path) {
158
+ let rel = path === '/sdk/v1.js' ? '/sdk.js' : path;
159
+ if (rel.endsWith('/'))
160
+ rel += 'index.html';
161
+ const full = join(PUBLIC_DIR, normalize(rel));
162
+ if (!full.startsWith(PUBLIC_DIR + '/') || rel.split('/').some((p) => p.startsWith('.'))) {
163
+ res.writeHead(404).end();
164
+ return;
165
+ }
166
+ try {
167
+ const data = await readFile(full);
168
+ const sdk = rel === '/sdk.js';
169
+ res.writeHead(200, {
170
+ 'content-type': TYPES[extname(full)] ?? 'application/octet-stream',
171
+ 'x-content-type-options': 'nosniff',
172
+ 'referrer-policy': 'strict-origin-when-cross-origin',
173
+ ...(sdk ? { 'cache-control': 'public, max-age=300', 'access-control-allow-origin': '*' } : {}),
174
+ });
175
+ res.end(data);
176
+ }
177
+ catch {
178
+ try {
179
+ const html = await readFile(join(PUBLIC_DIR, rel.replace(/\/?$/, '/index.html')));
180
+ res.writeHead(200, { 'content-type': TYPES['.html'], 'x-content-type-options': 'nosniff' });
181
+ res.end(html);
182
+ }
183
+ catch {
184
+ res.writeHead(404, { 'content-type': 'text/plain' }).end('Not found');
185
+ }
186
+ }
187
+ }
188
+ export const server = createServer((req, res) => {
189
+ const url = new URL(req.url ?? '/', 'http://local');
190
+ const path = url.pathname;
191
+ const run = path.startsWith('/v1/') || path.startsWith('/.well-known/')
192
+ ? api(req, res, url)
193
+ : reserved(res, path) ? Promise.resolve() : file(res, path);
194
+ run.catch((e) => {
195
+ deps.log('lite.error', { message: String(e) });
196
+ if (!res.headersSent)
197
+ res.writeHead(500, { 'content-type': 'application/json' });
198
+ res.end('{"error":"internal"}');
199
+ });
200
+ });
201
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
202
+ const port = Number(process.env.PORT ?? 8080);
203
+ server.listen(port, () => console.log(`heresay lite on :${port}`));
204
+ }
205
+ //# sourceMappingURL=node-server.js.map
@@ -9,7 +9,7 @@
9
9
  "scripts": {
10
10
  "build": "tsc -p tsconfig.json",
11
11
  "typecheck": "tsc -p tsconfig.json --noEmit",
12
- "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js' 'lib-test/test/telegram.test.js'",
12
+ "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js' 'lib-test/test/telegram.test.js' 'lib-test/test/store-catalyst.test.js'",
13
13
  "build:test": "tsc -p tsconfig.test.json"
14
14
  },
15
15
  "dependencies": {
@@ -1046,6 +1046,20 @@
1046
1046
  }).then(body);
1047
1047
  }
1048
1048
 
1049
+ /**
1050
+ * A device with no reports has nothing to hear back about, so loading the app need not ask
1051
+ * the server more than once a day (that call is also what tells the dashboard the SDK is live).
1052
+ * A device with reports asks on every load, as before.
1053
+ */
1054
+ var MINE_KEY = 'fbsdk.mine.' + KEY;
1055
+ function rememberMine() { save(MINE_KEY, JSON.stringify({ at: Date.now(), n: state.reports.length })); }
1056
+ function mineIsEmptyAndFresh() {
1057
+ try {
1058
+ var m = JSON.parse(load(MINE_KEY) || 'null');
1059
+ return !!m && m.n === 0 && Date.now() - m.at < 24 * 3600 * 1000;
1060
+ } catch (e) { return false; }
1061
+ }
1062
+
1049
1063
  function refresh() {
1050
1064
  if (PREVIEW) return Promise.resolve();
1051
1065
  return fetch(API + '/reports/mine', {
@@ -1055,6 +1069,7 @@
1055
1069
  body: JSON.stringify({ key: KEY, device_id: deviceId(), sdk: 'web' }),
1056
1070
  }).then(body).then(function (b) {
1057
1071
  state.reports = b.reports || [];
1072
+ rememberMine();
1058
1073
  renderBadge();
1059
1074
  renderList();
1060
1075
  }).catch(function () { /* offline or blocked: the button still works */ });
@@ -1382,6 +1397,7 @@
1382
1397
  state.type = null;
1383
1398
  state.draft = '';
1384
1399
  state.reports = [b.report].concat(state.reports);
1400
+ rememberMine();
1385
1401
  markSeen();
1386
1402
  state.justSent = true;
1387
1403
  view = 'mine';
@@ -1665,7 +1681,7 @@
1665
1681
  versionSeen(state.version);
1666
1682
  if (!host.isConnected) document.body.appendChild(host);
1667
1683
  placeFab();
1668
- refresh();
1684
+ if (!mineIsEmptyAndFresh()) refresh();
1669
1685
  if (attr('intro') === 'auto') setTimeout(introduce, 3000);
1670
1686
  }
1671
1687
  if (document.body) mount(); else document.addEventListener('DOMContentLoaded', mount);
package/src/backup.mjs ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Backup and restore of a Heresay's data: every Firestore document, as Firestore's own typed
3
+ * values, so a restore puts back exactly what was there (timestamps, nulls, nested maps).
4
+ *
5
+ * Not included: rate-limit counters (`rate/`, short-lived by design) and Firebase Auth's user
6
+ * list. Nobody needs the latter: the team is the member list in `meta/instance`, kept by email,
7
+ * and members sign in again with an email link on the restored Heresay.
8
+ *
9
+ * The file holds secrets (Telegram and Cliq tokens, hashed agent tokens, chat-app grants), so it
10
+ * is written readable by its owner only.
11
+ *
12
+ * `call(method, url, opts)` is google.mjs's `g`; tests pass one that talks to the emulator.
13
+ */
14
+ export const FORMAT = 'heresay-backup';
15
+ const SKIP_ROOT = new Set(['rate']);
16
+ const BATCH = 400;
17
+
18
+ const root = (base, id) => `${base}/projects/${id}/databases/(default)/documents`;
19
+
20
+ async function collectionIds(call, parent, project) {
21
+ const ids = [];
22
+ let pageToken;
23
+ do {
24
+ const b = await call('POST', `${parent}:listCollectionIds`, { project, body: { pageSize: 300, ...(pageToken ? { pageToken } : {}) } });
25
+ ids.push(...(b.collectionIds ?? []));
26
+ pageToken = b.nextPageToken;
27
+ } while (pageToken);
28
+ return ids;
29
+ }
30
+
31
+ /** Every document under `parent`, depth first. `showMissing` finds documents that only exist as a parent of subcollections. */
32
+ async function walk(call, base, project, parent, prefix, out, say) {
33
+ for (const col of await collectionIds(call, parent, project)) {
34
+ if (!prefix && SKIP_ROOT.has(col)) continue;
35
+ let pageToken;
36
+ do {
37
+ const q = new URLSearchParams({ pageSize: '300', showMissing: 'true', ...(pageToken ? { pageToken } : {}) });
38
+ const b = await call('GET', `${parent}/${col}?${q}`, { project });
39
+ for (const d of b.documents ?? []) {
40
+ const path = d.name.slice(d.name.indexOf('/documents/') + '/documents/'.length);
41
+ if (d.createTime) out.push({ path, fields: d.fields ?? {} });
42
+ if (out.length % 200 === 0) say?.(`Read ${out.length} documents`);
43
+ // Heresay's ids hold colons (`auth/code:x`). Firestore can't list subcollections under those
44
+ // (the colon reads as a method call, encoded or not). In Heresay they are leaf documents; any
45
+ // that can't be scanned is listed in the backup, never skipped silently.
46
+ const url = `${root(base, project)}/${path.split('/').map(encodeURIComponent).join('/')}`;
47
+ try { await walk(call, base, project, url, path, out, say); } catch (e) {
48
+ if (!path.split('/').pop().includes(':') || !/400|INVALID_ARGUMENT|isn't valid/i.test(String(e.message ?? e) + (e.status ?? ''))) throw e;
49
+ out.unscanned.push(path);
50
+ }
51
+ }
52
+ pageToken = b.nextPageToken;
53
+ } while (pageToken);
54
+ }
55
+ }
56
+
57
+ export async function dump(call, { base, project, version, say }) {
58
+ const documents = [];
59
+ documents.unscanned = [];
60
+ await walk(call, base, project, root(base, project), '', documents, say);
61
+ const unscanned = documents.unscanned;
62
+ documents.sort((a, b) => a.path.localeCompare(b.path));
63
+ return { format: FORMAT, format_version: 1, heresay: version, project, created_at: new Date().toISOString(), skipped: [...SKIP_ROOT], unscanned, documents: [...documents] };
64
+ }
65
+
66
+ export function summarize(backup) {
67
+ const by = {};
68
+ for (const d of backup.documents) {
69
+ const parts = d.path.split('/');
70
+ const kind = parts.length >= 4 ? parts[parts.length - 2] : parts[0];
71
+ by[kind] = (by[kind] ?? 0) + 1;
72
+ }
73
+ return by;
74
+ }
75
+
76
+ export function check(backup) {
77
+ if (backup?.format !== FORMAT || backup.format_version !== 1 || !Array.isArray(backup.documents)) {
78
+ throw new Error('That file isn’t a Heresay backup.');
79
+ }
80
+ for (const d of backup.documents) {
81
+ const parts = typeof d.path === 'string' ? d.path.split('/') : [];
82
+ const sound = parts.length >= 2 && parts.length % 2 === 0 && parts.every((x) => x && x !== '.' && x !== '..');
83
+ if (!sound || !d.fields || typeof d.fields !== 'object') {
84
+ throw new Error(`The backup has a damaged entry (${String(d.path).slice(0, 60)}).`);
85
+ }
86
+ }
87
+ return backup;
88
+ }
89
+
90
+ /** True if the project already holds a Heresay (its team document). */
91
+ export async function hasData(call, { base, project }) {
92
+ const ids = (await collectionIds(call, root(base, project), project)).filter((c) => !SKIP_ROOT.has(c));
93
+ return ids.length > 0;
94
+ }
95
+
96
+ /** Writes every document, overwriting any with the same path. Returns how many. */
97
+ export async function restore(call, backup, { base, project, say }) {
98
+ check(backup);
99
+ const docs = root(base, project);
100
+ let n = 0;
101
+ for (let i = 0; i < backup.documents.length; i += BATCH) {
102
+ const writes = backup.documents.slice(i, i + BATCH).map((d) => ({ update: { name: `projects/${project}/databases/(default)/documents/${d.path}`, fields: d.fields } }));
103
+ await call('POST', `${docs}:commit`, { project, body: { writes } });
104
+ n += writes.length;
105
+ say?.(`Wrote ${n} of ${backup.documents.length}`);
106
+ }
107
+ return n;
108
+ }
package/src/cli.mjs CHANGED
@@ -4,20 +4,34 @@
4
4
  * npx create-heresay status what's deployed where
5
5
  * npx create-heresay open open a dashboard
6
6
  * npx create-heresay remove delete a Heresay and its Google Cloud project
7
+ * npx create-heresay backup save a Heresay's data to a file
8
+ * npx create-heresay restore put a backup into a Heresay
7
9
  *
8
10
  * The UX is specified in docs/plan/cli-ux.md.
9
11
  */
10
12
  import * as p from '@clack/prompts';
11
13
  import pc from 'picocolors';
12
14
  import { spawn } from 'node:child_process';
15
+ import { readFileSync, writeFileSync } from 'node:fs';
16
+ import { resolve as resolvePath } from 'node:path';
13
17
  import { randomBytes } from 'node:crypto';
14
- import { account } from './google.mjs';
18
+ import { account, g } from './google.mjs';
19
+ import * as backup from './backup.mjs';
15
20
  import { firebase, logTo } from './firebase.mjs';
16
21
  import * as state from './state.mjs';
17
22
  import * as steps from './steps.mjs';
18
23
 
19
24
  const peacock = (s) => `\x1b[38;2;15;118;110m${s}\x1b[39m`;
20
- const url = (id) => `https://${process.env.HERESAY_SITE || id}.web.app`;
25
+ /**
26
+ * Where a Heresay answers. HERESAY_SITE (a named Hosting site) wins when set; otherwise the address
27
+ * saved at setup or the last deploy (a Lite host, or a named site deployed from CI), and only then
28
+ * the project's default site. Without the saved one, status checks an address that may be retired.
29
+ */
30
+ const url = (id) => {
31
+ if (process.env.HERESAY_SITE) return `https://${process.env.HERESAY_SITE}.web.app`;
32
+ const rec = state.load().instances[id];
33
+ return rec?.origin || rec?.url || `https://${id}.web.app`;
34
+ };
21
35
 
22
36
  // ---- arguments --------------------------------------------------------------------------
23
37
 
@@ -41,15 +55,31 @@ const HELP = `
41
55
  npx create-heresay update Deploy this version to a Heresay you set up
42
56
  npx create-heresay status See what's deployed, and where
43
57
  npx create-heresay open Open your dashboard
58
+ npx create-heresay backup Save all of a Heresay's data to a file
59
+ npx create-heresay restore Put a backup file into a Heresay: restore <file>
44
60
  npx create-heresay remove Delete a Heresay and its Google Cloud project
45
61
 
46
62
  Setup flags, to skip questions:
47
63
  --name <name> --project-id <id> --region us-central1|asia-south1|europe-west1
48
64
  --billing <account> --owner <email> --yes (take every default, never ask)
65
+
66
+ Free plan, no billing (Spark): the API runs on a host you choose instead of Cloud Functions.
67
+ --lite --origin https://your-host.example see docs/lite.md
68
+
69
+ Backup and restore:
70
+ --out <file> where backup writes --project-id <id> a Heresay set up elsewhere
71
+ --force restore into a Heresay that already has data
49
72
  `;
50
73
 
51
74
  // ---- small helpers ----------------------------------------------------------------------
52
75
 
76
+ /** A prompt with no terminal to answer it hangs, and Node exits with a confusing warning. Say what to do instead. */
77
+ function needsTerminal(what, flags) {
78
+ if (process.stdin.isTTY) return;
79
+ p.log.error(`${what} asks questions, and there's no terminal to answer them here. Run it in a terminal, or pass ${flags}.`);
80
+ process.exit(2);
81
+ }
82
+
53
83
  function bail(v) {
54
84
  if (p.isCancel(v)) { p.cancel('Stopped. Nothing else was changed; run this again to carry on.'); process.exit(0); }
55
85
  return v;
@@ -61,6 +91,11 @@ function openInBrowser(target) {
61
91
  try { spawn(cmd, args, { stdio: 'ignore', detached: true }).unref(); } catch { /* the URL is printed anyway */ }
62
92
  }
63
93
 
94
+ /** The named Hosting site a saved Heresay lives on, from its saved address. */
95
+ const savedSite = (rec) => /^https:\/\/([a-z0-9-]+)\.web\.app$/.exec(rec?.url ?? '')?.[1];
96
+ const savedCtx = (id, rec) => ({ id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner,
97
+ lite: rec.lite, origin: rec.origin, site: savedSite(rec), onlySite: rec.only_site });
98
+
64
99
  const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
65
100
  function suggestId(name) {
66
101
  const tail = randomBytes(3).toString('hex').slice(0, 4);
@@ -113,6 +148,8 @@ async function ensureLogin(args) {
113
148
  async function setup(args) {
114
149
  const version = steps.releaseVersion();
115
150
  p.intro(`${peacock(pc.bold('heresay'))} ${pc.dim('· every report gets a hearing')}`);
151
+ if (!args.yes) needsTerminal('Setup', '--yes (it takes every default; see --help for the rest)');
152
+ if (args.lite && args.yes && !args.origin) { p.log.error('Lite needs --origin https://your-host.example (the address your host will serve).'); process.exit(1); }
116
153
 
117
154
  const [major] = process.versions.node.split('.').map(Number);
118
155
  if (major < 20) {
@@ -127,7 +164,7 @@ async function setup(args) {
127
164
  if (unfinished.length && !args['project-id']) {
128
165
  const [id, rec] = unfinished[0];
129
166
  const resume = args.yes ? true : bail(await p.confirm({ message: `Found an unfinished setup for ${pc.bold(id)}. Pick up where it stopped?` }));
130
- if (resume) ctx = { id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner, version };
167
+ if (resume) ctx = { ...savedCtx(id, rec), version };
131
168
  else if (!args.yes) {
132
169
  const drop = bail(await p.confirm({ message: 'Forget it and start a new one? (The Google project stays; remove it with npx create-heresay remove.)', initialValue: false }));
133
170
  if (!drop) { p.outro('Nothing changed.'); return; }
@@ -135,8 +172,18 @@ async function setup(args) {
135
172
  }
136
173
  }
137
174
 
175
+ const lite = ctx ? !!ctx.lite : !!args.lite;
138
176
  if (!ctx) {
139
- p.note([
177
+ if (lite) p.note([
178
+ 'This sets up your own Heresay in your Google account, on the free Spark plan:',
179
+ '',
180
+ ` ${peacock('•')} A new Firebase project: its database and sign-in`,
181
+ ` ${peacock('•')} A key and a settings file for the server`,
182
+ '',
183
+ 'No billing account. The API, dashboard and SDK run as one Node server on a',
184
+ 'host you choose (any host that runs Docker or Node), at the address you give.',
185
+ ].join('\n'), 'About 3 minutes');
186
+ else p.note([
140
187
  'This sets up your own Heresay in your Google account:',
141
188
  '',
142
189
  ` ${peacock('•')} A new Firebase project, owned by you`,
@@ -177,7 +224,17 @@ async function setup(args) {
177
224
  })));
178
225
  if (!steps.REGIONS.some((r) => r.value === region)) { p.log.error(`Unknown region ${region}.`); process.exit(1); }
179
226
 
180
- const billing = await pickBilling(args);
227
+ const billing = lite ? null : await pickBilling(args);
228
+ let origin = null;
229
+ if (lite) {
230
+ origin = args.origin ?? (args.yes ? null : bail(await p.text({
231
+ message: 'Where will your Heresay run? (its public https address)',
232
+ placeholder: 'https://heresay.example.com',
233
+ validate: (v) => (/^https:\/\/[^\s/]+$/.test((v ?? '').replace(/\/$/, '')) ? undefined : 'An https address like https://heresay.example.com'),
234
+ })));
235
+ origin = origin && String(origin).replace(/\/$/, '');
236
+ if (!origin || !/^https:\/\/[^\s/]+$/.test(origin)) { p.log.error('Lite needs --origin https://your-host.example (the address your host will serve).'); process.exit(1); }
237
+ }
181
238
 
182
239
  const owner = args.owner ?? (args.yes ? email : bail(await p.text({
183
240
  message: 'Who can sign in to the dashboard?',
@@ -185,13 +242,32 @@ async function setup(args) {
185
242
  validate: (v) => (!v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? undefined : 'That isn’t an email address'),
186
243
  })));
187
244
 
188
- ctx = { id, name, region, billing, owner, version, account: email };
189
- state.update(id, { name, region, billing, owner, url: url(id), created_at: new Date().toISOString(), done: {} });
245
+ ctx = { id, name, region, billing, owner, version, account: email, lite, origin };
246
+ state.update(id, { name, region, billing, owner, lite, origin, url: lite ? origin : url(id), created_at: new Date().toISOString(), done: {} });
190
247
  if (!args.yes) p.log.message(pc.dim('You can add teammates in the dashboard later.'));
191
248
  }
192
249
 
193
250
  await build(ctx);
194
251
 
252
+ if (ctx.lite) {
253
+ const dir = state.workDir(ctx.id);
254
+ p.note([
255
+ `Everything your host needs is in ${pc.bold(dir)}:`,
256
+ '',
257
+ ` ${peacock('•')} Dockerfile builds the server`,
258
+ ` ${peacock('•')} lite.env its settings and key (secret: keep it out of git)`,
259
+ '',
260
+ 'Try it on this computer:',
261
+ pc.dim(` cd ${dir}`),
262
+ pc.dim(' docker build -t heresay-lite . && docker run --rm -p 8080:8080 --env-file lite.env heresay-lite'),
263
+ '',
264
+ `On a host, build that folder as a Docker service and add each line of lite.env as an environment variable. It must answer at ${pc.bold(ctx.origin)}.`,
265
+ `Then open ${ctx.origin}/app/ and sign in as ${ctx.owner}. Check with: npx create-heresay status`,
266
+ ].join('\n'), 'Your Heresay is ready for a host');
267
+ p.outro('Every report gets a hearing.');
268
+ return;
269
+ }
270
+
195
271
  p.note([
196
272
  pc.bold(peacock(url(ctx.id))),
197
273
  '',
@@ -236,6 +312,16 @@ async function pickBilling(args) {
236
312
  }
237
313
  }
238
314
 
315
+ const BUILD_LITE = [
316
+ ['project', 'Creating the project', 'Project created', steps.project],
317
+ ['services', 'Switching on services', 'Services switched on', steps.liteServices],
318
+ ['database', 'Creating the database', 'Database created', steps.database],
319
+ ['signin', 'Setting up sign-in', 'Sign-in set up', steps.liteSignIn],
320
+ ['owner', 'Adding you as owner', 'Owner added', steps.owner],
321
+ ['deploy', 'Preparing the server', 'Server prepared', steps.liteDeploy],
322
+ ['verify', 'Checking for your host', 'Checked', steps.liteVerify],
323
+ ];
324
+
239
325
  const BUILD = [
240
326
  ['project', 'Creating the project', 'Project created', steps.project],
241
327
  ['billing', 'Linking billing', 'Billing linked', steps.billing],
@@ -261,7 +347,7 @@ async function build(ctx, only) {
261
347
  (await import('./firebase.mjs')).log(`\n==== ${new Date().toISOString()} ${only ? 'update' : 'setup'} ${ctx.id} (Heresay ${ctx.version})`);
262
348
  p.log.step(pc.bold(only ? `Updating ${ctx.id}` : 'Building your Heresay'));
263
349
  const rec = state.load().instances[ctx.id] ?? {};
264
- for (const [key, doing, title, run] of BUILD) {
350
+ for (const [key, doing, title, run] of (ctx.lite ? BUILD_LITE : BUILD)) {
265
351
  if (only && !only.includes(key)) continue;
266
352
  if (!only && rec.done?.[key] && key !== 'deploy' && key !== 'verify') {
267
353
  p.log.success(`${title} ${pc.dim('(done before)')}`);
@@ -278,7 +364,7 @@ async function build(ctx, only) {
278
364
  if (key === 'signin' && ctx.googleError) {
279
365
  p.log.warn(`Google sign-in couldn’t be switched on (${ctx.googleError}). Email links work. To add Google later: https://console.firebase.google.com/project/${ctx.id}/authentication/providers`);
280
366
  }
281
- if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: url(ctx.id) });
367
+ if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: ctx.lite ? ctx.origin : `https://${steps.siteOf(ctx)}.web.app`, ...(steps.onlySite(ctx) ? { only_site: true } : {}) });
282
368
  } catch (e) {
283
369
  s.error(`${doing}: stopped`);
284
370
  fail(e, ctx.id);
@@ -288,14 +374,26 @@ async function build(ctx, only) {
288
374
 
289
375
  // ---- other commands ---------------------------------------------------------------------
290
376
 
291
- async function pickInstance(verb, args) {
377
+ /**
378
+ * Which Heresay a command is about. `anywhere`: the command only needs the project id (backup,
379
+ * restore), so a Heresay set up from another computer, or by a teammate, works with --project-id.
380
+ */
381
+ async function pickInstance(verb, args, { anywhere = false } = {}) {
292
382
  const all = state.load().instances;
293
383
  const ids = Object.keys(all);
294
384
  if (args['project-id']) {
295
- if (!all[args['project-id']]) { p.log.error(`This computer didn’t set up ${args['project-id']}.`); process.exit(1); }
385
+ if (!all[args['project-id']] && !anywhere) {
386
+ p.log.error(`${args['project-id']} wasn’t set up from this computer, so its settings aren’t here. Run this on the computer that set it up.`);
387
+ process.exit(1);
388
+ }
296
389
  return args['project-id'];
297
390
  }
298
- if (!ids.length) { p.log.error('This computer hasn’t set up a Heresay yet. Run npx create-heresay first.'); process.exit(1); }
391
+ if (!ids.length) {
392
+ p.log.error(anywhere
393
+ ? 'No Heresay was set up from this computer. Name yours with --project-id <id> (its Firebase project ID, listed at console.firebase.google.com), or run npx create-heresay to make one.'
394
+ : 'No Heresay was set up from this computer. Run this on the computer that set it up, or npx create-heresay to make a new one.');
395
+ process.exit(1);
396
+ }
299
397
  if (ids.length === 1) return ids[0];
300
398
  return bail(await p.select({ message: `Which Heresay do you want to ${verb}?`, options: ids.map((id) => ({ value: id, label: id, hint: all[id].url })) }));
301
399
  }
@@ -319,7 +417,8 @@ async function update(args) {
319
417
  if (!go) { p.outro('Nothing changed.'); return; }
320
418
  }
321
419
  const signedIn = await account();
322
- await build({ id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner, version, account: signedIn }, ['deploy', 'verify']);
420
+ await build({ ...savedCtx(id, rec), version, account: signedIn }, ['deploy', 'verify']);
421
+ if (rec.lite) { p.outro(`Rebuild your host from ${state.workDir(id)} to run ${version}.`); return; }
323
422
  p.outro(`${url(id)} is on ${version}.`);
324
423
  }
325
424
 
@@ -356,6 +455,7 @@ async function removeCmd(args) {
356
455
  `This deletes the Google Cloud project ${pc.bold(id)}: its dashboard, every app and every report.`,
357
456
  'Google keeps it recoverable for 30 days, then it is gone. Billing is unlinked straight away.',
358
457
  ].join('\n'));
458
+ needsTerminal('Remove', 'nothing: deleting a Heresay always needs a person to type its id');
359
459
  const typed = bail(await p.text({ message: `Type ${id} to confirm` }));
360
460
  if (typed !== id) { p.outro('That didn’t match. Nothing was deleted.'); return; }
361
461
  await account();
@@ -367,6 +467,61 @@ async function removeCmd(args) {
367
467
  p.outro('Done.');
368
468
  }
369
469
 
470
+ const FS = 'https://firestore.googleapis.com/v1';
471
+
472
+ async function backupCmd(args) {
473
+ p.intro(`${peacock(pc.bold('heresay'))} backup`);
474
+ const id = await pickInstance('back up', args, { anywhere: true });
475
+ await account();
476
+ const s = progress(false);
477
+ s.start(`Reading ${id}`);
478
+ let b;
479
+ try { b = await backup.dump(g, { base: FS, project: id, version: steps.releaseVersion(), say: (m) => s.message(m) }); } catch (e) { s.error('Couldn’t read it'); fail(e); }
480
+ const stamp = b.created_at.slice(0, 16).replace(/[-:]/g, '').replace('T', '-');
481
+ const file = resolvePath(String(args.out ?? `heresay-backup-${id}-${stamp}.json`));
482
+ writeFileSync(file, JSON.stringify(b) + '\n', { mode: 0o600 });
483
+ s.stop(`Saved ${b.documents.length} documents`);
484
+ const by = backup.summarize(b);
485
+ p.note([
486
+ ...Object.entries(by).map(([k, n]) => ` ${k.padEnd(16)} ${n}`),
487
+ '',
488
+ pc.bold(file),
489
+ '',
490
+ ...(b.unscanned.length ? [pc.yellow(`${b.unscanned.length} documents with ':' in their id were saved, but Firestore can’t list subcollections under them (Heresay keeps none there).`), ''] : []),
491
+ 'It holds secrets (notification tokens, hashed agent tokens). Keep it somewhere private.',
492
+ 'Put it back with: npx create-heresay restore <file>',
493
+ ].join('\n'), 'Backup');
494
+ p.outro('Done.');
495
+ }
496
+
497
+ async function restoreCmd(args) {
498
+ p.intro(`${peacock(pc.bold('heresay'))} restore`);
499
+ const path = args._[1];
500
+ if (!path) { p.log.error('Which file? npx create-heresay restore <file>'); process.exit(1); }
501
+ let b;
502
+ try { b = backup.check(JSON.parse(readFileSync(path, 'utf8'))); } catch (e) {
503
+ p.log.error(e.code === 'ENOENT' ? `There’s no file at ${path}.` : e instanceof SyntaxError ? `${path} isn’t a Heresay backup (it isn’t JSON).` : e.message);
504
+ process.exit(1);
505
+ }
506
+ const id = await pickInstance('restore into', args, { anywhere: true });
507
+ await account();
508
+ p.log.info(`${b.documents.length} documents from ${b.project} (${b.created_at.slice(0, 10)}) → ${id}`);
509
+ if (await backup.hasData(g, { base: FS, project: id }) && !args.force) {
510
+ p.log.error(`${id} already has data. Restoring would overwrite matching documents and keep the rest. Run again with --force if that’s what you want.`);
511
+ process.exit(1);
512
+ }
513
+ if (!args.yes) {
514
+ needsTerminal('Restore', '--yes to restore without typing the id');
515
+ const typed = bail(await p.text({ message: `Type ${id} to restore into it` }));
516
+ if (typed !== id) { p.outro('That didn’t match. Nothing was written.'); return; }
517
+ }
518
+ const s = progress(false);
519
+ s.start('Writing');
520
+ try { await backup.restore(g, b, { base: FS, project: id, say: (m) => s.message(m) }); } catch (e) { s.error('Stopped part way; run it again to finish'); fail(e); }
521
+ s.stop(`Restored ${b.documents.length} documents`);
522
+ p.outro(`Sign in at ${url(id)}/app/ with a team email. Reconnect repos with npx heresay connect --url ${url(id)}.`);
523
+ }
524
+
370
525
  export async function main(argv) {
371
526
  const args = parseArgs(argv);
372
527
  const cmd = args._[0];
@@ -377,6 +532,8 @@ export async function main(argv) {
377
532
  if (cmd === 'status') return status(args);
378
533
  if (cmd === 'open') return open(args);
379
534
  if (cmd === 'remove') return removeCmd(args);
535
+ if (cmd === 'backup') return backupCmd(args);
536
+ if (cmd === 'restore') return restoreCmd(args);
380
537
  console.log(`Unknown command: ${cmd}\n${HELP}`);
381
538
  process.exit(1);
382
539
  }
package/src/steps.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * ctx: { id, name, region, billing, owner, version }. `say(text)` updates the spinner line.
6
6
  */
7
- import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { chmodSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { g, op, patiently, GoogleError } from './google.mjs';
@@ -128,7 +128,14 @@ export async function database(ctx, say) {
128
128
  }
129
129
 
130
130
  /** The hosting site id: the project id unless HERESAY_SITE names another site in the project. */
131
- export const siteOf = (ctx) => process.env.HERESAY_SITE || ctx.id;
131
+ /**
132
+ * The hosting site: HERESAY_SITE if set, else the one this Heresay was last deployed to (saved in
133
+ * ~/.heresay), else the project's default site. So `update` from a laptop reaches the same site
134
+ * CI deploys to, instead of the default one.
135
+ */
136
+ export const siteOf = (ctx) => process.env.HERESAY_SITE || ctx.site || ctx.id;
137
+ /** Serve only the named site (the default one retired): HERESAY_ONLY_SITE=1, or saved from a deploy that set it. */
138
+ export const onlySite = (ctx) => process.env.HERESAY_ONLY_SITE === '1' || !!ctx.onlySite;
132
139
 
133
140
  // ---- the release, laid out for `firebase deploy` ----------------------------------------
134
141
 
@@ -151,13 +158,14 @@ export function prepareRelease(ctx) {
151
158
  // address, and repos already connected to it, must keep working. HERESAY_ONLY_SITE=1 opts out
152
159
  // for an instance that has retired the default address.
153
160
  if (siteOf(ctx) !== ctx.id) {
154
- cfg.hosting = process.env.HERESAY_ONLY_SITE === '1'
161
+ cfg.hosting = onlySite(ctx)
155
162
  ? { ...cfg.hosting, site: siteOf(ctx) }
156
163
  : [{ ...cfg.hosting, site: siteOf(ctx) }, { ...cfg.hosting, site: ctx.id }];
157
164
  }
158
165
  writeFileSync(join(dir, 'firebase.json'), JSON.stringify(cfg, null, 2) + '\n');
159
166
  writeFileSync(join(dir, '.firebaserc'), JSON.stringify({ projects: { default: ctx.id } }, null, 2) + '\n');
160
- writeFileSync(join(dir, 'functions', '.env'), `HERESAY_REGION=${ctx.region}\n`);
167
+ // HERESAY_SITE: the API names this site (not the default one) in OAuth discovery and alert links.
168
+ writeFileSync(join(dir, 'functions', '.env'), `HERESAY_REGION=${ctx.region}\n${siteOf(ctx) !== ctx.id ? `HERESAY_SITE=${siteOf(ctx)}\n` : ''}`);
161
169
  return dir;
162
170
  }
163
171
 
@@ -307,6 +315,115 @@ export async function verify(ctx, say) {
307
315
  }
308
316
  }
309
317
 
318
+ // ---- Lite: Spark plan, the API on a host you choose -------------------------------------
319
+ //
320
+ // No billing account and no Cloud Functions. Firestore and Auth stay on Firebase; the same API
321
+ // runs from functions/lib/providers/firebase/node-server.js on any Node host. See docs/lite.md.
322
+
323
+ const LITE_SERVICES = ['firestore.googleapis.com', 'identitytoolkit.googleapis.com', 'firebaserules.googleapis.com', 'iam.googleapis.com'];
324
+ const IAM = 'https://iam.googleapis.com/v1';
325
+
326
+ export async function liteServices(ctx, say) {
327
+ say('Switching on Firestore and Auth');
328
+ const o = await patiently(() => g('POST', `${SU}/projects/${ctx.id}/services:batchEnable`, { body: { serviceIds: LITE_SERVICES } }), { forMs: 90_000 });
329
+ await op(SU, o, { timeoutMs: 6 * 60_000 });
330
+ return 'Firestore, Auth';
331
+ }
332
+
333
+ /** Email-link sign-in, and the host's address allowed to use it. */
334
+ export async function liteSignIn(ctx, say) {
335
+ await webApp(ctx, say);
336
+ say('Switching on email links');
337
+ await g('POST', `https://identitytoolkit.googleapis.com/v2/projects/${ctx.id}/identityPlatform:initializeAuth`, { project: ctx.id, body: {} })
338
+ .catch((x) => { if (x.status !== 409 && !/already/i.test(x.message)) throw x; });
339
+ await patiently(() => g('PATCH', `${IDT}/projects/${ctx.id}/config?updateMask=signIn.email.enabled,signIn.email.passwordRequired`, {
340
+ project: ctx.id, body: { signIn: { email: { enabled: true, passwordRequired: false } } },
341
+ }), { forMs: 90_000 }).catch((e) => {
342
+ throw new StepError(`Sign-in couldn’t be switched on (${e.message}).`,
343
+ `Open https://console.firebase.google.com/project/${ctx.id}/authentication, click Get started, then run this again.`);
344
+ });
345
+ say('Allowing ' + new URL(ctx.origin).hostname);
346
+ const cfg = await patiently(() => g('GET', `${IDT}/projects/${ctx.id}/config`, { project: ctx.id }), { forMs: 90_000 });
347
+ const domains = new Set(cfg.authorizedDomains ?? []);
348
+ domains.add(new URL(ctx.origin).hostname);
349
+ await g('PATCH', `${IDT}/projects/${ctx.id}/config?updateMask=authorizedDomains`, { project: ctx.id, body: { authorizedDomains: [...domains] } });
350
+ return 'email links, ' + new URL(ctx.origin).hostname;
351
+ }
352
+
353
+ /** What the host needs: the runtime files, and one env file with everything it reads. */
354
+ export async function liteDeploy(ctx, say) {
355
+ const dir = workDir(ctx.id);
356
+ mkdirSync(dir, { recursive: true });
357
+ for (const f of readdirSync(dir)) if (!['service-account.json', 'lite.env'].includes(f)) rmSync(join(dir, f), { recursive: true, force: true });
358
+ cpSync(RELEASE, dir, { recursive: true });
359
+ writeFileSync(join(dir, 'firebase.json'), JSON.stringify({ firestore: { rules: 'firestore.rules', indexes: 'firestore.indexes.json' } }, null, 2) + '\n');
360
+ writeFileSync(join(dir, '.firebaserc'), JSON.stringify({ projects: { default: ctx.id } }, null, 2) + '\n');
361
+ writeFileSync(join(dir, 'Dockerfile'), [
362
+ 'FROM node:22-slim',
363
+ 'ENV NODE_ENV=production PORT=8080 HERESAY_TRUST_PROXY=1',
364
+ 'WORKDIR /app',
365
+ 'COPY functions/package.json functions/package-lock.json ./functions/',
366
+ 'RUN npm --prefix functions ci --omit=dev',
367
+ 'COPY functions/lib ./functions/lib',
368
+ 'COPY public ./public',
369
+ 'USER node',
370
+ 'EXPOSE 8080',
371
+ 'CMD ["node", "functions/lib/providers/firebase/node-server.js"]',
372
+ '',
373
+ ].join('\n'));
374
+
375
+ for (let attempt = 1; ; attempt++) {
376
+ say(attempt === 1 ? 'Locking the database' : `Trying again (${attempt} of 3)`);
377
+ const r = await firebase(['deploy', '--only', 'firestore', '--project', ctx.id, '--non-interactive', '--force'], { cwd: dir });
378
+ if (r.code === 0) break;
379
+ if (attempt < 3 && /permission|403|429|RESOURCE_EXHAUSTED|Internal error|retry|unavailable/i.test(r.out)) {
380
+ say('Google is still setting up the project; waiting a minute');
381
+ await new Promise((res) => setTimeout(res, 60_000));
382
+ continue;
383
+ }
384
+ throw new StepError(`Deploy failed: ${deployError(r.out)}`, 'Your project is fine. Run the same command to try again.');
385
+ }
386
+
387
+ const keyPath = join(dir, 'service-account.json');
388
+ if (!existsSync(keyPath)) {
389
+ say('Creating the server’s key');
390
+ const list = await patiently(() => g('GET', `${IAM}/projects/${ctx.id}/serviceAccounts`, { project: ctx.id }), { forMs: 120_000 });
391
+ const sa = (list.accounts ?? []).find((a) => a.email.startsWith('firebase-adminsdk'));
392
+ if (!sa) throw new StepError('The Firebase service account isn’t there yet.', 'Give it a minute and run this again.');
393
+ let key;
394
+ try {
395
+ key = await g('POST', `${IAM}/${sa.name}/keys`, { project: ctx.id, body: {} });
396
+ } catch (e) {
397
+ throw new StepError(`Google wouldn’t create a key for the server (${e.message}).`,
398
+ 'An organisation policy may block service-account keys. Create the key by hand in the Firebase console (Project settings, Service accounts), save it as service-account.json in ' + dir + ', and run this again.');
399
+ }
400
+ writeFileSync(keyPath, Buffer.from(key.privateKeyData, 'base64'), { mode: 0o600 });
401
+ }
402
+ chmodSync(keyPath, 0o600);
403
+
404
+ say('Reading the web config');
405
+ const appId = await webApp(ctx, () => {});
406
+ const web = await patiently(() => g('GET', `${FB}/projects/${ctx.id}/webApps/${appId}/config`, { project: ctx.id }), { forMs: 90_000 });
407
+ const config = { apiKey: web.apiKey, authDomain: web.authDomain, projectId: web.projectId, appId: web.appId, messagingSenderId: web.messagingSenderId };
408
+ const oneLine = (v) => JSON.stringify(v);
409
+ writeFileSync(join(dir, 'lite.env'), [
410
+ `HERESAY_ORIGIN=${ctx.origin}`,
411
+ `GCLOUD_PROJECT=${ctx.id}`,
412
+ `HERESAY_FIREBASE_CONFIG=${oneLine(config)}`,
413
+ `GOOGLE_APPLICATION_CREDENTIALS_JSON=${oneLine(JSON.parse(readFileSync(keyPath, 'utf8')))}`,
414
+ '',
415
+ ].join('\n'), { mode: 0o600 });
416
+ return dir;
417
+ }
418
+
419
+ export async function liteVerify(ctx) {
420
+ try {
421
+ const h = await (await fetch(`${ctx.origin}/v1/health`, { signal: AbortSignal.timeout(8000) })).json();
422
+ if (h.ok) return `running, version ${h.version}`;
423
+ } catch { /* not started yet, which is expected on first setup */ }
424
+ return 'ready for your host';
425
+ }
426
+
310
427
  // ---- remove -----------------------------------------------------------------------------
311
428
 
312
429
  export async function remove(id) {