Personal Telegram developer console for GitHub

feat/studio-g0-foundation
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 237 lines 7.77 KB
Raw
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 });