Personal Telegram developer console for GitHub
security: consume TOTP steps durably across destructive approvals
Codex committed
Oct 25, 2026 at 17:24 UTC
a4329e510a3d1ea4ef5bf7a75737fd9b9a5b56f9
4 files changed
+263
-12
src/bot.js
+9
-2
@@ -380,8 +380,8 @@ export class NexaDevBot extends LegacyNexaDevBot {
380
};
381
}
382
383
- const validCode = await this.destructiveTotp.verify(match[1]);
384
- if (!validCode) {
383
+ const verifiedStep = await this.destructiveTotp.verifyStep(match[1]);
384
+ if (!verifiedStep) {
385
const attempts = Number(pending.attempts || 0) + 1;
386
if (attempts >= 5) {
387
await this.replayStore.clearSecondFactorPending({
@@ -421,6 +421,13 @@ export class NexaDevBot extends LegacyNexaDevBot {
421
ownerId: String(ownerId),
422
risk: 'DESTRUCTIVE'
423
});
424
+ // Claim the owner/step independently of the action Approval. Store no OTP.
425
+ const claimedStep = await this.replayStore.consume({
426
+ ownerId: String(ownerId),
427
+ nonce: `second-factor-step:${verifiedStep.counter}`,
428
+ expiresAt: verifiedStep.expiresAt
429
+ });
430
+ if (!claimedStep) throw new Error('TOTP step already used');
431
payload = await this.approvals.consume(pending.token, {
432
ownerId: String(ownerId),
433
pluginId: preview.pluginId,
src/core/totp.js
+12
-9
@@ -59,21 +59,24 @@ export class TotpVerifier {
59
}
60
61
async verify(code) {
62
+ return (await this.verifyStep(code)) !== null;
63
+ }
64
+
65
+ async verifyStep(code) {
66
if (!this.isConfigured())
67
throw new Error('Destructive second factor is not configured');
68
const supplied = String(code || '').trim();
65
- if (!new RegExp(`^\\d{${this.digits}}$`).test(supplied)) return false;
69
+ if (!new RegExp(`^\\d{${this.digits}}$`).test(supplied)) return null;
70
const currentCounter = Math.floor(this.now() / this.periodMs);
71
for (let delta = -this.window; delta <= this.window; delta += 1) {
68
- if (
69
- constantTimeCodeEqual(
70
- supplied,
71
- await this.#generate(currentCounter + delta)
72
- )
73
- )
74
- return true;
72
+ const counter = currentCounter + delta;
73
+ if (constantTimeCodeEqual(supplied, await this.#generate(counter)))
74
+ return {
75
+ counter,
76
+ expiresAt: (counter + this.window + 1) * this.periodMs
77
+ };
78
}
76
- return false;
79
+ return null;
80
}
81
82
async #generate(counter) {
test/destructive-second-factor.test.js
+5
-1
@@ -1,6 +1,7 @@
1
import test from 'node:test';
2
import assert from 'node:assert/strict';
3
import { NexaDevBot } from '../src/bot.js';
4
+import { makeReplayNamespace } from './helpers/replay-namespace.js';
5
6
const TOTP_SECRET = 'JBSWY3DPEHPK3PXP';
7
@@ -42,7 +43,10 @@ async function currentTotp(secret, now = Date.now()) {
43
}
44
45
function makeBot(secret = TOTP_SECRET) {
45
- const bot = new NexaDevBot({ DESTRUCTIVE_TOTP_SECRET: secret });
46
+ const bot = new NexaDevBot({
47
+ DESTRUCTIVE_TOTP_SECRET: secret,
48
+ APPROVAL_REPLAY_GUARD: makeReplayNamespace()
49
+ });
50
const payload = {
51
v: 1,
52
pluginId: 'github',
test/totp-replay.test.js
new
+237
@@ -0,0 +1,237 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { NexaDevBot } from '../src/bot.js';
4
+import { TotpVerifier } from '../src/core/totp.js';
5
+import { makeReplayNamespace } from './helpers/replay-namespace.js';
6
+
7
+// RFC 4226 secret and counters: 1 => 287082, 3 => 969429.
8
+const SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
9
+const CODE = '287082';
10
+
11
+function makeHarness(namespace = makeReplayNamespace(), effects = []) {
12
+ const bot = new NexaDevBot({
13
+ APPROVAL_REPLAY_GUARD: namespace,
14
+ APPROVAL_SIGNING_SECRET: 'signed-approval-test-secret',
15
+ DESTRUCTIVE_TOTP_SECRET: SECRET
16
+ });
17
+ const audit = [];
18
+ bot.audit.sink = (event) => audit.push(event);
19
+ bot.router.dispatchCallback = async (data, context) => {
20
+ if (context.approved) effects.push(data);
21
+ return { text: 'executed', reply_markup: { inline_keyboard: [] } };
22
+ };
23
+ bot.telegram.answerCallbackQuery = async () => ({ ok: true });
24
+ bot.telegram.editMessageText = async () => ({ ok: true });
25
+ bot.telegram.sendMessage = async () => ({ ok: true });
26
+ return { bot, namespace, effects, audit };
27
+}
28
+
29
+async function challenge(harness, prNumber = 1, ownerId = 123) {
30
+ const token = await harness.bot.approvals.issue({
31
+ pluginId: 'github',
32
+ actionId: 'github.pull_request.merge',
33
+ risk: 'DESTRUCTIVE',
34
+ ownerId: String(ownerId),
35
+ input: { repoId: 7, prNumber, headSha: 'a'.repeat(40) }
36
+ });
37
+ const result = await harness.bot.handleUpdate({
38
+ callback_query: {
39
+ id: `approve-${prNumber}-${ownerId}`,
40
+ from: { id: ownerId },
41
+ data: `approve:${token}`,
42
+ message: { message_id: prNumber, chat: { id: ownerId } }
43
+ }
44
+ });
45
+ assert.equal(result.secondFactorRequired, true);
46
+ assert.equal(result.ok, true);
47
+ return token;
48
+}
49
+
50
+function submit(harness, code = CODE, ownerId = 123) {
51
+ return harness.bot.handleUpdate({
52
+ message: {
53
+ message_id: 100,
54
+ chat: { id: ownerId },
55
+ from: { id: ownerId },
56
+ text: `/totp ${code}`
57
+ }
58
+ });
59
+}
60
+
61
+test('a used TOTP cannot authorize a second distinct signed destructive approval', async (t) => {
62
+ t.mock.method(Date, 'now', () => 59_000);
63
+ const harness = makeHarness();
64
+ await challenge(harness, 1);
65
+ assert.equal((await submit(harness)).secondFactorVerified, true);
66
+ const secondToken = await challenge(harness, 2);
67
+
68
+ const replay = await submit(harness);
69
+
70
+ assert.equal(replay.ok, false);
71
+ assert.equal(replay.secondFactorRejected, true);
72
+ assert.match(replay.error, /already used|replay/i);
73
+ assert.equal(harness.effects.length, 1);
74
+ // Reusing the factor must not also consume the unused action approval.
75
+ assert.equal(
76
+ (await harness.bot.approvals.verify(secondToken, { ownerId: '123' })).input
77
+ .prNumber,
78
+ 2
79
+ );
80
+});
81
+
82
+test('concurrent distinct signed approvals have only one TOTP claim winner', async (t) => {
83
+ t.mock.method(Date, 'now', () => 59_000);
84
+ const namespace = makeReplayNamespace();
85
+ const effects = [];
86
+ const first = makeHarness(namespace, effects);
87
+ const second = makeHarness(namespace, effects);
88
+ let releaseFirst;
89
+ let readFirst;
90
+ const firstRead = new Promise((resolve) => {
91
+ readFirst = resolve;
92
+ });
93
+ const firstGate = new Promise((resolve) => {
94
+ releaseFirst = resolve;
95
+ });
96
+ const getPending = first.bot.replayStore.getSecondFactorPending.bind(
97
+ first.bot.replayStore
98
+ );
99
+ first.bot.replayStore.getSecondFactorPending = async (input) => {
100
+ const pending = await getPending(input);
101
+ readFirst();
102
+ await firstGate;
103
+ return pending;
104
+ };
105
+ await challenge(first, 1);
106
+ const firstSubmission = submit(first);
107
+ await firstRead;
108
+ await challenge(second, 2);
109
+ const secondSubmission = submit(second);
110
+ releaseFirst();
111
+
112
+ const results = await Promise.all([firstSubmission, secondSubmission]);
113
+
114
+ assert.equal(results.filter((result) => result.ok).length, 1);
115
+ assert.equal(
116
+ results.filter((result) => result.secondFactorRejected).length,
117
+ 1
118
+ );
119
+ assert.equal(effects.length, 1);
120
+});
121
+
122
+test('TOTP consumption survives bot and replay guard recreation', async (t) => {
123
+ t.mock.method(Date, 'now', () => 59_000);
124
+ const namespace = makeReplayNamespace();
125
+ const effects = [];
126
+ const first = makeHarness(namespace, effects);
127
+ await challenge(first, 1);
128
+ assert.equal((await submit(first)).ok, true);
129
+ const recreated = makeHarness(namespace, effects);
130
+ await challenge(recreated, 2);
131
+
132
+ assert.equal((await submit(recreated)).secondFactorRejected, true);
133
+ assert.equal(effects.length, 1);
134
+});
135
+
136
+test('TOTP claim persists until the final acceptance boundary and stores no raw code', async (t) => {
137
+ let now = 59_000;
138
+ t.mock.method(Date, 'now', () => now);
139
+ const harness = makeHarness();
140
+ await challenge(harness, 1);
141
+ assert.equal((await submit(harness)).ok, true);
142
+ const stepClaims = [...harness.namespace.states.values()].filter(
143
+ (state) => state.data.get('used') === 90_000
144
+ );
145
+ assert.equal(stepClaims.length, 1);
146
+ assert.equal(stepClaims[0].alarm, 90_000);
147
+
148
+ now = 89_999;
149
+ await challenge(harness, 2);
150
+ assert.equal((await submit(harness)).secondFactorRejected, true);
151
+ now = 90_000;
152
+ await challenge(harness, 3);
153
+ const expired = await submit(harness);
154
+ assert.equal(expired.secondFactorRejected, true);
155
+ assert.match(expired.error, /invalid totp/i);
156
+ assert.equal((await submit(harness, '969429')).ok, true);
157
+ assert.equal(harness.effects.length, 2);
158
+
159
+ const persisted = JSON.stringify(
160
+ [...harness.namespace.states].map(([id, state]) => [id, [...state.data]])
161
+ );
162
+ assert.equal(persisted.includes(CODE), false);
163
+ assert.equal(persisted.includes(SECRET), false);
164
+ assert.equal(JSON.stringify(harness.audit).includes(CODE), false);
165
+});
166
+
167
+test('TOTP claim storage outage rejects before consuming the approval or executing', async (t) => {
168
+ t.mock.method(Date, 'now', () => 59_000);
169
+ const namespace = makeReplayNamespace();
170
+ const harness = makeHarness(namespace);
171
+ const token = await challenge(harness, 1);
172
+ const get = namespace.get.bind(namespace);
173
+ namespace.get = (id) => {
174
+ const stub = get(id);
175
+ return {
176
+ async fetch(request) {
177
+ if (String(id).includes(':second-factor-step:')) {
178
+ return Response.json({ accepted: false }, { status: 503 });
179
+ }
180
+ return stub.fetch(request);
181
+ }
182
+ };
183
+ };
184
+
185
+ const result = await submit(harness);
186
+
187
+ assert.equal(result.ok, false);
188
+ assert.equal(result.secondFactorRejected, true);
189
+ assert.equal(harness.effects.length, 0);
190
+ assert.equal(
191
+ (await harness.bot.approvals.verify(token, { ownerId: '123' })).input
192
+ .prNumber,
193
+ 1
194
+ );
195
+});
196
+
197
+test('invalid pending Approval cannot burn an otherwise unused TOTP step', async (t) => {
198
+ t.mock.method(Date, 'now', () => 59_000);
199
+ const harness = makeHarness();
200
+ await harness.bot.replayStore.setSecondFactorPending({
201
+ ownerId: '123',
202
+ token: 'invalid-approval-signature',
203
+ expiresAt: 179_000
204
+ });
205
+ assert.equal((await submit(harness)).secondFactorRejected, true);
206
+ await challenge(harness, 1);
207
+
208
+ assert.equal((await submit(harness)).secondFactorVerified, true);
209
+ assert.equal(harness.effects.length, 1);
210
+});
211
+
212
+test('TOTP consumption is scoped to its owner', async (t) => {
213
+ t.mock.method(Date, 'now', () => 59_000);
214
+ const harness = makeHarness();
215
+ await challenge(harness, 1, 123);
216
+ assert.equal((await submit(harness, CODE, 123)).ok, true);
217
+ await challenge(harness, 2, 456);
218
+
219
+ assert.equal((await submit(harness, CODE, 456)).ok, true);
220
+ assert.equal(harness.effects.length, 2);
221
+});
222
+
223
+test('boolean TOTP verification retains the configured window boundaries', async () => {
224
+ let now = 0;
225
+ const verifier = new TotpVerifier({ secret: SECRET, now: () => now });
226
+ for (const [time, accepted] of [
227
+ [0, true],
228
+ [59_999, true],
229
+ [60_000, true],
230
+ [89_999, true],
231
+ [90_000, false]
232
+ ]) {
233
+ now = time;
234
+ assert.equal(await verifier.verify(CODE), accepted, `time ${time}`);
235
+ }
236
+ assert.equal(await verifier.verify('not-an-otp'), false);
237
+});