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