Personal Telegram developer console for GitHub
feat(hardening): require TOTP for destructive approvals (#52)
davoodmehraban89 committed
Oct 5, 2026 at 13:15 UTC
5eb76b86733d53ac0c02a178dfabb06589f32efd
10 files changed
+521
-34
README.md
+2
@@ -100,6 +100,7 @@ Workspace، Draft، short navigation refs، pending input و Commit intent را
100
- `READ` فقط برای Owner مجاز بدون confirmation اجرا میشود.
101
- `WRITE` و `DESTRUCTIVE` در درخواست اولیه Provider mutation انجام نمیدهند.
102
- Approval معتبر به Owner، Action، Risk، Target و Expiry متصل است.
103
+- عملیات `DESTRUCTIVE` علاوه بر Safe Approval به TOTP مستقل نیز نیاز دارد؛ کد TOTP و Secret آن وارد Audit/Log نمیشوند.
104
- Replay Guard مصرف یکباره را حتی بین Worker isolateهای مختلف enforce میکند.
105
- لغو Approval هیچ mutationی انجام نمیدهد.
106
- Provider failure باید صریح نمایش داده شود؛ Success ساختگی ممنوع است.
@@ -118,6 +119,7 @@ Bindings/Secrets اصلی:
119
- `TELEGRAM_BOT_TOKEN` — Secret
120
- `TELEGRAM_WEBHOOK_SECRET` — Secret و fallback امن امضای Approval
121
- `APPROVAL_SIGNING_SECRET` — اختیاری؛ در صورت وجود برای امضا اولویت دارد
122
+- `DESTRUCTIVE_TOTP_SECRET` — Secret مستقل Base32 برای عامل دوم عملیات `DESTRUCTIVE`؛ بدون آن عملیات مخرب fail-closed میشود
123
- `OWNER_TELEGRAM_ID` — Owner مجاز
124
- `GITHUB_TOKEN` — Secret
125
- `GITHUB_OWNER` — اختیاری
docs/OPERATIONS_RUNBOOK.md
+6
-1
@@ -17,8 +17,13 @@ Rollback only to a known-good deployed version. Any Cloudflare operation changin
17
## Workspace safety
18
Workspace mutations remain Draft → Diff → Commit Message → Ready → Safe Approval → branch commit. The target is `nexa/edit-*`; direct `main` mutation, force update and silent conflict resolution are prohibited.
19
20
+## DESTRUCTIVE second factor
21
+Every DESTRUCTIVE action requires two independent checks: the existing owner-bound Safe Approval and a six-digit TOTP generated from the separately provisioned `DESTRUCTIVE_TOTP_SECRET`. If the TOTP secret, durable pending state, approval token or TOTP code is unavailable/invalid/expired, the operation fails closed and performs no provider mutation. Five invalid TOTP attempts cancel the pending second-factor challenge and require a fresh Approval. TOTP codes, the TOTP secret and signed Approval tokens must never be written to audit, incident or application logs.
22
+
23
+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.
24
+
25
## Security regression gate
21
-Before accepting a release, verify owner-only Telegram boundary, central action policy, HMAC approval verification, durable replay guard, owner-scoped Workspace state, explicit provider failures, bounded Telegram rendering, minimal public `/status`, and Production/Preview isolation.
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.
27
28
## Recovery
29
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/bot-legacy.js
+1
-1
@@ -137,7 +137,7 @@ export class NexaDevBot {
137
this.registry = new PluginRegistry([this.githubPlugin, this.cloudflarePlugin]);
138
this.policy = new ActionPolicy();
139
this.audit = new AuditLogger({
140
- secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET]
140
+ secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET, env.DESTRUCTIVE_TOTP_SECRET]
141
});
142
this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
143
}
src/bot.js
+168
-31
@@ -1,46 +1,96 @@
1
import { NexaDevBot as LegacyNexaDevBot } from './bot-legacy.js';
2
+import { TotpVerifier } from './core/totp.js';
3
+
4
+const escapeHtml = value => String(value ?? '')
5
+ .replaceAll('&', '&')
6
+ .replaceAll('<', '<')
7
+ .replaceAll('>', '>');
8
+
9
+function destructiveSourceCallback(payload = {}) {
10
+ if (payload.actionId === 'cloudflare.worker.deploy_version') {
11
+ const versionId = String(payload.input?.versionId || '');
12
+ if (!versionId) throw new Error('Destructive approval target is invalid');
13
+ return `cfdeploy:${versionId}`;
14
+ }
15
+ if (payload.actionId === 'github.pull_request.merge') {
16
+ const repoId = Number(payload.input?.repoId);
17
+ const prNumber = Number(payload.input?.prNumber);
18
+ const headSha = String(payload.input?.headSha || '');
19
+ if (!Number.isSafeInteger(repoId) || !Number.isSafeInteger(prNumber) || !/^[a-f0-9]{40}$/i.test(headSha)) {
20
+ throw new Error('Destructive approval target is invalid');
21
+ }
22
+ return `mergepr:${repoId.toString(36)}:${prNumber.toString(36)}:${headSha}`;
23
+ }
24
+ throw new Error('Destructive approval action is not supported');
25
+}
26
+
27
+function secondFactorFailureMarkup(payload = {}) {
28
+ if (payload.actionId === 'cloudflare.worker.deploy_version') {
29
+ return { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] };
30
+ }
31
+ return { inline_keyboard: [[{ text: '↩️ پروژهها', callback_data: 'menu:repos' }]] };
32
+}
33
34
export class NexaDevBot extends LegacyNexaDevBot {
35
+ constructor(env = {}) {
36
+ super(env);
37
+ this.destructiveTotp = new TotpVerifier({ secret: env.DESTRUCTIVE_TOTP_SECRET || '' });
38
+ }
39
+
40
async handleCallbackQuery(query) {
41
const data = query?.data || 'menu:main';
42
const ownerId = query?.from?.id;
43
const chatId = query?.message?.chat?.id;
44
const messageId = query?.message?.message_id;
45
+
46
if (data.startsWith('approve:') && ownerId !== undefined && ownerId !== null) {
47
const token = data.slice(8);
48
let preview = null;
49
try { preview = await this.approvals.verify(token, { ownerId: String(ownerId) }); } catch {}
13
- if (preview?.actionId === 'cloudflare.worker.deploy_version') {
14
- let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
15
- try {
16
- const payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'cloudflare', actionId: 'cloudflare.worker.deploy_version', risk: 'DESTRUCTIVE' });
17
- const source = `cfdeploy:${payload.input.versionId}`;
18
- const routed = await this.router.dispatchCallback(source, { isOwner: true, ownerId: String(ownerId), approved: true });
19
- if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved Cloudflare action could not be dispatched');
20
- const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
21
- return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
22
- } catch (error) {
23
- const text = `⚠️ <b>Cloudflare Deploy اجرا نشد</b>\nهیچ تغییر تأییدنشدهای انجام نشد.\n\n${String(error?.message || 'Approval rejected').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')}`;
24
- const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] });
25
- return { ok: false, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
50
+
51
+ if (preview?.risk === 'DESTRUCTIVE') {
52
+ let callbackAnswered = true;
53
+ try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
54
+
55
+ if (!this.destructiveTotp.isConfigured()) {
56
+ const error = 'Destructive second factor (TOTP) is not configured';
57
+ this.audit.log({ event: 'second_factor_unavailable', pluginId: preview.pluginId, actionId: preview.actionId, risk: 'DESTRUCTIVE', outcome: 'rejected' });
58
+ const res = await this.telegram.editMessageText(
59
+ chatId,
60
+ messageId,
61
+ `⚠️ <b>عملیات متوقف شد</b>\nعامل دوم TOTP برای عملیات DESTRUCTIVE پیکربندی نشده است.\nهیچ تغییری اجرا نشد.`,
62
+ secondFactorFailureMarkup(preview)
63
+ );
64
+ return { ok: false, secondFactorRequired: true, approvalRejected: true, error, callbackAnswered, edited: true, res };
65
}
27
- }
28
- if (preview?.actionId === 'github.pull_request.merge') {
29
- let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
66
+
67
try {
31
- const payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE' });
32
- const input = payload.input || {}; const source = `mergepr:${Number(input.repoId).toString(36)}:${Number(input.prNumber).toString(36)}:${input.headSha}`;
33
- const routed = await this.router.dispatchCallback(source, { isOwner: true, ownerId: String(ownerId), approved: true });
34
- if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved merge could not be dispatched');
35
- const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
36
- return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
68
+ await this.replayStore.setSecondFactorPending({
69
+ ownerId: String(ownerId),
70
+ token,
71
+ expiresAt: preview.expiresAt,
72
+ attempts: 0
73
+ });
74
+ this.audit.log({ event: 'second_factor_required', pluginId: preview.pluginId, actionId: preview.actionId, risk: 'DESTRUCTIVE', outcome: 'pending' });
75
+ const res = await this.telegram.editMessageText(
76
+ chatId,
77
+ messageId,
78
+ '🔐 <b>عامل دوم لازم است</b>\nApproval تلگرام معتبر است، اما عملیات هنوز اجرا نشده.\n\nکد ۶ رقمی برنامه Authenticator را به شکل زیر ارسال کنید:\n<code>/totp 123456</code>\n\nکد یا Secret در Audit ذخیره نمیشود.',
79
+ secondFactorFailureMarkup(preview)
80
+ );
81
+ return { ok: true, secondFactorRequired: true, actionId: preview.actionId, risk: preview.risk, callbackAnswered, edited: true, res };
82
} catch (error) {
38
- const text = `⚠️ <b>Merge اجرا نشد</b>\nهیچ Merge تأییدنشدهای انجام نشد.\n\n${String(error?.message || 'Approval rejected').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')}`;
39
- const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ بازگشت', callback_data: 'menu:repos' }]] });
40
- return { ok: false, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
83
+ const res = await this.telegram.editMessageText(
84
+ chatId,
85
+ messageId,
86
+ `⚠️ <b>عامل دوم آماده نشد</b>\nهیچ تغییر DESTRUCTIVE اجرا نشد.\n\n${escapeHtml(error?.message || 'Second factor unavailable')}`,
87
+ secondFactorFailureMarkup(preview)
88
+ );
89
+ return { ok: false, secondFactorRequired: true, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
90
}
91
}
92
}
93
+
94
if (data.startsWith('cfdeploy:')) {
95
let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
96
try {
@@ -49,16 +99,17 @@ export class NexaDevBot extends LegacyNexaDevBot {
99
if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
100
const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input });
101
const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit');
52
- const text = `⚠️ <b>تأیید نهایی Cloudflare لازم است</b>\nVersion: <code>${routed.approval.input.versionId}</code>\n\nTraffic این Worker روی نسخه انتخابشده قرار میگیرد.`;
53
- const markup = { inline_keyboard: [[{ text: '✅ تأیید Deploy / Rollback', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: 'cf:versions' }]] };
102
+ const text = `⚠️ <b>تأیید نهایی Cloudflare لازم است</b>\nVersion: <code>${routed.approval.input.versionId}</code>\n\nTraffic این Worker روی نسخه انتخابشده قرار میگیرد. پس از این تأیید، عامل دوم TOTP نیز لازم است.`;
103
+ const markup = { inline_keyboard: [[{ text: '✅ ادامه تأیید Deploy / Rollback', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: 'cf:versions' }]] };
104
const res = await this.telegram.editMessageText(chatId, messageId, text, markup);
105
return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
106
} catch (error) {
57
- const text = `⚠️ <b>Cloudflare Deploy آماده نشد</b>\n${String(error?.message || 'Unavailable').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')}`;
107
+ const text = `⚠️ <b>Cloudflare Deploy آماده نشد</b>\n${escapeHtml(error?.message || 'Unavailable')}`;
108
const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] });
109
return { ok: false, error: error?.message, callbackAnswered, edited: true, res };
110
}
111
}
112
+
113
if (data.startsWith('mergepr:')) {
114
let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
115
try {
@@ -67,16 +118,102 @@ export class NexaDevBot extends LegacyNexaDevBot {
118
if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
119
const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input });
120
const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit');
70
- const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0,12)}</code>\n\nMerge فقط برای همین Head و فقط یکبار قابل اجراست.`;
71
- const markup = { inline_keyboard: [[{ text: '✅ تأیید و Merge', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: routed.approval.cancelCallback }]] };
121
+ const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0,12)}</code>\n\nMerge فقط برای همین Head و فقط یکبار قابل اجراست. پس از این تأیید، عامل دوم TOTP نیز لازم است.`;
122
+ const markup = { inline_keyboard: [[{ text: '✅ ادامه تأیید Merge', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: routed.approval.cancelCallback }]] };
123
const res = await this.telegram.editMessageText(chatId, messageId, text, markup);
124
return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
125
} catch (error) {
75
- const text = `⚠️ <b>Merge آماده نشد</b>\n${String(error?.message || 'Merge unavailable').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')}`;
126
+ const text = `⚠️ <b>Merge آماده نشد</b>\n${escapeHtml(error?.message || 'Merge unavailable')}`;
127
const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ پروژهها', callback_data: 'menu:repos' }]] });
128
return { ok: false, error: error?.message, callbackAnswered, edited: true, res };
129
}
130
}
131
+
132
return super.handleCallbackQuery(query);
133
}
134
+
135
+ async handleMessage(message) {
136
+ const rawText = typeof message?.text === 'string' ? message.text.trim() : '';
137
+ if (!rawText.startsWith('/totp')) return super.handleMessage(message);
138
+
139
+ const chatId = message?.chat?.id;
140
+ const ownerId = message?.from?.id;
141
+ if (!chatId || ownerId === undefined || ownerId === null) {
142
+ return { ok: false, secondFactorRejected: true, error: 'Second-factor owner context is missing' };
143
+ }
144
+
145
+ if (!this.destructiveTotp.isConfigured()) {
146
+ const error = 'Destructive second factor (TOTP) is not configured';
147
+ const res = await this.telegram.sendMessage(chatId, '⚠️ <b>عامل دوم پیکربندی نشده است</b>\nهیچ عملیات DESTRUCTIVE اجرا نشد.');
148
+ return { ok: false, secondFactorRejected: true, error, res };
149
+ }
150
+
151
+ const match = rawText.match(/^\/totp\s+(\d{6})$/);
152
+ if (!match) {
153
+ const res = await this.telegram.sendMessage(chatId, '⚠️ فرمت کد درست نیست. فقط به شکل <code>/totp 123456</code> ارسال کنید.');
154
+ return { ok: false, secondFactorRejected: true, error: 'Invalid TOTP format', res };
155
+ }
156
+
157
+ let pending;
158
+ try {
159
+ pending = await this.replayStore.getSecondFactorPending({ ownerId: String(ownerId) });
160
+ } catch (error) {
161
+ const res = await this.telegram.sendMessage(chatId, '⚠️ وضعیت عامل دوم در دسترس نیست؛ عملیات متوقف شد.');
162
+ return { ok: false, secondFactorRejected: true, error: error?.message || 'Second-factor state unavailable', res };
163
+ }
164
+
165
+ if (!pending) {
166
+ const res = await this.telegram.sendMessage(chatId, '⚠️ درخواست DESTRUCTIVE منتظر عامل دوم پیدا نشد. از ابتدا یک Approval تازه ایجاد کنید.');
167
+ return { ok: false, secondFactorRejected: true, error: 'Second-factor challenge is unavailable', res };
168
+ }
169
+
170
+ const validCode = await this.destructiveTotp.verify(match[1]);
171
+ if (!validCode) {
172
+ const attempts = Number(pending.attempts || 0) + 1;
173
+ if (attempts >= 5) {
174
+ await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) });
175
+ } else {
176
+ await this.replayStore.setSecondFactorPending({ ownerId: String(ownerId), token: pending.token, expiresAt: pending.expiresAt, attempts });
177
+ }
178
+ this.audit.log({ event: 'second_factor_rejected', risk: 'DESTRUCTIVE', outcome: 'rejected', reason: attempts >= 5 ? 'attempt_limit' : 'invalid_code' });
179
+ const res = await this.telegram.sendMessage(
180
+ chatId,
181
+ attempts >= 5
182
+ ? '⚠️ <b>عامل دوم رد شد</b>\nتعداد تلاش مجاز تمام شد. برای ادامه Approval تازه بسازید.'
183
+ : '⚠️ <b>کد TOTP معتبر نیست</b>\nهیچ تغییری اجرا نشد.'
184
+ );
185
+ return { ok: false, secondFactorRejected: true, error: 'Invalid TOTP code', res };
186
+ }
187
+
188
+ let payload;
189
+ try {
190
+ const preview = await this.approvals.verify(pending.token, { ownerId: String(ownerId), risk: 'DESTRUCTIVE' });
191
+ payload = await this.approvals.consume(pending.token, {
192
+ ownerId: String(ownerId),
193
+ pluginId: preview.pluginId,
194
+ actionId: preview.actionId,
195
+ risk: 'DESTRUCTIVE'
196
+ });
197
+ await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) });
198
+ this.audit.log({ event: 'second_factor_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: 'DESTRUCTIVE', outcome: 'verified' });
199
+
200
+ const routed = await this.router.dispatchCallback(destructiveSourceCallback(payload), {
201
+ isOwner: true,
202
+ ownerId: String(ownerId),
203
+ approved: true
204
+ });
205
+ if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved destructive action could not be dispatched');
206
+
207
+ const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
208
+ return { ok: true, approved: true, secondFactorVerified: true, actionId: payload.actionId, res };
209
+ } catch (error) {
210
+ try { await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) }); } catch {}
211
+ const res = await this.telegram.sendMessage(
212
+ chatId,
213
+ `⚠️ <b>عملیات DESTRUCTIVE اجرا نشد</b>\nهیچ Success ساختگی ثبت نمیشود.\n\n${escapeHtml(error?.message || 'Approval rejected')}`,
214
+ secondFactorFailureMarkup(payload || {})
215
+ );
216
+ return { ok: false, secondFactorRejected: true, error: error?.message || 'Destructive approval rejected', res };
217
+ }
218
+ }
219
}
src/core/durable-replay-store.js
+31
@@ -7,6 +7,9 @@ export class DurableApprovalReplayStore {
7
if (!owner || !nonceValue) throw new Error('Invalid durable approval replay input');
8
return this.namespace.get(this.namespace.idFromName(`${owner}:${nonceValue}`));
9
}
10
+ #secondFactorStub(ownerId) {
11
+ return this.#stub(ownerId, 'second-factor');
12
+ }
13
async put({ ownerId, nonce, expiresAt, payload } = {}) {
14
const expiry = Number(expiresAt); if (!Number.isFinite(expiry) || !payload) throw new Error('Invalid durable approval replay input');
15
const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/prepare', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ expiresAt: expiry, payload }) }));
@@ -26,4 +29,32 @@ export class DurableApprovalReplayStore {
29
if (!response.ok || body?.accepted !== true) throw new Error(`Durable approval replay protection failed (${response.status})`);
30
return true;
31
}
32
+ async setSecondFactorPending({ ownerId, token, expiresAt, attempts = 0 } = {}) {
33
+ const expiry = Number(expiresAt);
34
+ const attemptCount = Number(attempts);
35
+ if (!String(ownerId ?? '') || !String(token || '') || !Number.isFinite(expiry) || expiry < Date.now() || !Number.isSafeInteger(attemptCount) || attemptCount < 0) {
36
+ throw new Error('Invalid second-factor pending state');
37
+ }
38
+ const response = await this.#secondFactorStub(ownerId).fetch(new Request('https://approval-replay/second-factor/put', {
39
+ method: 'POST',
40
+ headers: { 'content-type': 'application/json' },
41
+ body: JSON.stringify({ token: String(token), expiresAt: expiry, attempts: attemptCount })
42
+ }));
43
+ if (!response.ok) throw new Error(`Durable second-factor state failed (${response.status})`);
44
+ return true;
45
+ }
46
+ async getSecondFactorPending({ ownerId } = {}) {
47
+ if (!String(ownerId ?? '')) throw new Error('Invalid second-factor owner');
48
+ const response = await this.#secondFactorStub(ownerId).fetch(new Request('https://approval-replay/second-factor/get'));
49
+ if (response.status === 404 || response.status === 410) return null;
50
+ if (!response.ok) throw new Error(`Durable second-factor state failed (${response.status})`);
51
+ const body = await response.json().catch(() => null);
52
+ return body?.pending || null;
53
+ }
54
+ async clearSecondFactorPending({ ownerId } = {}) {
55
+ if (!String(ownerId ?? '')) throw new Error('Invalid second-factor owner');
56
+ const response = await this.#secondFactorStub(ownerId).fetch(new Request('https://approval-replay/second-factor/clear', { method: 'POST' }));
57
+ if (!response.ok) throw new Error(`Durable second-factor clear failed (${response.status})`);
58
+ return true;
59
+ }
60
}
src/core/totp.js
new
+86
@@ -0,0 +1,86 @@
1
+const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
2
+
3
+function decodeBase32(secret) {
4
+ const normalized = String(secret || '').replace(/\s+/g, '').replace(/=+$/g, '').toUpperCase();
5
+ if (!normalized) throw new Error('TOTP secret is not configured');
6
+ let bits = '';
7
+ for (const char of normalized) {
8
+ const index = BASE32_ALPHABET.indexOf(char);
9
+ if (index < 0) throw new Error('TOTP secret is invalid');
10
+ bits += index.toString(2).padStart(5, '0');
11
+ }
12
+ const bytes = [];
13
+ for (let offset = 0; offset + 8 <= bits.length; offset += 8) {
14
+ bytes.push(Number.parseInt(bits.slice(offset, offset + 8), 2));
15
+ }
16
+ if (!bytes.length) throw new Error('TOTP secret is invalid');
17
+ return new Uint8Array(bytes);
18
+}
19
+
20
+function counterBytes(counter) {
21
+ const buffer = new ArrayBuffer(8);
22
+ const view = new DataView(buffer);
23
+ view.setUint32(0, Math.floor(counter / 2 ** 32));
24
+ view.setUint32(4, counter >>> 0);
25
+ return buffer;
26
+}
27
+
28
+function constantTimeCodeEqual(left, right) {
29
+ const a = String(left || '');
30
+ const b = String(right || '');
31
+ if (a.length !== b.length) return false;
32
+ let mismatch = 0;
33
+ for (let index = 0; index < a.length; index += 1) mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
34
+ return mismatch === 0;
35
+}
36
+
37
+export class TotpVerifier {
38
+ constructor({ secret = '', now = () => Date.now(), periodMs = 30_000, digits = 6, window = 1 } = {}) {
39
+ this.secret = String(secret || '');
40
+ this.now = now;
41
+ this.periodMs = periodMs;
42
+ this.digits = digits;
43
+ this.window = window;
44
+ this.keyPromise = null;
45
+ }
46
+
47
+ isConfigured() {
48
+ return Boolean(this.secret.trim());
49
+ }
50
+
51
+ async verify(code) {
52
+ if (!this.isConfigured()) throw new Error('Destructive second factor is not configured');
53
+ const supplied = String(code || '').trim();
54
+ if (!new RegExp(`^\\d{${this.digits}}$`).test(supplied)) return false;
55
+ const currentCounter = Math.floor(this.now() / this.periodMs);
56
+ for (let delta = -this.window; delta <= this.window; delta += 1) {
57
+ if (constantTimeCodeEqual(supplied, await this.#generate(currentCounter + delta))) return true;
58
+ }
59
+ return false;
60
+ }
61
+
62
+ async #generate(counter) {
63
+ if (!Number.isSafeInteger(counter) || counter < 0) return '';
64
+ const key = await this.#key();
65
+ const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, counterBytes(counter)));
66
+ const offset = digest[digest.length - 1] & 0x0f;
67
+ const binary = ((digest[offset] & 0x7f) << 24)
68
+ | (digest[offset + 1] << 16)
69
+ | (digest[offset + 2] << 8)
70
+ | digest[offset + 3];
71
+ return String(binary % (10 ** this.digits)).padStart(this.digits, '0');
72
+ }
73
+
74
+ async #key() {
75
+ if (!this.keyPromise) {
76
+ this.keyPromise = crypto.subtle.importKey(
77
+ 'raw',
78
+ decodeBase32(this.secret),
79
+ { name: 'HMAC', hash: 'SHA-1' },
80
+ false,
81
+ ['sign']
82
+ );
83
+ }
84
+ return this.keyPromise;
85
+ }
86
+}
src/durable/approval-replay-guard.js
+31
@@ -4,6 +4,37 @@ export class ApprovalReplayGuard {
4
constructor(state) { this.state = state; }
5
async fetch(request) {
6
const url = new URL(request.url);
7
+
8
+ if (request.method === 'POST' && url.pathname === '/second-factor/put') {
9
+ const payload = await request.json().catch(() => null);
10
+ const token = String(payload?.token || '');
11
+ const expiresAt = Number(payload?.expiresAt);
12
+ const attempts = Number(payload?.attempts || 0);
13
+ if (!token || !Number.isFinite(expiresAt) || expiresAt < Date.now() || !Number.isSafeInteger(attempts) || attempts < 0) {
14
+ return json({ stored: false }, 400);
15
+ }
16
+ await this.state.storage.transaction(async txn => {
17
+ await txn.put('secondFactorPending', { token, expiresAt, attempts });
18
+ });
19
+ await this.state.storage.setAlarm(expiresAt);
20
+ return json({ stored: true });
21
+ }
22
+
23
+ if (request.method === 'GET' && url.pathname === '/second-factor/get') {
24
+ const pending = await this.state.storage.transaction(async txn => txn.get('secondFactorPending'));
25
+ if (!pending) return json({ pending: null }, 404);
26
+ if (!Number.isFinite(Number(pending.expiresAt)) || Number(pending.expiresAt) < Date.now()) {
27
+ await this.state.storage.transaction(async txn => txn.delete('secondFactorPending'));
28
+ return json({ pending: null }, 410);
29
+ }
30
+ return json({ pending });
31
+ }
32
+
33
+ if (request.method === 'POST' && url.pathname === '/second-factor/clear') {
34
+ await this.state.storage.transaction(async txn => txn.delete('secondFactorPending'));
35
+ return json({ cleared: true });
36
+ }
37
+
38
if (request.method === 'POST' && url.pathname === '/prepare') {
39
const payload = await request.json().catch(() => null); const expiresAt = Number(payload?.expiresAt);
40
if (!Number.isFinite(expiresAt) || expiresAt < Date.now() || !payload?.payload) return json({ prepared: false }, 400);
src/index.js
+1
-1
@@ -5,4 +5,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]){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
+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});}};
test/destructive-second-factor.test.js
new
+145
@@ -0,0 +1,145 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { NexaDevBot } from '../src/bot.js';
4
+
5
+const TOTP_SECRET = 'JBSWY3DPEHPK3PXP';
6
+
7
+function decodeBase32(value) {
8
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
9
+ let bits = '';
10
+ for (const ch of value.replace(/=+$/g, '').toUpperCase()) {
11
+ const index = alphabet.indexOf(ch);
12
+ if (index < 0) throw new Error('invalid base32');
13
+ bits += index.toString(2).padStart(5, '0');
14
+ }
15
+ const out = [];
16
+ for (let i = 0; i + 8 <= bits.length; i += 8) out.push(Number.parseInt(bits.slice(i, i + 8), 2));
17
+ return new Uint8Array(out);
18
+}
19
+
20
+async function currentTotp(secret, now = Date.now()) {
21
+ const counter = Math.floor(now / 30_000);
22
+ const buffer = new ArrayBuffer(8);
23
+ const view = new DataView(buffer);
24
+ view.setUint32(0, Math.floor(counter / 2 ** 32));
25
+ view.setUint32(4, counter >>> 0);
26
+ const key = await crypto.subtle.importKey('raw', decodeBase32(secret), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']);
27
+ const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, buffer));
28
+ const offset = digest[digest.length - 1] & 0x0f;
29
+ const binary = ((digest[offset] & 0x7f) << 24) | (digest[offset + 1] << 16) | (digest[offset + 2] << 8) | digest[offset + 3];
30
+ return String(binary % 1_000_000).padStart(6, '0');
31
+}
32
+
33
+function makeBot(secret = TOTP_SECRET) {
34
+ const bot = new NexaDevBot({ DESTRUCTIVE_TOTP_SECRET: secret });
35
+ const payload = {
36
+ v: 1,
37
+ pluginId: 'github',
38
+ actionId: 'github.pull_request.merge',
39
+ risk: 'DESTRUCTIVE',
40
+ ownerId: '123',
41
+ input: { repoId: 7, prNumber: 39, headSha: 'a'.repeat(40) },
42
+ issuedAt: Date.now(),
43
+ expiresAt: Date.now() + 120_000,
44
+ nonce: 'nonce123'
45
+ };
46
+ const pending = new Map();
47
+ let consumeCount = 0;
48
+ let executeCount = 0;
49
+
50
+ bot.approvals.verify = async () => payload;
51
+ bot.approvals.consume = async () => { consumeCount += 1; return payload; };
52
+ bot.replayStore.setSecondFactorPending = async ({ ownerId, token, expiresAt }) => {
53
+ pending.set(String(ownerId), { token, expiresAt });
54
+ return true;
55
+ };
56
+ bot.replayStore.getSecondFactorPending = async ({ ownerId }) => pending.get(String(ownerId)) || null;
57
+ bot.replayStore.clearSecondFactorPending = async ({ ownerId }) => { pending.delete(String(ownerId)); return true; };
58
+ bot.router.dispatchCallback = async (_data, context) => {
59
+ if (context?.approved) executeCount += 1;
60
+ return { text: 'executed', reply_markup: { inline_keyboard: [] } };
61
+ };
62
+ bot.telegram.answerCallbackQuery = async () => ({ ok: true });
63
+ bot.telegram.editMessageText = async (_chatId, _messageId, text, replyMarkup) => ({ ok: true, result: { text, reply_markup: replyMarkup } });
64
+ bot.telegram.sendMessage = async (_chatId, text, replyMarkup) => ({ ok: true, result: { text, reply_markup: replyMarkup } });
65
+
66
+ return { bot, get consumeCount() { return consumeCount; }, get executeCount() { return executeCount; } };
67
+}
68
+
69
+test('DESTRUCTIVE approval fails closed when second-factor secret is not configured', async () => {
70
+ const harness = makeBot('');
71
+ const result = await harness.bot.handleUpdate({
72
+ callback_query: {
73
+ id: 'approve-missing-factor',
74
+ from: { id: 123 },
75
+ data: 'approve:signed-token',
76
+ message: { message_id: 900, chat: { id: 123 } }
77
+ }
78
+ });
79
+
80
+ assert.equal(result.ok, false);
81
+ assert.equal(harness.consumeCount, 0, 'approval must not be consumed without second factor');
82
+ assert.equal(harness.executeCount, 0, 'DESTRUCTIVE provider action must not execute without second factor');
83
+ assert.match(String(result.error || ''), /second factor|totp|configured/i);
84
+});
85
+
86
+test('DESTRUCTIVE approval requires valid TOTP before consuming approval or executing provider mutation', async () => {
87
+ const harness = makeBot();
88
+
89
+ const first = await harness.bot.handleUpdate({
90
+ callback_query: {
91
+ id: 'approve-first-factor',
92
+ from: { id: 123 },
93
+ data: 'approve:signed-token',
94
+ message: { message_id: 901, chat: { id: 123 } }
95
+ }
96
+ });
97
+
98
+ assert.equal(first.ok, true);
99
+ assert.equal(first.secondFactorRequired, true);
100
+ assert.equal(harness.consumeCount, 0);
101
+ assert.equal(harness.executeCount, 0);
102
+
103
+ const wrong = await harness.bot.handleUpdate({
104
+ message: { message_id: 902, chat: { id: 123 }, from: { id: 123 }, text: '/totp 000000' }
105
+ });
106
+ assert.equal(wrong.ok, false);
107
+ assert.equal(wrong.secondFactorRejected, true);
108
+ assert.equal(harness.consumeCount, 0);
109
+ assert.equal(harness.executeCount, 0);
110
+
111
+ const code = await currentTotp(TOTP_SECRET);
112
+ const accepted = await harness.bot.handleUpdate({
113
+ message: { message_id: 903, chat: { id: 123 }, from: { id: 123 }, text: `/totp ${code}` }
114
+ });
115
+ assert.equal(accepted.ok, true);
116
+ assert.equal(accepted.secondFactorVerified, true);
117
+ assert.equal(harness.consumeCount, 1);
118
+ assert.equal(harness.executeCount, 1);
119
+});
120
+
121
+test('TOTP code and signed approval token are never written to audit output', async () => {
122
+ const harness = makeBot();
123
+ const originalLog = console.log;
124
+ const logs = [];
125
+ console.log = (...args) => logs.push(args.map(String).join(' '));
126
+ try {
127
+ await harness.bot.handleUpdate({
128
+ callback_query: {
129
+ id: 'approve-audit-factor',
130
+ from: { id: 123 },
131
+ data: 'approve:signed-token',
132
+ message: { message_id: 904, chat: { id: 123 } }
133
+ }
134
+ });
135
+ const code = await currentTotp(TOTP_SECRET);
136
+ await harness.bot.handleUpdate({
137
+ message: { message_id: 905, chat: { id: 123 }, from: { id: 123 }, text: `/totp ${code}` }
138
+ });
139
+ const output = logs.join('\n');
140
+ assert.doesNotMatch(output, new RegExp(code));
141
+ assert.doesNotMatch(output, /signed-token/);
142
+ } finally {
143
+ console.log = originalLog;
144
+ }
145
+});
test/durable-replay.test.js
+50
@@ -128,3 +128,53 @@ test('Worker exports ApprovalReplayGuard and Wrangler declares SQLite durable bi
128
storage: 'sqlite'
129
});
130
});
131
+
132
+
133
+test('DurableApprovalReplayStore persists owner-scoped second-factor pending state without exposing it in logs', async () => {
134
+ let stored = null;
135
+ const namespace = makeNamespace(async (_id, request) => {
136
+ const url = new URL(request.url);
137
+ if (request.method === 'POST' && url.pathname === '/second-factor/put') {
138
+ stored = await request.json();
139
+ return Response.json({ stored: true });
140
+ }
141
+ if (request.method === 'GET' && url.pathname === '/second-factor/get') {
142
+ return stored ? Response.json({ pending: stored }) : Response.json({ pending: null }, { status: 404 });
143
+ }
144
+ if (request.method === 'POST' && url.pathname === '/second-factor/clear') {
145
+ stored = null;
146
+ return Response.json({ cleared: true });
147
+ }
148
+ return new Response('Not Found', { status: 404 });
149
+ });
150
+ const store = new DurableApprovalReplayStore({ namespace });
151
+ const expiresAt = Date.now() + 60_000;
152
+
153
+ await store.setSecondFactorPending({ ownerId: '123', token: 'signed-token', expiresAt });
154
+ assert.deepEqual(await store.getSecondFactorPending({ ownerId: '123' }), { token: 'signed-token', expiresAt, attempts: 0 });
155
+ await store.clearSecondFactorPending({ ownerId: '123' });
156
+ assert.equal(await store.getSecondFactorPending({ ownerId: '123' }), null);
157
+ assert.ok(namespace.ids.every(id => id === '123:second-factor'));
158
+});
159
+
160
+test('ApprovalReplayGuard expires and clears second-factor pending state fail-closed', async () => {
161
+ const state = makeState();
162
+ const guard = new ApprovalReplayGuard(state);
163
+ const expiresAt = Date.now() + 60_000;
164
+
165
+ const put = await guard.fetch(new Request('https://approval-replay/second-factor/put', {
166
+ method: 'POST',
167
+ headers: { 'content-type': 'application/json' },
168
+ body: JSON.stringify({ token: 'signed-token', expiresAt })
169
+ }));
170
+ assert.equal(put.status, 200);
171
+
172
+ const get = await guard.fetch(new Request('https://approval-replay/second-factor/get'));
173
+ assert.equal(get.status, 200);
174
+ assert.deepEqual(await get.json(), { pending: { token: 'signed-token', expiresAt, attempts: 0 } });
175
+
176
+ const clear = await guard.fetch(new Request('https://approval-replay/second-factor/clear', { method: 'POST' }));
177
+ assert.equal(clear.status, 200);
178
+ const after = await guard.fetch(new Request('https://approval-replay/second-factor/get'));
179
+ assert.equal(after.status, 404);
180
+});