@obzerver/server 0.3.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/alerts.d.ts +4 -1
- package/dist/alerts.js +7 -5
- package/dist/alerts.js.map +1 -1
- package/dist/cli.js +23 -5
- package/dist/cli.js.map +1 -1
- package/dist/db.d.ts +2 -0
- package/dist/db.js +17 -0
- package/dist/db.js.map +1 -1
- package/dist/issues.d.ts +20 -2
- package/dist/issues.js +29 -4
- package/dist/issues.js.map +1 -1
- package/dist/mailer.d.ts +1 -0
- package/dist/mailer.js +1 -0
- package/dist/mailer.js.map +1 -1
- package/dist/mcp.js +4 -3
- package/dist/mcp.js.map +1 -1
- package/dist/projects.d.ts +49 -0
- package/dist/projects.js +184 -0
- package/dist/projects.js.map +1 -0
- package/dist/queries.js +3 -2
- package/dist/queries.js.map +1 -1
- package/dist/seed.js +1 -1
- package/dist/seed.js.map +1 -1
- package/dist/server.d.ts +6 -0
- package/dist/server.js +256 -50
- package/dist/server.js.map +1 -1
- package/dist/trackers.d.ts +201 -0
- package/dist/trackers.js +585 -0
- package/dist/trackers.js.map +1 -0
- package/package.json +3 -3
- package/public/assets/index-C4xcvzwn.css +1 -0
- package/public/assets/index-Dnpzem0I.js +513 -0
- package/public/index.html +2 -2
- package/public/assets/index-BsUhutDT.js +0 -479
- package/public/assets/index-CqB1oW93.css +0 -1
package/dist/trackers.js
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
// Issue tracker integrations: GitHub Issues and Linear.
|
|
2
|
+
//
|
|
3
|
+
// The Obzerver issue stays the verification engine (linked to telemetry); the ticket in GitHub or
|
|
4
|
+
// Linear is where people work. The two are kept in step:
|
|
5
|
+
// - a ticket closed or completed there → the issue starts verification here
|
|
6
|
+
// - a ticket reopened there → the issue reopens here
|
|
7
|
+
// - an issue resolved here → the ticket is closed there
|
|
8
|
+
// - verification passes / fails / times out → a comment there (and a reopen when it fails)
|
|
9
|
+
// Status comes in by polling (works behind a firewall) and, when configured, by signed webhooks.
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import { getSetting, setSetting } from './db.js';
|
|
12
|
+
import { withProject, currentProjectSlug } from './projects.js';
|
|
13
|
+
import { addTimeline, issueRow, resolveIssue } from './issues.js';
|
|
14
|
+
export const PROVIDERS = ['github', 'linear', 'clickup', 'trello'];
|
|
15
|
+
export const PROVIDER_LABEL = { github: 'GitHub', linear: 'Linear', clickup: 'ClickUp', trello: 'Trello' };
|
|
16
|
+
export class TrackerError extends Error {
|
|
17
|
+
status;
|
|
18
|
+
constructor(message, status = 502) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const env = (k) => process.env[k]?.trim() || undefined;
|
|
24
|
+
const GITHUB_API = () => (env('OBZERVER_GITHUB_API_URL') || 'https://api.github.com').replace(/\/$/, '');
|
|
25
|
+
const LINEAR_API = () => env('OBZERVER_LINEAR_API_URL') || 'https://api.linear.app/graphql';
|
|
26
|
+
const CLICKUP_API = () => (env('OBZERVER_CLICKUP_API_URL') || 'https://api.clickup.com/api/v2').replace(/\/$/, '');
|
|
27
|
+
const TRELLO_API = () => (env('OBZERVER_TRELLO_API_URL') || 'https://api.trello.com/1').replace(/\/$/, '');
|
|
28
|
+
// ---------------------------------------------------------------- settings
|
|
29
|
+
function stored(db) {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(getSetting(db, 'trackers') || '{}');
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return {};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Effective settings: env vars win per provider. GitHub: OBZERVER_GITHUB_TOKEN + _REPO. Linear: OBZERVER_LINEAR_API_KEY + _TEAM.
|
|
39
|
+
* ClickUp: OBZERVER_CLICKUP_TOKEN + _LIST. Trello: OBZERVER_TRELLO_KEY + _TOKEN + _LIST + _DONE_LIST (+ _BOARD).
|
|
40
|
+
*/
|
|
41
|
+
export function trackerSettings(db) {
|
|
42
|
+
const s = stored(db);
|
|
43
|
+
const ghEnv = env('OBZERVER_GITHUB_TOKEN') && env('OBZERVER_GITHUB_REPO')
|
|
44
|
+
? { token: env('OBZERVER_GITHUB_TOKEN'), repo: env('OBZERVER_GITHUB_REPO'), labels: (env('OBZERVER_GITHUB_LABELS') || '').split(',').map((l) => l.trim()).filter(Boolean) }
|
|
45
|
+
: null;
|
|
46
|
+
const lnEnv = env('OBZERVER_LINEAR_API_KEY') && env('OBZERVER_LINEAR_TEAM')
|
|
47
|
+
? { apiKey: env('OBZERVER_LINEAR_API_KEY'), teamId: env('OBZERVER_LINEAR_TEAM') }
|
|
48
|
+
: null;
|
|
49
|
+
const cuEnv = env('OBZERVER_CLICKUP_TOKEN') && env('OBZERVER_CLICKUP_LIST')
|
|
50
|
+
? { token: env('OBZERVER_CLICKUP_TOKEN'), listId: normalizeClickupList(env('OBZERVER_CLICKUP_LIST')) }
|
|
51
|
+
: null;
|
|
52
|
+
const trEnv = env('OBZERVER_TRELLO_KEY') && env('OBZERVER_TRELLO_TOKEN') && env('OBZERVER_TRELLO_LIST') && env('OBZERVER_TRELLO_DONE_LIST')
|
|
53
|
+
? { apiKey: env('OBZERVER_TRELLO_KEY'), token: env('OBZERVER_TRELLO_TOKEN'), boardId: normalizeTrelloBoard(env('OBZERVER_TRELLO_BOARD') || ''), listId: env('OBZERVER_TRELLO_LIST'), doneListId: env('OBZERVER_TRELLO_DONE_LIST') }
|
|
54
|
+
: null;
|
|
55
|
+
let githubWebhookSecret = s.githubWebhookSecret || '';
|
|
56
|
+
if (!githubWebhookSecret) {
|
|
57
|
+
githubWebhookSecret = crypto.randomBytes(24).toString('hex');
|
|
58
|
+
setSetting(db, 'trackers', JSON.stringify({ ...s, githubWebhookSecret }));
|
|
59
|
+
}
|
|
60
|
+
const autoEnv = env('OBZERVER_TRACKER_AUTO_CREATE');
|
|
61
|
+
return {
|
|
62
|
+
github: ghEnv || s.github || null,
|
|
63
|
+
linear: lnEnv || s.linear || null,
|
|
64
|
+
clickup: cuEnv || s.clickup || null,
|
|
65
|
+
trello: trEnv || s.trello || null,
|
|
66
|
+
autoCreate: (autoEnv && PROVIDERS.includes(autoEnv) ? autoEnv : s.autoCreate) || null,
|
|
67
|
+
githubWebhookSecret,
|
|
68
|
+
linearWebhookSecret: env('OBZERVER_LINEAR_WEBHOOK_SECRET') || s.linearWebhookSecret || '',
|
|
69
|
+
source: {
|
|
70
|
+
github: ghEnv ? 'env' : s.github ? 'settings' : null, linear: lnEnv ? 'env' : s.linear ? 'settings' : null,
|
|
71
|
+
clickup: cuEnv ? 'env' : s.clickup ? 'settings' : null, trello: trEnv ? 'env' : s.trello ? 'settings' : null,
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** "https://github.com/acme/shop.git" → "acme/shop". */
|
|
76
|
+
export const normalizeRepo = (repo) => repo.trim().replace(/^https?:\/\/github\.com\//, '').replace(/^git@github\.com:/, '').replace(/\.git$/, '').replace(/\/$/, '');
|
|
77
|
+
/** "https://app.clickup.com/9012/v/li/901234567" → "901234567". */
|
|
78
|
+
export const normalizeClickupList = (v) => (/\/li\/([\w-]+)/.exec(v)?.[1] ?? v.trim());
|
|
79
|
+
/** "https://trello.com/b/AbCd1234/my-board" → "AbCd1234". */
|
|
80
|
+
export const normalizeTrelloBoard = (v) => (/trello\.com\/b\/([\w-]+)/.exec(v)?.[1] ?? v.trim());
|
|
81
|
+
/** Never reveals more than the last 4 characters, and nothing of short secrets. */
|
|
82
|
+
export const mask = (secret) => (secret.length >= 16 ? `••••${secret.slice(-4)}` : '••••');
|
|
83
|
+
/** Settings for the dashboard: secrets masked. */
|
|
84
|
+
export function publicTrackerSettings(db) {
|
|
85
|
+
const s = trackerSettings(db);
|
|
86
|
+
return {
|
|
87
|
+
github: s.github ? { repo: s.github.repo, labels: s.github.labels, token: mask(s.github.token), source: s.source.github } : null,
|
|
88
|
+
linear: s.linear ? { teamId: s.linear.teamId, teamName: s.linear.teamName ?? null, apiKey: mask(s.linear.apiKey), source: s.source.linear } : null,
|
|
89
|
+
clickup: s.clickup ? { listId: s.clickup.listId, listName: s.clickup.listName ?? null, token: mask(s.clickup.token), source: s.source.clickup } : null,
|
|
90
|
+
trello: s.trello ? {
|
|
91
|
+
boardId: s.trello.boardId, boardName: s.trello.boardName ?? null, listId: s.trello.listId, listName: s.trello.listName ?? null,
|
|
92
|
+
doneListId: s.trello.doneListId, doneListName: s.trello.doneListName ?? null, apiKey: mask(s.trello.apiKey), token: mask(s.trello.token), source: s.source.trello,
|
|
93
|
+
} : null,
|
|
94
|
+
autoCreate: s.autoCreate,
|
|
95
|
+
webhooks: {
|
|
96
|
+
github: { path: `/api/integrations/${currentProjectSlug()}/github/webhook`, secret: s.githubWebhookSecret },
|
|
97
|
+
linear: { path: `/api/integrations/${currentProjectSlug()}/linear/webhook`, secretSet: !!s.linearWebhookSecret },
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Save from the dashboard. A masked secret means "keep the stored one"; null removes a provider. */
|
|
102
|
+
export function saveTrackerSettings(db, input) {
|
|
103
|
+
const cur = stored(db);
|
|
104
|
+
const next = { ...cur };
|
|
105
|
+
const keep = (v, old) => (v === undefined || v.includes('••••') ? old || '' : v.trim());
|
|
106
|
+
if (input.github === null)
|
|
107
|
+
next.github = null;
|
|
108
|
+
else if (input.github) {
|
|
109
|
+
const repo = normalizeRepo(input.github.repo ?? cur.github?.repo ?? '');
|
|
110
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo))
|
|
111
|
+
throw new TrackerError('Repository must look like owner/name', 400);
|
|
112
|
+
const token = keep(input.github.token, cur.github?.token);
|
|
113
|
+
if (!token)
|
|
114
|
+
throw new TrackerError('A GitHub token is required', 400);
|
|
115
|
+
const labels = Array.isArray(input.github.labels) ? input.github.labels : String(input.github.labels ?? (cur.github?.labels || []).join(',')).split(',');
|
|
116
|
+
next.github = { token, repo, labels: labels.map((l) => l.trim()).filter(Boolean) };
|
|
117
|
+
}
|
|
118
|
+
if (input.linear === null)
|
|
119
|
+
next.linear = null;
|
|
120
|
+
else if (input.linear) {
|
|
121
|
+
const apiKey = keep(input.linear.apiKey, cur.linear?.apiKey);
|
|
122
|
+
if (!apiKey)
|
|
123
|
+
throw new TrackerError('A Linear API key is required', 400);
|
|
124
|
+
const teamId = (input.linear.teamId ?? cur.linear?.teamId ?? '').trim();
|
|
125
|
+
if (!teamId)
|
|
126
|
+
throw new TrackerError('Pick a Linear team', 400);
|
|
127
|
+
next.linear = { apiKey, teamId, teamName: input.linear.teamName ?? cur.linear?.teamName };
|
|
128
|
+
}
|
|
129
|
+
if (input.clickup === null)
|
|
130
|
+
next.clickup = null;
|
|
131
|
+
else if (input.clickup) {
|
|
132
|
+
const token = keep(input.clickup.token, cur.clickup?.token);
|
|
133
|
+
if (!token)
|
|
134
|
+
throw new TrackerError('A ClickUp API token is required', 400);
|
|
135
|
+
const listId = normalizeClickupList(input.clickup.listId ?? cur.clickup?.listId ?? '');
|
|
136
|
+
if (!listId)
|
|
137
|
+
throw new TrackerError('Enter the ClickUp list for new tasks', 400);
|
|
138
|
+
next.clickup = { token, listId, listName: input.clickup.listName ?? cur.clickup?.listName };
|
|
139
|
+
}
|
|
140
|
+
if (input.trello === null)
|
|
141
|
+
next.trello = null;
|
|
142
|
+
else if (input.trello) {
|
|
143
|
+
const t = input.trello, c = cur.trello;
|
|
144
|
+
const apiKey = keep(t.apiKey, c?.apiKey), token = keep(t.token, c?.token);
|
|
145
|
+
if (!apiKey || !token)
|
|
146
|
+
throw new TrackerError('A Trello API key and token are required', 400);
|
|
147
|
+
const boardId = normalizeTrelloBoard(t.boardId ?? c?.boardId ?? '');
|
|
148
|
+
const listId = (t.listId ?? c?.listId ?? '').trim(), doneListId = (t.doneListId ?? c?.doneListId ?? '').trim();
|
|
149
|
+
if (!boardId || !listId || !doneListId)
|
|
150
|
+
throw new TrackerError('Pick a board, a list for new cards and a done list', 400);
|
|
151
|
+
if (listId === doneListId)
|
|
152
|
+
throw new TrackerError('The done list must be different from the list for new cards', 400);
|
|
153
|
+
next.trello = {
|
|
154
|
+
apiKey, token, boardId, boardName: t.boardName ?? c?.boardName, listId, listName: t.listName ?? c?.listName,
|
|
155
|
+
doneListId, doneListName: t.doneListName ?? c?.doneListName,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
if (input.autoCreate !== undefined) {
|
|
159
|
+
if (input.autoCreate !== null && !PROVIDERS.includes(input.autoCreate))
|
|
160
|
+
throw new TrackerError(`autoCreate must be one of ${PROVIDERS.join(', ')} or null`, 400);
|
|
161
|
+
next.autoCreate = input.autoCreate;
|
|
162
|
+
}
|
|
163
|
+
if (input.linearWebhookSecret !== undefined)
|
|
164
|
+
next.linearWebhookSecret = keep(input.linearWebhookSecret, cur.linearWebhookSecret);
|
|
165
|
+
setSetting(db, 'trackers', JSON.stringify(next));
|
|
166
|
+
}
|
|
167
|
+
async function http(url, init) {
|
|
168
|
+
let res;
|
|
169
|
+
try {
|
|
170
|
+
res = await fetch(url, { ...init, signal: AbortSignal.timeout(10000) });
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
throw new TrackerError(`${init.label}: ${e.message}`);
|
|
174
|
+
}
|
|
175
|
+
const text = await res.text();
|
|
176
|
+
let body = null;
|
|
177
|
+
try {
|
|
178
|
+
body = text ? JSON.parse(text) : null;
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
body = text;
|
|
182
|
+
}
|
|
183
|
+
if (!res.ok) {
|
|
184
|
+
const msg = body?.message || (typeof body === 'string' ? body.slice(0, 200) : res.statusText);
|
|
185
|
+
throw new TrackerError(`${init.label} returned ${res.status}: ${msg}`, res.status === 401 || res.status === 403 || res.status === 404 ? 400 : 502);
|
|
186
|
+
}
|
|
187
|
+
return body;
|
|
188
|
+
}
|
|
189
|
+
export function githubClient(cfg) {
|
|
190
|
+
const base = GITHUB_API();
|
|
191
|
+
const headers = {
|
|
192
|
+
authorization: `Bearer ${cfg.token}`, accept: 'application/vnd.github+json',
|
|
193
|
+
'x-github-api-version': '2022-11-28', 'user-agent': 'obzerver', 'content-type': 'application/json',
|
|
194
|
+
};
|
|
195
|
+
const call = (method, p, body) => http(`${base}${p}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), label: 'GitHub' });
|
|
196
|
+
const toTicket = (i) => ({
|
|
197
|
+
provider: 'github', id: String(i.number), key: `#${i.number}`, url: i.html_url,
|
|
198
|
+
state: i.state === 'open' ? 'open' : i.state_reason === 'not_planned' ? 'canceled' : 'closed',
|
|
199
|
+
stateName: i.state === 'open' ? 'Open' : i.state_reason === 'not_planned' ? 'Closed (not planned)' : 'Closed',
|
|
200
|
+
});
|
|
201
|
+
const repo = `/repos/${cfg.repo}`;
|
|
202
|
+
return {
|
|
203
|
+
async test() {
|
|
204
|
+
const r = await call('GET', repo);
|
|
205
|
+
if (r.has_issues === false)
|
|
206
|
+
throw new TrackerError(`Issues are turned off for ${cfg.repo}`, 400);
|
|
207
|
+
return { ok: true, detail: `Connected to ${r.full_name || cfg.repo}` };
|
|
208
|
+
},
|
|
209
|
+
async create(title, body) { return toTicket(await call('POST', `${repo}/issues`, { title, body, labels: cfg.labels })); },
|
|
210
|
+
async get(id) { return toTicket(await call('GET', `${repo}/issues/${id}`)); },
|
|
211
|
+
async comment(id, body) { await call('POST', `${repo}/issues/${id}/comments`, { body }); },
|
|
212
|
+
async close(id) { await call('PATCH', `${repo}/issues/${id}`, { state: 'closed', state_reason: 'completed' }); },
|
|
213
|
+
async reopen(id) { await call('PATCH', `${repo}/issues/${id}`, { state: 'open' }); },
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
export function linearClient(cfg) {
|
|
217
|
+
const gql = async (query, variables = {}) => {
|
|
218
|
+
const r = await http(LINEAR_API(), {
|
|
219
|
+
method: 'POST', label: 'Linear',
|
|
220
|
+
headers: { authorization: cfg.apiKey, 'content-type': 'application/json' },
|
|
221
|
+
body: JSON.stringify({ query, variables }),
|
|
222
|
+
});
|
|
223
|
+
if (r.errors?.length)
|
|
224
|
+
throw new TrackerError(`Linear: ${r.errors.map((e) => e.message).join('; ')}`, 400);
|
|
225
|
+
return r.data;
|
|
226
|
+
};
|
|
227
|
+
const fields = 'id identifier url state { type name }';
|
|
228
|
+
const toTicket = (i) => ({
|
|
229
|
+
provider: 'linear', id: i.id, key: i.identifier, url: i.url, stateName: i.state.name,
|
|
230
|
+
state: i.state.type === 'completed' ? 'closed' : i.state.type === 'canceled' ? 'canceled' : 'open',
|
|
231
|
+
});
|
|
232
|
+
// Workflow states differ per team: pick the first of the wanted type by position.
|
|
233
|
+
const stateOfType = async (types) => {
|
|
234
|
+
const d = await gql('query ObzTeamStates($id: String!) { team(id: $id) { states { nodes { id type position } } } }', { id: cfg.teamId });
|
|
235
|
+
for (const t of types) {
|
|
236
|
+
const s = d.team.states.nodes.filter((n) => n.type === t).sort((a, b) => a.position - b.position)[0];
|
|
237
|
+
if (s)
|
|
238
|
+
return s.id;
|
|
239
|
+
}
|
|
240
|
+
throw new TrackerError(`Linear team has no ${types.join('/')} state`, 400);
|
|
241
|
+
};
|
|
242
|
+
const setState = async (id, types) => {
|
|
243
|
+
const stateId = await stateOfType(types);
|
|
244
|
+
await gql('mutation ObzUpdate($id: String!, $stateId: String!) { issueUpdate(id: $id, input: { stateId: $stateId }) { success } }', { id, stateId });
|
|
245
|
+
};
|
|
246
|
+
return {
|
|
247
|
+
async test() {
|
|
248
|
+
const d = await gql('query ObzTest { viewer { name } teams { nodes { id key name } } }');
|
|
249
|
+
return { ok: true, detail: `Connected as ${d.viewer.name}`, teams: d.teams.nodes };
|
|
250
|
+
},
|
|
251
|
+
async create(title, body) {
|
|
252
|
+
const d = await gql(`mutation ObzCreate($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { ${fields} } } }`, { input: { teamId: cfg.teamId, title, description: body } });
|
|
253
|
+
if (!d.issueCreate.success)
|
|
254
|
+
throw new TrackerError('Linear did not create the issue');
|
|
255
|
+
return toTicket(d.issueCreate.issue);
|
|
256
|
+
},
|
|
257
|
+
async get(id) {
|
|
258
|
+
const d = await gql(`query ObzIssue($id: String!) { issue(id: $id) { ${fields} } }`, { id });
|
|
259
|
+
return toTicket(d.issue);
|
|
260
|
+
},
|
|
261
|
+
async comment(id, body) {
|
|
262
|
+
await gql('mutation ObzComment($input: CommentCreateInput!) { commentCreate(input: $input) { success } }', { input: { issueId: id, body } });
|
|
263
|
+
},
|
|
264
|
+
close: (id) => setState(id, ['completed']),
|
|
265
|
+
reopen: (id) => setState(id, ['unstarted', 'backlog', 'started']),
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
export function clickupClient(cfg) {
|
|
269
|
+
const base = CLICKUP_API();
|
|
270
|
+
const headers = { authorization: cfg.token, 'content-type': 'application/json' };
|
|
271
|
+
const call = (method, p, body) => http(`${base}${p}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), label: 'ClickUp' });
|
|
272
|
+
const closedTypes = new Set(['closed', 'done']);
|
|
273
|
+
const toTicket = (t) => ({
|
|
274
|
+
provider: 'clickup', id: String(t.id), key: t.custom_id || `#${t.id}`, url: t.url,
|
|
275
|
+
state: closedTypes.has(t.status?.type) ? 'closed' : 'open', stateName: t.status?.status || 'unknown',
|
|
276
|
+
});
|
|
277
|
+
// Status names are per list: pick the first of the wanted type by order.
|
|
278
|
+
const statusOf = async (types) => {
|
|
279
|
+
const list = await call('GET', `/list/${cfg.listId}`);
|
|
280
|
+
const statuses = (list.statuses || []);
|
|
281
|
+
for (const t of types) {
|
|
282
|
+
const s = statuses.filter((x) => x.type === t).sort((a, b) => Number(a.orderindex) - Number(b.orderindex))[0];
|
|
283
|
+
if (s)
|
|
284
|
+
return s.status;
|
|
285
|
+
}
|
|
286
|
+
throw new TrackerError(`The ClickUp list has no ${types.join('/')} status`, 400);
|
|
287
|
+
};
|
|
288
|
+
return {
|
|
289
|
+
async test() {
|
|
290
|
+
const me = await call('GET', '/user');
|
|
291
|
+
if (!cfg.listId)
|
|
292
|
+
return { ok: true, detail: `Connected as ${me.user?.username || 'ClickUp user'}` };
|
|
293
|
+
const list = await call('GET', `/list/${cfg.listId}`);
|
|
294
|
+
return { ok: true, detail: `Connected as ${me.user?.username || 'ClickUp user'} · list "${list.name}"`, listName: list.name };
|
|
295
|
+
},
|
|
296
|
+
async create(title, body) {
|
|
297
|
+
return toTicket(await call('POST', `/list/${cfg.listId}/task`, { name: title, markdown_content: body, description: body }));
|
|
298
|
+
},
|
|
299
|
+
async get(id) { return toTicket(await call('GET', `/task/${id}`)); },
|
|
300
|
+
async comment(id, body) { await call('POST', `/task/${id}/comment`, { comment_text: body, notify_all: false }); },
|
|
301
|
+
async close(id) { await call('PUT', `/task/${id}`, { status: await statusOf(['closed', 'done']) }); },
|
|
302
|
+
async reopen(id) { await call('PUT', `/task/${id}`, { status: await statusOf(['open', 'custom']) }); },
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
export function trelloClient(cfg) {
|
|
306
|
+
const base = TRELLO_API();
|
|
307
|
+
const auth = `key=${encodeURIComponent(cfg.apiKey)}&token=${encodeURIComponent(cfg.token)}`;
|
|
308
|
+
const call = (method, p, body) => http(`${base}${p}${p.includes('?') ? '&' : '?'}${auth}`, {
|
|
309
|
+
method, headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
310
|
+
body: body === undefined ? undefined : JSON.stringify(body), label: 'Trello',
|
|
311
|
+
});
|
|
312
|
+
const toTicket = (c) => {
|
|
313
|
+
const done = c.idList === cfg.doneListId;
|
|
314
|
+
return {
|
|
315
|
+
provider: 'trello', id: String(c.id), key: `#${c.idShort}`, url: c.shortUrl || c.url,
|
|
316
|
+
// A card archived anywhere but the done list was dropped, not finished.
|
|
317
|
+
state: done ? 'closed' : c.closed ? 'canceled' : 'open',
|
|
318
|
+
stateName: done ? (cfg.doneListName || 'Done') : c.closed ? 'Archived' : (c.idList === cfg.listId ? (cfg.listName || 'Open') : 'In progress'),
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
const fields = 'fields=idList,closed,shortUrl,url,idShort';
|
|
322
|
+
return {
|
|
323
|
+
async test() {
|
|
324
|
+
const me = await call('GET', '/members/me?fields=fullName,username');
|
|
325
|
+
const who = me.fullName || me.username || 'Trello user';
|
|
326
|
+
if (!cfg.boardId) {
|
|
327
|
+
const boards = await call('GET', '/members/me/boards?fields=name&filter=open');
|
|
328
|
+
return { ok: true, detail: `Connected as ${who}. Pick a board.`, boards: boards.map((b) => ({ id: b.id, name: b.name })) };
|
|
329
|
+
}
|
|
330
|
+
const board = await call('GET', `/boards/${cfg.boardId}?fields=name&lists=open`);
|
|
331
|
+
return { ok: true, detail: `Connected as ${who} · board "${board.name}"`, lists: (board.lists || []).map((l) => ({ id: l.id, name: l.name })) };
|
|
332
|
+
},
|
|
333
|
+
async create(title, body) { return toTicket(await call('POST', `/cards?${fields}`, { idList: cfg.listId, name: title, desc: body })); },
|
|
334
|
+
async get(id) { return toTicket(await call('GET', `/cards/${id}?${fields}`)); },
|
|
335
|
+
async comment(id, body) { await call('POST', `/cards/${id}/actions/comments`, { text: body }); },
|
|
336
|
+
async close(id) { await call('PUT', `/cards/${id}`, { idList: cfg.doneListId, closed: false }); },
|
|
337
|
+
async reopen(id) { await call('PUT', `/cards/${id}`, { idList: cfg.listId, closed: false }); },
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
export function clientFor(db, provider) {
|
|
341
|
+
const s = trackerSettings(db);
|
|
342
|
+
if (provider === 'github' && s.github)
|
|
343
|
+
return githubClient(s.github);
|
|
344
|
+
if (provider === 'linear' && s.linear)
|
|
345
|
+
return linearClient(s.linear);
|
|
346
|
+
if (provider === 'clickup' && s.clickup)
|
|
347
|
+
return clickupClient(s.clickup);
|
|
348
|
+
if (provider === 'trello' && s.trello)
|
|
349
|
+
return trelloClient(s.trello);
|
|
350
|
+
throw new TrackerError(`${PROVIDER_LABEL[provider]} is not connected (Integrations → ${PROVIDER_LABEL[provider]})`, 400);
|
|
351
|
+
}
|
|
352
|
+
/** Test connection with unsaved values (masked secrets fall back to the stored ones). */
|
|
353
|
+
export async function testTracker(db, provider, input) {
|
|
354
|
+
const cur = trackerSettings(db);
|
|
355
|
+
const pick = (v, old) => (v && !v.includes('••••') ? v.trim() : old || '');
|
|
356
|
+
if (provider === 'github') {
|
|
357
|
+
const token = pick(input.github?.token, cur.github?.token);
|
|
358
|
+
const repo = normalizeRepo(input.github?.repo || cur.github?.repo || '');
|
|
359
|
+
if (!token || !repo)
|
|
360
|
+
throw new TrackerError('Enter a token and a repository', 400);
|
|
361
|
+
return githubClient({ token, repo, labels: [] }).test();
|
|
362
|
+
}
|
|
363
|
+
if (provider === 'linear') {
|
|
364
|
+
const apiKey = pick(input.linear?.apiKey, cur.linear?.apiKey);
|
|
365
|
+
if (!apiKey)
|
|
366
|
+
throw new TrackerError('Enter a Linear API key', 400);
|
|
367
|
+
return linearClient({ apiKey, teamId: input.linear?.teamId || cur.linear?.teamId || '' }).test();
|
|
368
|
+
}
|
|
369
|
+
if (provider === 'clickup') {
|
|
370
|
+
const token = pick(input.clickup?.token, cur.clickup?.token);
|
|
371
|
+
if (!token)
|
|
372
|
+
throw new TrackerError('Enter a ClickUp API token', 400);
|
|
373
|
+
return clickupClient({ token, listId: normalizeClickupList(input.clickup?.listId ?? cur.clickup?.listId ?? '') }).test();
|
|
374
|
+
}
|
|
375
|
+
const apiKey = pick(input.trello?.apiKey, cur.trello?.apiKey);
|
|
376
|
+
const token = pick(input.trello?.token, cur.trello?.token);
|
|
377
|
+
if (!apiKey || !token)
|
|
378
|
+
throw new TrackerError('Enter a Trello API key and token', 400);
|
|
379
|
+
const boardId = normalizeTrelloBoard(input.trello?.boardId ?? cur.trello?.boardId ?? '');
|
|
380
|
+
return trelloClient({ apiKey, token, boardId, listId: '', doneListId: '' }).test();
|
|
381
|
+
}
|
|
382
|
+
// ---------------------------------------------------------------- ticket body
|
|
383
|
+
const fence = (s) => '```\n' + s.replace(/```/g, '```') + '\n```';
|
|
384
|
+
/** Markdown with the context an engineer (or a coding agent) needs, from the issue's telemetry. */
|
|
385
|
+
export function ticketBody(db, issue, provider, publicUrl) {
|
|
386
|
+
const out = [];
|
|
387
|
+
out.push(`**Reported by Obzerver** · severity **${issue.severity}**${issue.service ? ` · app \`${issue.service}\`` : ''}`);
|
|
388
|
+
if (issue.description)
|
|
389
|
+
out.push('', issue.description);
|
|
390
|
+
if (issue.sourceType === 'error' && issue.sourceRef) {
|
|
391
|
+
const g = db.get('SELECT * FROM error_groups WHERE fingerprint = ?', issue.sourceRef);
|
|
392
|
+
const last = db.get('SELECT stack, trace_id FROM errors WHERE fingerprint = ? ORDER BY ts DESC LIMIT 1', issue.sourceRef);
|
|
393
|
+
const users = db.get('SELECT COUNT(DISTINCT user_id) n FROM errors WHERE fingerprint = ? AND user_id IS NOT NULL', issue.sourceRef)?.n ?? 0;
|
|
394
|
+
if (g) {
|
|
395
|
+
out.push('', '### Error', `\`${g.class}: ${String(g.message).slice(0, 300)}\``, '');
|
|
396
|
+
if (g.operation)
|
|
397
|
+
out.push(`- **Where:** \`${g.operation}\``);
|
|
398
|
+
out.push(`- **Occurrences:** ${g.count} · **users affected:** ${users}`);
|
|
399
|
+
out.push(`- **First seen:** ${new Date(g.first_seen).toISOString()}${g.first_version ? ` in release \`${g.first_version}\`` : ''}`);
|
|
400
|
+
out.push(`- **Last seen:** ${new Date(g.last_seen).toISOString()}`);
|
|
401
|
+
if (last?.stack) {
|
|
402
|
+
const stack = String(last.stack).split('\n').slice(0, 15).join('\n');
|
|
403
|
+
out.push('', provider === 'github' ? `<details><summary>Stack trace</summary>\n\n${fence(stack)}\n\n</details>` : `**Stack trace**\n\n${fence(stack)}`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
else if (issue.sourceType === 'execution' && issue.sourceRef) {
|
|
408
|
+
const t = db.get('SELECT name, service, version, status, duration, ts, error_class, error_message FROM traces WHERE id = ?', Number(issue.sourceRef));
|
|
409
|
+
if (t) {
|
|
410
|
+
out.push('', '### Execution', `- **Operation:** \`${t.name}\`${t.status ? ` → ${t.status}` : ''} in ${Math.round(t.duration)} ms`);
|
|
411
|
+
out.push(`- **When:** ${new Date(t.ts).toISOString()}${t.version ? ` · release \`${t.version}\`` : ''}`);
|
|
412
|
+
if (t.error_class)
|
|
413
|
+
out.push(`- **Error:** \`${t.error_class}: ${String(t.error_message || '').slice(0, 300)}\``);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
else if (issue.sourceType === 'operation' && issue.sourceRef) {
|
|
417
|
+
out.push('', `- **Operation:** \`${issue.sourceRef}\``);
|
|
418
|
+
}
|
|
419
|
+
const link = publicUrl ? withProject(`${publicUrl.replace(/\/$/, '')}/issues/${issue.id}`) : null;
|
|
420
|
+
out.push('', '---');
|
|
421
|
+
out.push(link ? `[Open in Obzerver](${link}) · issue #${issue.id}` : `Obzerver issue #${issue.id}`);
|
|
422
|
+
out.push('When this ticket is closed, Obzerver checks the fix against live traffic and comments here with the result.');
|
|
423
|
+
return out.join('\n');
|
|
424
|
+
}
|
|
425
|
+
// ---------------------------------------------------------------- linking and sync
|
|
426
|
+
function saveTicket(db, issueId, t, now = Date.now()) {
|
|
427
|
+
db.run('UPDATE issues SET ext_provider = ?, ext_id = ?, ext_key = ?, ext_url = ?, ext_state = ?, ext_synced = ?, updated = ? WHERE id = ?', t.provider, t.id, t.key, t.url, t.state, now, now, issueId);
|
|
428
|
+
}
|
|
429
|
+
/** Create a ticket for an issue and link it. */
|
|
430
|
+
export async function createTicket(db, issueId, provider, publicUrl) {
|
|
431
|
+
const r = db.get('SELECT * FROM issues WHERE id = ?', issueId);
|
|
432
|
+
if (!r)
|
|
433
|
+
throw new TrackerError('Issue not found', 404);
|
|
434
|
+
if (r.ext_provider)
|
|
435
|
+
throw new TrackerError(`Already linked to ${PROVIDER_LABEL[r.ext_provider]} ${r.ext_key}`, 409);
|
|
436
|
+
const issue = issueRow(r);
|
|
437
|
+
const t = await clientFor(db, provider).create(issue.title, ticketBody(db, issue, provider, publicUrl));
|
|
438
|
+
saveTicket(db, issueId, t);
|
|
439
|
+
addTimeline(db, issueId, `Linked to ${PROVIDER_LABEL[provider]} ${t.key}`);
|
|
440
|
+
return t;
|
|
441
|
+
}
|
|
442
|
+
const OPEN_HERE = ['open', 'in_progress', 'unverified'];
|
|
443
|
+
const DONE_HERE = ['verifying', 'resolved', 'closed'];
|
|
444
|
+
/** Bring the issue in line with its ticket's state. Returns what happened (null = nothing to do). */
|
|
445
|
+
export function applyTicketState(db, issueId, state, stateName, now = Date.now()) {
|
|
446
|
+
const r = db.get('SELECT * FROM issues WHERE id = ?', issueId);
|
|
447
|
+
if (!r)
|
|
448
|
+
return null;
|
|
449
|
+
const prev = r.ext_state;
|
|
450
|
+
db.run('UPDATE issues SET ext_state = ?, ext_synced = ? WHERE id = ?', state, now, issueId);
|
|
451
|
+
if (prev === state)
|
|
452
|
+
return null;
|
|
453
|
+
const where = `${PROVIDER_LABEL[r.ext_provider]} ${r.ext_key}`;
|
|
454
|
+
const status = r.status;
|
|
455
|
+
if (state === 'closed' && OPEN_HERE.includes(status)) {
|
|
456
|
+
resolveIssue(db, issueId, `${where} closed (${stateName})`, now);
|
|
457
|
+
return 'resolved';
|
|
458
|
+
}
|
|
459
|
+
if (state === 'canceled' && status !== 'closed') {
|
|
460
|
+
db.run("UPDATE issues SET status = 'closed' WHERE id = ?", issueId);
|
|
461
|
+
addTimeline(db, issueId, `${where} canceled (${stateName}): closed without verification`, now);
|
|
462
|
+
return 'canceled';
|
|
463
|
+
}
|
|
464
|
+
if (state === 'open' && DONE_HERE.includes(status) && prev && prev !== 'open') {
|
|
465
|
+
db.run("UPDATE issues SET status = 'open', resolved_at = NULL WHERE id = ?", issueId);
|
|
466
|
+
addTimeline(db, issueId, `${where} reopened`, now);
|
|
467
|
+
return 'reopened';
|
|
468
|
+
}
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
/** Poll linked tickets and apply their state. Runs every couple of minutes; webhooks make it instant. */
|
|
472
|
+
export async function syncTickets(db, log, now = Date.now()) {
|
|
473
|
+
const rows = db.all(`SELECT id, ext_provider, ext_id FROM issues WHERE ext_provider IS NOT NULL
|
|
474
|
+
AND (status != 'closed' OR updated > ?) ORDER BY ext_synced ASC LIMIT 50`, now - 7 * 86400e3);
|
|
475
|
+
let changed = 0;
|
|
476
|
+
for (const r of rows) {
|
|
477
|
+
try {
|
|
478
|
+
const t = await clientFor(db, r.ext_provider).get(r.ext_id);
|
|
479
|
+
if (applyTicketState(db, r.id, t.state, t.stateName, now))
|
|
480
|
+
changed++;
|
|
481
|
+
}
|
|
482
|
+
catch (e) {
|
|
483
|
+
log?.(`ticket sync #${r.id}: ${e.message}`);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return changed;
|
|
487
|
+
}
|
|
488
|
+
async function safely(db, issueId, what, fn, log) {
|
|
489
|
+
try {
|
|
490
|
+
await fn();
|
|
491
|
+
}
|
|
492
|
+
catch (e) {
|
|
493
|
+
const msg = `${what} failed: ${e.message}`;
|
|
494
|
+
addTimeline(db, issueId, msg);
|
|
495
|
+
log?.(`issue #${issueId}: ${msg}`);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
/** An issue was resolved in Obzerver: close its ticket. */
|
|
499
|
+
export async function onIssueResolved(db, issueId, log) {
|
|
500
|
+
const r = db.get('SELECT * FROM issues WHERE id = ?', issueId);
|
|
501
|
+
if (!r?.ext_provider || r.ext_state !== 'open')
|
|
502
|
+
return;
|
|
503
|
+
const client = clientFor(db, r.ext_provider);
|
|
504
|
+
await safely(db, issueId, `Closing ${r.ext_key}`, async () => {
|
|
505
|
+
await client.close(r.ext_id);
|
|
506
|
+
await client.comment(r.ext_id, r.status === 'verifying'
|
|
507
|
+
? 'Marked resolved in Obzerver. Verifying the fix against live traffic; the result will be posted here.'
|
|
508
|
+
: 'Marked resolved in Obzerver.');
|
|
509
|
+
db.run("UPDATE issues SET ext_state = 'closed', ext_synced = ? WHERE id = ?", Date.now(), issueId);
|
|
510
|
+
}, log);
|
|
511
|
+
}
|
|
512
|
+
/** Verification finished: report on the ticket, and reopen it when the fix did not hold. */
|
|
513
|
+
export async function onVerification(db, changes, log) {
|
|
514
|
+
for (const c of changes) {
|
|
515
|
+
const r = db.get('SELECT * FROM issues WHERE id = ?', c.issueId);
|
|
516
|
+
if (!r?.ext_provider)
|
|
517
|
+
continue;
|
|
518
|
+
const client = clientFor(db, r.ext_provider);
|
|
519
|
+
const release = r.fix_version ? ` in release \`${r.fix_version}\`` : '';
|
|
520
|
+
if (c.status === 'closed') {
|
|
521
|
+
await safely(db, c.issueId, `Reporting to ${r.ext_key}`, async () => {
|
|
522
|
+
await client.comment(r.ext_id, `✅ **Verified fixed by Obzerver**${release}. ${c.reason}`);
|
|
523
|
+
if (r.ext_state === 'open') {
|
|
524
|
+
await client.close(r.ext_id);
|
|
525
|
+
db.run("UPDATE issues SET ext_state = 'closed' WHERE id = ?", c.issueId);
|
|
526
|
+
}
|
|
527
|
+
}, log);
|
|
528
|
+
}
|
|
529
|
+
else if (c.status === 'open') {
|
|
530
|
+
await safely(db, c.issueId, `Reopening ${r.ext_key}`, async () => {
|
|
531
|
+
await client.reopen(r.ext_id);
|
|
532
|
+
await client.comment(r.ext_id, `🔁 **Reopened by Obzerver: the fix did not hold**${release}. ${c.reason}`);
|
|
533
|
+
db.run("UPDATE issues SET ext_state = 'open', ext_synced = ? WHERE id = ?", Date.now(), c.issueId);
|
|
534
|
+
}, log);
|
|
535
|
+
}
|
|
536
|
+
else if (c.status === 'unverified') {
|
|
537
|
+
await safely(db, c.issueId, `Reporting to ${r.ext_key}`, () => client.comment(r.ext_id, '⚠️ **Obzerver could not verify this fix** after 7 days (not enough traffic on the affected code). Close it manually if you are confident.'), log);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
// ---------------------------------------------------------------- webhooks
|
|
542
|
+
const safeEqual = (a, b) => {
|
|
543
|
+
const x = Buffer.from(a), y = Buffer.from(b);
|
|
544
|
+
return x.length === y.length && crypto.timingSafeEqual(x, y);
|
|
545
|
+
};
|
|
546
|
+
export function verifyGithubSignature(secret, raw, header) {
|
|
547
|
+
if (!secret || !header)
|
|
548
|
+
return false;
|
|
549
|
+
return safeEqual(`sha256=${crypto.createHmac('sha256', secret).update(raw).digest('hex')}`, header);
|
|
550
|
+
}
|
|
551
|
+
export function verifyLinearSignature(secret, raw, header) {
|
|
552
|
+
if (!secret || !header)
|
|
553
|
+
return false;
|
|
554
|
+
return safeEqual(crypto.createHmac('sha256', secret).update(raw).digest('hex'), header);
|
|
555
|
+
}
|
|
556
|
+
/** GitHub `issues` event → the linked issue (matched by repository and number). */
|
|
557
|
+
export function handleGithubEvent(db, event, payload) {
|
|
558
|
+
if (event === 'ping')
|
|
559
|
+
return 'pong';
|
|
560
|
+
if (event !== 'issues' || !payload?.issue)
|
|
561
|
+
return 'ignored';
|
|
562
|
+
const repo = trackerSettings(db).github?.repo;
|
|
563
|
+
if (repo && String(payload.repository?.full_name || '').toLowerCase() !== repo.toLowerCase())
|
|
564
|
+
return 'other repository';
|
|
565
|
+
const r = db.get("SELECT id FROM issues WHERE ext_provider = 'github' AND ext_id = ?", String(payload.issue.number));
|
|
566
|
+
if (!r)
|
|
567
|
+
return 'not linked';
|
|
568
|
+
const i = payload.issue;
|
|
569
|
+
const state = i.state === 'open' ? 'open' : i.state_reason === 'not_planned' ? 'canceled' : 'closed';
|
|
570
|
+
return applyTicketState(db, r.id, state, state === 'open' ? 'Open' : state === 'canceled' ? 'Closed (not planned)' : 'Closed') || 'no change';
|
|
571
|
+
}
|
|
572
|
+
/** Linear `Issue` update → the linked issue (matched by Linear issue id). */
|
|
573
|
+
export function handleLinearEvent(db, payload) {
|
|
574
|
+
if (payload?.type !== 'Issue' || !payload.data?.id)
|
|
575
|
+
return 'ignored';
|
|
576
|
+
const r = db.get("SELECT id FROM issues WHERE ext_provider = 'linear' AND ext_id = ?", String(payload.data.id));
|
|
577
|
+
if (!r)
|
|
578
|
+
return 'not linked';
|
|
579
|
+
const type = payload.data.state?.type;
|
|
580
|
+
if (!type)
|
|
581
|
+
return 'no state';
|
|
582
|
+
const state = type === 'completed' ? 'closed' : type === 'canceled' ? 'canceled' : 'open';
|
|
583
|
+
return applyTicketState(db, r.id, state, payload.data.state?.name || type) || 'no change';
|
|
584
|
+
}
|
|
585
|
+
//# sourceMappingURL=trackers.js.map
|