Personal Telegram developer console for GitHub

test: define Mini App workspace editor behavior

davoodmehraban89 committed Oct 4, 2026 at 11:09 UTC 82fa5411416d68c2800b8900b212fdd10080a560
1 file changed +203
test/workspace-editor-v2.test.js new
+203
@@ -0,0 +1,203 @@
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 +});