Personal Telegram developer console for GitHub

phase2-20261005-n
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 203 lines 7.07 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { validateEditableFile } from '../src/core/workspace-policy.js';
4 import { createWorkspaceController } from '../src/plugins/github/workspace.js';
5
6 const encoder = new TextEncoder();
7
8 async function loadWebAppAuth() {
9 try {
10 return await import('../src/core/telegram-webapp-auth.js');
11 } catch {
12 return {};
13 }
14 }
15
16 async function loadWorkspaceEditor() {
17 try {
18 return await import('../src/workspace-editor.js');
19 } catch {
20 return {};
21 }
22 }
23
24 async function hmacSha256(keyBytes, value) {
25 const key = await crypto.subtle.importKey(
26 'raw',
27 keyBytes,
28 { name: 'HMAC', hash: 'SHA-256' },
29 false,
30 ['sign']
31 );
32 return new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(value)));
33 }
34
35 const hex = bytes => Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
36
37 async function signedInitData({ botToken, userId, authDate }) {
38 const fields = new URLSearchParams({
39 auth_date: String(authDate),
40 query_id: 'AAE-test-query',
41 user: JSON.stringify({ id: userId, first_name: 'Owner' })
42 });
43 const dataCheckString = [...fields.entries()]
44 .sort(([a], [b]) => a.localeCompare(b))
45 .map(([key, value]) => `${key}=${value}`)
46 .join('\n');
47 const secretKey = await hmacSha256(encoder.encode('WebAppData'), botToken);
48 const signature = await hmacSha256(secretKey, dataCheckString);
49 fields.set('hash', hex(signature));
50 return fields.toString();
51 }
52
53 test('README-sized Markdown is editable while the expanded editor ceiling remains bounded', () => {
54 const readme = `# Nexa Dev Bot\n\n${'x'.repeat(8200)}`;
55 const accepted = validateEditableFile({ path: 'README.md', text: readme });
56 assert.equal(accepted.editable, true, accepted.reason);
57
58 const tooManyChars = validateEditableFile({ path: 'README.md', text: 'x'.repeat(20001) });
59 assert.equal(tooManyChars.editable, false);
60 assert.match(tooManyChars.reason, /20,000|20000/);
61
62 const tooManyBytes = validateEditableFile({ path: 'README.md', text: 'ok', byteLength: 65537 });
63 assert.equal(tooManyBytes.editable, false);
64 assert.match(tooManyBytes.reason, /65,536|65536/);
65 });
66
67 test('Workspace view exposes a real Telegram Web App editor instead of primary ForceReply paste', async () => {
68 const workspaces = {
69 async getWorkspace() {
70 return {
71 id: 'W000000001',
72 repoId: 123,
73 path: 'README.md',
74 state: 'DRAFT',
75 baseHeadSha: 'a'.repeat(40),
76 originalText: '# before\n',
77 draftText: '# before\n',
78 commitMessage: ''
79 };
80 }
81 };
82 const controller = createWorkspaceController({
83 github: {},
84 workspaces,
85 editorUrl: 'https://example.com/workspace/editor'
86 });
87 const view = await controller.resolveCallback('ws:W000000001', { ownerId: '42' }).execute();
88 const buttons = view.reply_markup.inline_keyboard.flat();
89 const editor = buttons.find(button => button.web_app?.url);
90 assert.ok(editor, 'Workspace must include a web_app editor button');
91 assert.equal(editor.web_app.url, 'https://example.com/workspace/editor?workspaceId=W000000001');
92 assert.doesNotMatch(editor.text, /Paste/i);
93 assert.equal(buttons.some(button => button.callback_data === 'wtext:W000000001'), false);
94 });
95
96 test('Telegram Mini App initData validation is owner-bound, tamper-resistant and freshness-bounded', async () => {
97 const auth = await loadWebAppAuth();
98 assert.equal(typeof auth.validateTelegramWebAppInitData, 'function', 'Mini App auth helper must exist');
99 const botToken = '123456:TEST_ONLY_TOKEN';
100 const nowSeconds = 1_800_000_000;
101 const initData = await signedInitData({ botToken, userId: 42, authDate: nowSeconds - 30 });
102
103 const valid = await auth.validateTelegramWebAppInitData(initData, {
104 botToken,
105 ownerId: '42',
106 now: () => nowSeconds * 1000,
107 maxAgeSeconds: 3600
108 });
109 assert.equal(valid.userId, '42');
110 assert.equal(valid.authDate, nowSeconds - 30);
111
112 await assert.rejects(
113 () => auth.validateTelegramWebAppInitData(initData.replace('Owner', 'Intruder'), {
114 botToken,
115 ownerId: '42',
116 now: () => nowSeconds * 1000,
117 maxAgeSeconds: 3600
118 }),
119 /signature|hash|invalid/i
120 );
121
122 await assert.rejects(
123 () => auth.validateTelegramWebAppInitData(initData, {
124 botToken,
125 ownerId: '99',
126 now: () => nowSeconds * 1000,
127 maxAgeSeconds: 3600
128 }),
129 /owner|forbidden/i
130 );
131
132 const stale = await signedInitData({ botToken, userId: 42, authDate: nowSeconds - 7200 });
133 await assert.rejects(
134 () => auth.validateTelegramWebAppInitData(stale, {
135 botToken,
136 ownerId: '42',
137 now: () => nowSeconds * 1000,
138 maxAgeSeconds: 3600
139 }),
140 /expired|stale|auth_date/i
141 );
142 });
143
144 test('Workspace editor HTTP handler loads and saves only the durable draft and never performs a provider write', async () => {
145 const editorModule = await loadWorkspaceEditor();
146 assert.equal(typeof editorModule.handleWorkspaceEditorRequest, 'function', 'Workspace editor HTTP handler must exist');
147 assert.equal(typeof editorModule.renderWorkspaceEditorPage, 'function', 'Workspace editor page renderer must exist');
148
149 const botToken = '123456:TEST_ONLY_TOKEN';
150 const nowSeconds = 1_800_000_000;
151 const initData = await signedInitData({ botToken, userId: 42, authDate: nowSeconds - 10 });
152 const calls = [];
153 const workspaces = {
154 async getWorkspace({ ownerId, workspaceId }) {
155 calls.push(['getWorkspace', ownerId, workspaceId]);
156 return {
157 id: workspaceId,
158 path: 'README.md',
159 state: 'DRAFT',
160 originalText: '# old\n',
161 draftText: '# old\n'
162 };
163 },
164 async updateDraft({ ownerId, workspaceId, text, digest }) {
165 calls.push(['updateDraft', ownerId, workspaceId, text, digest]);
166 return { id: workspaceId, path: 'README.md', state: 'DRAFT', draftText: text };
167 }
168 };
169 const context = {
170 workspaces,
171 botToken,
172 ownerId: '42',
173 now: () => nowSeconds * 1000
174 };
175 const headers = { 'x-telegram-init-data': initData };
176
177 const getResponse = await editorModule.handleWorkspaceEditorRequest(
178 new Request('https://example.com/workspace/api/editor?workspaceId=W000000001', { headers }),
179 context
180 );
181 assert.equal(getResponse.status, 200);
182 assert.equal(getResponse.headers.get('cache-control'), 'no-store');
183 const loaded = await getResponse.json();
184 assert.equal(loaded.workspace.path, 'README.md');
185 assert.equal(loaded.workspace.draftText, '# old\n');
186
187 const putResponse = await editorModule.handleWorkspaceEditorRequest(
188 new Request('https://example.com/workspace/api/editor', {
189 method: 'PUT',
190 headers: { ...headers, 'content-type': 'application/json' },
191 body: JSON.stringify({ workspaceId: 'W000000001', text: '# new\n' })
192 }),
193 context
194 );
195 assert.equal(putResponse.status, 200);
196 assert.equal(calls.filter(call => call[0] === 'updateDraft').length, 1);
197 assert.equal(calls.find(call => call[0] === 'updateDraft')[3], '# new\n');
198
199 const html = editorModule.renderWorkspaceEditorPage();
200 assert.match(html, /<textarea/i);
201 assert.match(html, /Telegram\.WebApp/i);
202 assert.match(html, /ذخیره|Save/i);
203 });