Personal Telegram developer console for GitHub

test(hardening): require TOTP for destructive approvals

davoodmehraban89 committed Oct 5, 2026 at 09:49 UTC d33724386240258e1af8088de9c3cdea60e5b004
1 file changed +145
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 +});