create-heresay 0.1.0 → 0.2.2

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,12 +1,11 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.1.0",
3
+ "version": "0.2.2",
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",
7
7
  "bin": {
8
- "create-heresay": "bin/create-heresay.mjs",
9
- "heresay": "bin/create-heresay.mjs"
8
+ "create-heresay": "bin/create-heresay.mjs"
10
9
  },
11
10
  "files": [
12
11
  "bin",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.1.0
1
+ 0.2.2
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Coding agents. A repo gets a token from `npx heresay connect`; with it, an agent sees the
3
+ * accepted briefs for the apps whose code is in that repo, and can claim, hand off, note and
4
+ * mark them fixed. It never sees open reports and never accepts or declines: those stay human.
5
+ */
6
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
7
+ import { CLAIM_TTL_MS, LIMITS, PLATFORMS, isPlatform, } from './types.js';
8
+ const json = (status, body) => ({ status, body });
9
+ const str = (v, max) => {
10
+ if (typeof v !== 'string')
11
+ return null;
12
+ const t = v.trim();
13
+ return t ? t.slice(0, max) : null;
14
+ };
15
+ const hash = (s) => createHash('sha256').update(s).digest('hex');
16
+ /** 'https://github.com/Acme/Web.git' and 'git@github.com:acme/web' are the same repo. */
17
+ export function normaliseRepo(v) {
18
+ const s = str(v, LIMITS.repoMax);
19
+ if (!s)
20
+ return null;
21
+ const r = s.toLowerCase()
22
+ .replace(/^git@([^:]+):/, '$1/')
23
+ .replace(/^[a-z+]+:\/\//, '')
24
+ .replace(/^[^@/]+@/, '')
25
+ .replace(/\.git$/, '')
26
+ .replace(/\/+$/, '');
27
+ return /^[a-z0-9._~/-]+$/.test(r) ? r : null;
28
+ }
29
+ // ---- tokens, managed by the team from the dashboard ---------------------------------------
30
+ /** hst_<id>_<secret>. The id finds the record; the secret is checked against its hash. */
31
+ export async function tokenFromHeader(req, deps) {
32
+ const m = /^Bearer hst_([A-Za-z0-9-]{8,40})_([A-Za-z0-9_-]{20,80})$/.exec(req.headers['authorization'] ?? '');
33
+ if (!m)
34
+ return null;
35
+ const t = await deps.store.getAgentToken(m[1]);
36
+ if (!t || t.revoked_at)
37
+ return null;
38
+ const a = Buffer.from(hash(m[2])), b = Buffer.from(t.secret_hash);
39
+ if (a.length !== b.length || !timingSafeEqual(a, b))
40
+ return null;
41
+ return t;
42
+ }
43
+ const publicToken = (t) => {
44
+ const { secret_hash: _, ...rest } = t;
45
+ return rest;
46
+ };
47
+ /** GET/POST /v1/agent-tokens, DELETE /v1/agent-tokens/:id. Any team member. */
48
+ export async function tokens(p, me, req, deps, body) {
49
+ if (p.length === 1 && req.method === 'GET') {
50
+ const all = (await deps.store.listAgentTokens()).filter((t) => !t.revoked_at);
51
+ all.sort((a, b) => a.created_at.localeCompare(b.created_at));
52
+ return json(200, { tokens: all.map(publicToken) });
53
+ }
54
+ if (p.length === 1 && req.method === 'POST') {
55
+ // No repo: the token is for a prompt, and binds to the repo that first connects with it.
56
+ const repo = body.repo === undefined || body.repo === null || body.repo === '' ? null : normaliseRepo(body.repo);
57
+ if (repo === null && body.repo)
58
+ return json(400, { error: 'name the repo, for example github.com/acme/web' });
59
+ const ids = Array.isArray(body.app_ids) ? body.app_ids.filter((x) => typeof x === 'string') : [];
60
+ for (const id of ids)
61
+ if (!(await deps.store.getProject(id)))
62
+ return json(400, { error: `no such app: ${id}` });
63
+ const id = randomBytes(9).toString('base64url').replace(/_/g, '-');
64
+ const secret = randomBytes(24).toString('base64url');
65
+ const t = {
66
+ id, secret_hash: hash(secret), repo, app_ids: [...new Set(ids)], created_by: me.email,
67
+ created_at: new Date(deps.now()).toISOString(), last_used_at: null, revoked_at: null,
68
+ };
69
+ await deps.store.createAgentToken(t);
70
+ deps.log('api.agent_token_created', { by: me.email, repo, apps: t.app_ids.length });
71
+ // The only time the secret leaves the server.
72
+ return json(201, { token: `hst_${id}_${secret}`, agent: publicToken(t) });
73
+ }
74
+ if (p.length === 2 && req.method === 'DELETE') {
75
+ const t = await deps.store.getAgentToken(p[1]);
76
+ if (!t || t.revoked_at)
77
+ return json(404, { error: 'no such token' });
78
+ await deps.store.updateAgentToken(t.id, { revoked_at: new Date(deps.now()).toISOString() });
79
+ deps.log('api.agent_token_revoked', { by: me.email, repo: t.repo });
80
+ return json(200, { ok: true });
81
+ }
82
+ return json(404, { error: 'not found' });
83
+ }
84
+ /** The repos connected to an app: where a brief for it can be routed. */
85
+ export async function reposFor(project_id, deps) {
86
+ const ts = (await deps.store.listAgentTokens()).filter((t) => !t.revoked_at && t.repo && t.app_ids.includes(project_id));
87
+ ts.sort((a, b) => a.created_at.localeCompare(b.created_at));
88
+ return [...new Set(ts.map((t) => t.repo))];
89
+ }
90
+ // ---- briefs as an agent sees them ---------------------------------------------------------
91
+ const claimLive = (t, now) => !!t.claim && now - Date.parse(t.claim.at) < CLAIM_TTL_MS;
92
+ /** A brief is for this repo if it was routed here, or routed nowhere yet. */
93
+ const visibleTo = (t, token) => (t.repo ?? null) === null || t.repo === token.repo;
94
+ function summary(t, p, now) {
95
+ return {
96
+ id: t.id, app: { id: p.id, name: p.name, platform: p.platform },
97
+ type: t.type, route: t.context.route, app_version: t.context.app_version,
98
+ accepted_at: t.accepted_at, repo: t.repo ?? null,
99
+ claimed_by: claimLive(t, now) ? t.claim.repo : null,
100
+ notes: (t.notes ?? []).length,
101
+ };
102
+ }
103
+ // ---- /v1/agent/* --------------------------------------------------------------------------
104
+ export async function agent(p, req, deps, body, prompt, createProject, toReporter) {
105
+ const token = await tokenFromHeader(req, deps);
106
+ if (!token)
107
+ return json(401, { error: 'this agent token is not valid (revoked, or never issued). Run npx heresay connect again.' });
108
+ const now = deps.now();
109
+ const at = new Date(now).toISOString();
110
+ if (!token.last_used_at || now - Date.parse(token.last_used_at) > 3600_000) {
111
+ await deps.store.updateAgentToken(token.id, { last_used_at: at });
112
+ }
113
+ const apps = (await Promise.all(token.app_ids.map((id) => deps.store.getProject(id)))).filter((x) => !!x);
114
+ if (p[0] === 'me' && req.method === 'GET') {
115
+ return json(200, { repo: token.repo, version: deps.version, apps: apps.map(appView) });
116
+ }
117
+ if (p[0] === 'bind' && req.method === 'POST') {
118
+ const repo = normaliseRepo(body.repo);
119
+ if (!repo)
120
+ return json(400, { error: 'name the repo, for example github.com/acme/web' });
121
+ if (token.repo && token.repo !== repo)
122
+ return json(409, { error: `this token belongs to ${token.repo}`, repo: token.repo });
123
+ if (!token.repo) {
124
+ await deps.store.updateAgentToken(token.id, { repo });
125
+ deps.log('api.agent_token_bound', { repo, by: token.created_by });
126
+ }
127
+ return json(200, { repo, version: deps.version, apps: apps.map(appView) });
128
+ }
129
+ // Everything else needs to know which repo it is working in.
130
+ if (!token.repo)
131
+ return json(409, { error: 'this token isn\'t connected to a repo yet. Run npx heresay connect with it in the repo first.' });
132
+ const repoName = token.repo;
133
+ const me = `agent:${repoName}`;
134
+ if (p[0] === 'apps') {
135
+ if (p.length === 1 && req.method === 'GET')
136
+ return json(200, { apps: apps.map(appView) });
137
+ if (p.length === 1 && req.method === 'POST') {
138
+ if (body.platform !== undefined && !isPlatform(body.platform)) {
139
+ return json(400, { error: `platform must be one of ${PLATFORMS.join(', ')}` });
140
+ }
141
+ const res = await createProject(token.created_by, { ...body, allowed_origins: body.sites ?? body.allowed_origins });
142
+ if (res.status !== 201)
143
+ return res;
144
+ const project = res.body.project;
145
+ // An app created from a repo belongs to that repo's token from then on.
146
+ await deps.store.updateAgentToken(token.id, { app_ids: [...token.app_ids, project.id] });
147
+ deps.log('api.agent_app_created', { repo: repoName, project_id: project.id });
148
+ return json(201, { app: appView(project) });
149
+ }
150
+ const app = apps.find((a) => a.id === p[1]);
151
+ if (!app)
152
+ return json(404, { error: 'this repo is not connected to that app' });
153
+ if (p[2] === 'verify' && req.method === 'POST') {
154
+ // What `heresay check` found in this repo: the file holding the app's key.
155
+ const file = str(body.file, 300);
156
+ if (!file)
157
+ return json(400, { error: 'say which file has the key' });
158
+ const code_found = { at, repo: repoName, file };
159
+ await deps.store.updateProject(app.id, { code_found });
160
+ deps.log('api.install_verified', { project_id: app.id, repo: repoName });
161
+ return json(200, { code_found });
162
+ }
163
+ if (p[2] === 'check' && req.method === 'GET') {
164
+ // Counts and screens only. Report text is untrusted, and an install check doesn't need it.
165
+ const rs = await deps.store.listReports(app.id);
166
+ const first = [...rs].sort((a, b) => a.created_at.localeCompare(b.created_at))[0];
167
+ return json(200, {
168
+ reports: rs.length,
169
+ first: first ? { route: first.context.route, app_version: first.context.app_version, created_at: first.created_at } : null,
170
+ framework: app.framework, framework_detected: !!app.framework_detected,
171
+ sdk_seen: app.sdk_seen ?? null, code_found: app.code_found ?? null,
172
+ installed: !!(app.sdk_seen || app.code_found),
173
+ });
174
+ }
175
+ return json(404, { error: 'not found' });
176
+ }
177
+ if (p[0] !== 'briefs')
178
+ return json(404, { error: 'not found' });
179
+ if (p.length === 1 && req.method === 'GET') {
180
+ const out = [];
181
+ for (const app of apps) {
182
+ for (const t of await deps.store.listTasks(app.id)) {
183
+ const r = await deps.store.getReport(app.id, t.report_id);
184
+ if (r?.status !== 'accepted' || !visibleTo(t, token))
185
+ continue;
186
+ out.push(summary(t, app, now));
187
+ }
188
+ }
189
+ out.sort((a, b) => Number(!!a.claimed_by && a.claimed_by !== repoName) - Number(!!b.claimed_by && b.claimed_by !== repoName)
190
+ || a.accepted_at.localeCompare(b.accepted_at));
191
+ return json(200, { repo: repoName, briefs: out });
192
+ }
193
+ // One brief. Found by id within this token's apps only.
194
+ let found = null;
195
+ for (const app of apps) {
196
+ const t = await deps.store.getTask(app.id, p[1]);
197
+ if (t) {
198
+ found = { app, task: t };
199
+ break;
200
+ }
201
+ }
202
+ if (!found || !visibleTo(found.task, token))
203
+ return json(404, { error: 'no such brief for this repo' });
204
+ const { app } = found;
205
+ const report = await deps.store.getReport(app.id, found.task.report_id);
206
+ const done = report?.status !== 'accepted';
207
+ if (p.length === 2 && req.method === 'GET') {
208
+ const t = found.task;
209
+ return json(200, {
210
+ brief: { ...summary(t, app, now), status: report?.status ?? 'accepted', notes: t.notes ?? [], developer_note: t.note },
211
+ prompt: prompt(app, t),
212
+ });
213
+ }
214
+ if (req.method !== 'POST')
215
+ return json(404, { error: 'not found' });
216
+ if (done)
217
+ return json(409, { error: `this brief is already ${report?.status}`, status: report?.status });
218
+ const takenByOther = (t) => claimLive(t, now) && t.claim.repo !== repoName;
219
+ const addNote = (t, text, kind) => ({ ...t, notes: [...(t.notes ?? []), { by: me, at, text, kind }] });
220
+ if (p[2] === 'claim') {
221
+ let refused = '';
222
+ const t = await deps.store.updateTask(app.id, found.task.id, (cur) => {
223
+ if (takenByOther(cur)) {
224
+ refused = cur.claim.repo;
225
+ return cur;
226
+ }
227
+ return { ...cur, claim: { repo: repoName, at } };
228
+ });
229
+ if (refused)
230
+ return json(409, { error: `already in progress in ${refused}`, claimed_by: refused });
231
+ deps.log('api.brief_claimed', { repo: repoName, report_id: t.id });
232
+ return json(200, { brief: summary(t, app, now) });
233
+ }
234
+ if (p[2] === 'notes') {
235
+ const text = str(body.note, LIMITS.reasonMax);
236
+ if (!text)
237
+ return json(400, { error: 'write the note' });
238
+ const t = await deps.store.updateTask(app.id, found.task.id, (cur) => {
239
+ const next = addNote(cur, text, 'note');
240
+ // Working on it keeps the claim fresh.
241
+ return cur.claim?.repo === repoName ? { ...next, claim: { repo: repoName, at } } : next;
242
+ });
243
+ return json(200, { brief: summary(t, app, now) });
244
+ }
245
+ if (p[2] === 'handoff') {
246
+ const to = normaliseRepo(body.repo);
247
+ const text = str(body.note, LIMITS.reasonMax);
248
+ if (!text)
249
+ return json(400, { error: 'say what you found, so the next agent starts from it' });
250
+ const repos = await reposFor(app.id, deps);
251
+ if (!to || !repos.includes(to)) {
252
+ return json(400, { error: `hand off to a repo connected to ${app.name}: ${repos.join(', ') || 'none yet'}`, repos });
253
+ }
254
+ if (to === repoName)
255
+ return json(400, { error: 'that is this repo' });
256
+ let refused = '';
257
+ const t = await deps.store.updateTask(app.id, found.task.id, (cur) => {
258
+ if (takenByOther(cur)) {
259
+ refused = cur.claim.repo;
260
+ return cur;
261
+ }
262
+ return { ...addNote(cur, `Handed to ${to}: ${text}`, 'handoff'), repo: to, claim: null };
263
+ });
264
+ if (refused)
265
+ return json(409, { error: `in progress in ${refused}`, claimed_by: refused });
266
+ deps.log('api.brief_handed_off', { from: repoName, to, report_id: t.id });
267
+ return json(200, { brief: summary(t, app, now) });
268
+ }
269
+ if (p[2] === 'fixed') {
270
+ // Required, like a decline reason: the reporter reads it.
271
+ const note = str(body.note, LIMITS.reasonMax);
272
+ if (!note)
273
+ return json(400, { error: 'write a note for the person who reported it: what changed, in their words' });
274
+ if (takenByOther(found.task))
275
+ return json(409, { error: `in progress in ${found.task.claim.repo}` });
276
+ const res = await toReporter(app, found.task.id, note, me);
277
+ if (res.status === 200) {
278
+ await deps.store.updateTask(app.id, found.task.id, (cur) => ({ ...addNote(cur, `Fixed: ${note}`, 'note'), claim: null }));
279
+ }
280
+ return res;
281
+ }
282
+ return json(404, { error: 'not found' });
283
+ }
284
+ const appView = (p) => ({
285
+ id: p.id, name: p.name, platform: p.platform, framework: p.framework,
286
+ framework_detected: !!p.framework_detected, key: p.key, allowed_origins: p.allowed_origins,
287
+ });
288
+ //# sourceMappingURL=agent.js.map
@@ -1,10 +1,31 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { LIMITS, PLATFORMS, REPORT_ORDER, REPORT_TYPES, isPlatform, isReportType, toReporterView, } from './types.js';
2
+ import { agent, normaliseRepo, reposFor, tokens } from './agent.js';
3
+ import { LIMITS, PLATFORMS, REPORT_ORDER, REPORT_TYPES, isFramework, isPlatform, isReportType, toReporterView, } from './types.js';
3
4
  /**
4
5
  * Fixed windows. The public endpoint has no login, so each of these is a separate line of
5
6
  * defence: the device id is chosen by the client and can be rotated, the IP limit catches that,
6
7
  * and the key limit caps what any one project can be flooded with whatever else gets through.
7
8
  */
9
+ /** Reading your own reports: generous, but not unlimited. Per network. */
10
+ export const MINE_LIMIT = { limit: 240, windowMs: 3600_000 };
11
+ /** How often "seen running" is written, at most, per app. */
12
+ const SEEN_EVERY_MS = 10 * 60_000;
13
+ /**
14
+ * Every SDK call proves the SDK is loaded in the app. Remember when and where, so the dashboard
15
+ * can say "installed" without anyone sending a test report. Not from this Heresay's own pages.
16
+ */
17
+ async function markSeen(project, req, body, deps) {
18
+ const now = deps.now();
19
+ if (project.sdk_seen && now - Date.parse(project.sdk_seen.at) < SEEN_EVERY_MS)
20
+ return;
21
+ const origin = req.headers['origin'] ? normaliseOrigin(req.headers['origin']) : null;
22
+ if (origin && (deps.selfOrigins ?? []).includes(origin))
23
+ return;
24
+ const sdk = typeof body.sdk === 'string' && ['web', 'ios', 'macos'].includes(body.sdk) ? body.sdk : (origin ? 'web' : null);
25
+ await deps.store.updateProject(project.id, {
26
+ sdk_seen: { at: new Date(now).toISOString(), where: origin ?? (sdk === 'ios' ? 'the iOS app' : sdk === 'macos' ? 'the Mac app' : 'the app'), sdk },
27
+ });
28
+ }
8
29
  export const RATE_LIMITS = [
9
30
  { scope: 'device', limit: 5, windowMs: 10 * 60_000 },
10
31
  { scope: 'device', limit: 20, windowMs: 24 * 3600_000 },
@@ -26,6 +47,7 @@ export function parseContext(v) {
26
47
  return {
27
48
  route: f('route'), app_version: f('app_version'), platform: f('platform'), os: f('os'),
28
49
  browser: f('browser'), user_id: f('user_id'), user_label: f('user_label'),
50
+ framework: isFramework(c.framework) ? c.framework : null,
29
51
  };
30
52
  }
31
53
  export const normaliseOrigin = (o) => o.trim().replace(/\/+$/, '').toLowerCase();
@@ -82,6 +104,10 @@ async function route(req, deps) {
82
104
  return mine(req, deps);
83
105
  if (p[0] === 'reports' && req.method === 'OPTIONS')
84
106
  return preflight(req);
107
+ // Coding agents, with a per-repo token instead of a person's sign-in.
108
+ if (p[0] === 'agent') {
109
+ return agent(p.slice(1), req, deps, parseBody(req.body), agentPrompt, (by, body) => createProject({ email: by, role: 'member', added_at: '', added_by: null }, { ...req, body }, deps), async (project, id, note, by) => transitionRes(await deps.store.move(project.id, id, 'accepted', 'fixed', { fix_note: note, triaged_by: by, updated_at: new Date(deps.now()).toISOString() })));
110
+ }
85
111
  // The team, signed in to the dashboard.
86
112
  const who = await caller(req, deps);
87
113
  if (!who)
@@ -99,6 +125,8 @@ async function route(req, deps) {
99
125
  }
100
126
  if (p[0] === 'team')
101
127
  return team(p, member, req, deps);
128
+ if (p[0] === 'agent-tokens')
129
+ return tokens(p, member, req, deps, parseBody(req.body));
102
130
  if (p[0] === 'projects' && p.length === 1) {
103
131
  if (req.method === 'GET')
104
132
  return listProjects(deps);
@@ -111,8 +139,22 @@ async function route(req, deps) {
111
139
  return json(404, { error: 'no such app' });
112
140
  if (p.length === 2 && req.method === 'GET')
113
141
  return json(200, { project });
142
+ if (p.length === 2 && req.method === 'PATCH')
143
+ return updateProject(project, member, req, deps);
144
+ if (p.length === 2 && req.method === 'DELETE')
145
+ return deleteProject(project, member, req, deps);
114
146
  if (p[2] === 'reports' && p.length === 3 && req.method === 'GET') {
115
- return json(200, { reports: sortForTriage(await deps.store.listReports(project.id)) });
147
+ // Alongside each accepted report: where its fix is going, and whether an agent has it.
148
+ const now = deps.now();
149
+ const briefs = {};
150
+ for (const t of await deps.store.listTasks(project.id)) {
151
+ const live = t.claim && now - Date.parse(t.claim.at) < 24 * 3600_000;
152
+ briefs[t.id] = { repo: t.repo ?? null, claimed_by: live ? t.claim.repo : null, notes: t.notes ?? [] };
153
+ }
154
+ return json(200, { reports: sortForTriage(await deps.store.listReports(project.id)), briefs });
155
+ }
156
+ if (p[2] === 'repos' && p.length === 3 && req.method === 'GET') {
157
+ return json(200, { repos: await reposFor(project.id, deps) });
116
158
  }
117
159
  if (p[2] === 'reports' && p[3] && req.method === 'POST') {
118
160
  return triage(project, p[3], p[4], member.email, req, deps);
@@ -244,9 +286,16 @@ async function submit(req, deps) {
244
286
  const report = {
245
287
  id: newId('r_'), project_id: project.id, device_id: body.device_id, type: body.type, text,
246
288
  context: parseContext(body.context), status: 'open', decline_reason: null,
247
- created_at: at, updated_at: at, triaged_by: null,
289
+ fix_note: null, created_at: at, updated_at: at, triaged_by: null,
248
290
  };
249
291
  await deps.store.createReport(report);
292
+ await markSeen(project, req, body, deps);
293
+ // Nobody said what the app is built with, and the SDK could tell: remember it. Not from
294
+ // this Heresay's own test page, which isn't the app.
295
+ const fromSelf = (deps.selfOrigins ?? []).includes(normaliseOrigin(req.headers['origin'] ?? ''));
296
+ if (!project.framework && report.context.framework && !fromSelf) {
297
+ await deps.store.updateProject(project.id, { framework: report.context.framework, framework_detected: true });
298
+ }
250
299
  deps.log('api.report_created', { project_id: project.id, report_id: report.id, type: report.type });
251
300
  return json(201, { report: toReporterView(report) }, headers);
252
301
  }
@@ -263,6 +312,12 @@ async function mine(req, deps) {
263
312
  // The device id is random and long, so knowing it is what proves these are yours.
264
313
  if (!validDeviceId(body.device_id))
265
314
  return json(400, { error: 'bad device_id' }, headers);
315
+ const now = deps.now();
316
+ const start = Math.floor(now / MINE_LIMIT.windowMs) * MINE_LIMIT.windowMs;
317
+ if (!(await deps.store.hit(`mine:${sha(req.ip)}:${start}`, MINE_LIMIT.limit, start + MINE_LIMIT.windowMs))) {
318
+ return json(429, { error: 'too many requests, try again later' }, { ...headers, 'retry-after': String(Math.ceil((start + MINE_LIMIT.windowMs - now) / 1000)) });
319
+ }
320
+ await markSeen(project, req, body, deps);
266
321
  const rs = await deps.store.listReportsForDevice(project.id, body.device_id);
267
322
  rs.sort((a, b) => b.created_at.localeCompare(a.created_at));
268
323
  return json(200, { reports: rs.map(toReporterView) }, headers);
@@ -324,6 +379,66 @@ async function createProject(me, req, deps) {
324
379
  deps.log('api.project_created', { project_id: project.id, by: me.email, platform });
325
380
  return json(201, { project });
326
381
  }
382
+ /** Going back in the add-app wizard edits the app rather than making another. The key stays. */
383
+ async function updateProject(project, me, req, deps) {
384
+ const body = parseBody(req.body);
385
+ const patch = {};
386
+ if (body.name !== undefined) {
387
+ const name = str(body.name, 80);
388
+ if (!name)
389
+ return json(400, { error: 'an app needs a name' });
390
+ patch.name = name;
391
+ }
392
+ if (body.platform !== undefined) {
393
+ if (!isPlatform(body.platform))
394
+ return json(400, { error: `platform must be one of ${PLATFORMS.join(', ')}` });
395
+ patch.platform = body.platform;
396
+ }
397
+ if (body.framework !== undefined) {
398
+ const f = str(body.framework, 40);
399
+ patch.framework = f ? f.toLowerCase() : null;
400
+ patch.framework_detected = false;
401
+ }
402
+ if (body.allowed_origins !== undefined) {
403
+ const origins = [];
404
+ for (const o of Array.isArray(body.allowed_origins) ? body.allowed_origins : []) {
405
+ if (typeof o !== 'string' || !o.trim())
406
+ continue;
407
+ let u;
408
+ try {
409
+ u = new URL(o.trim());
410
+ }
411
+ catch {
412
+ return json(400, { error: `not a URL: ${o}` });
413
+ }
414
+ origins.push(normaliseOrigin(u.origin));
415
+ }
416
+ patch.allowed_origins = [...new Set(origins)];
417
+ }
418
+ await deps.store.updateProject(project.id, patch);
419
+ deps.log('api.project_updated', { project_id: project.id, by: me.email, fields: Object.keys(patch) });
420
+ return json(200, { project: { ...project, ...patch } });
421
+ }
422
+ /**
423
+ * Gone for good: the app, its reports and briefs. Its key stops working at once. Connected
424
+ * repos keep their tokens (they may serve other apps) but lose this app.
425
+ */
426
+ async function deleteProject(project, me, req, deps) {
427
+ if (me.role !== 'owner')
428
+ return json(403, { error: 'only an owner can delete an app' });
429
+ const body = parseBody(req.body);
430
+ // Typed, not clicked: this can't be undone.
431
+ if (body.confirm !== project.name)
432
+ return json(400, { error: 'type the app\'s name to confirm' });
433
+ await deps.store.deleteProject(project.id);
434
+ for (const t of await deps.store.listAgentTokens()) {
435
+ if (t.app_ids.includes(project.id)) {
436
+ await deps.store.updateAgentToken(t.id, { app_ids: t.app_ids.filter((id) => id !== project.id) });
437
+ }
438
+ }
439
+ deps.log('api.project_deleted', { project_id: project.id, by: me.email });
440
+ return json(200, { ok: true });
441
+ }
327
442
  function transitionRes(t) {
328
443
  if (t.ok)
329
444
  return json(200, { report: t.report });
@@ -340,10 +455,15 @@ async function triage(project, report_id, action, uid, req, deps) {
340
455
  const report = await deps.store.getReport(project.id, report_id);
341
456
  if (!report)
342
457
  return json(404, { error: 'no such report' });
458
+ // Route the fix to a repo now: the one asked for, else the app's first connected repo.
459
+ const repos = await reposFor(project.id, deps);
460
+ const asked = body.repo === undefined || body.repo === null ? null : normaliseRepo(body.repo);
461
+ if (asked && !repos.includes(asked))
462
+ return json(400, { error: `${asked} is not connected to ${project.name}`, repos });
343
463
  const task = {
344
464
  id: report.id, project_id: project.id, report_id: report.id, type: report.type,
345
465
  text: report.text, context: report.context, note: str(body.note, LIMITS.reasonMax),
346
- accepted_by: uid, accepted_at: at,
466
+ accepted_by: uid, accepted_at: at, repo: asked ?? repos[0] ?? null, claim: null, notes: [],
347
467
  };
348
468
  t = await deps.store.accept(project.id, report_id, task, at);
349
469
  }
@@ -355,7 +475,8 @@ async function triage(project, report_id, action, uid, req, deps) {
355
475
  t = await deps.store.move(project.id, report_id, 'open', 'declined', { decline_reason: reason, triaged_by: uid, updated_at: at });
356
476
  }
357
477
  else if (action === 'fixed') {
358
- t = await deps.store.move(project.id, report_id, 'accepted', 'fixed', { triaged_by: uid, updated_at: at });
478
+ // Optional from the dashboard; when given, the reporter reads it next to "Fixed".
479
+ t = await deps.store.move(project.id, report_id, 'accepted', 'fixed', { fix_note: str(body.note, LIMITS.reasonMax), triaged_by: uid, updated_at: at });
359
480
  }
360
481
  else {
361
482
  return json(404, { error: 'not found' });
@@ -4,6 +4,7 @@ export class MemoryStore {
4
4
  projects = new Map();
5
5
  reports = new Map();
6
6
  tasks = new Map();
7
+ tokens = new Map();
7
8
  buckets = new Map();
8
9
  async getInstance() { return this.instance ? structuredClone(this.instance) : null; }
9
10
  async updateInstance(fn) {
@@ -17,6 +18,20 @@ export class MemoryStore {
17
18
  return [...this.projects.values()].find((p) => p.key === key) ?? null;
18
19
  }
19
20
  async listProjects() { return [...this.projects.values()]; }
21
+ async updateProject(id, patch) {
22
+ const p = this.projects.get(id);
23
+ if (p)
24
+ this.projects.set(id, { ...p, ...patch, id });
25
+ }
26
+ async deleteProject(id) {
27
+ this.projects.delete(id);
28
+ for (const [k, r] of this.reports)
29
+ if (r.project_id === id)
30
+ this.reports.delete(k);
31
+ for (const [k, t] of this.tasks)
32
+ if (t.project_id === id)
33
+ this.tasks.delete(k);
34
+ }
20
35
  async createReport(r) { this.reports.set(r.id, { ...r }); }
21
36
  async getReport(project_id, id) {
22
37
  const r = this.reports.get(id);
@@ -48,12 +63,34 @@ export class MemoryStore {
48
63
  const next = {
49
64
  ...r, status: to, triaged_by: patch.triaged_by, updated_at: patch.updated_at,
50
65
  decline_reason: patch.decline_reason ?? r.decline_reason,
66
+ fix_note: patch.fix_note !== undefined ? patch.fix_note : (r.fix_note ?? null),
51
67
  };
52
68
  this.reports.set(report_id, next);
53
69
  return { ok: true, report: next };
54
70
  }
55
71
  async getTask(project_id, report_id) {
56
- return this.tasks.get(`${project_id}/${report_id}`) ?? null;
72
+ const t = this.tasks.get(`${project_id}/${report_id}`);
73
+ return t ? structuredClone(t) : null;
74
+ }
75
+ async listTasks(project_id) {
76
+ return [...this.tasks.values()].filter((t) => t.project_id === project_id).map((t) => structuredClone(t));
77
+ }
78
+ async updateTask(project_id, report_id, fn) {
79
+ const k = `${project_id}/${report_id}`;
80
+ const t = this.tasks.get(k);
81
+ if (!t)
82
+ return null;
83
+ const next = fn(structuredClone(t));
84
+ this.tasks.set(k, structuredClone(next));
85
+ return structuredClone(next);
86
+ }
87
+ async createAgentToken(t) { this.tokens.set(t.id, structuredClone(t)); }
88
+ async getAgentToken(id) { const t = this.tokens.get(id); return t ? structuredClone(t) : null; }
89
+ async listAgentTokens() { return [...this.tokens.values()].map((t) => structuredClone(t)); }
90
+ async updateAgentToken(id, patch) {
91
+ const t = this.tokens.get(id);
92
+ if (t)
93
+ this.tokens.set(id, { ...t, ...patch, id });
57
94
  }
58
95
  async hit(bucket, limit) {
59
96
  const n = this.buckets.get(bucket) ?? 0;
@@ -7,11 +7,17 @@ export const isReportType = (v) => typeof v === 'string' && REPORT_TYPES.include
7
7
  export const REPORT_ORDER = {
8
8
  broken: 0, confusing: 1, improvement: 2, idea: 3,
9
9
  };
10
+ /** Frameworks the web SDK can recognise on a page. */
11
+ export const FRAMEWORKS = ['html', 'react', 'next', 'vue', 'nuxt', 'svelte', 'angular', 'swiftui', 'uikit', 'appkit'];
12
+ export const isFramework = (v) => typeof v === 'string' && FRAMEWORKS.includes(v);
10
13
  export const PLATFORMS = ['web', 'ios', 'macos', 'android', 'react-native', 'flutter'];
11
14
  export const isPlatform = (v) => typeof v === 'string' && PLATFORMS.includes(v);
15
+ /** A claim nobody has touched for this long is dropped, so a crashed agent can't block a brief. */
16
+ export const CLAIM_TTL_MS = 24 * 3600_000;
12
17
  export const toReporterView = (r) => ({
13
18
  id: r.id, type: r.type, text: r.text, status: r.status,
14
- decline_reason: r.decline_reason, created_at: r.created_at, updated_at: r.updated_at,
19
+ decline_reason: r.decline_reason, fix_note: r.fix_note ?? null,
20
+ created_at: r.created_at, updated_at: r.updated_at,
15
21
  });
16
22
  export const LIMITS = {
17
23
  textMax: 2000,
@@ -19,5 +25,6 @@ export const LIMITS = {
19
25
  deviceIdMin: 16,
20
26
  deviceIdMax: 64,
21
27
  reasonMax: 1000,
28
+ repoMax: 200,
22
29
  };
23
30
  //# sourceMappingURL=types.js.map
@@ -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.1.0';
2
+ export const VERSION = '0.2.2';
3
3
  //# sourceMappingURL=version.js.map