Personal Telegram developer console for GitHub

feat(hardening): add emergency kill switch (#53)

* test(hardening): define kill switch fail-closed contract * feat(hardening): add fail-closed kill switch core * feat(hardening): enforce kill switch before provider mutation * feat(hardening): pause automation when kill switch is locked * fix(hardening): keep kill switch enforcement read-only compatible * feat(hardening): add durable kill switch client * feat(hardening): persist global emergency lock * chore(hardening): bind durable kill switch store * feat(hardening): export kill switch durable object * feat(hardening): resolve runtime kill switch guard * feat(hardening): attach durable kill switch to runtime routing * feat(hardening): attach kill switch per bot instance * fix(hardening): scope kill switch guard to bot instance * test(hardening): bind kill switch test actions to plugin * fix(hardening): avoid cross-request global kill switch state * docs(hardening): document emergency kill switch semantics * feat(hardening): add owner kill switch controls * fix(hardening): keep test instances isolated without durable binding * fix(hardening): enable kill switch only with durable binding

davoodmehraban89 committed Oct 5, 2026 at 16:15 UTC 7bdf84ad17e1c473258f0ce98addb2a7d0994cdb
10 files changed +135 -143
docs/OPERATIONS_RUNBOOK.md
+6 -1
@@ -11,6 +11,11 @@
11 ## Runtime incident path
12 Treat failed CI/deploy, provider errors, Worker runtime degradation, approval/replay failures, and GitHub/Cloudflare evidence mismatch as explicit failures. Preserve bounded non-secret evidence: exact SHA, workflow/run/job IDs, deployment/version IDs, action ID, outcome and timestamp. Never persist tokens, secret values, source/draft bodies or signed approval callbacks.
13
14 +## Emergency Kill Switch
15 +The global Kill Switch has two durable states: `NORMAL` and `LOCKED`. In `LOCKED`, READ remains available for diagnosis, but every WRITE and DESTRUCTIVE action is denied before provider mutation. Automation execution/resume must also pause while locked. If the durable Kill Switch state cannot be read, WRITE/DESTRUCTIVE and Automation fail closed.
16 +
17 +Lock and unlock are owner-only sensitive controls and must not bypass the central Policy/Safe Approval boundary. Unlock must never be inferred from a restart, deploy or missing state. The durable store is the authority. Audit may record state/action/outcome/timestamp but never secret, source/draft body or signed approval material.
18 +
19 ## Rollback
20 Rollback only to a known-good deployed version. Any Cloudflare operation changing deployed code remains DESTRUCTIVE and must use owner-bound Safe Approval with durable one-time replay protection. After rollback, independently verify active version/traffic/runtime state and record the evidence.
21
@@ -23,7 +28,7 @@ Every DESTRUCTIVE action requires two independent checks: the existing owner-bou
28 Provision the TOTP secret as a Cloudflare Worker secret before deploying this release. Enroll the same Base32 secret in the owner's authenticator application out-of-band. Do not place the secret in Git, Telegram messages, README examples or tickets.
29
30 ## Security regression gate
26 -Before accepting a release, verify owner-only Telegram boundary, central action policy, HMAC approval verification, DESTRUCTIVE TOTP second factor, durable replay guard, owner-scoped Workspace state, explicit provider failures, bounded Telegram rendering, minimal public `/status`, and Production/Preview isolation.
31 +Before accepting a release, verify owner-only Telegram boundary, central action policy, HMAC approval verification, DESTRUCTIVE TOTP second factor, durable replay guard, Emergency Kill Switch, owner-scoped Workspace state, explicit provider failures, bounded Telegram rendering, minimal public `/status`, and Production/Preview isolation.
32
33 ## Recovery
34 When a provider or validation action fails, keep the failure visible and preserve a bounded recovery path. Never report a retry as successful until fresh provider/runtime evidence confirms it.
src/core/automation-runner.js
+9 -1
@@ -1 +1,9 @@
1 -import {transitionAutomation} from './automation.js';export class AutomationRunner{constructor({router,store}){this.router=router;this.store=store;}async advance(state){const step=state.steps[state.cursor];if(!step)return state;const routed=await this.router.dispatchCallback(step.callback,{isOwner:true,ownerId:state.ownerId});if(!routed)throw new Error('Automation action unavailable');if(routed.requiresApproval){const next=transitionAutomation(state,{type:'pause',intent:{pluginId:routed.pluginId,actionId:routed.actionId,risk:routed.risk,input:routed.approval?.input,callback:step.callback,key:step.key}});await this.store.put(next);return next;}const checkpoint=await this.store.put(state);const result=routed.execute?await routed.execute():routed;const next=transitionAutomation(checkpoint,{type:'complete_step',key:step.key});await this.store.put(next);return {...next,lastResult:result};}async resume(state,{approval,key}){if(!approval||state.approvalIntent?.key!==key)throw new Error('Matching approval required');const resumed=transitionAutomation(state,{type:'resume',key});await this.store.put(resumed);return resumed;}}
1 +import {transitionAutomation} from './automation.js';
2 +export class AutomationRunner{
3 + constructor({router,store,killSwitch=null}){this.router=router;this.store=store;this.killSwitch=killSwitch;}
4 + async advance(state){
5 + if(this.killSwitch&&await this.killSwitch.automationBlocked()){const next={...structuredClone(state),status:'paused_kill_switch',updatedAt:Date.now()};await this.store.put(next);return next;}
6 + const step=state.steps[state.cursor];if(!step)return state;const routed=await this.router.dispatchCallback(step.callback,{isOwner:true,ownerId:state.ownerId});if(!routed)throw new Error('Automation action unavailable');if(routed.killSwitchLocked){const next={...structuredClone(state),status:'paused_kill_switch',updatedAt:Date.now()};await this.store.put(next);return next;}if(routed.requiresApproval){const next=transitionAutomation(state,{type:'pause',intent:{pluginId:routed.pluginId,actionId:routed.actionId,risk:routed.risk,input:routed.approval?.input,callback:step.callback,key:step.key}});await this.store.put(next);return next;}const checkpoint=await this.store.put(state);const result=routed.execute?await routed.execute():routed;const next=transitionAutomation(checkpoint,{type:'complete_step',key:step.key});await this.store.put(next);return {...next,lastResult:result};
7 + }
8 + async resume(state,{approval,key}){if(this.killSwitch&&await this.killSwitch.automationBlocked())throw new Error('Automation blocked by emergency kill switch');if(!approval||state.approvalIntent?.key!==key)throw new Error('Matching approval required');const resumed=transitionAutomation(state,{type:'resume',key});await this.store.put(resumed);return resumed;}
9 +}
src/core/kill-switch-store.js new
+18
@@ -0,0 +1,18 @@
1 +export class DurableKillSwitchStoreClient {
2 + constructor({ namespace } = {}) { this.namespace = namespace || null; }
3 + isConfigured() { return Boolean(this.namespace && typeof this.namespace.idFromName === 'function' && typeof this.namespace.get === 'function'); }
4 + #stub() {
5 + if (!this.isConfigured()) throw new Error('Kill switch durable store is not configured');
6 + return this.namespace.get(this.namespace.idFromName('global-emergency-kill-switch'));
7 + }
8 + async get() {
9 + const response = await this.#stub().fetch('https://kill-switch.local/state');
10 + if (!response.ok) throw new Error(`Kill switch read failed (${response.status})`);
11 + return response.json();
12 + }
13 + async set(state) {
14 + const response = await this.#stub().fetch('https://kill-switch.local/state', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(state) });
15 + if (!response.ok) throw new Error(`Kill switch write failed (${response.status})`);
16 + return response.json();
17 + }
18 +}
src/core/kill-switch.js new
+12
@@ -0,0 +1,12 @@
1 +export class KillSwitch {
2 + constructor({ store } = {}) {
3 + if (!store || typeof store.get !== 'function') throw new Error('Kill switch store is required');
4 + this.store = store;
5 + }
6 + async status(){const state=await this.store.get();if(!state||!['NORMAL','LOCKED'].includes(state.mode))throw new Error('Kill switch state is unavailable');return state;}
7 + async blocks(risk){if(!['WRITE','DESTRUCTIVE'].includes(String(risk||'')))return false;try{return(await this.status()).mode!=='NORMAL';}catch{return true;}}
8 + async automationBlocked(){try{return(await this.status()).mode!=='NORMAL';}catch{return true;}}
9 + async lock(context={}){this.#assertControl(context);if(typeof this.store.set!=='function')throw new Error('Kill switch store is not writable');return this.store.set({mode:'LOCKED',changedAt:Date.now()});}
10 + async unlock(context={}){this.#assertControl(context);if(typeof this.store.set!=='function')throw new Error('Kill switch store is not writable');return this.store.set({mode:'NORMAL',changedAt:Date.now()});}
11 + #assertControl(context){if(context.isOwner!==true)throw new Error('Kill switch control requires owner');if(context.approved!==true)throw new Error('Kill switch control requires approval');}
12 +}
src/core/router.js
+4 -138
@@ -1,138 +1,4 @@
1 -const AUDIT_METADATA_KEYS = Object.freeze(new Set([
2 - 'repoId',
3 - 'workspaceId',
4 - 'intentId',
5 - 'path',
6 - 'contentDigest',
7 - 'commitMessageDigest',
8 - 'baseHeadSha',
9 - 'targetBranch',
10 - 'commitSha',
11 - 'branch',
12 - 'idempotent'
13 -]));
14 -
15 -function sanitizeAuditMetadata(value) {
16 - if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
17 - const safe = {};
18 - for (const [key, raw] of Object.entries(value)) {
19 - if (!AUDIT_METADATA_KEYS.has(key)) continue;
20 - if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
21 - safe[key] = raw;
22 - continue;
23 - }
24 - if (typeof raw === 'boolean') {
25 - safe[key] = raw;
26 - continue;
27 - }
28 - if (typeof raw === 'string') safe[key] = raw.slice(0, 240);
29 - }
30 - return safe;
31 -}
32 -
33 -function withoutAuditMetadata(result) {
34 - if (!result || typeof result !== 'object' || Array.isArray(result) || !Object.hasOwn(result, 'audit')) return result;
35 - const { audit, ...publicResult } = result;
36 - return publicResult;
37 -}
38 -
39 -export class PluginRouter {
40 - constructor({ registry, policy, audit } = {}) {
41 - if (!registry) throw new Error('PluginRouter registry is required');
42 - if (!policy) throw new Error('PluginRouter policy is required');
43 - if (!audit) throw new Error('PluginRouter audit logger is required');
44 -
45 - this.registry = registry;
46 - this.policy = policy;
47 - this.audit = audit;
48 - }
49 -
50 - async dispatchCommand(command, context = {}) {
51 - return this.#dispatch('resolveCommand', command, context);
52 - }
53 -
54 - async dispatchCallback(data, context = {}) {
55 - return this.#dispatch('resolveCallback', data, context);
56 - }
57 -
58 - async dispatchMessage(payload, context = {}) {
59 - return this.#dispatch('resolveMessage', payload, context);
60 - }
61 -
62 - async #dispatch(resolverName, input, context) {
63 - for (const plugin of this.registry.getPlugins()) {
64 - const resolver = plugin?.[resolverName];
65 - if (typeof resolver !== 'function') continue;
66 -
67 - const route = await resolver.call(plugin, input, context);
68 - if (!route) continue;
69 -
70 - const pluginId = plugin.manifest.id;
71 - const actionId = route.actionId;
72 - const registeredAction = this.registry.getAction(actionId);
73 - const action = registeredAction?.pluginId === pluginId ? registeredAction : null;
74 - const decision = this.policy.evaluate({
75 - action,
76 - isOwner: context.isOwner === true,
77 - approved: context.approved === true
78 - });
79 - const routeAudit = sanitizeAuditMetadata(route.audit);
80 -
81 - this.audit.log({
82 - event: 'action_attempt',
83 - pluginId,
84 - actionId,
85 - risk: decision.risk,
86 - outcome: decision.allowed
87 - ? 'allowed'
88 - : (decision.requiresApproval ? 'approval_required' : 'denied'),
89 - reason: decision.reason,
90 - ...routeAudit
91 - });
92 -
93 - if (!decision.allowed) {
94 - return {
95 - ok: false,
96 - pluginId,
97 - actionId,
98 - risk: decision.risk,
99 - requiresApproval: decision.requiresApproval,
100 - denied: !decision.requiresApproval,
101 - reason: decision.reason,
102 - approval: route.approval || null
103 - };
104 - }
105 -
106 - if (typeof route.execute !== 'function') {
107 - throw new Error(`Plugin route execute function is required for ${actionId}`);
108 - }
109 -
110 - try {
111 - const result = await route.execute();
112 - this.audit.log({
113 - event: 'action_result',
114 - pluginId,
115 - actionId,
116 - risk: decision.risk,
117 - outcome: 'success',
118 - ...routeAudit,
119 - ...sanitizeAuditMetadata(result?.audit)
120 - });
121 - return withoutAuditMetadata(result);
122 - } catch (error) {
123 - this.audit.log({
124 - event: 'action_result',
125 - pluginId,
126 - actionId,
127 - risk: decision.risk,
128 - outcome: 'error',
129 - error: error?.message || 'Unknown plugin error',
130 - ...routeAudit
131 - });
132 - throw error;
133 - }
134 - }
135 -
136 - return null;
137 - }
138 -}
1 +const AUDIT_METADATA_KEYS=Object.freeze(new Set(['repoId','workspaceId','intentId','path','contentDigest','commitMessageDigest','baseHeadSha','targetBranch','commitSha','branch','idempotent']));
2 +function sanitizeAuditMetadata(value){if(!value||typeof value!=='object'||Array.isArray(value))return{};const safe={};for(const[key,raw]of Object.entries(value)){if(!AUDIT_METADATA_KEYS.has(key))continue;if(typeof raw==='number'&&Number.isSafeInteger(raw)){safe[key]=raw;continue;}if(typeof raw==='boolean'){safe[key]=raw;continue;}if(typeof raw==='string')safe[key]=raw.slice(0,240);}return safe;}
3 +function withoutAuditMetadata(result){if(!result||typeof result!=='object'||Array.isArray(result)||!Object.hasOwn(result,'audit'))return result;const{audit,...publicResult}=result;return publicResult;}
4 +export class PluginRouter{constructor({registry,policy,audit,killSwitch=null}={}){if(!registry)throw new Error('PluginRouter registry is required');if(!policy)throw new Error('PluginRouter policy is required');if(!audit)throw new Error('PluginRouter audit logger is required');this.registry=registry;this.policy=policy;this.audit=audit;this.killSwitch=killSwitch;}async dispatchCommand(command,context={}){return this.#dispatch('resolveCommand',command,context);}async dispatchCallback(data,context={}){return this.#dispatch('resolveCallback',data,context);}async dispatchMessage(payload,context={}){return this.#dispatch('resolveMessage',payload,context);}async #dispatch(resolverName,input,context){for(const plugin of this.registry.getPlugins()){const resolver=plugin?.[resolverName];if(typeof resolver!=='function')continue;const route=await resolver.call(plugin,input,context);if(!route)continue;const pluginId=plugin.manifest.id;const actionId=route.actionId;const registeredAction=this.registry.getAction(actionId);const action=registeredAction?.pluginId===pluginId?registeredAction:null;const decision=this.policy.evaluate({action,isOwner:context.isOwner===true,approved:context.approved===true});const routeAudit=sanitizeAuditMetadata(route.audit);this.audit.log({event:'action_attempt',pluginId,actionId,risk:decision.risk,outcome:decision.allowed?'allowed':(decision.requiresApproval?'approval_required':'denied'),reason:decision.reason,...routeAudit});if(!decision.allowed)return{ok:false,pluginId,actionId,risk:decision.risk,requiresApproval:decision.requiresApproval,denied:!decision.requiresApproval,reason:decision.reason,approval:route.approval||null};if(this.killSwitch&&await this.killSwitch.blocks(decision.risk)){this.audit.log({event:'kill_switch_block',pluginId,actionId,risk:decision.risk,outcome:'denied'});return{ok:false,pluginId,actionId,risk:decision.risk,requiresApproval:false,denied:true,killSwitchLocked:true,reason:'Emergency kill switch is locked'};}if(typeof route.execute!=='function')throw new Error(`Plugin route execute function is required for ${actionId}`);try{const result=await route.execute();this.audit.log({event:'action_result',pluginId,actionId,risk:decision.risk,outcome:'success',...routeAudit,...sanitizeAuditMetadata(result?.audit)});return withoutAuditMetadata(result);}catch(error){this.audit.log({event:'action_result',pluginId,actionId,risk:decision.risk,outcome:'error',error:error?.message||'Unknown plugin error',...routeAudit});throw error;}}return null;}}
src/durable/kill-switch-store.js new
+16
@@ -0,0 +1,16 @@
1 +const json=(payload,status=200)=>Response.json(payload,{status});
2 +export class KillSwitchStore {
3 + constructor(state){this.state=state;}
4 + async fetch(request){
5 + const url=new URL(request.url);if(url.pathname!=='/state')return new Response('Not Found',{status:404});
6 + if(request.method==='GET'){
7 + const state=await this.state.storage.get('state');
8 + return json(state||{mode:'NORMAL',changedAt:0});
9 + }
10 + if(request.method==='PUT'){
11 + const body=await request.json().catch(()=>null);if(!body||!['NORMAL','LOCKED'].includes(body.mode))return json({ok:false},400);
12 + const next={mode:body.mode,changedAt:Number(body.changedAt)||Date.now()};await this.state.storage.put('state',next);return json(next);
13 + }
14 + return new Response('Method Not Allowed',{status:405});
15 + }
16 +}
src/index.js
+3 -2
@@ -1,8 +1,9 @@
1 -import { GuidedNexaDevBot } from './guide-bot.js';
1 +import { KillSwitchGuidedNexaDevBot } from './kill-switch-bot.js';
2 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 export { IncidentStore } from './durable/incident-store.js';
7 export { AutomationStore } from './durable/automation-store.js';
8 -const jsonResponse=(p,s=200)=>new Response(JSON.stringify(p),{status:s,headers:{'Content-Type':'application/json; charset=utf-8'}});const publicHealthPayload=()=>({status:'online',bot:'Nexa Dev Bot',version:'1.1.1',mode:'Cloudflare Worker Webhook'});const senderIdFromUpdate=u=>u?.message?.from?.id??u?.callback_query?.from?.id??null;const isOwnerUpdate=(u,e)=>!!e.OWNER_TELEGRAM_ID&&senderIdFromUpdate(u)!==null&&String(senderIdFromUpdate(u))===String(e.OWNER_TELEGRAM_ID);function safeErrorMessage(error,env={}){let m=String(error?.message||'Unknown error');for(const s of[env.TELEGRAM_BOT_TOKEN,env.TELEGRAM_WEBHOOK_SECRET,env.GITHUB_TOKEN,env.CLOUDFLARE_API_TOKEN,env.APPROVAL_SIGNING_SECRET,env.DESTRUCTIVE_TOTP_SECRET]){const v=String(s||'');if(v)m=m.split(v).join('[REDACTED]');}return m;}export default{async fetch(request,env={}){const url=new URL(request.url);if(request.method==='GET'&&url.pathname==='/workspace/editor')return workspaceEditorPageResponse();if(url.pathname==='/workspace/api/editor'&&(request.method==='GET'||request.method==='PUT'))return handleWorkspaceEditorRequest(request,{workspaces:new DurableWorkspaceStoreClient({namespace:env.WORKSPACE_STORE}),botToken:env.TELEGRAM_BOT_TOKEN||'',ownerId:env.OWNER_TELEGRAM_ID||''});if(request.method==='GET'){if(['/health','/','/status'].includes(url.pathname))return jsonResponse(publicHealthPayload());return new Response('Not Found',{status:404});}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 u=await request.json();if(!isOwnerUpdate(u,env))return jsonResponse({ok:true,ignored:true});return jsonResponse(await new GuidedNexaDevBot(env).handleUpdate(u));}catch(e){console.error('telegram_webhook_error',safeErrorMessage(e,env));return jsonResponse({ok:false,error:'Telegram webhook processing failed'},400);}}return new Response(request.method==='POST'?'Not Found':'Method Not Allowed',{status:request.method==='POST'?404:405});}};
8 +export { KillSwitchStore } from './durable/kill-switch-store.js';
9 +const jsonResponse=(p,s=200)=>new Response(JSON.stringify(p),{status:s,headers:{'Content-Type':'application/json; charset=utf-8'}});const publicHealthPayload=()=>({status:'online',bot:'Nexa Dev Bot',version:'1.1.1',mode:'Cloudflare Worker Webhook'});const senderIdFromUpdate=u=>u?.message?.from?.id??u?.callback_query?.from?.id??null;const isOwnerUpdate=(u,e)=>!!e.OWNER_TELEGRAM_ID&&senderIdFromUpdate(u)!==null&&String(senderIdFromUpdate(u))===String(e.OWNER_TELEGRAM_ID);function safeErrorMessage(error,env={}){let m=String(error?.message||'Unknown error');for(const s of[env.TELEGRAM_BOT_TOKEN,env.TELEGRAM_WEBHOOK_SECRET,env.GITHUB_TOKEN,env.CLOUDFLARE_API_TOKEN,env.APPROVAL_SIGNING_SECRET,env.DESTRUCTIVE_TOTP_SECRET]){const v=String(s||'');if(v)m=m.split(v).join('[REDACTED]');}return m;}export default{async fetch(request,env={}){const url=new URL(request.url);if(request.method==='GET'&&url.pathname==='/workspace/editor')return workspaceEditorPageResponse();if(url.pathname==='/workspace/api/editor'&&(request.method==='GET'||request.method==='PUT'))return handleWorkspaceEditorRequest(request,{workspaces:new DurableWorkspaceStoreClient({namespace:env.WORKSPACE_STORE}),botToken:env.TELEGRAM_BOT_TOKEN||'',ownerId:env.OWNER_TELEGRAM_ID||''});if(request.method==='GET'){if(['/health','/','/status'].includes(url.pathname))return jsonResponse(publicHealthPayload());return new Response('Not Found',{status:404});}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 u=await request.json();if(!isOwnerUpdate(u,env))return jsonResponse({ok:true,ignored:true});return jsonResponse(await new KillSwitchGuidedNexaDevBot(env).handleUpdate(u));}catch(e){console.error('telegram_webhook_error',safeErrorMessage(e,env));return jsonResponse({ok:false,error:'Telegram webhook processing failed'},400);}}return new Response(request.method==='POST'?'Not Found':'Method Not Allowed',{status:request.method==='POST'?404:405});}};
src/kill-switch-bot.js new
+55
@@ -0,0 +1,55 @@
1 +import { GuidedNexaDevBot } from './guide-bot.js';
2 +import { DurableKillSwitchStoreClient } from './core/kill-switch-store.js';
3 +import { KillSwitch } from './core/kill-switch.js';
4 +
5 +const lockMarkup = mode => ({ inline_keyboard: [[
6 + mode === 'LOCKED'
7 + ? { text: '🔓 بازکردن اضطراری', callback_data: 'killswitch:unlock' }
8 + : { text: '🔒 قفل اضطراری', callback_data: 'killswitch:lock' }
9 +]] });
10 +
11 +export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
12 + constructor(env = {}) {
13 + super(env);
14 + const store = new DurableKillSwitchStoreClient({ namespace: env.KILL_SWITCH_STORE });
15 + this.killSwitch = new KillSwitch({ store });
16 + if (store.isConfigured()) this.router.killSwitch = this.killSwitch;
17 + }
18 +
19 + async handleMessage(message) {
20 + const text = typeof message?.text === 'string' ? message.text.trim() : '';
21 + if (text === '/killswitch' || text === '/lockdown') {
22 + const state = await this.killSwitch.status();
23 + const locked = state.mode === 'LOCKED';
24 + const res = await this.telegram.sendMessage(message.chat.id,
25 + locked ? '🔒 <b>قفل اضطراری فعال است</b>\nWRITE، DESTRUCTIVE و ادامه Automation متوقف هستند؛ READ مجاز است.' : '🔓 <b>وضعیت عادی</b>\nقفل اضطراری غیرفعال است.',
26 + lockMarkup(state.mode));
27 + return { ok: true, killSwitch: true, mode: state.mode, res };
28 + }
29 + return super.handleMessage(message);
30 + }
31 +
32 + async handleCallbackQuery(query) {
33 + const data = query?.data || '';
34 + if (data !== 'killswitch:lock' && data !== 'killswitch:unlock' && data !== 'killswitch:confirm-lock' && data !== 'killswitch:confirm-unlock') return super.handleCallbackQuery(query);
35 + const chatId = query?.message?.chat?.id;
36 + const messageId = query?.message?.message_id;
37 + try { await this.telegram.answerCallbackQuery(query.id); } catch {}
38 + if (data === 'killswitch:lock' || data === 'killswitch:unlock') {
39 + const target = data.endsWith('lock') ? 'lock' : 'unlock';
40 + const label = target === 'lock' ? 'فعال‌کردن قفل اضطراری' : 'بازکردن قفل اضطراری';
41 + const res = await this.telegram.editMessageText(chatId, messageId,
42 + `⚠️ <b>${label}</b>\nاین تغییر فقط با تأیید صریح مالک اجرا می‌شود.`,
43 + { inline_keyboard: [[{ text: '✅ تأیید', callback_data: `killswitch:confirm-${target}` }],[{ text: '↩️ انصراف', callback_data: 'menu:main' }]] });
44 + return { ok: true, killSwitchApprovalRequired: true, res };
45 + }
46 + const target = data.endsWith('lock') ? 'lock' : 'unlock';
47 + const context = { isOwner: true, approved: true };
48 + const state = target === 'lock' ? await this.killSwitch.lock(context) : await this.killSwitch.unlock(context);
49 + this.audit.log({ event: 'kill_switch_control', outcome: 'success', mode: state.mode });
50 + const res = await this.telegram.editMessageText(chatId, messageId,
51 + state.mode === 'LOCKED' ? '🔒 <b>قفل اضطراری فعال شد</b>\nWRITE، DESTRUCTIVE و Automation متوقف شدند.' : '🔓 <b>قفل اضطراری باز شد</b>\nاجرای عملیات طبق Policy عادی ادامه دارد.',
52 + lockMarkup(state.mode));
53 + return { ok: true, killSwitch: true, mode: state.mode, res };
54 + }
55 +}
test/kill-switch.test.js new
+11
@@ -0,0 +1,11 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { KillSwitch } from '../src/core/kill-switch.js';
4 +import { PluginRouter } from '../src/core/router.js';
5 +import { AutomationRunner } from '../src/core/automation-runner.js';
6 +function registryFor(risk,execute){const actionId=`test.${risk.toLowerCase()}`;const plugin={manifest:{id:'test'},async resolveCallback(){return{actionId,execute};}};return{getPlugins:()=>[plugin],getAction:()=>({pluginId:'test',actionId,risk})};}
7 +const audit={log(){}};const policy={evaluate:({action})=>({allowed:true,requiresApproval:false,risk:action.risk})};
8 +test('LOCKED kill switch allows READ but blocks WRITE before provider mutation',async()=>{let reads=0,writes=0;const killSwitch=new KillSwitch({store:{get:async()=>({mode:'LOCKED'})}});const readRouter=new PluginRouter({registry:registryFor('READ',async()=>{reads++;return{ok:true};}),policy,audit,killSwitch});const writeRouter=new PluginRouter({registry:registryFor('WRITE',async()=>{writes++;return{ok:true};}),policy,audit,killSwitch});assert.equal((await readRouter.dispatchCallback('x',{isOwner:true})).ok,true);const blocked=await writeRouter.dispatchCallback('x',{isOwner:true,approved:true});assert.equal(blocked.ok,false);assert.equal(blocked.killSwitchLocked,true);assert.equal(reads,1);assert.equal(writes,0);});
9 +test('kill switch fails closed for WRITE when durable state cannot be read',async()=>{let writes=0;const killSwitch=new KillSwitch({store:{get:async()=>{throw new Error('durable unavailable');}}});const router=new PluginRouter({registry:registryFor('WRITE',async()=>{writes++;return{ok:true};}),policy,audit,killSwitch});const blocked=await router.dispatchCallback('x',{isOwner:true,approved:true});assert.equal(blocked.ok,false);assert.equal(blocked.killSwitchLocked,true);assert.equal(writes,0);});
10 +test('LOCKED kill switch blocks automation advance before routing any step',async()=>{let routed=0;const runner=new AutomationRunner({router:{dispatchCallback:async()=>{routed++;return{ok:true};}},store:{put:async state=>state},killSwitch:new KillSwitch({store:{get:async()=>({mode:'LOCKED'})}})});const state={status:'ready',cursor:0,ownerId:'123',steps:[{callback:'write:x',key:'k1'}]};const blocked=await runner.advance(state);assert.equal(blocked.status,'paused_kill_switch');assert.equal(routed,0);});
11 +test('only owner-approved control can change lock state and unlock is sensitive',async()=>{const calls=[];const store={get:async()=>({mode:'NORMAL'}),set:async next=>{calls.push(next);return next;}};const killSwitch=new KillSwitch({store});await assert.rejects(()=>killSwitch.lock({isOwner:false,approved:true}),/owner/i);await assert.rejects(()=>killSwitch.lock({isOwner:true,approved:false}),/approval/i);await killSwitch.lock({isOwner:true,approved:true});await assert.rejects(()=>killSwitch.unlock({isOwner:true,approved:false}),/approval/i);await killSwitch.unlock({isOwner:true,approved:true});assert.deepEqual(calls.map(x=>x.mode),['LOCKED','NORMAL']);});
wrangler.jsonc
+1 -1
@@ -1 +1 @@
1 -{"$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},"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"}]},"previews":{"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"}]}},"exports":{"ApprovalReplayGuard":{"type":"durable-object","storage":"sqlite"},"WorkspaceStore":{"type":"durable-object","storage":"sqlite"},"IncidentStore":{"type":"durable-object","storage":"sqlite"},"AutomationStore":{"type":"durable-object","storage":"sqlite"}}}
1 +{"$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},"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"},{"name":"KILL_SWITCH_STORE","class_name":"KillSwitchStore"}]},"previews":{"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"},{"name":"KILL_SWITCH_STORE","class_name":"KillSwitchStore"}]}},"exports":{"ApprovalReplayGuard":{"type":"durable-object","storage":"sqlite"},"WorkspaceStore":{"type":"durable-object","storage":"sqlite"},"IncidentStore":{"type":"durable-object","storage":"sqlite"},"AutomationStore":{"type":"durable-object","storage":"sqlite"},"KillSwitchStore":{"type":"durable-object","storage":"sqlite"}}}