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 368 lines 15.6 KB
Raw
1 import {
2 WORKSPACE_EDITOR_LIMITS,
3 buildWorkspaceDiff,
4 digestText,
5 validateEditableFile
6 } from './core/workspace-policy.js';
7 import { validateTelegramWebAppInitData } from './core/telegram-webapp-auth.js';
8 import { readBoundedJson } from './core/bounded-json.js';
9
10 const WORKSPACE_ID = /^[A-Za-z0-9_-]{10}$/;
11
12 const jsonResponse = (payload, status = 200) =>
13 new Response(JSON.stringify(payload), {
14 status,
15 headers: {
16 'content-type': 'application/json; charset=utf-8',
17 'cache-control': 'no-store'
18 }
19 });
20
21 function safeWorkspaceId(value) {
22 const id = String(value || '');
23 if (!WORKSPACE_ID.test(id)) throw new Error('Workspace ID is invalid');
24 return id;
25 }
26
27 function statusForError(error) {
28 const message = String(error?.message || '');
29 if (/signature|hash|auth_date|owner|initData|user/i.test(message)) return 403;
30 if (/not found|expired/i.test(message)) return 404;
31 if (/limited|not editable|binary|LFS|sensitive/i.test(message)) return 422;
32 if (/invalid|required|JSON|body|path|member|Change Set/i.test(message))
33 return 400;
34 return 500;
35 }
36
37 export async function handleWorkspaceEditorRequest(
38 request,
39 { workspaces, github, botToken, ownerId, now = () => Date.now() } = {}
40 ) {
41 try {
42 if (!workspaces)
43 throw new Error('Durable workspace store is not configured');
44 const initData = request.headers.get('x-telegram-init-data') || '';
45 const identity = await validateTelegramWebAppInitData(initData, {
46 botToken,
47 ownerId,
48 now,
49 maxAgeSeconds: 3600
50 });
51 const owner = identity.userId;
52 const url = new URL(request.url);
53
54 if (request.method === 'GET') {
55 const refId = url.searchParams.get('refId');
56 if (refId !== null) {
57 const ref = await workspaces.resolveNavigationRef({
58 ownerId: owner,
59 refId: safeWorkspaceId(refId)
60 });
61 if (!ref || ref.type !== 'file')
62 throw new Error('File reference not found or expired');
63 if (!github) throw new Error('File preview service is not configured');
64 let snapshot, file;
65 try {
66 const repo = await github.getRepository(ref.repoId);
67 snapshot = await github.getBranchSnapshot(
68 ref.repoId,
69 repo.defaultBranch
70 );
71 file = await github.getFileAtRef(
72 ref.repoId,
73 ref.path,
74 snapshot.headSha
75 );
76 } catch {
77 throw new Error('File preview provider request failed');
78 }
79 const policy = validateEditableFile({
80 path: file.path,
81 text: file.content,
82 byteLength: file.size
83 });
84 if (!policy.editable)
85 return jsonResponse(
86 {
87 ok: false,
88 error: 'این فایل برای نمایش امن در Mini App مجاز نیست.'
89 },
90 422
91 );
92 return jsonResponse({
93 workspace: {
94 path: file.path,
95 files: [{ path: file.path }],
96 draftText: policy.text,
97 state: 'READ_ONLY',
98 readOnly: true,
99 baseHeadSha: snapshot.headSha.slice(0, 10)
100 },
101 limits: WORKSPACE_EDITOR_LIMITS
102 });
103 }
104 const workspaceId = safeWorkspaceId(url.searchParams.get('workspaceId'));
105 const workspace = await workspaces.getWorkspace({
106 ownerId: owner,
107 workspaceId
108 });
109 if (!workspace) throw new Error('Workspace not found or expired');
110 const files =
111 Array.isArray(workspace.files) && workspace.files.length
112 ? workspace.files
113 : [
114 {
115 path: workspace.path,
116 originalText: workspace.originalText,
117 draftText: workspace.draftText
118 }
119 ];
120 if (url.searchParams.get('view') === 'diff') {
121 return jsonResponse({
122 workspace: {
123 id: workspace.id,
124 path: workspace.path || files[0].path,
125 state: workspace.state || 'DRAFT',
126 readOnly: true,
127 files: files.map((file) => ({ path: file.path }))
128 },
129 diff: buildWorkspaceDiff({ files, maxChars: 10000 }),
130 limits: WORKSPACE_EDITOR_LIMITS
131 });
132 }
133 const requestedPath = String(
134 url.searchParams.get('path') || workspace.path || files[0].path
135 );
136 const selected = files.find((file) => file.path === requestedPath);
137 if (!selected)
138 throw new Error('Editor path is not a member of this Change Set');
139 return jsonResponse({
140 workspace: {
141 id: workspace.id,
142 path: selected.path,
143 files: files.map((file) => ({ path: file.path })),
144 state: workspace.state || 'DRAFT',
145 baseHeadSha: String(workspace.baseHeadSha || '').slice(0, 10),
146 draftText: String(selected.draftText ?? '')
147 },
148 limits: WORKSPACE_EDITOR_LIMITS
149 });
150 }
151
152 if (request.method === 'PUT') {
153 let body;
154 try {
155 body = await readBoundedJson(
156 request,
157 WORKSPACE_EDITOR_LIMITS.maxBytes + 4096
158 );
159 } catch (error) {
160 if (error instanceof RangeError)
161 return jsonResponse(
162 { ok: false, error: 'Editor request body is too large' },
163 413
164 );
165 if (error instanceof SyntaxError)
166 return jsonResponse(
167 { ok: false, error: 'Editor request body must be valid JSON' },
168 400
169 );
170 throw error;
171 }
172 const workspaceId = safeWorkspaceId(body?.workspaceId);
173 const workspace = await workspaces.getWorkspace({
174 ownerId: owner,
175 workspaceId
176 });
177 if (!workspace) throw new Error('Workspace not found or expired');
178 const files =
179 Array.isArray(workspace.files) && workspace.files.length
180 ? workspace.files
181 : [{ path: workspace.path, draftText: workspace.draftText }];
182 const requestedPath = String(
183 body?.path || workspace.path || files[0].path
184 );
185 const selected = files.find((file) => file.path === requestedPath);
186 if (!selected)
187 throw new Error('Editor path is not a member of this Change Set');
188 const policy = validateEditableFile({
189 path: selected.path,
190 text: body?.text
191 });
192 if (!policy.editable)
193 return jsonResponse({ ok: false, error: policy.reason }, 422);
194 const digest = await digestText(policy.text);
195 const updated =
196 typeof workspaces.updateWorkspaceFileDraft === 'function'
197 ? await workspaces.updateWorkspaceFileDraft({
198 ownerId: owner,
199 workspaceId,
200 path: selected.path,
201 text: policy.text,
202 digest
203 })
204 : await workspaces.updateDraft({
205 ownerId: owner,
206 workspaceId,
207 text: policy.text,
208 digest
209 });
210 return jsonResponse({
211 ok: true,
212 workspace: {
213 id: updated?.id || workspaceId,
214 path: selected.path,
215 state: updated?.state || 'DRAFT',
216 charLength: policy.charLength,
217 byteLength: policy.byteLength
218 }
219 });
220 }
221
222 return jsonResponse({ ok: false, error: 'Method not allowed' }, 405);
223 } catch (error) {
224 if (error?.code === 'DIFF_COMPLEXITY_LIMIT')
225 return jsonResponse(
226 {
227 ok: false,
228 code: error.code,
229 error:
230 'تغییرات برای محاسبهٔ امن Diff پیچیده‌اند؛ فایل‌ها را در تغییرهای کوچک‌تر ویرایش کنید.'
231 },
232 422
233 );
234 const status = statusForError(error);
235 return jsonResponse(
236 {
237 ok: false,
238 error:
239 status === 500
240 ? 'Workspace editor request failed'
241 : String(error?.message || 'Workspace editor request failed')
242 },
243 status
244 );
245 }
246 }
247
248 export function renderWorkspaceEditorPage() {
249 return `<!doctype html>
250 <html lang="fa" dir="rtl">
251 <head>
252 <meta charset="utf-8">
253 <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
254 <meta name="color-scheme" content="light dark">
255 <title>Nexa Workspace Editor</title>
256 <script src="https://telegram.org/js/telegram-web-app.js"></script>
257 <style>
258 :root{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color-scheme:light dark}
259 *{box-sizing:border-box}body{margin:0;background:var(--tg-theme-bg-color,#111827);color:var(--tg-theme-text-color,#f9fafb)}
260 main{min-height:100vh;display:flex;flex-direction:column;gap:10px;padding:12px max(12px,env(safe-area-inset-right)) calc(12px + env(safe-area-inset-bottom)) max(12px,env(safe-area-inset-left))}
261 .meta{display:flex;justify-content:space-between;gap:10px;align-items:center;font-size:13px}.path{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;direction:ltr;text-align:left}
262 textarea{width:100%;flex:1;min-height:58vh;resize:none;border:1px solid var(--tg-theme-hint-color,#6b7280);border-radius:10px;padding:12px;background:var(--tg-theme-secondary-bg-color,#1f2937);color:var(--tg-theme-text-color,#f9fafb);font:14px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;direction:ltr;text-align:left;tab-size:2;white-space:pre;overflow:auto}
263 .status{min-height:22px;font-size:13px;color:var(--tg-theme-hint-color,#9ca3af)}.status.error{color:#ef4444}.status.ok{color:#22c55e}
264 .actions{display:grid;grid-template-columns:1fr 1fr;gap:8px}.actions button{border:0;border-radius:10px;padding:12px;font-weight:700;cursor:pointer}.primary{background:var(--tg-theme-button-color,#2563eb);color:var(--tg-theme-button-text-color,#fff)}.secondary{background:var(--tg-theme-secondary-bg-color,#374151);color:var(--tg-theme-text-color,#fff)}
265 </style>
266 </head>
267 <body>
268 <main>
269 <div class="meta"><strong>🧑‍💻 Workspace Editor</strong><span id="counter">—</span></div>
270 <select id="files" aria-label="فایل Change Set" disabled></select>
271 <div id="path" class="path">در حال بارگذاری…</div>
272 <textarea id="editor" spellcheck="false" autocapitalize="off" autocomplete="off" disabled></textarea>
273 <div id="status" class="status">در حال اتصال امن به Workspace…</div>
274 <div class="actions"><button id="save" class="primary" disabled>💾 ذخیره Draft</button><button id="close" class="secondary">↩️ بازگشت به ربات</button></div>
275 </main>
276 <script>
277 (() => {
278 const tg = window.Telegram && window.Telegram.WebApp;
279 const editor = document.getElementById('editor');
280 const status = document.getElementById('status');
281 const path = document.getElementById('path');
282 const files = document.getElementById('files');
283 const counter = document.getElementById('counter');
284 const save = document.getElementById('save');
285 const close = document.getElementById('close');
286 const params = new URLSearchParams(location.search);
287 const workspaceId = params.get('workspaceId') || '';
288 const refId = params.get('refId') || '';
289 const diffMode = params.get('view') === 'diff';
290 let readOnly = false;
291 const byteLength = value => new TextEncoder().encode(value).byteLength;
292 const codePoints = value => Array.from(value).length;
293 let limits = ${JSON.stringify(WORKSPACE_EDITOR_LIMITS)};
294
295 function setStatus(message, kind='') { status.textContent = message; status.className = 'status' + (kind ? ' ' + kind : ''); }
296 function updateCounter() {
297 const chars = codePoints(editor.value); const bytes = byteLength(editor.value);
298 counter.textContent = chars.toLocaleString() + ' / ' + limits.maxChars.toLocaleString() + ' · ' + bytes.toLocaleString() + ' B / ' + limits.maxBytes.toLocaleString() + ' B';
299 const valid = chars <= limits.maxChars && bytes <= limits.maxBytes;
300 save.disabled = readOnly || !valid || editor.disabled;
301 if (!valid) setStatus('محتوا از سقف امن Editor بیشتر است.', 'error');
302 }
303 async function api(url, options={}) {
304 const headers = Object.assign({}, options.headers || {}, { 'x-telegram-init-data': tg ? tg.initData : '' });
305 const response = await fetch(url, Object.assign({}, options, { headers }));
306 const body = await response.json().catch(() => ({}));
307 if (!response.ok) throw new Error(body.error || ('HTTP ' + response.status));
308 return body;
309 }
310 async function load() {
311 if (!tg || !tg.initData) throw new Error('این Editor باید از داخل Telegram باز شود.');
312 tg.ready(); tg.expand();
313 if (!/^[A-Za-z0-9_-]{10}$/.test(refId || workspaceId)) throw new Error('Workspace نامعتبر است.');
314 const selectedPath = params.get('path') || '';
315 const query = refId ? 'refId=' + encodeURIComponent(refId) : 'workspaceId=' + encodeURIComponent(workspaceId) + (selectedPath ? '&path=' + encodeURIComponent(selectedPath) : '') + (diffMode ? '&view=diff' : '');
316 const body = await api('/workspace/api/editor?' + query);
317 limits = body.limits || limits;
318 // Never interpolate repository-controlled paths into HTML.
319 files.replaceChildren();
320 for (const file of (body.workspace.files || [{path:body.workspace.path}])) {
321 const option = document.createElement('option');
322 option.value = file.path;
323 option.textContent = file.path;
324 files.appendChild(option);
325 }
326 files.value = body.workspace.path; files.disabled = false;
327 path.textContent = body.workspace.path;
328 readOnly = body.workspace.readOnly === true;
329 editor.readOnly = readOnly;
330 save.hidden = readOnly;
331 editor.value = body.diff ? body.diff.text : body.workspace.draftText || '';
332 editor.disabled = false;
333 setStatus(body.diff ? ('Diff · +' + body.diff.additions + ' / -' + body.diff.deletions + (body.diff.truncated ? ' · نمایش کوتاه شده است.' : '')) : readOnly ? 'نمایش فقط‌خواندنی؛ هیچ Draft یا Commit ساخته نشده است.' : 'Draft محلی آماده ویرایش است؛ تا قبل از Safe Approval هیچ تغییری در GitHub انجام نمی‌شود.');
334 updateCounter();
335 }
336 editor.addEventListener('input', updateCounter);
337 files.addEventListener('change', () => { params.set('path', files.value); location.search = params.toString(); });
338 save.addEventListener('click', async () => {
339 if (readOnly) return;
340 save.disabled = true; setStatus('در حال ذخیره Draft…');
341 try {
342 await api('/workspace/api/editor', { method:'PUT', headers:{'content-type':'application/json'}, body:JSON.stringify({workspaceId, path:files.value, text:editor.value}) });
343 setStatus('Draft ذخیره شد. برای Diff و Commit به ربات برگردید.', 'ok');
344 updateCounter();
345 if (tg && tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success');
346 } catch (error) { setStatus(error.message || 'ذخیره Draft ناموفق بود.', 'error'); updateCounter(); }
347 });
348 close.addEventListener('click', () => { if (tg) tg.close(); else history.back(); });
349 load().catch(error => { editor.disabled = true; save.disabled = true; setStatus(error.message || 'Editor قابل استفاده نیست.', 'error'); });
350 })();
351 </script>
352 </body>
353 </html>`;
354 }
355
356 export function workspaceEditorPageResponse() {
357 return new Response(renderWorkspaceEditorPage(), {
358 status: 200,
359 headers: {
360 'content-type': 'text/html; charset=utf-8',
361 'cache-control': 'no-store',
362 'x-content-type-options': 'nosniff',
363 'referrer-policy': 'no-referrer',
364 'content-security-policy':
365 "default-src 'none'; script-src 'unsafe-inline' https://telegram.org; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'"
366 }
367 });
368 }