Personal Telegram developer console for GitHub

feat(cp6): add durable incident manager

* feat(cp6): add incident domain * feat(cp6): add durable incident store * feat(cp6): add incident store client * feat(cp6): export incident durable object * feat(cp6): bind dedicated incident store * test(cp6): cover incident redaction and dedupe domain

davoodmehraban89 committed Oct 5, 2026 at 06:20 UTC 25ea460e64c7ede4b72a375f01c366628b0d8006
6 files changed +39 -160
src/core/incident-store.js new
+1
@@ -0,0 +1 @@
1 +export class DurableIncidentStoreClient { constructor({namespace,ownerId}){this.namespace=namespace;this.ownerId=String(ownerId||'');} stub(){if(!this.namespace||!this.ownerId)throw new Error('Incident store is not configured');return this.namespace.get(this.namespace.idFromName('owner:'+this.ownerId));} async request(path,body){const r=await this.stub().fetch('https://incident.local'+path+'?owner='+encodeURIComponent(this.ownerId),{method:body?'POST':'GET',headers:{'content-type':'application/json'},body:body?JSON.stringify(body):undefined});if(!r.ok)throw new Error('Incident store request failed');return r.json();} list(){return this.request('/');} upsert(e){return this.request('/upsert',e);} resolve(id){return this.request('/resolve',{id});} }
src/core/incidents.js new
+5
@@ -0,0 +1,5 @@
1 +const SECRET = /(token|secret|password|authorization|api[_-]?key)=?[^\s&]*/gi;
2 +export const redactIncidentText = value => String(value ?? '').replace(SECRET, '$1=[REDACTED]').replace(/https?:\/\/[^\s?]+\?[^\s]*/gi, m => m.split('?')[0] + '?[REDACTED]');
3 +export const incidentFingerprint = ({ provider='', repo='', sha='', kind='' }={}) => [provider,repo,sha,kind].map(v=>String(v).trim().toLowerCase()).join('|');
4 +export const incidentSeverity = evidence => evidence?.runtimeMismatch || evidence?.deployFailure ? 'critical' : evidence?.ciFailure ? 'high' : 'medium';
5 +export function normalizeIncident(input={}) { const fingerprint=incidentFingerprint(input); if(!fingerprint.replaceAll('|','')) throw new Error('Incident evidence is required'); return { fingerprint, provider:String(input.provider||''), repo:String(input.repo||''), sha:String(input.sha||''), kind:String(input.kind||''), severity:incidentSeverity(input), summary:redactIncidentText(input.summary||input.kind||'Operational incident'), evidenceRef:redactIncidentText(input.evidenceRef||''), status:'open' }; }
src/durable/incident-store.js new
+12
@@ -0,0 +1,12 @@
1 +import { normalizeIncident } from '../core/incidents.js';
2 +const json=(data,status=200)=>new Response(JSON.stringify(data),{status,headers:{'content-type':'application/json'}});
3 +export class IncidentStore {
4 + constructor(state){this.state=state;this.storage=state.storage;}
5 + async fetch(request){const url=new URL(request.url); const owner=url.searchParams.get('owner')||''; if(!owner)return json({error:'owner required'},400); const key='incidents:'+owner; const items=(await this.storage.get(key))||[];
6 + if(request.method==='GET') return json({version:1,items});
7 + const body=await request.json().catch(()=>({}));
8 + if(request.method==='POST'&&url.pathname.endsWith('/upsert')){const next=normalizeIncident(body); const i=items.findIndex(x=>x.fingerprint===next.fingerprint); const now=Date.now(); if(i>=0){items[i]={...items[i],...next,status:'open',count:(items[i].count||1)+1,updatedAt:now};}else items.unshift({...next,id:crypto.randomUUID(),count:1,createdAt:now,updatedAt:now}); await this.storage.put(key,items.slice(0,100)); return json(i>=0?items[i]:items[0]);}
9 + if(request.method==='POST'&&url.pathname.endsWith('/resolve')){const i=items.findIndex(x=>x.id===body.id); if(i<0)return json({error:'not found'},404); items[i]={...items[i],status:'resolved',resolvedAt:Date.now(),updatedAt:Date.now()}; await this.storage.put(key,items); return json(items[i]);}
10 + return json({error:'not found'},404);
11 + }
12 +}
src/index.js
+13 -115
@@ -3,118 +3,16 @@ import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
3 import { handleWorkspaceEditorRequest, workspaceEditorPageResponse } from './workspace-editor.js';
4 export { ApprovalReplayGuard } from './durable/approval-replay-guard.js';
5 export { WorkspaceStore } from './durable/workspace-store.js';
6 -
7 -const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
8 - status,
9 - headers: { 'Content-Type': 'application/json; charset=utf-8' }
10 -});
11 -
12 -const publicHealthPayload = () => ({
13 - status: 'online',
14 - bot: 'Nexa Dev Bot',
15 - version: '1.1.1',
16 - mode: 'Cloudflare Worker Webhook'
17 -});
18 -
19 -function senderIdFromUpdate(update) {
20 - return update?.message?.from?.id ?? update?.callback_query?.from?.id ?? null;
21 -}
22 -
23 -function isOwnerUpdate(update, env) {
24 - if (!env.OWNER_TELEGRAM_ID) return false;
25 - const senderId = senderIdFromUpdate(update);
26 - return senderId !== null && String(senderId) === String(env.OWNER_TELEGRAM_ID);
27 -}
28 -
29 -function safeErrorMessage(error, env = {}) {
30 - let message = String(error?.message || 'Unknown error');
31 - for (const secret of [
32 - env.TELEGRAM_BOT_TOKEN,
33 - env.TELEGRAM_WEBHOOK_SECRET,
34 - env.GITHUB_TOKEN,
35 - env.CLOUDFLARE_API_TOKEN,
36 - env.APPROVAL_SIGNING_SECRET
37 - ]) {
38 - const value = String(secret || '');
39 - if (value) message = message.split(value).join('[REDACTED]');
40 - }
41 - return message;
42 -}
43 -
44 -/**
45 - * Cloudflare Worker entrypoint.
46 - * Security invariants:
47 - * - Public health endpoints expose only minimal non-sensitive service identity.
48 - * - Telegram webhook requests must carry the configured secret header.
49 - * - Telegram updates are owner-only and unauthorized senders are ignored silently.
50 - * - Workspace Mini App API validates Telegram initData, freshness and owner identity.
51 - * - Mini App saves only the durable Draft; GitHub writes remain behind Safe Approval.
52 - * - Missing security or transport configuration fails closed.
53 - */
54 -export default {
55 - async fetch(request, env = {}, ctx = {}) {
56 - const url = new URL(request.url);
57 -
58 - if (request.method === 'GET' && url.pathname === '/workspace/editor') {
59 - return workspaceEditorPageResponse();
60 - }
61 -
62 - if (url.pathname === '/workspace/api/editor' && (request.method === 'GET' || request.method === 'PUT')) {
63 - const workspaces = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
64 - return handleWorkspaceEditorRequest(request, {
65 - workspaces,
66 - botToken: env.TELEGRAM_BOT_TOKEN || '',
67 - ownerId: env.OWNER_TELEGRAM_ID || ''
68 - });
69 - }
70 -
71 - if (request.method === 'GET') {
72 - if (url.pathname === '/health' || url.pathname === '/' || url.pathname === '/status') {
73 - return jsonResponse(publicHealthPayload());
74 - }
75 -
76 - return new Response('Not Found', { status: 404 });
77 - }
78 -
79 - if (request.method === 'POST' && url.pathname === '/telegram/webhook') {
80 - if (!env.TELEGRAM_WEBHOOK_SECRET) {
81 - return new Response('Webhook secret not configured', { status: 503 });
82 - }
83 -
84 - const suppliedSecret = request.headers.get('X-Telegram-Bot-Api-Secret-Token');
85 - if (suppliedSecret !== env.TELEGRAM_WEBHOOK_SECRET) {
86 - return new Response('Forbidden', { status: 403 });
87 - }
88 -
89 - if (!env.OWNER_TELEGRAM_ID) {
90 - return new Response('Owner not configured', { status: 503 });
91 - }
92 -
93 - if (!env.TELEGRAM_BOT_TOKEN) {
94 - return new Response('Telegram bot token not configured', { status: 503 });
95 - }
96 -
97 - try {
98 - const update = await request.json();
99 -
100 - if (!isOwnerUpdate(update, env)) {
101 - return jsonResponse({ ok: true, ignored: true });
102 - }
103 -
104 - const bot = new GuidedNexaDevBot(env);
105 - const result = await bot.handleUpdate(update);
106 - return jsonResponse(result);
107 - } catch (err) {
108 - const safeError = safeErrorMessage(err, env);
109 - console.error('telegram_webhook_error', safeError);
110 - return jsonResponse({ ok: false, error: 'Telegram webhook processing failed' }, 400);
111 - }
112 - }
113 -
114 - if (request.method === 'POST') {
115 - return new Response('Not Found', { status: 404 });
116 - }
117 -
118 - return new Response('Method Not Allowed', { status: 405 });
119 - }
120 -};
6 +export { IncidentStore } from './durable/incident-store.js';
7 +
8 +const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } });
9 +const publicHealthPayload = () => ({ status: 'online', bot: 'Nexa Dev Bot', version: '1.1.1', mode: 'Cloudflare Worker Webhook' });
10 +function senderIdFromUpdate(update) { return update?.message?.from?.id ?? update?.callback_query?.from?.id ?? null; }
11 +function isOwnerUpdate(update, env) { if (!env.OWNER_TELEGRAM_ID) return false; const senderId = senderIdFromUpdate(update); return senderId !== null && String(senderId) === String(env.OWNER_TELEGRAM_ID); }
12 +function safeErrorMessage(error, env = {}) { let message=String(error?.message||'Unknown error'); for(const secret of [env.TELEGRAM_BOT_TOKEN,env.TELEGRAM_WEBHOOK_SECRET,env.GITHUB_TOKEN,env.CLOUDFLARE_API_TOKEN,env.APPROVAL_SIGNING_SECRET]){const value=String(secret||'');if(value)message=message.split(value).join('[REDACTED]');} return message; }
13 +export default { async fetch(request,env={},ctx={}) { const url=new URL(request.url);
14 + if(request.method==='GET'&&url.pathname==='/workspace/editor')return workspaceEditorPageResponse();
15 + if(url.pathname==='/workspace/api/editor'&&(request.method==='GET'||request.method==='PUT')){const workspaces=new DurableWorkspaceStoreClient({namespace:env.WORKSPACE_STORE});return handleWorkspaceEditorRequest(request,{workspaces,botToken:env.TELEGRAM_BOT_TOKEN||'',ownerId:env.OWNER_TELEGRAM_ID||''});}
16 + if(request.method==='GET'){if(url.pathname==='/health'||url.pathname==='/'||url.pathname==='/status')return jsonResponse(publicHealthPayload());return new Response('Not Found',{status:404});}
17 + if(request.method==='POST'&&url.pathname==='/telegram/webhook'){if(!env.TELEGRAM_WEBHOOK_SECRET)return new Response('Webhook secret not configured',{status:503});if(request.headers.get('X-Telegram-Bot-Api-Secret-Token')!==env.TELEGRAM_WEBHOOK_SECRET)return new Response('Forbidden',{status:403});if(!env.OWNER_TELEGRAM_ID)return new Response('Owner not configured',{status:503});if(!env.TELEGRAM_BOT_TOKEN)return new Response('Telegram bot token not configured',{status:503});try{const update=await request.json();if(!isOwnerUpdate(update,env))return jsonResponse({ok:true,ignored:true});const bot=new GuidedNexaDevBot(env);return jsonResponse(await bot.handleUpdate(update));}catch(err){console.error('telegram_webhook_error',safeErrorMessage(err,env));return jsonResponse({ok:false,error:'Telegram webhook processing failed'},400);}}
18 + if(request.method==='POST')return new Response('Not Found',{status:404}); return new Response('Method Not Allowed',{status:405}); } };
test/incidents.test.js new
+4
@@ -0,0 +1,4 @@
1 +import test from 'node:test';import assert from 'node:assert/strict';import {incidentFingerprint,redactIncidentText,normalizeIncident} from '../src/core/incidents.js';
2 +test('CP6 fingerprint separates provider repo sha and kind',()=>{assert.notEqual(incidentFingerprint({provider:'github',repo:'a',sha:'1',kind:'ci'}),incidentFingerprint({provider:'github',repo:'a',sha:'2',kind:'ci'}));});
3 +test('CP6 redacts token/query material',()=>{const s=redactIncidentText('token=abc https://x.test/a?secret=bad');assert.doesNotMatch(s,/abc|bad/);});
4 +test('CP6 normalized incidents are open and source backed',()=>{const i=normalizeIncident({provider:'github',repo:'r',sha:'a'.repeat(40),kind:'ci',ciFailure:true,summary:'failed'});assert.equal(i.status,'open');assert.equal(i.severity,'high');assert.match(i.fingerprint,/github/);});
wrangler.jsonc
+4 -45
@@ -1,47 +1,6 @@
1 {
2 - "$schema": "node_modules/wrangler/config-schema.json",
3 - "name": "nexa-dev-bot",
4 - "main": "src/index.js",
5 - "compatibility_date": "2026-10-02",
6 - "workers_dev": true,
7 - "keep_vars": true,
8 - "observability": {
9 - "enabled": true
10 - },
11 - "durable_objects": {
12 - "bindings": [
13 - {
14 - "name": "APPROVAL_REPLAY_GUARD",
15 - "class_name": "ApprovalReplayGuard"
16 - },
17 - {
18 - "name": "WORKSPACE_STORE",
19 - "class_name": "WorkspaceStore"
20 - }
21 - ]
22 - },
23 - "previews": {
24 - "durable_objects": {
25 - "bindings": [
26 - {
27 - "name": "APPROVAL_REPLAY_GUARD",
28 - "class_name": "ApprovalReplayGuard"
29 - },
30 - {
31 - "name": "WORKSPACE_STORE",
32 - "class_name": "WorkspaceStore"
33 - }
34 - ]
35 - }
36 - },
37 - "exports": {
38 - "ApprovalReplayGuard": {
39 - "type": "durable-object",
40 - "storage": "sqlite"
41 - },
42 - "WorkspaceStore": {
43 - "type": "durable-object",
44 - "storage": "sqlite"
45 - }
46 - }
2 + "$schema":"node_modules/wrangler/config-schema.json","name":"nexa-dev-bot","main":"src/index.js","compatibility_date":"2026-10-02","workers_dev":true,"keep_vars":true,"observability":{"enabled":true},
3 + "durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"}]},
4 + "previews":{"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"}]}},
5 + "exports":{"ApprovalReplayGuard":{"type":"durable-object","storage":"sqlite"},"WorkspaceStore":{"type":"durable-object","storage":"sqlite"},"IncidentStore":{"type":"durable-object","storage":"sqlite"}}
6 }