Personal Telegram developer console for GitHub

fix: establish tested G0 worker and Telegram safety foundations

Codex committed Oct 24, 2026 at 18:38 UTC abf760e5d2631c8c4ef48a7738b33a9eae34ab4d
27 files changed +1115 -162
.github/workflows/ci.yml
+7 -1
@@ -24,7 +24,10 @@ jobs:
24 package-manager-cache: false
25
26 - name: Install dependencies
27 - run: npm install --no-audit --no-fund
27 + run: npm ci --no-audit --no-fund
28 +
29 + - name: Lint and check formatting
30 + run: npm run lint && npm run format:check
31
32 - name: Verify test discovery
33 shell: bash
@@ -43,3 +46,6 @@ jobs:
46
47 - name: Run tests
48 run: npm test
49 +
50 + - name: Validate Worker bundle without deployment
51 + run: npm run build:check
README.md
+5 -1
@@ -25,6 +25,10 @@ V2.1 شامل Workspace Editor، Ops Console، Security Center، Configuration C
25
26 ## Workspace Editor
27
28 +مرجع سقف‌های فعلی `WORKSPACE_EDITOR_LIMITS` در `src/core/workspace-policy.js` است: هر فایل حداکثر **۲۰٬۰۰۰ نویسهٔ Unicode و ۶۵٬۵۳۶ بایت UTF-8**، هر Change Set حداکثر **۸ فایل و ۱۳۱٬۰۷۲ بایت**. صفحهٔ Editor، API، پیام راهنما و ورودی فایل تلگرام از همین مرجع استفاده می‌کنند. محدودیت ۳٬۰۰۰/۱۲٬۰۰۰ در طرح‌های تاریخی Phase 1 دیگر مقدار جاری نیست.
29 +
30 +قرارداد توسعهٔ Nexa Studio نسخهٔ ۳ در [docs/contract/NEXA_STUDIO_V3.md](docs/contract/NEXA_STUDIO_V3.md) و فایل Word اصلی کنار آن نگهداری می‌شود. برچسب محصول V2.1 مربوط به بات موجود است؛ نسخهٔ انتشار کد از `package.json` خوانده می‌شود و با شمارهٔ قرارداد یکی نیست.
31 +
32 جریان ویرایش فایل:
33
34 1. `پروژه‌ها` → انتخاب Repository.
@@ -157,4 +161,4 @@ npm start
161 - GitHub WRITE نباید پیش از Approval معتبر Provider call بزند.
162 - Source، Draft، Secret و Signed Approval token نباید وارد Audit log یا diagnostics شوند.
163 - Public `/status` فقط health حداقلی می‌دهد؛ جزئیات عملیاتی متعلق به Telegram owner-only است.
160 -- Production، Preview و Durable state آزمایشی باید از هم تفکیک بمانند.
\ No newline at end of file
164 +- Production، Preview و Durable state آزمایشی باید از هم تفکیک بمانند.
src/bot-legacy.js
+2 -2
@@ -494,7 +494,7 @@ export class NexaDevBot {
494 }
495 view = routed;
496 } else if (quickMenu === 'status') {
497 - view = this.menu.getServiceStatusView();
497 + view = await this.menu.getServiceStatusView();
498 } else if (quickMenu === 'tools') {
499 view = this.menu.getToolsView();
500 } else {
@@ -526,7 +526,7 @@ export class NexaDevBot {
526 }
527
528 if (text === '/status') {
529 - const view = this.menu.getServiceStatusView();
529 + const view = await this.menu.getServiceStatusView();
530 const res = await this.telegram.sendMessage(
531 chatId,
532 view.text,
src/core/telegram-update-guard.js new
+53
@@ -0,0 +1,53 @@
1 +export const TELEGRAM_UPDATE_RETENTION_MS = 24 * 60 * 60_000;
2 +
3 +export async function telegramBotIdentity(botToken) {
4 + const token = String(botToken || '');
5 + if (!token) throw new Error('Telegram bot identity is not configured');
6 + const numericId = token.match(/^(\d+):/);
7 + if (numericId) return numericId[1];
8 + const digest = await crypto.subtle.digest(
9 + 'SHA-256',
10 + new TextEncoder().encode(token)
11 + );
12 + return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
13 +}
14 +
15 +export async function consumeTelegramUpdate({
16 + namespace,
17 + botId,
18 + updateId,
19 + now = Date.now
20 +} = {}) {
21 + if (!Number.isSafeInteger(updateId) || updateId < 0)
22 + throw new Error('Telegram update_id must be a nonnegative safe integer');
23 + if (!/^(?:\d+|sha256:[a-f0-9]{64})$/.test(String(botId || '')))
24 + throw new Error('Telegram bot identity is invalid');
25 + if (
26 + !namespace ||
27 + typeof namespace.idFromName !== 'function' ||
28 + typeof namespace.get !== 'function'
29 + ) {
30 + throw new Error('Telegram update guard is not configured');
31 + }
32 + const expiresAt = Number(now()) + TELEGRAM_UPDATE_RETENTION_MS;
33 + if (!Number.isSafeInteger(expiresAt))
34 + throw new Error('Telegram update claim expiry is invalid');
35 + const id = namespace.idFromName(`telegram-webhook:v1:${botId}:${updateId}`);
36 + const response = await namespace.get(id).fetch(
37 + new Request('https://approval-replay/telegram/claim', {
38 + method: 'POST',
39 + headers: { 'content-type': 'application/json' },
40 + body: JSON.stringify({ expiresAt })
41 + })
42 + );
43 + const body = await response.json().catch(() => null);
44 + if (
45 + response.status === 409 &&
46 + body?.accepted === false &&
47 + body?.reason === 'duplicate'
48 + )
49 + return false;
50 + if (!response.ok || body?.accepted !== true)
51 + throw new Error('Telegram update guard claim failed');
52 + return true;
53 +}
src/core/workspace-policy.js
+2 -2
@@ -48,9 +48,9 @@ export function validateEditableFile({ path, text, byteLength } = {}) {
48 )
49 reason = 'Git LFS pointer files are not editable.';
50 else if (charLength > MAX_CHARS)
51 - reason = 'Editable text is limited to 20,000 Unicode characters.';
51 + reason = `Editable text is limited to ${MAX_CHARS.toLocaleString('en-US')} Unicode characters.`;
52 else if (effectiveBytes > MAX_BYTES)
53 - reason = 'Editable text is limited to 65,536 UTF-8 bytes.';
53 + reason = `Editable text is limited to ${MAX_BYTES.toLocaleString('en-US')} UTF-8 bytes.`;
54
55 return {
56 editable: reason === '',
src/durable/approval-replay-guard.js
+33 -1
@@ -7,6 +7,28 @@ export class ApprovalReplayGuard {
7 async fetch(request) {
8 const url = new URL(request.url);
9
10 + if (request.method === 'POST' && url.pathname === '/telegram/claim') {
11 + const payload = await request.json().catch(() => null);
12 + const expiresAt = Number(payload?.expiresAt);
13 + const now = Date.now();
14 + if (!Number.isSafeInteger(expiresAt) || expiresAt <= now) {
15 + return json({ accepted: false, reason: 'invalid_expiry' }, 400);
16 + }
17 + const accepted = await this.state.storage.transaction(async (txn) => {
18 + const claimedUntil = Number(await txn.get('telegramUpdateExpiresAt'));
19 + if (Number.isFinite(claimedUntil) && claimedUntil > now) {
20 + await txn.setAlarm(claimedUntil);
21 + return false;
22 + }
23 + await txn.put('telegramUpdateExpiresAt', expiresAt);
24 + await txn.setAlarm(expiresAt);
25 + return true;
26 + });
27 + return accepted
28 + ? json({ accepted: true })
29 + : json({ accepted: false, reason: 'duplicate' }, 409);
30 + }
31 +
32 if (request.method === 'POST' && url.pathname === '/second-factor/put') {
33 const payload = await request.json().catch(() => null);
34 const token = String(payload?.token || '');
@@ -106,6 +128,16 @@ export class ApprovalReplayGuard {
128 return json({ accepted: true });
129 }
130 async alarm() {
109 - await this.state.storage.deleteAll();
131 + const telegramClaim = await this.state.storage.transaction(async (txn) => {
132 + const expiresAt = await txn.get('telegramUpdateExpiresAt');
133 + if (expiresAt === undefined) return false;
134 + if (Number(expiresAt) > Date.now()) await txn.setAlarm(Number(expiresAt));
135 + else {
136 + await txn.delete('telegramUpdateExpiresAt');
137 + await txn.deleteAlarm();
138 + }
139 + return true;
140 + });
141 + if (!telegramClaim) await this.state.storage.deleteAll();
142 }
143 }
src/github.js
+1
@@ -266,6 +266,7 @@ export class GitHubService {
266 title: pr.title || '',
267 author: pr.user?.login || 'unknown',
268 state: pr.state || '',
269 + draft: !!pr.draft,
270 merged: !!(pr.merged ?? pr.merged_at),
271 body: pr.body || '',
272 url: pr.html_url || '',
src/index.js
+63 -24
@@ -1,5 +1,10 @@
1 import { KillSwitchGuidedNexaDevBot } from './kill-switch-bot.js';
2 import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
3 +import { RELEASE_VERSION } from './version.js';
4 +import {
5 + consumeTelegramUpdate,
6 + telegramBotIdentity
7 +} from './core/telegram-update-guard.js';
8 import {
9 handleWorkspaceEditorRequest,
10 workspaceEditorPageResponse
@@ -17,7 +22,7 @@ const jsonResponse = (p, s = 200) =>
22 const publicHealthPayload = () => ({
23 status: 'online',
24 bot: 'Nexa Dev Bot',
20 - version: '1.1.1',
25 + version: RELEASE_VERSION,
26 mode: 'Cloudflare Worker Webhook'
27 });
28 const senderIdFromUpdate = (u) =>
@@ -26,21 +31,6 @@ const isOwnerUpdate = (u, e) =>
31 !!e.OWNER_TELEGRAM_ID &&
32 senderIdFromUpdate(u) !== null &&
33 String(senderIdFromUpdate(u)) === String(e.OWNER_TELEGRAM_ID);
29 -function safeErrorMessage(error, env = {}) {
30 - let m = String(error?.message || 'Unknown error');
31 - for (const s of [
32 - env.TELEGRAM_BOT_TOKEN,
33 - env.TELEGRAM_WEBHOOK_SECRET,
34 - env.GITHUB_TOKEN,
35 - env.CLOUDFLARE_API_TOKEN,
36 - env.APPROVAL_SIGNING_SECRET,
37 - env.DESTRUCTIVE_TOTP_SECRET
38 - ]) {
39 - const v = String(s || '');
40 - if (v) m = m.split(v).join('[REDACTED]');
41 - }
42 - return m;
43 -}
34 export default {
35 async fetch(request, env = {}) {
36 const url = new URL(request.url);
@@ -58,7 +48,14 @@ export default {
48 ownerId: env.OWNER_TELEGRAM_ID || ''
49 });
50 if (request.method === 'GET') {
61 - if (['/health', '/', '/status'].includes(url.pathname))
51 + if (url.pathname === '/health')
52 + return new Response('ok', {
53 + headers: {
54 + 'content-type': 'text/plain; charset=utf-8',
55 + 'cache-control': 'no-store'
56 + }
57 + });
58 + if (['/', '/status'].includes(url.pathname))
59 return jsonResponse(publicHealthPayload());
60 return new Response('Not Found', { status: 404 });
61 }
@@ -76,20 +73,62 @@ export default {
73 return new Response('Telegram bot token not configured', {
74 status: 503
75 });
76 + let update;
77 try {
80 - const u = await request.json();
81 - if (!isOwnerUpdate(u, env))
82 - return jsonResponse({ ok: true, ignored: true });
78 + update = await request.json();
79 + } catch {
80 return jsonResponse(
84 - await new KillSwitchGuidedNexaDevBot(env).handleUpdate(u)
81 + { ok: false, error: 'Invalid Telegram update' },
82 + 400
83 );
86 - } catch (e) {
87 - console.error('telegram_webhook_error', safeErrorMessage(e, env));
84 + }
85 + if (!Number.isSafeInteger(update?.update_id) || update.update_id < 0) {
86 return jsonResponse(
89 - { ok: false, error: 'Telegram webhook processing failed' },
87 + { ok: false, error: 'Invalid Telegram update_id' },
88 400
89 );
90 }
91 + if (!isOwnerUpdate(update, env))
92 + return jsonResponse({ ok: true, ignored: true });
93 + try {
94 + const accepted = await consumeTelegramUpdate({
95 + namespace: env.APPROVAL_REPLAY_GUARD,
96 + botId: await telegramBotIdentity(env.TELEGRAM_BOT_TOKEN),
97 + updateId: update.update_id
98 + });
99 + if (!accepted) return jsonResponse({ ok: true, duplicate: true });
100 + } catch {
101 + console.error(
102 + 'telegram_webhook_guard_error',
103 + JSON.stringify({ updateId: update.update_id, outcome: 'unavailable' })
104 + );
105 + return jsonResponse(
106 + { ok: false, error: 'Telegram update guard unavailable' },
107 + 503
108 + );
109 + }
110 + // Claim before effects: retries are at-most-once; a process crash after the
111 + // durable claim can lose this update. No raw update is retained for replay.
112 + try {
113 + const result = await new KillSwitchGuidedNexaDevBot(env).handleUpdate(
114 + update
115 + );
116 + if (result?.ok !== false) return jsonResponse(result);
117 + } catch {
118 + // Provider messages can contain tokens or draft text; log metadata only.
119 + }
120 + console.error(
121 + 'telegram_webhook_error',
122 + JSON.stringify({
123 + updateId: update.update_id,
124 + outcome: 'processed_error'
125 + })
126 + );
127 + return jsonResponse({
128 + ok: false,
129 + processed_error: true,
130 + error: 'Telegram webhook processing failed'
131 + });
132 }
133 return new Response(
134 request.method === 'POST' ? 'Not Found' : 'Method Not Allowed',
src/kill-switch-bot.js
+27 -13
@@ -3,13 +3,10 @@ import { DurableKillSwitchStoreClient } from './core/kill-switch-store.js';
3 import { KillSwitch } from './core/kill-switch.js';
4
5 const lockMarkup = (mode) => ({
6 - inline_keyboard: [
7 - [
8 - mode === 'LOCKED'
9 - ? { text: '🔓 بازکردن اضطراری', callback_data: 'killswitch:unlock' }
10 - : { text: '🔒 قفل اضطراری', callback_data: 'killswitch:lock' }
11 - ]
12 - ]
6 + inline_keyboard:
7 + mode === 'LOCKED'
8 + ? [[{ text: '↩️ منوی اصلی', callback_data: 'menu:main' }]]
9 + : [[{ text: '🔒 قفل اضطراری', callback_data: 'killswitch:lock' }]]
10 });
11
12 export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
@@ -53,8 +50,29 @@ export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
50 try {
51 await this.telegram.answerCallbackQuery(query.id);
52 } catch {}
53 + // Historical unlock callbacks never verified a signed approval or TOTP.
54 + // Keep them fail-closed until the complete unlock protocol is implemented.
55 + if (data === 'killswitch:unlock' || data === 'killswitch:confirm-unlock') {
56 + this.audit.log({
57 + event: 'kill_switch_control',
58 + outcome: 'denied',
59 + reason: 'unlock_protocol_required'
60 + });
61 + const res = await this.telegram.editMessageText(
62 + chatId,
63 + messageId,
64 + '🔒 قفل فعال می‌ماند. بازکردن قفل به Safe Approval معتبر و TOTP نیاز دارد؛ مسیر قدیمی قابل استفاده نیست.',
65 + lockMarkup('LOCKED')
66 + );
67 + return {
68 + ok: false,
69 + killSwitch: true,
70 + reason: 'unlock_protocol_required',
71 + res
72 + };
73 + }
74 if (data === 'killswitch:lock' || data === 'killswitch:unlock') {
57 - const target = data.endsWith('lock') ? 'lock' : 'unlock';
75 + const target = 'lock';
76 const label =
77 target === 'lock' ? 'فعال‌کردن قفل اضطراری' : 'بازکردن قفل اضطراری';
78 const res = await this.telegram.editMessageText(
@@ -75,12 +93,8 @@ export class KillSwitchGuidedNexaDevBot extends GuidedNexaDevBot {
93 );
94 return { ok: true, killSwitchApprovalRequired: true, res };
95 }
78 - const target = data.endsWith('lock') ? 'lock' : 'unlock';
96 const context = { isOwner: true, approved: true };
80 - const state =
81 - target === 'lock'
82 - ? await this.killSwitch.lock(context)
83 - : await this.killSwitch.unlock(context);
97 + const state = await this.killSwitch.lock(context);
98 this.audit.log({
99 event: 'kill_switch_control',
100 outcome: 'success',
src/plugins/cloudflare/plugin.js
+1 -1
@@ -183,7 +183,7 @@ export function createCloudflarePlugin({ cloudflare, github } = {}) {
183 ? 'SUCCESS / موفق'
184 : state.state.toUpperCase();
185 return {
186 - text: `🚦 <b>CI/CD Control Plane</b>\nState: <b>${label}</b>\nSHA: <code>${escapeHtml(targetSha.slice(0, 12) || '-')}</code>\nCI: <b>${escapeHtml(ci?.conclusion || ci?.status || 'unknown')}</b>\nDeploy: <b>${escapeHtml(deploy?.conclusion || deploy?.status || 'unknown')}</b>\nRuntime: <code>${escapeHtml(state.versionId || runtime?.deployment?.versions?.[0]?.versionId || '-')}</code>\n\n${escapeHtml(state.reason)}</b>`,
186 + text: `🚦 <b>CI/CD Control Plane</b>\nState: <b>${label}</b>\nSHA: <code>${escapeHtml(targetSha.slice(0, 12) || '-')}</code>\nCI: <b>${escapeHtml(ci?.conclusion || ci?.status || 'unknown')}</b>\nDeploy: <b>${escapeHtml(deploy?.conclusion || deploy?.status || 'unknown')}</b>\nRuntime: <code>${escapeHtml(state.versionId || runtime?.deployment?.versions?.[0]?.versionId || '-')}</code>\n\n${escapeHtml(state.reason)}`,
187 reply_markup: {
188 inline_keyboard: [
189 [{ text: '🔄 بروزرسانی', callback_data: 'cf:delivery' }],
src/plugins/github/workspace.js
+8 -5
@@ -3,7 +3,8 @@ import {
3 digestText,
4 makeTargetBranch,
5 normalizeCommitMessage,
6 - validateEditableFile
6 + validateEditableFile,
7 + WORKSPACE_EDITOR_LIMITS
8 } from '../../core/workspace-policy.js';
9 import { DEFAULT_CONFIG } from '../../config.js';
10 import { commitWorkspaceIntent } from './workspace-commit.js';
@@ -12,6 +13,7 @@ export { commitWorkspaceIntent } from './workspace-commit.js';
13
14 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
15 const INTENT_8 = '[A-Za-z0-9_-]{8}';
16 +const editorLimitHint = `${WORKSPACE_EDITOR_LIMITS.maxChars.toLocaleString('en-US')} کاراکتر Unicode و ${WORKSPACE_EDITOR_LIMITS.maxBytes.toLocaleString('en-US')} بایت UTF-8`;
17 const escapeHtml = (value) =>
18 String(value ?? '')
19 .replaceAll('&', '&amp;')
@@ -270,8 +272,9 @@ export function createWorkspaceController({
272 text: file.content,
273 byteLength: file.size
274 });
273 - const preview =
274 - file.content.length > 2600
275 + const preview = !validateEditableFile({ path: file.path }).editable
276 + ? 'محتوای فایل حساس در تلگرام نمایش داده نمی‌شود.'
277 + : file.content.length > 2600
278 ? `${file.content.slice(0, 2600)}\n…`
279 : file.content;
280 const reason = repo.archived
@@ -499,9 +502,9 @@ export function createWorkspaceController({
502 const draftMode = mode === 'draft';
503 return {
504 text: fileMode
502 - ? `📎 <b>فایل متنی جایگزین را ارسال کنید</b>\nمقصد در مخزن: <code>${escapeHtml(workspace.path)}</code>\n\nفایل ارسال‌شده فقط به‌عنوان محتوای جایگزین Draft استفاده می‌شود؛ نام فایل مقصد را تغییر نمی‌دهد. سقف Policy: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8 معتبر. فایل‌های باینری، LFS یا محتوای غیرمجاز رد می‌شوند.`
505 + ? `📎 <b>فایل متنی جایگزین را ارسال کنید</b>\nمقصد در مخزن: <code>${escapeHtml(workspace.path)}</code>\n\nفایل ارسال‌شده فقط به‌عنوان محتوای جایگزین Draft استفاده می‌شود؛ نام فایل مقصد را تغییر نمی‌دهد. سقف Policy: ${editorLimitHint} معتبر. فایل‌های باینری، LFS یا محتوای غیرمجاز رد می‌شوند.`
506 : draftMode
504 - ? `📝 <b>ورودی متنی قدیمی Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nاین مسیر فقط برای سازگاری پیام‌های قدیمی باقی مانده است. Editor جدید مسیر اصلی است. سقف: 20,000 کاراکتر Unicode و 65,536 بایت UTF-8.`
507 + ? `📝 <b>ورودی متنی قدیمی Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nاین مسیر فقط برای سازگاری پیام‌های قدیمی باقی مانده است. Editor جدید مسیر اصلی است. سقف: ${editorLimitHint}.`
508 : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
509 reply_markup: {
510 inline_keyboard: [
src/telegram.js
+6 -1
@@ -1,3 +1,5 @@
1 +import { WORKSPACE_EDITOR_LIMITS } from './core/workspace-policy.js';
2 +
3 export class TelegramClient {
4 constructor(botToken, options = {}) {
5 this.botToken = botToken;
@@ -45,7 +47,10 @@ export class TelegramClient {
47 return body;
48 }
49
48 - async downloadTextFile(fileId, { maxBytes = 12000 } = {}) {
50 + async downloadTextFile(
51 + fileId,
52 + { maxBytes = WORKSPACE_EDITOR_LIMITS.maxBytes } = {}
53 + ) {
54 if (!this.botToken) throw new Error('TELEGRAM_BOT_TOKEN is not configured');
55 const id = String(fileId || '');
56 if (!id) throw new Error('Telegram file_id is required');
src/version.js new
+3
@@ -0,0 +1,3 @@
1 +import metadata from '../package.json' with { type: 'json' };
2 +
3 +export const RELEASE_VERSION = metadata.version;
src/workspace-editor.js
+1 -1
@@ -208,7 +208,7 @@ export function renderWorkspaceEditorPage() {
208 const workspaceId = params.get('workspaceId') || '';
209 const byteLength = value => new TextEncoder().encode(value).byteLength;
210 const codePoints = value => Array.from(value).length;
211 - let limits = { maxChars: 20000, maxBytes: 65536 };
211 + let limits = ${JSON.stringify(WORKSPACE_EDITOR_LIMITS)};
212
213 function setStatus(message, kind='') { status.textContent = message; status.className = 'status' + (kind ? ' ' + kind : ''); }
214 function updateCounter() {
test/approval-expiry-ui.test.js
+5 -39
@@ -1,44 +1,10 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 -
5 -function makeReplayNamespace() {
6 - const used = new Set();
7 - return {
8 - idFromName(name) {
9 - return String(name);
10 - },
11 - get(id) {
12 - return {
13 - async fetch(request) {
14 - const body = await request.json();
15 - const expiresAt = Number(body?.expiresAt);
16 - if (!Number.isFinite(expiresAt)) {
17 - return Response.json(
18 - { accepted: false, reason: 'invalid_expiry' },
19 - { status: 400 }
20 - );
21 - }
22 - if (expiresAt < Date.now()) {
23 - return Response.json(
24 - { accepted: false, reason: 'expired' },
25 - { status: 410 }
26 - );
27 - }
28 - const key = String(id);
29 - if (used.has(key)) {
30 - return Response.json(
31 - { accepted: false, reason: 'already_used' },
32 - { status: 409 }
33 - );
34 - }
35 - used.add(key);
36 - return Response.json({ accepted: true });
37 - }
38 - };
39 - }
40 - };
41 -}
4 +import {
5 + makeReplayNamespace,
6 + withUpdateId
7 +} from './helpers/replay-namespace.js';
8
9 const env = {
10 TELEGRAM_WEBHOOK_SECRET: 'right',
@@ -57,7 +23,7 @@ function webhook(update) {
23 'content-type': 'application/json',
24 'X-Telegram-Bot-Api-Secret-Token': 'right'
25 },
60 - body: JSON.stringify(update)
26 + body: JSON.stringify(withUpdateId(update))
27 });
28 }
29
test/approval-flow.test.js
+7 -40
@@ -1,44 +1,10 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 -
5 -function makeReplayNamespace() {
6 - const used = new Set();
7 - return {
8 - idFromName(name) {
9 - return String(name);
10 - },
11 - get(id) {
12 - return {
13 - async fetch(request) {
14 - const body = await request.json();
15 - const expiresAt = Number(body?.expiresAt);
16 - if (!Number.isFinite(expiresAt)) {
17 - return Response.json(
18 - { accepted: false, reason: 'invalid_expiry' },
19 - { status: 400 }
20 - );
21 - }
22 - if (expiresAt < Date.now()) {
23 - return Response.json(
24 - { accepted: false, reason: 'expired' },
25 - { status: 410 }
26 - );
27 - }
28 - const key = String(id);
29 - if (used.has(key)) {
30 - return Response.json(
31 - { accepted: false, reason: 'already_used' },
32 - { status: 409 }
33 - );
34 - }
35 - used.add(key);
36 - return Response.json({ accepted: true });
37 - }
38 - };
39 - }
40 - };
41 -}
4 +import {
5 + makeReplayNamespace,
6 + withUpdateId
7 +} from './helpers/replay-namespace.js';
8
9 const env = {
10 TELEGRAM_WEBHOOK_SECRET: 'right',
@@ -57,7 +23,7 @@ function webhook(update) {
23 'content-type': 'application/json',
24 'X-Telegram-Bot-Api-Secret-Token': 'right'
25 },
60 - body: JSON.stringify(update)
26 + body: JSON.stringify(withUpdateId(update))
27 });
28 }
29
@@ -215,7 +181,8 @@ test('approve callback executes exactly once and replay is rejected', async () =
181 }
182 });
183 assert.equal(replay.ok, false);
218 - assert.match(String(replay.error || ''), /used|replay|approval/i);
184 + assert.equal(replay.processed_error, true);
185 + assert.equal(replay.error, 'Telegram webhook processing failed');
186
187 const writesAfterReplay = mock.githubCalls.filter(
188 (call) => call.method === 'POST'
test/approval-provider-error-ui.test.js
+5 -25
@@ -1,30 +1,10 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 -
5 -function makeReplayNamespace() {
6 - const used = new Set();
7 - return {
8 - idFromName(name) {
9 - return String(name);
10 - },
11 - get(id) {
12 - return {
13 - async fetch(request) {
14 - const body = await request.json();
15 - const key = String(id);
16 - if (used.has(key))
17 - return Response.json(
18 - { accepted: false, reason: 'already_used' },
19 - { status: 409 }
20 - );
21 - used.add(key);
22 - return Response.json({ accepted: true, expiresAt: body.expiresAt });
23 - }
24 - };
25 - }
26 - };
27 -}
4 +import {
5 + makeReplayNamespace,
6 + withUpdateId
7 +} from './helpers/replay-namespace.js';
8
9 const env = {
10 TELEGRAM_WEBHOOK_SECRET: 'right',
@@ -43,7 +23,7 @@ function webhook(update) {
23 'content-type': 'application/json',
24 'X-Telegram-Bot-Api-Secret-Token': 'right'
25 },
46 - body: JSON.stringify(update)
26 + body: JSON.stringify(withUpdateId(update))
27 });
28 }
29
test/editor-policy-consistency.test.js new
+32
@@ -0,0 +1,32 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { TelegramClient } from '../src/telegram.js';
4 +
5 +test('default document upload accepts a valid editor-sized draft above the old 12KB ceiling', async () => {
6 + const text = 'a'.repeat(15000);
7 + const client = new TelegramClient('test-only-token', {
8 + fetch: async (url) =>
9 + String(url).endsWith('/getFile')
10 + ? Response.json({
11 + ok: true,
12 + result: { file_path: 'documents/draft.txt', file_size: 15000 }
13 + })
14 + : new Response(text)
15 + });
16 + assert.equal((await client.downloadTextFile('test-file')).text, text);
17 +});
18 +
19 +test('default document upload rejects content above the current editor byte ceiling before downloading', async () => {
20 + let calls = 0;
21 + const client = new TelegramClient('test-only-token', {
22 + fetch: async () => {
23 + calls++;
24 + return Response.json({
25 + ok: true,
26 + result: { file_path: 'documents/draft.txt', file_size: 65537 }
27 + });
28 + }
29 + });
30 + await assert.rejects(client.downloadTextFile('test-file'), /65536/);
31 + assert.equal(calls, 1);
32 +});
test/g0-bot-regressions.test.js new
+140
@@ -0,0 +1,140 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GuidedNexaDevBot } from '../src/guide-bot.js';
4 +
5 +const repository = {
6 + id: 1001,
7 + name: 'nexa-dev-bot',
8 + full_name: 'owner/nexa-dev-bot',
9 + default_branch: 'main',
10 + private: true
11 +};
12 +const targetSha = 'a'.repeat(40);
13 +const versionId = '11111111-1111-4111-8111-111111111111';
14 +
15 +function installProviders(t, { githubFailure = false } = {}) {
16 + const telegramCalls = [];
17 + t.mock.method(globalThis, 'fetch', async (url, options = {}) => {
18 + const endpoint = new URL(url);
19 + if (endpoint.hostname === 'api.telegram.org') {
20 + const body = JSON.parse(options.body);
21 + telegramCalls.push({ method: endpoint.pathname.split('/').at(-1), body });
22 + return Response.json({ ok: true, result: { message_id: 700 } });
23 + }
24 + assert.equal(
25 + options.method || 'GET',
26 + 'GET',
27 + 'diagnostics must remain read-only'
28 + );
29 + if (endpoint.hostname === 'api.github.com') {
30 + if (endpoint.pathname === '/user/repos') {
31 + return githubFailure
32 + ? Response.json({ message: 'Permission denied' }, { status: 403 })
33 + : Response.json([repository]);
34 + }
35 + if (endpoint.pathname === '/repositories/1001')
36 + return Response.json(repository);
37 + if (endpoint.pathname === '/repos/owner/nexa-dev-bot/commits') {
38 + return Response.json([
39 + { sha: targetSha, commit: { message: 'docs: verify delivery' } }
40 + ]);
41 + }
42 + if (endpoint.pathname === '/repos/owner/nexa-dev-bot/actions/runs') {
43 + return Response.json({ workflow_runs: [] });
44 + }
45 + }
46 + if (endpoint.hostname === 'api.cloudflare.com') {
47 + const resource = endpoint.pathname.split('/').at(-1);
48 + const result = {
49 + deployments: {
50 + deployments: [
51 + {
52 + id: 'deployment-1',
53 + versions: [{ version_id: versionId, percentage: 100 }]
54 + }
55 + ]
56 + },
57 + versions: { items: [{ id: versionId }] },
58 + settings: { bindings: [], observability: {} }
59 + }[resource];
60 + if (result) return Response.json({ success: true, result });
61 + }
62 + throw new Error(
63 + `Unexpected provider request: ${endpoint.hostname}${endpoint.pathname}`
64 + );
65 + });
66 + return telegramCalls;
67 +}
68 +
69 +function createBot() {
70 + return new GuidedNexaDevBot({
71 + TELEGRAM_BOT_TOKEN: 'telegram-test-token',
72 + TELEGRAM_WEBHOOK_SECRET: 'webhook-test-secret',
73 + OWNER_TELEGRAM_ID: '123',
74 + GITHUB_TOKEN: 'github-test-token',
75 + GITHUB_OWNER: 'owner',
76 + CLOUDFLARE_API_TOKEN: 'cloudflare-test-token',
77 + CLOUDFLARE_ACCOUNT_ID: 'account-1',
78 + CLOUDFLARE_WORKER_NAME: 'nexa-dev-bot'
79 + });
80 +}
81 +
82 +for (const text of ['/status', '📊 وضعیت']) {
83 + for (const githubFailure of [false, true]) {
84 + test(`${text} sends the resolved live status when GitHub ${githubFailure ? 'fails' : 'succeeds'}`, async (t) => {
85 + const calls = installProviders(t, { githubFailure });
86 + const result = await createBot().handleMessage({
87 + chat: { id: 123 },
88 + from: { id: 123 },
89 + text
90 + });
91 +
92 + assert.equal(result.ok, true);
93 + assert.equal(calls.length, 1);
94 + assert.equal(calls[0].method, 'sendMessage');
95 + assert.equal(
96 + typeof calls[0].body.text,
97 + 'string',
98 + 'status must resolve before sending'
99 + );
100 + assert.match(calls[0].body.text, /GitHub live READ/);
101 + assert.match(
102 + calls[0].body.text,
103 + githubFailure ? /❌ ناموفق.*403/ : /✅ متصل؛ 1 Repository/
104 + );
105 + assert.ok(
106 + calls[0].body.reply_markup.inline_keyboard
107 + .flat()
108 + .some((button) => button.callback_data === 'menu:status')
109 + );
110 + });
111 + }
112 +}
113 +
114 +test('Cloudflare delivery callback sends balanced Telegram HTML with provider evidence', async (t) => {
115 + const calls = installProviders(t);
116 + const result = await createBot().handleCallbackQuery({
117 + id: 'delivery-audit',
118 + from: { id: 123 },
119 + data: 'cf:delivery',
120 + message: { chat: { id: 123 }, message_id: 700 }
121 + });
122 +
123 + assert.equal(result.ok, true);
124 + const edited = calls.find((call) => call.method === 'editMessageText');
125 + assert.equal(edited.body.message_id, 700);
126 + assert.equal(edited.body.parse_mode, 'HTML');
127 + assert.match(edited.body.text, /CI\/CD Control Plane/);
128 + assert.match(edited.body.text, /State: <b>UNKNOWN<\/b>/);
129 + assert.match(edited.body.text, /aaaaaaaaaaaa/);
130 + assert.match(edited.body.text, /Delivery evidence is incomplete/);
131 + assert.match(edited.body.text, new RegExp(versionId));
132 + const tags = [];
133 + for (const [, closing, tag] of edited.body.text.matchAll(
134 + /<(\/?)(b|code)>/g
135 + )) {
136 + if (closing) assert.equal(tags.pop(), tag, `unmatched closing ${tag} tag`);
137 + else tags.push(tag);
138 + }
139 + assert.deepEqual(tags, [], 'Telegram HTML must close every opened tag');
140 +});
test/g0-github-safety.test.js new
+139
@@ -0,0 +1,139 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GitHubService } from '../src/github.js';
4 +import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5 +import { createWorkspaceController } from '../src/plugins/github/workspace.js';
6 +
7 +const HEAD_SHA = 'a'.repeat(40);
8 +const TREE_SHA = 'b'.repeat(40);
9 +const REPO_URL = 'https://api.github.com/repos/owner/demo';
10 +const REPO = {
11 + id: 123,
12 + name: 'demo',
13 + full_name: 'owner/demo',
14 + default_branch: 'main',
15 + archived: false
16 +};
17 +
18 +async function withGitHubFetch(handler, run) {
19 + const originalFetch = globalThis.fetch;
20 + globalThis.fetch = async (url, options = {}) => {
21 + const value = String(url);
22 + if (value === 'https://api.github.com/repositories/123') {
23 + return Response.json(REPO);
24 + }
25 + return handler(value, options);
26 + };
27 + try {
28 + return await run(new GitHubService('fixture-token'));
29 + } finally {
30 + globalThis.fetch = originalFetch;
31 + }
32 +}
33 +
34 +async function filePreview(path, content) {
35 + return withGitHubFetch(
36 + async (url) => {
37 + if (url === `${REPO_URL}/git/ref/heads/main`) {
38 + return Response.json({ object: { sha: HEAD_SHA } });
39 + }
40 + if (url === `${REPO_URL}/git/commits/${HEAD_SHA}`) {
41 + return Response.json({ tree: { sha: TREE_SHA } });
42 + }
43 + if (url === `${REPO_URL}/contents/${path}?ref=${HEAD_SHA}`) {
44 + return Response.json({
45 + type: 'file',
46 + path,
47 + sha: 'c'.repeat(40),
48 + size: content.length,
49 + encoding: 'base64',
50 + content: btoa(content)
51 + });
52 + }
53 + throw new Error(`Unexpected fixture request: ${url}`);
54 + },
55 + async (github) => {
56 + const controller = createWorkspaceController({
57 + github,
58 + workspaces: {
59 + async resolveNavigationRef({ ownerId, refId }) {
60 + assert.equal(ownerId, '42');
61 + assert.equal(refId, 'R123456789');
62 + return { repoId: 123, path, type: 'file' };
63 + }
64 + }
65 + });
66 + return controller
67 + .resolveCallback('wnav:R123456789', { ownerId: '42' })
68 + .execute();
69 + }
70 + );
71 +}
72 +
73 +test('sensitive file previews withhold source from the Telegram payload and offer no Edit', async () => {
74 + const content = 'AUDIT_SECRET_SENTINEL=<private-value>\n';
75 + const view = await filePreview('.env.production', content);
76 +
77 + assert.doesNotMatch(
78 + JSON.stringify(view),
79 + /AUDIT_SECRET_SENTINEL|private-value/
80 + );
81 + assert.equal(
82 + view.reply_markup.inline_keyboard
83 + .flat()
84 + .some((button) => button.callback_data?.startsWith('wedit:')),
85 + false
86 + );
87 + assert.match(view.text, /حساس|Sensitive/);
88 +});
89 +
90 +test('ordinary legacy file previews retain escaped source and the Edit action', async () => {
91 + const view = await filePreview('app.js', 'console.log("<ordinary>");\n');
92 +
93 + assert.match(view.text, /&lt;ordinary&gt;/);
94 + assert.ok(
95 + view.reply_markup.inline_keyboard
96 + .flat()
97 + .some((button) => button.callback_data === 'wedit:R123456789')
98 + );
99 +});
100 +
101 +test('draft PRs remain draft through the provider and cannot reach the merge mutation', async () => {
102 + let mergeRequests = 0;
103 + await withGitHubFetch(
104 + async (url, options) => {
105 + if (url === `${REPO_URL}/pulls/19`) {
106 + return Response.json({
107 + number: 19,
108 + title: 'Draft change',
109 + state: 'open',
110 + draft: true,
111 + merged: false,
112 + user: { login: 'developer' },
113 + head: { ref: 'feature/draft', sha: HEAD_SHA },
114 + base: { ref: 'main' }
115 + });
116 + }
117 + if (url === `${REPO_URL}/pulls/19/merge` && options.method === 'PUT') {
118 + mergeRequests += 1;
119 + return Response.json({ merged: true, sha: 'd'.repeat(40) });
120 + }
121 + throw new Error(`Unexpected fixture request: ${url}`);
122 + },
123 + async (github) => {
124 + const plugin = createGitHubPlugin({ github, menu: {} });
125 + const merge = plugin.resolveCallback(`mergepr:3f:j:${HEAD_SHA}`);
126 +
127 + await assert.rejects(merge.execute(), /not mergeable/i);
128 + assert.equal(mergeRequests, 0);
129 + assert.equal((await github.getPullRequest(123, 19)).draft, true);
130 + const detail = await plugin.resolveCallback('prdetail:123:19').execute();
131 + assert.equal(
132 + detail.reply_markup.inline_keyboard
133 + .flat()
134 + .some((button) => button.callback_data?.startsWith('mergepr:')),
135 + false
136 + );
137 + }
138 + );
139 +});
test/helpers/replay-namespace.js new
+90
@@ -0,0 +1,90 @@
1 +import { ApprovalReplayGuard } from '../../src/durable/approval-replay-guard.js';
2 +
3 +export function makeReplayState({ failAlarm = false } = {}) {
4 + const data = new Map();
5 + let alarm = null;
6 + let transactionTail = Promise.resolve();
7 + const api = {
8 + async get(key) {
9 + return structuredClone(data.get(key));
10 + },
11 + async put(key, value) {
12 + data.set(key, structuredClone(value));
13 + },
14 + async delete(key) {
15 + return data.delete(key);
16 + },
17 + async setAlarm(value) {
18 + alarm = value;
19 + },
20 + async deleteAlarm() {
21 + alarm = null;
22 + },
23 + async deleteAll() {
24 + data.clear();
25 + alarm = null;
26 + }
27 + };
28 + return {
29 + data,
30 + get alarm() {
31 + return alarm;
32 + },
33 + storage: {
34 + ...api,
35 + transaction(fn) {
36 + const run = transactionTail.then(async () => {
37 + const pending = structuredClone(data);
38 + let nextAlarm = alarm;
39 + const result = await fn({
40 + async get(key) {
41 + return structuredClone(pending.get(key));
42 + },
43 + async put(key, value) {
44 + pending.set(key, structuredClone(value));
45 + },
46 + async delete(key) {
47 + return pending.delete(key);
48 + },
49 + async setAlarm(value) {
50 + if (failAlarm) throw new Error('alarm unavailable');
51 + nextAlarm = value;
52 + },
53 + async deleteAlarm() {
54 + nextAlarm = null;
55 + }
56 + });
57 + data.clear();
58 + for (const [key, value] of pending) data.set(key, value);
59 + alarm = nextAlarm;
60 + return result;
61 + });
62 + transactionTail = run.catch(() => {});
63 + return run;
64 + }
65 + }
66 + };
67 +}
68 +
69 +export function makeReplayNamespace(options) {
70 + const states = new Map();
71 + return {
72 + states,
73 + idFromName(name) {
74 + return String(name);
75 + },
76 + get(id) {
77 + if (!states.has(id)) states.set(id, makeReplayState(options));
78 + // Construct again for every request to exercise durable state after eviction.
79 + return {
80 + fetch: (request) =>
81 + new ApprovalReplayGuard(states.get(id)).fetch(request)
82 + };
83 + }
84 + };
85 +}
86 +
87 +let nextUpdateId = 1;
88 +export function withUpdateId(update) {
89 + return { update_id: nextUpdateId++, ...update };
90 +}
test/index.test.js
+10 -4
@@ -1,8 +1,13 @@
1 import { describe, it } from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 +import {
5 + makeReplayNamespace,
6 + withUpdateId
7 +} from './helpers/replay-namespace.js';
8
9 const runtime = {
10 + APPROVAL_REPLAY_GUARD: makeReplayNamespace(),
11 TELEGRAM_WEBHOOK_SECRET: 'unit-test-secret',
12 OWNER_TELEGRAM_ID: '123',
13 TELEGRAM_BOT_TOKEN: 'unit-test-token',
@@ -10,7 +15,6 @@ const runtime = {
15 };
16
17 const startUpdate = {
13 - update_id: 101,
18 message: {
19 message_id: 202,
20 from: { id: 123 },
@@ -26,7 +30,7 @@ function webhookRequest(update = startUpdate) {
30 'Content-Type': 'application/json',
31 'X-Telegram-Bot-Api-Secret-Token': 'unit-test-secret'
32 },
29 - body: JSON.stringify(update)
33 + body: JSON.stringify(withUpdateId(update))
34 });
35 }
36
@@ -155,9 +159,11 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
159 APPROVAL_SIGNING_SECRET: approvalSecret,
160 CLOUDFLARE_API_TOKEN: cloudflareSecret
161 });
158 - assert.equal(res.status, 400);
162 + assert.equal(res.status, 200);
163 + assert.equal((await res.json()).processed_error, true);
164 assert.ok(logs.some((line) => /telegram_webhook_error/i.test(line)));
160 - assert.ok(logs.some((line) => /401|Unauthorized/i.test(line)));
165 + assert.ok(logs.every((line) => !/401|Unauthorized/i.test(line)));
166 + assert.ok(logs.some((line) => /processed_error/i.test(line)));
167 assert.ok(logs.every((line) => !line.includes(secretToken)));
168 assert.ok(logs.every((line) => !line.includes(approvalSecret)));
169 assert.ok(logs.every((line) => !line.includes(cloudflareSecret)));
test/kill-switch-ui-safety.test.js new
+63
@@ -0,0 +1,63 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { KillSwitchGuidedNexaDevBot } from '../src/kill-switch-bot.js';
4 +
5 +function setup() {
6 + const edits = [],
7 + writes = [];
8 + const bot = new KillSwitchGuidedNexaDevBot({ OWNER_TELEGRAM_ID: '42' });
9 + bot.killSwitch = {
10 + status: async () => ({ mode: 'LOCKED' }),
11 + lock: async () => {
12 + writes.push('lock');
13 + return { mode: 'LOCKED' };
14 + },
15 + unlock: async () => {
16 + writes.push('unlock');
17 + return { mode: 'NORMAL' };
18 + }
19 + };
20 + bot.telegram = {
21 + answerCallbackQuery: async () => {},
22 + editMessageText: async (...args) => {
23 + edits.push(args);
24 + },
25 + sendMessage: async (...args) => {
26 + edits.push(args);
27 + }
28 + };
29 + bot.audit = { log() {} };
30 + return { bot, edits, writes };
31 +}
32 +
33 +test('locked state exposes navigation without an unauthenticated unlock button', async () => {
34 + const { bot, edits } = setup();
35 + await bot.handleMessage({ chat: { id: 42 }, text: '/killswitch' });
36 + const markup = edits[0][2];
37 + assert.ok(
38 + markup.inline_keyboard
39 + .flat()
40 + .some((button) => button.callback_data === 'menu:main')
41 + );
42 + assert.equal(
43 + markup.inline_keyboard
44 + .flat()
45 + .some((button) => button.callback_data.includes('unlock')),
46 + false
47 + );
48 +});
49 +
50 +for (const data of ['killswitch:unlock', 'killswitch:confirm-unlock']) {
51 + test(`stale ${data} cannot mutate state without signed approval and TOTP`, async () => {
52 + const { bot, edits, writes } = setup();
53 + const result = await bot.handleCallbackQuery({
54 + id: 'query',
55 + data,
56 + from: { id: 42 },
57 + message: { chat: { id: 42 }, message_id: 1 }
58 + });
59 + assert.deepEqual(writes, []);
60 + assert.equal(result.ok, false);
61 + assert.match(edits[0][2], /TOTP/);
62 + });
63 +}
test/navigation.test.js
+6 -1
@@ -1,8 +1,13 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 +import {
5 + makeReplayNamespace,
6 + withUpdateId
7 +} from './helpers/replay-namespace.js';
8
9 const env = {
10 + APPROVAL_REPLAY_GUARD: makeReplayNamespace(),
11 TELEGRAM_WEBHOOK_SECRET: 'right',
12 OWNER_TELEGRAM_ID: '123',
13 TELEGRAM_BOT_TOKEN: 'telegram-test-token',
@@ -17,7 +22,7 @@ function webhook(update) {
22 'content-type': 'application/json',
23 'X-Telegram-Bot-Api-Secret-Token': 'right'
24 },
20 - body: JSON.stringify(update)
25 + body: JSON.stringify(withUpdateId(update))
26 });
27 }
28 const json = (data, status = 200) =>
test/security.test.js
+8 -1
@@ -1,6 +1,10 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 +import {
5 + makeReplayNamespace,
6 + withUpdateId
7 +} from './helpers/replay-namespace.js';
8
9 function telegramRequest(secret, update) {
10 const headers = { 'content-type': 'application/json' };
@@ -9,7 +13,7 @@ function telegramRequest(secret, update) {
13 return new Request('https://example.com/telegram/webhook', {
14 method: 'POST',
15 headers,
12 - body: JSON.stringify(update)
16 + body: JSON.stringify(withUpdateId(update))
17 });
18 }
19
@@ -48,6 +52,7 @@ test('webhook rejects a wrong Telegram secret', async () => {
52 };
53
54 const res = await worker.fetch(req, {
55 + APPROVAL_REPLAY_GUARD: makeReplayNamespace(),
56 TELEGRAM_WEBHOOK_SECRET: 'right',
57 OWNER_TELEGRAM_ID: '123',
58 TELEGRAM_BOT_TOKEN: 'token'
@@ -72,6 +77,7 @@ test('unauthorized Telegram users receive no bot response', async () => {
77 };
78
79 const res = await worker.fetch(req, {
80 + APPROVAL_REPLAY_GUARD: makeReplayNamespace(),
81 TELEGRAM_WEBHOOK_SECRET: 'right',
82 OWNER_TELEGRAM_ID: '123',
83 TELEGRAM_BOT_TOKEN: 'token'
@@ -120,6 +126,7 @@ test('temporary diagnostic command no longer exposes Telegram ID', async () => {
126 };
127
128 const res = await worker.fetch(req, {
129 + APPROVAL_REPLAY_GUARD: makeReplayNamespace(),
130 TELEGRAM_WEBHOOK_SECRET: 'right',
131 OWNER_TELEGRAM_ID: '123',
132 TELEGRAM_BOT_TOKEN: 'token'
test/telegram-update-guard.test.js new
+364
@@ -0,0 +1,364 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import worker from '../src/index.js';
4 +import { ApprovalReplayGuard } from '../src/durable/approval-replay-guard.js';
5 +import { KillSwitchGuidedNexaDevBot } from '../src/kill-switch-bot.js';
6 +import {
7 + makeReplayNamespace,
8 + makeReplayState
9 +} from './helpers/replay-namespace.js';
10 +
11 +let module = {};
12 +try {
13 + module = await import('../src/core/telegram-update-guard.js');
14 +} catch {}
15 +const consume = (input) => {
16 + assert.equal(
17 + typeof module.consumeTelegramUpdate,
18 + 'function',
19 + 'durable Telegram update claims must exist'
20 + );
21 + return module.consumeTelegramUpdate(input);
22 +};
23 +const identity = (token) => {
24 + assert.equal(
25 + typeof module.telegramBotIdentity,
26 + 'function',
27 + 'bot identity derivation must exist'
28 + );
29 + return module.telegramBotIdentity(token);
30 +};
31 +const DAY = 86_400_000;
32 +const fixedTime = 1_800_000_000_000;
33 +const ownerUpdate = (updateId = 7) => ({
34 + update_id: updateId,
35 + message: {
36 + message_id: 4,
37 + from: { id: 123 },
38 + chat: { id: 123 },
39 + text: '/help'
40 + }
41 +});
42 +const webhook = (update) =>
43 + new Request('https://example.test/telegram/webhook', {
44 + method: 'POST',
45 + headers: {
46 + 'content-type': 'application/json',
47 + 'X-Telegram-Bot-Api-Secret-Token': 'right'
48 + },
49 + body: typeof update === 'string' ? update : JSON.stringify(update)
50 + });
51 +const env = (namespace = makeReplayNamespace()) => ({
52 + TELEGRAM_WEBHOOK_SECRET: 'right',
53 + OWNER_TELEGRAM_ID: '123',
54 + TELEGRAM_BOT_TOKEN: '12345:test-secret',
55 + APPROVAL_REPLAY_GUARD: namespace
56 +});
57 +
58 +test('durable claims reject duplicates across object recreation without storing update content', async () => {
59 + const namespace = makeReplayNamespace();
60 + assert.equal(await consume({ namespace, botId: '12345', updateId: 0 }), true);
61 + assert.equal(
62 + await consume({ namespace, botId: '12345', updateId: 0 }),
63 + false
64 + );
65 + const [key, state] = [...namespace.states][0];
66 + assert.equal(key, 'telegram-webhook:v1:12345:0');
67 + assert.equal(state.data.size, 1);
68 + assert.ok(
69 + [...state.data.values()].every((value) => typeof value === 'number')
70 + );
71 +});
72 +
73 +test('claims expire exactly after 24 hours even when the cleanup alarm is delayed', async () => {
74 + const previousNow = Date.now;
75 + let current = fixedTime;
76 + Date.now = () => current;
77 + try {
78 + const namespace = makeReplayNamespace();
79 + const claim = () =>
80 + consume({ namespace, botId: '12345', updateId: 9, now: Date.now });
81 + assert.equal(await claim(), true);
82 + const state = [...namespace.states.values()][0];
83 + assert.equal(state.alarm, fixedTime + DAY);
84 + current += DAY - 1;
85 + assert.equal(await claim(), false);
86 + assert.equal(
87 + state.alarm,
88 + fixedTime + DAY,
89 + 'a duplicate must not extend retention'
90 + );
91 + current += 1;
92 + assert.equal(await claim(), true);
93 + assert.equal(state.alarm, fixedTime + 2 * DAY);
94 + await new ApprovalReplayGuard(state).alarm();
95 + assert.equal(
96 + await claim(),
97 + false,
98 + 'a delayed old alarm must not delete a renewed claim'
99 + );
100 + current += DAY;
101 + await new ApprovalReplayGuard(state).alarm();
102 + assert.equal(state.data.size, 0);
103 + assert.equal(state.alarm, null);
104 + } finally {
105 + Date.now = previousNow;
106 + }
107 +});
108 +
109 +test('concurrent deliveries have one durable claim winner', async () => {
110 + const namespace = makeReplayNamespace();
111 + const results = await Promise.all(
112 + Array.from({ length: 12 }, () =>
113 + consume({ namespace, botId: '12345', updateId: 8 })
114 + )
115 + );
116 + assert.equal(results.filter(Boolean).length, 1);
117 +});
118 +
119 +test('different bots and approval nonces do not share webhook claims', async () => {
120 + const namespace = makeReplayNamespace();
121 + for (const botId of ['12345', '67890'])
122 + assert.equal(await consume({ namespace, botId, updateId: 7 }), true);
123 + const approval = await namespace.get(namespace.idFromName('12345:7')).fetch(
124 + new Request('https://approval-replay/consume', {
125 + method: 'POST',
126 + body: JSON.stringify({ expiresAt: Date.now() + 60_000 })
127 + })
128 + );
129 + assert.equal(approval.status, 200);
130 +});
131 +
132 +test('invalid update ids cannot allocate durable objects', async () => {
133 + assert.equal(typeof module.consumeTelegramUpdate, 'function');
134 + let calls = 0;
135 + const namespace = {
136 + idFromName() {
137 + calls++;
138 + },
139 + get() {
140 + calls++;
141 + }
142 + };
143 + for (const updateId of [
144 + undefined,
145 + null,
146 + '1',
147 + -1,
148 + 1.5,
149 + NaN,
150 + Infinity,
151 + Number.MAX_SAFE_INTEGER + 1
152 + ]) {
153 + await assert.rejects(
154 + async () => consume({ namespace, botId: '12345', updateId }),
155 + /update|integer/i
156 + );
157 + }
158 + assert.equal(calls, 0);
159 +});
160 +
161 +test('guard configuration and unexpected replies fail closed', async () => {
162 + await assert.rejects(
163 + async () => consume({ botId: '12345', updateId: 1 }),
164 + /configured/i
165 + );
166 + for (const response of [
167 + Response.json({}),
168 + Response.json({ accepted: true }, { status: 500 }),
169 + Response.json({ accepted: false }, { status: 409 })
170 + ]) {
171 + const namespace = {
172 + idFromName: (name) => name,
173 + get: () => ({ fetch: async () => response })
174 + };
175 + await assert.rejects(
176 + async () => consume({ namespace, botId: '12345', updateId: 1 }),
177 + /guard|claim/i
178 + );
179 + }
180 +});
181 +
182 +test('bot identities survive token rotation and nonstandard tokens are hashed', async () => {
183 + assert.equal(await identity('12345:old-secret'), '12345');
184 + assert.equal(await identity('12345:new-secret'), '12345');
185 + const hashed = await identity('nonstandard-test-secret');
186 + assert.match(hashed, /^sha256:[a-f0-9]{64}$/);
187 + assert.equal(await identity('nonstandard-test-secret'), hashed);
188 + assert.notEqual(await identity('another-test-secret'), hashed);
189 + assert.doesNotMatch(hashed, /nonstandard|test-secret/);
190 +});
191 +
192 +test('claim expiry and cleanup alarm roll back together when alarm scheduling fails', async () => {
193 + assert.equal(typeof module.consumeTelegramUpdate, 'function');
194 + const state = makeReplayState({ failAlarm: true });
195 + const namespace = {
196 + idFromName: (name) => name,
197 + get: () => ({
198 + fetch: (request) => new ApprovalReplayGuard(state).fetch(request)
199 + })
200 + };
201 + await assert.rejects(async () =>
202 + consume({ namespace, botId: '12345', updateId: 1 })
203 + );
204 + assert.equal(state.data.size, 0);
205 +});
206 +
207 +test('webhook duplicate and concurrent deliveries produce only one bot response', async () => {
208 + const originalFetch = globalThis.fetch;
209 + let effects = 0;
210 + globalThis.fetch = async () => {
211 + effects++;
212 + return Response.json({ ok: true, result: { message_id: 9 } });
213 + };
214 + try {
215 + const runtime = env();
216 + const responses = await Promise.all(
217 + Array.from({ length: 5 }, () =>
218 + worker.fetch(webhook(ownerUpdate()), runtime)
219 + )
220 + );
221 + assert.ok(responses.every((response) => response.status === 200));
222 + const bodies = await Promise.all(
223 + responses.map((response) => response.json())
224 + );
225 + assert.equal(effects, 1);
226 + assert.equal(bodies.filter((body) => body.duplicate === true).length, 4);
227 + } finally {
228 + globalThis.fetch = originalFetch;
229 + }
230 +});
231 +
232 +test('webhook rejects malformed JSON and invalid update ids before side effects', async () => {
233 + const originalFetch = globalThis.fetch;
234 + let effects = 0;
235 + globalThis.fetch = async () => {
236 + effects++;
237 + throw new Error('must not execute');
238 + };
239 + try {
240 + for (const update of [
241 + '{',
242 + { ...ownerUpdate(), update_id: undefined },
243 + ownerUpdate('7'),
244 + ownerUpdate(-1)
245 + ]) {
246 + assert.equal((await worker.fetch(webhook(update), env())).status, 400);
247 + }
248 + assert.equal(effects, 0);
249 + } finally {
250 + globalThis.fetch = originalFetch;
251 + }
252 +});
253 +
254 +test('owner updates fail closed if the durable guard is absent or unavailable', async () => {
255 + const originalFetch = globalThis.fetch;
256 + const originalError = console.error;
257 + let effects = 0;
258 + globalThis.fetch = async () => {
259 + effects++;
260 + return Response.json({ ok: true });
261 + };
262 + console.error = () => {};
263 + try {
264 + for (const namespace of [
265 + null,
266 + {
267 + idFromName: (name) => name,
268 + get: () => ({
269 + fetch: async () => {
270 + throw new Error('private provider text');
271 + }
272 + })
273 + }
274 + ]) {
275 + assert.equal(
276 + (await worker.fetch(webhook(ownerUpdate()), env(namespace))).status,
277 + 503
278 + );
279 + }
280 + assert.equal(effects, 0);
281 + } finally {
282 + globalThis.fetch = originalFetch;
283 + console.error = originalError;
284 + }
285 +});
286 +
287 +test('nonowner updates do not claim durable keys or execute the bot', async () => {
288 + let claims = 0;
289 + const namespace = {
290 + idFromName() {
291 + claims++;
292 + throw new Error('must not claim');
293 + },
294 + get() {
295 + claims++;
296 + }
297 + };
298 + const update = ownerUpdate();
299 + update.message.from.id = 999;
300 + const response = await worker.fetch(webhook(update), env(namespace));
301 + assert.equal(response.status, 200);
302 + assert.equal((await response.json()).ignored, true);
303 + assert.equal(claims, 0);
304 +});
305 +
306 +test('claimed handler failures acknowledge once and log only fixed metadata', async () => {
307 + const originalFetch = globalThis.fetch;
308 + const originalError = console.error;
309 + const logs = [];
310 + let effects = 0;
311 + const privateText =
312 + 'private draft github_pat_unconfigured-token upstream error';
313 + globalThis.fetch = async () => {
314 + effects++;
315 + throw new Error(privateText);
316 + };
317 + console.error = (...values) => logs.push(values.map(String).join(' '));
318 + try {
319 + const runtime = env();
320 + const response = await worker.fetch(webhook(ownerUpdate()), runtime);
321 + assert.equal(response.status, 200);
322 + assert.deepEqual(await response.json(), {
323 + ok: false,
324 + processed_error: true,
325 + error: 'Telegram webhook processing failed'
326 + });
327 + const retry = await worker.fetch(webhook(ownerUpdate()), runtime);
328 + assert.equal(retry.status, 200);
329 + assert.equal((await retry.json()).duplicate, true);
330 + assert.equal(effects, 1);
331 + assert.equal(logs.length, 1);
332 + assert.match(logs[0], /telegram_webhook_error/);
333 + assert.doesNotMatch(logs.join('\n'), /private|github_pat_|upstream|draft/);
334 + } finally {
335 + globalThis.fetch = originalFetch;
336 + console.error = originalError;
337 + }
338 +});
339 +
340 +test('handled bot failures cannot return provider or source text from the webhook', async () => {
341 + const originalHandleUpdate =
342 + KillSwitchGuidedNexaDevBot.prototype.handleUpdate;
343 + const originalError = console.error;
344 + const logs = [];
345 + KillSwitchGuidedNexaDevBot.prototype.handleUpdate = async () => ({
346 + ok: false,
347 + error: 'private draft provider error'
348 + });
349 + console.error = (...values) => logs.push(values.map(String).join(' '));
350 + try {
351 + const response = await worker.fetch(webhook(ownerUpdate()), env());
352 + assert.equal(response.status, 200);
353 + assert.deepEqual(await response.json(), {
354 + ok: false,
355 + processed_error: true,
356 + error: 'Telegram webhook processing failed'
357 + });
358 + assert.equal(logs.length, 1);
359 + assert.doesNotMatch(logs.join('\n'), /private|draft|provider/);
360 + } finally {
361 + KillSwitchGuidedNexaDevBot.prototype.handleUpdate = originalHandleUpdate;
362 + console.error = originalError;
363 + }
364 +});
test/worker-health-version.test.js new
+34
@@ -0,0 +1,34 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFile } from 'node:fs/promises';
4 +import worker from '../src/index.js';
5 +
6 +test('/health reveals only ok, without release or runtime metadata', async () => {
7 + const response = await worker.fetch(
8 + new Request('https://example.test/health'),
9 + {}
10 + );
11 + assert.equal(response.status, 200);
12 + assert.equal(await response.text(), 'ok');
13 + assert.equal(response.headers.get('cache-control'), 'no-store');
14 +});
15 +
16 +test('/status and / use the package release version', async () => {
17 + const metadata = JSON.parse(
18 + await readFile(new URL('../package.json', import.meta.url), 'utf8')
19 + );
20 + for (const route of ['/', '/status']) {
21 + const response = await worker.fetch(
22 + new Request(`https://example.test${route}`),
23 + {}
24 + );
25 + const body = await response.json();
26 + assert.equal(body.version, metadata.version);
27 + assert.deepEqual(Object.keys(body).sort(), [
28 + 'bot',
29 + 'mode',
30 + 'status',
31 + 'version'
32 + ]);
33 + }
34 +});