create-heresay 0.2.42 → 0.2.44

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.42",
3
+ "version": "0.2.44",
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.42
1
+ 0.2.44
@@ -207,7 +207,7 @@ export async function notificationSettings(p, req, deps, body) {
207
207
  if (!deps.sendNotification)
208
208
  return json(503, { error: 'Notification delivery is unavailable.' });
209
209
  try {
210
- await deps.sendNotification(provider, target, 'Heresay notifications are connected. You will receive the events selected in Notifications.');
210
+ await deps.sendNotification(provider, target, '✅ Heresay is connected. You will get the alerts you chose in Notifications.');
211
211
  return json(200, { ok: true });
212
212
  }
213
213
  catch {
@@ -216,6 +216,11 @@ export async function notificationSettings(p, req, deps, body) {
216
216
  }
217
217
  return json(404, { error: 'not found' });
218
218
  }
219
+ const HEADLINE = {
220
+ new_report: ['🔔', 'New report'], accepted: ['✅', 'Accepted'], fixed: ['🛠️', 'Fixed'], handoff: ['🔁', 'Handed off'],
221
+ };
222
+ const TYPE = { broken: ['🐞', 'Broken'], confusing: ['🤔', 'Confusing'], improvement: ['✨', 'Improvement'], idea: ['💡', 'Idea'] };
223
+ const esc = (t) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
219
224
  const actionsReady = (tg) => !!(tg.webhook_secret && tg.webhook_url);
220
225
  /** Metadata only: open reports and reporter details must never flow into an integration. */
221
226
  export async function notify(event, project, reportId, deps) {
@@ -227,16 +232,24 @@ export async function notify(event, project, reportId, deps) {
227
232
  new_report: 'A new report needs your review', accepted: 'A report was accepted for a coding agent',
228
233
  fixed: 'A report was marked fixed', handoff: 'A coding agent handed off a report',
229
234
  };
235
+ const [emoji, head] = HEADLINE[event];
236
+ // The type is one of four fixed words, never the reporter's text.
237
+ const found = await deps.store.getReport(project.id, reportId).catch(() => null);
238
+ const type = (found && TYPE[found.type]) || null;
230
239
  const origin = deps.selfOrigins?.[0];
231
- const text = `Heresay: ${labels[event]}.\nApp: ${project.name}\nReport: ${reportId}`
232
- + (origin ? `\n${origin}/app/#/apps/${encodeURIComponent(project.id)}` : '');
240
+ const link = origin ? `${origin}/app/#/apps/${encodeURIComponent(project.id)}` : null;
241
+ const meta = [type ? `${type[0]} ${type[1]}` : null, reportId];
242
+ const text = [`${emoji} ${head} · ${project.name}`, `${labels[event]}.`, meta.filter(Boolean).join(' · ')].join('\n') + (link ? `\n${link}` : '');
243
+ // Telegram gets bold and a link; the app name is the team's own, escaped, and nothing from a reporter is in it.
244
+ const html = `${emoji} <b>${esc(head)}</b> · ${esc(project.name)}\n${esc(labels[event])}.\n${type ? `${type[0]} ${type[1]} · ` : ''}<code>${esc(reportId)}</code>`
245
+ + (link ? `\n<a href="${esc(link)}">Open in Heresay →</a>` : '');
233
246
  await Promise.all(['telegram', 'cliq'].map(async (provider) => {
234
247
  if (!settings[provider].enabled)
235
248
  return;
236
249
  try {
237
250
  const markup = provider === 'telegram' && event === 'new_report' && actionsReady(settings.telegram)
238
251
  ? reportKeyboard(project.id, reportId) : null;
239
- await deps.sendNotification(provider, settings[provider], text, markup ? { telegram_markup: markup } : undefined);
252
+ await deps.sendNotification(provider, settings[provider], provider === 'telegram' ? html : text, provider === 'telegram' ? { telegram_html: true, ...(markup ? { telegram_markup: markup } : {}) } : undefined);
240
253
  deps.log('api.notification_sent', { provider, notification_event: event, project_id: project.id, report_id: reportId });
241
254
  }
242
255
  catch {
@@ -258,7 +271,7 @@ export function notificationSender(http = fetch) {
258
271
  throw new Error('Notification token missing.');
259
272
  if (provider === 'telegram' && 'chat_id' in destination) {
260
273
  url = `https://api.telegram.org/bot${destination.token}/sendMessage`;
261
- body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true }, ...(extra?.telegram_markup ? { reply_markup: extra.telegram_markup } : {}) };
274
+ body = { chat_id: destination.chat_id, text, ...(extra?.telegram_html ? { parse_mode: 'HTML' } : {}), link_preview_options: { is_disabled: true }, ...(extra?.telegram_markup ? { reply_markup: extra.telegram_markup } : {}) };
262
275
  }
263
276
  else if (provider === 'cliq' && 'endpoint' in destination && validCliqEndpoint(destination.endpoint)) {
264
277
  const u = new URL(destination.endpoint);
@@ -36,9 +36,9 @@ export function reportKeyboard(project_id, report_id) {
36
36
  if (Buffer.byteLength(data('a')) > 64)
37
37
  return null;
38
38
  return { inline_keyboard: [[
39
- { text: 'Accept', callback_data: data('a') },
40
- { text: 'Decline', callback_data: data('d') },
41
- { text: 'Show full text', callback_data: data('t') },
39
+ { text: '✅ Accept', callback_data: data('a') },
40
+ { text: '✖️ Decline', callback_data: data('d') },
41
+ { text: '📄 Full text', callback_data: data('t') },
42
42
  ]] };
43
43
  }
44
44
  // ---- keeping Telegram's webhook in step with the saved bot ----------------------------------
@@ -253,7 +253,7 @@ async function handleUpdate(u, members, tg, deps, triage) {
253
253
  const res = await triage(project, report.id, 'accept', email, fakeReq(), deps);
254
254
  if (res.status === 200) {
255
255
  await answer('Accepted');
256
- await finish(api, token, cb.message, `Accepted by ${email}`);
256
+ await finish(api, token, cb.message, `✅ Accepted by ${email}`);
257
257
  return;
258
258
  }
259
259
  await alreadyOrFail(res, project, report.id, answer, cb.message);
@@ -346,7 +346,7 @@ async function handleUpdate(u, members, tg, deps, triage) {
346
346
  const original = { message_id: Number(pending.data.message_id), chat: msg.chat, text: String(pending.data.text ?? '') };
347
347
  if (res.status === 200) {
348
348
  await deps.store.deleteAuth('decline', key);
349
- await finish(api, token, original, `Declined by ${email}: ${text}`);
349
+ await finish(api, token, original, `✖️ Declined by ${email}: ${text}`);
350
350
  await reply('Declined. The reporter will see your reason.');
351
351
  return;
352
352
  }
@@ -376,7 +376,9 @@ const fakeReq = (body = {}) => ({ method: 'POST', path: '', query: {}, headers:
376
376
  async function finish(api, token, message, line) {
377
377
  await api(token, 'editMessageText', {
378
378
  chat_id: message.chat.id, message_id: message.message_id,
379
- text: capText(`${(message.text ?? '').replace(/\n\n(Accepted|Declined) by [\s\S]*$/, '')}\n\n${line}`.trim()),
379
+ text: capText(`${(message.text ?? '').replace(/\n\n(✅ Accepted|✖️ Declined|Accepted|Declined) by [\s\S]*$/, '')}\n\n${line}`.trim()),
380
+ // The alert's bold and link, kept: the outcome is added after them, so their positions still hold.
381
+ ...(message.entities?.length ? { entities: message.entities } : {}),
380
382
  link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [] },
381
383
  });
382
384
  }
@@ -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.42';
2
+ export const VERSION = '0.2.44';
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
@@ -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/cli.mjs CHANGED
@@ -17,7 +17,8 @@ import * as state from './state.mjs';
17
17
  import * as steps from './steps.mjs';
18
18
 
19
19
  const peacock = (s) => `\x1b[38;2;15;118;110m${s}\x1b[39m`;
20
- const url = (id) => `https://${process.env.HERESAY_SITE || id}.web.app`;
20
+ // A Lite Heresay lives wherever its owner runs it; the address is kept when it is set up.
21
+ const url = (id) => state.load().instances[id]?.origin || `https://${process.env.HERESAY_SITE || id}.web.app`;
21
22
 
22
23
  // ---- arguments --------------------------------------------------------------------------
23
24
 
@@ -46,6 +47,9 @@ const HELP = `
46
47
  Setup flags, to skip questions:
47
48
  --name <name> --project-id <id> --region us-central1|asia-south1|europe-west1
48
49
  --billing <account> --owner <email> --yes (take every default, never ask)
50
+
51
+ Free plan, no billing (Spark): the API runs on a host you choose instead of Cloud Functions.
52
+ --lite --origin https://your-host.example see docs/lite.md
49
53
  `;
50
54
 
51
55
  // ---- small helpers ----------------------------------------------------------------------
@@ -127,7 +131,7 @@ async function setup(args) {
127
131
  if (unfinished.length && !args['project-id']) {
128
132
  const [id, rec] = unfinished[0];
129
133
  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 };
134
+ if (resume) ctx = { id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner, version, lite: rec.lite, origin: rec.origin };
131
135
  else if (!args.yes) {
132
136
  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
137
  if (!drop) { p.outro('Nothing changed.'); return; }
@@ -135,8 +139,18 @@ async function setup(args) {
135
139
  }
136
140
  }
137
141
 
142
+ const lite = ctx ? !!ctx.lite : !!args.lite;
138
143
  if (!ctx) {
139
- p.note([
144
+ if (lite) p.note([
145
+ 'This sets up your own Heresay in your Google account, on the free Spark plan:',
146
+ '',
147
+ ` ${peacock('•')} A new Firebase project: its database and sign-in`,
148
+ ` ${peacock('•')} A key and a settings file for the server`,
149
+ '',
150
+ 'No billing account. The API, dashboard and SDK run as one Node server on a',
151
+ 'host you choose (any host that runs Docker or Node), at the address you give.',
152
+ ].join('\n'), 'About 3 minutes');
153
+ else p.note([
140
154
  'This sets up your own Heresay in your Google account:',
141
155
  '',
142
156
  ` ${peacock('•')} A new Firebase project, owned by you`,
@@ -177,7 +191,17 @@ async function setup(args) {
177
191
  })));
178
192
  if (!steps.REGIONS.some((r) => r.value === region)) { p.log.error(`Unknown region ${region}.`); process.exit(1); }
179
193
 
180
- const billing = await pickBilling(args);
194
+ const billing = lite ? null : await pickBilling(args);
195
+ let origin = null;
196
+ if (lite) {
197
+ origin = args.origin ?? (args.yes ? null : bail(await p.text({
198
+ message: 'Where will your Heresay run? (its public https address)',
199
+ placeholder: 'https://heresay.example.com',
200
+ validate: (v) => (/^https:\/\/[^\s/]+$/.test((v ?? '').replace(/\/$/, '')) ? undefined : 'An https address like https://heresay.example.com'),
201
+ })));
202
+ origin = origin && String(origin).replace(/\/$/, '');
203
+ 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); }
204
+ }
181
205
 
182
206
  const owner = args.owner ?? (args.yes ? email : bail(await p.text({
183
207
  message: 'Who can sign in to the dashboard?',
@@ -185,13 +209,32 @@ async function setup(args) {
185
209
  validate: (v) => (!v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? undefined : 'That isn’t an email address'),
186
210
  })));
187
211
 
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: {} });
212
+ ctx = { id, name, region, billing, owner, version, account: email, lite, origin };
213
+ state.update(id, { name, region, billing, owner, lite, origin, url: lite ? origin : url(id), created_at: new Date().toISOString(), done: {} });
190
214
  if (!args.yes) p.log.message(pc.dim('You can add teammates in the dashboard later.'));
191
215
  }
192
216
 
193
217
  await build(ctx);
194
218
 
219
+ if (ctx.lite) {
220
+ const dir = state.workDir(ctx.id);
221
+ p.note([
222
+ `Everything your host needs is in ${pc.bold(dir)}:`,
223
+ '',
224
+ ` ${peacock('•')} Dockerfile builds the server`,
225
+ ` ${peacock('•')} lite.env its settings and key (secret: keep it out of git)`,
226
+ '',
227
+ 'Try it on this computer:',
228
+ pc.dim(` cd ${dir}`),
229
+ pc.dim(' docker build -t heresay-lite . && docker run --rm -p 8080:8080 --env-file lite.env heresay-lite'),
230
+ '',
231
+ `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)}.`,
232
+ `Then open ${ctx.origin}/app/ and sign in as ${ctx.owner}. Check with: npx create-heresay status`,
233
+ ].join('\n'), 'Your Heresay is ready for a host');
234
+ p.outro('Every report gets a hearing.');
235
+ return;
236
+ }
237
+
195
238
  p.note([
196
239
  pc.bold(peacock(url(ctx.id))),
197
240
  '',
@@ -236,6 +279,16 @@ async function pickBilling(args) {
236
279
  }
237
280
  }
238
281
 
282
+ const BUILD_LITE = [
283
+ ['project', 'Creating the project', 'Project created', steps.project],
284
+ ['services', 'Switching on services', 'Services switched on', steps.liteServices],
285
+ ['database', 'Creating the database', 'Database created', steps.database],
286
+ ['signin', 'Setting up sign-in', 'Sign-in set up', steps.liteSignIn],
287
+ ['owner', 'Adding you as owner', 'Owner added', steps.owner],
288
+ ['deploy', 'Preparing the server', 'Server prepared', steps.liteDeploy],
289
+ ['verify', 'Checking for your host', 'Checked', steps.liteVerify],
290
+ ];
291
+
239
292
  const BUILD = [
240
293
  ['project', 'Creating the project', 'Project created', steps.project],
241
294
  ['billing', 'Linking billing', 'Billing linked', steps.billing],
@@ -261,7 +314,7 @@ async function build(ctx, only) {
261
314
  (await import('./firebase.mjs')).log(`\n==== ${new Date().toISOString()} ${only ? 'update' : 'setup'} ${ctx.id} (Heresay ${ctx.version})`);
262
315
  p.log.step(pc.bold(only ? `Updating ${ctx.id}` : 'Building your Heresay'));
263
316
  const rec = state.load().instances[ctx.id] ?? {};
264
- for (const [key, doing, title, run] of BUILD) {
317
+ for (const [key, doing, title, run] of (ctx.lite ? BUILD_LITE : BUILD)) {
265
318
  if (only && !only.includes(key)) continue;
266
319
  if (!only && rec.done?.[key] && key !== 'deploy' && key !== 'verify') {
267
320
  p.log.success(`${title} ${pc.dim('(done before)')}`);
@@ -278,7 +331,7 @@ async function build(ctx, only) {
278
331
  if (key === 'signin' && ctx.googleError) {
279
332
  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
333
  }
281
- if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: url(ctx.id) });
334
+ if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: ctx.lite ? ctx.origin : url(ctx.id) });
282
335
  } catch (e) {
283
336
  s.error(`${doing}: stopped`);
284
337
  fail(e, ctx.id);
@@ -319,7 +372,8 @@ async function update(args) {
319
372
  if (!go) { p.outro('Nothing changed.'); return; }
320
373
  }
321
374
  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']);
375
+ await build({ id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner, version, account: signedIn, lite: rec.lite, origin: rec.origin }, ['deploy', 'verify']);
376
+ if (rec.lite) { p.outro(`Rebuild your host from ${state.workDir(id)} to run ${version}.`); return; }
323
377
  p.outro(`${url(id)} is on ${version}.`);
324
378
  }
325
379
 
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';
@@ -307,6 +307,115 @@ export async function verify(ctx, say) {
307
307
  }
308
308
  }
309
309
 
310
+ // ---- Lite: Spark plan, the API on a host you choose -------------------------------------
311
+ //
312
+ // No billing account and no Cloud Functions. Firestore and Auth stay on Firebase; the same API
313
+ // runs from functions/lib/providers/firebase/node-server.js on any Node host. See docs/lite.md.
314
+
315
+ const LITE_SERVICES = ['firestore.googleapis.com', 'identitytoolkit.googleapis.com', 'firebaserules.googleapis.com', 'iam.googleapis.com'];
316
+ const IAM = 'https://iam.googleapis.com/v1';
317
+
318
+ export async function liteServices(ctx, say) {
319
+ say('Switching on Firestore and Auth');
320
+ const o = await patiently(() => g('POST', `${SU}/projects/${ctx.id}/services:batchEnable`, { body: { serviceIds: LITE_SERVICES } }), { forMs: 90_000 });
321
+ await op(SU, o, { timeoutMs: 6 * 60_000 });
322
+ return 'Firestore, Auth';
323
+ }
324
+
325
+ /** Email-link sign-in, and the host's address allowed to use it. */
326
+ export async function liteSignIn(ctx, say) {
327
+ await webApp(ctx, say);
328
+ say('Switching on email links');
329
+ await g('POST', `https://identitytoolkit.googleapis.com/v2/projects/${ctx.id}/identityPlatform:initializeAuth`, { project: ctx.id, body: {} })
330
+ .catch((x) => { if (x.status !== 409 && !/already/i.test(x.message)) throw x; });
331
+ await patiently(() => g('PATCH', `${IDT}/projects/${ctx.id}/config?updateMask=signIn.email.enabled,signIn.email.passwordRequired`, {
332
+ project: ctx.id, body: { signIn: { email: { enabled: true, passwordRequired: false } } },
333
+ }), { forMs: 90_000 }).catch((e) => {
334
+ throw new StepError(`Sign-in couldn’t be switched on (${e.message}).`,
335
+ `Open https://console.firebase.google.com/project/${ctx.id}/authentication, click Get started, then run this again.`);
336
+ });
337
+ say('Allowing ' + new URL(ctx.origin).hostname);
338
+ const cfg = await patiently(() => g('GET', `${IDT}/projects/${ctx.id}/config`, { project: ctx.id }), { forMs: 90_000 });
339
+ const domains = new Set(cfg.authorizedDomains ?? []);
340
+ domains.add(new URL(ctx.origin).hostname);
341
+ await g('PATCH', `${IDT}/projects/${ctx.id}/config?updateMask=authorizedDomains`, { project: ctx.id, body: { authorizedDomains: [...domains] } });
342
+ return 'email links, ' + new URL(ctx.origin).hostname;
343
+ }
344
+
345
+ /** What the host needs: the runtime files, and one env file with everything it reads. */
346
+ export async function liteDeploy(ctx, say) {
347
+ const dir = workDir(ctx.id);
348
+ mkdirSync(dir, { recursive: true });
349
+ for (const f of readdirSync(dir)) if (!['service-account.json', 'lite.env'].includes(f)) rmSync(join(dir, f), { recursive: true, force: true });
350
+ cpSync(RELEASE, dir, { recursive: true });
351
+ writeFileSync(join(dir, 'firebase.json'), JSON.stringify({ firestore: { rules: 'firestore.rules', indexes: 'firestore.indexes.json' } }, null, 2) + '\n');
352
+ writeFileSync(join(dir, '.firebaserc'), JSON.stringify({ projects: { default: ctx.id } }, null, 2) + '\n');
353
+ writeFileSync(join(dir, 'Dockerfile'), [
354
+ 'FROM node:22-slim',
355
+ 'ENV NODE_ENV=production PORT=8080 HERESAY_TRUST_PROXY=1',
356
+ 'WORKDIR /app',
357
+ 'COPY functions/package.json functions/package-lock.json ./functions/',
358
+ 'RUN npm --prefix functions ci --omit=dev',
359
+ 'COPY functions/lib ./functions/lib',
360
+ 'COPY public ./public',
361
+ 'USER node',
362
+ 'EXPOSE 8080',
363
+ 'CMD ["node", "functions/lib/providers/firebase/node-server.js"]',
364
+ '',
365
+ ].join('\n'));
366
+
367
+ for (let attempt = 1; ; attempt++) {
368
+ say(attempt === 1 ? 'Locking the database' : `Trying again (${attempt} of 3)`);
369
+ const r = await firebase(['deploy', '--only', 'firestore', '--project', ctx.id, '--non-interactive', '--force'], { cwd: dir });
370
+ if (r.code === 0) break;
371
+ if (attempt < 3 && /permission|403|429|RESOURCE_EXHAUSTED|Internal error|retry|unavailable/i.test(r.out)) {
372
+ say('Google is still setting up the project; waiting a minute');
373
+ await new Promise((res) => setTimeout(res, 60_000));
374
+ continue;
375
+ }
376
+ throw new StepError(`Deploy failed: ${deployError(r.out)}`, 'Your project is fine. Run the same command to try again.');
377
+ }
378
+
379
+ const keyPath = join(dir, 'service-account.json');
380
+ if (!existsSync(keyPath)) {
381
+ say('Creating the server’s key');
382
+ const list = await patiently(() => g('GET', `${IAM}/projects/${ctx.id}/serviceAccounts`, { project: ctx.id }), { forMs: 120_000 });
383
+ const sa = (list.accounts ?? []).find((a) => a.email.startsWith('firebase-adminsdk'));
384
+ if (!sa) throw new StepError('The Firebase service account isn’t there yet.', 'Give it a minute and run this again.');
385
+ let key;
386
+ try {
387
+ key = await g('POST', `${IAM}/${sa.name}/keys`, { project: ctx.id, body: {} });
388
+ } catch (e) {
389
+ throw new StepError(`Google wouldn’t create a key for the server (${e.message}).`,
390
+ '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.');
391
+ }
392
+ writeFileSync(keyPath, Buffer.from(key.privateKeyData, 'base64'), { mode: 0o600 });
393
+ }
394
+ chmodSync(keyPath, 0o600);
395
+
396
+ say('Reading the web config');
397
+ const appId = await webApp(ctx, () => {});
398
+ const web = await patiently(() => g('GET', `${FB}/projects/${ctx.id}/webApps/${appId}/config`, { project: ctx.id }), { forMs: 90_000 });
399
+ const config = { apiKey: web.apiKey, authDomain: web.authDomain, projectId: web.projectId, appId: web.appId, messagingSenderId: web.messagingSenderId };
400
+ const oneLine = (v) => JSON.stringify(v);
401
+ writeFileSync(join(dir, 'lite.env'), [
402
+ `HERESAY_ORIGIN=${ctx.origin}`,
403
+ `GCLOUD_PROJECT=${ctx.id}`,
404
+ `HERESAY_FIREBASE_CONFIG=${oneLine(config)}`,
405
+ `GOOGLE_APPLICATION_CREDENTIALS_JSON=${oneLine(JSON.parse(readFileSync(keyPath, 'utf8')))}`,
406
+ '',
407
+ ].join('\n'), { mode: 0o600 });
408
+ return dir;
409
+ }
410
+
411
+ export async function liteVerify(ctx) {
412
+ try {
413
+ const h = await (await fetch(`${ctx.origin}/v1/health`, { signal: AbortSignal.timeout(8000) })).json();
414
+ if (h.ok) return `running, version ${h.version}`;
415
+ } catch { /* not started yet, which is expected on first setup */ }
416
+ return 'ready for your host';
417
+ }
418
+
310
419
  // ---- remove -----------------------------------------------------------------------------
311
420
 
312
421
  export async function remove(id) {