Personal Telegram developer console for GitHub

fix/phase2-final-ux
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 218 lines 11.6 KB
Raw
1 import {
2 WORKSPACE_EDITOR_LIMITS,
3 digestText,
4 validateEditableFile
5 } from './core/workspace-policy.js';
6 import { validateTelegramWebAppInitData } from './core/telegram-webapp-auth.js';
7
8 const WORKSPACE_ID = /^[A-Za-z0-9_-]{10}$/;
9
10 const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
11 status,
12 headers: {
13 'content-type': 'application/json; charset=utf-8',
14 'cache-control': 'no-store'
15 }
16 });
17
18 function safeWorkspaceId(value) {
19 const id = String(value || '');
20 if (!WORKSPACE_ID.test(id)) throw new Error('Workspace ID is invalid');
21 return id;
22 }
23
24 function statusForError(error) {
25 const message = String(error?.message || '');
26 if (/signature|hash|auth_date|owner|initData|user/i.test(message)) return 403;
27 if (/not found|expired/i.test(message)) return 404;
28 if (/limited|not editable|binary|LFS|sensitive/i.test(message)) return 422;
29 if (/invalid|required|JSON|body|path|member|Change Set/i.test(message)) return 400;
30 return 500;
31 }
32
33 export async function handleWorkspaceEditorRequest(request, {
34 workspaces,
35 botToken,
36 ownerId,
37 now = () => Date.now()
38 } = {}) {
39 try {
40 if (!workspaces) throw new Error('Durable workspace store is not configured');
41 const initData = request.headers.get('x-telegram-init-data') || '';
42 const identity = await validateTelegramWebAppInitData(initData, {
43 botToken,
44 ownerId,
45 now,
46 maxAgeSeconds: 3600
47 });
48 const owner = identity.userId;
49 const url = new URL(request.url);
50
51 if (request.method === 'GET') {
52 const workspaceId = safeWorkspaceId(url.searchParams.get('workspaceId'));
53 const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId });
54 if (!workspace) throw new Error('Workspace not found or expired');
55 const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }];
56 const requestedPath = String(url.searchParams.get('path') || workspace.path || files[0].path);
57 const selected = files.find(file => file.path === requestedPath);
58 if (!selected) throw new Error('Editor path is not a member of this Change Set');
59 return jsonResponse({
60 workspace: {
61 id: workspace.id,
62 path: selected.path,
63 files: files.map(file => ({ path: file.path })),
64 state: workspace.state || 'DRAFT',
65 baseHeadSha: String(workspace.baseHeadSha || '').slice(0, 10),
66 draftText: String(selected.draftText ?? '')
67 },
68 limits: WORKSPACE_EDITOR_LIMITS
69 });
70 }
71
72 if (request.method === 'PUT') {
73 const contentLength = Number(request.headers.get('content-length'));
74 if (Number.isFinite(contentLength) && contentLength > WORKSPACE_EDITOR_LIMITS.maxBytes + 4096) {
75 return jsonResponse({ ok: false, error: 'Editor request body is too large' }, 413);
76 }
77 let body;
78 try {
79 body = await request.json();
80 } catch {
81 throw new Error('Editor request body must be valid JSON');
82 }
83 const workspaceId = safeWorkspaceId(body?.workspaceId);
84 const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId });
85 if (!workspace) throw new Error('Workspace not found or expired');
86 const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }];
87 const requestedPath = String(body?.path || workspace.path || files[0].path);
88 const selected = files.find(file => file.path === requestedPath);
89 if (!selected) throw new Error('Editor path is not a member of this Change Set');
90 const policy = validateEditableFile({ path: selected.path, text: body?.text });
91 if (!policy.editable) return jsonResponse({ ok: false, error: policy.reason }, 422);
92 const digest = await digestText(policy.text);
93 const updated = typeof workspaces.updateWorkspaceFileDraft === 'function'
94 ? await workspaces.updateWorkspaceFileDraft({ ownerId: owner, workspaceId, path: selected.path, text: policy.text, digest })
95 : await workspaces.updateDraft({ ownerId: owner, workspaceId, text: policy.text, digest });
96 return jsonResponse({
97 ok: true,
98 workspace: {
99 id: updated?.id || workspaceId,
100 path: selected.path,
101 state: updated?.state || 'DRAFT',
102 charLength: policy.charLength,
103 byteLength: policy.byteLength
104 }
105 });
106 }
107
108 return jsonResponse({ ok: false, error: 'Method not allowed' }, 405);
109 } catch (error) {
110 return jsonResponse({ ok: false, error: String(error?.message || 'Workspace editor request failed') }, statusForError(error));
111 }
112 }
113
114 export function renderWorkspaceEditorPage() {
115 return `<!doctype html>
116 <html lang="fa" dir="rtl">
117 <head>
118 <meta charset="utf-8">
119 <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
120 <meta name="color-scheme" content="light dark">
121 <title>Nexa Workspace Editor</title>
122 <script src="https://telegram.org/js/telegram-web-app.js"></script>
123 <style>
124 :root{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color-scheme:light dark}
125 *{box-sizing:border-box}body{margin:0;background:var(--tg-theme-bg-color,#111827);color:var(--tg-theme-text-color,#f9fafb)}
126 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))}
127 .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}
128 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}
129 .status{min-height:22px;font-size:13px;color:var(--tg-theme-hint-color,#9ca3af)}.status.error{color:#ef4444}.status.ok{color:#22c55e}
130 .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)}
131 </style>
132 </head>
133 <body>
134 <main>
135 <div class="meta"><strong>🧑‍💻 Workspace Editor</strong><span id="counter">—</span></div>
136 <select id="files" aria-label="فایل Change Set" disabled></select>
137 <div id="path" class="path">در حال بارگذاری…</div>
138 <textarea id="editor" spellcheck="false" autocapitalize="off" autocomplete="off" disabled></textarea>
139 <div id="status" class="status">در حال اتصال امن به Workspace…</div>
140 <div class="actions"><button id="save" class="primary" disabled>💾 ذخیره Draft</button><button id="close" class="secondary">↩️ بازگشت به ربات</button></div>
141 </main>
142 <script>
143 (() => {
144 const tg = window.Telegram && window.Telegram.WebApp;
145 const editor = document.getElementById('editor');
146 const status = document.getElementById('status');
147 const path = document.getElementById('path');
148 const files = document.getElementById('files');
149 const counter = document.getElementById('counter');
150 const save = document.getElementById('save');
151 const close = document.getElementById('close');
152 const params = new URLSearchParams(location.search);
153 const workspaceId = params.get('workspaceId') || '';
154 const byteLength = value => new TextEncoder().encode(value).byteLength;
155 const codePoints = value => Array.from(value).length;
156 let limits = { maxChars: 20000, maxBytes: 65536 };
157
158 function setStatus(message, kind='') { status.textContent = message; status.className = 'status' + (kind ? ' ' + kind : ''); }
159 function updateCounter() {
160 const chars = codePoints(editor.value); const bytes = byteLength(editor.value);
161 counter.textContent = chars.toLocaleString() + ' / ' + limits.maxChars.toLocaleString() + ' · ' + bytes.toLocaleString() + ' B / ' + limits.maxBytes.toLocaleString() + ' B';
162 const valid = chars <= limits.maxChars && bytes <= limits.maxBytes;
163 save.disabled = !valid || editor.disabled;
164 if (!valid) setStatus('محتوا از سقف امن Editor بیشتر است.', 'error');
165 }
166 async function api(url, options={}) {
167 const headers = Object.assign({}, options.headers || {}, { 'x-telegram-init-data': tg ? tg.initData : '' });
168 const response = await fetch(url, Object.assign({}, options, { headers }));
169 const body = await response.json().catch(() => ({}));
170 if (!response.ok) throw new Error(body.error || ('HTTP ' + response.status));
171 return body;
172 }
173 async function load() {
174 if (!tg || !tg.initData) throw new Error('این Editor باید از داخل Telegram باز شود.');
175 tg.ready(); tg.expand();
176 if (!/^[A-Za-z0-9_-]{10}$/.test(workspaceId)) throw new Error('Workspace نامعتبر است.');
177 const selectedPath = params.get('path') || '';
178 const body = await api('/workspace/api/editor?workspaceId=' + encodeURIComponent(workspaceId) + (selectedPath ? '&path=' + encodeURIComponent(selectedPath) : ''));
179 limits = body.limits || limits;
180 files.innerHTML = (body.workspace.files || [{path:body.workspace.path}]).map(file => '<option value="' + file.path.replaceAll('&','&amp;').replaceAll('"','&quot;') + '">' + file.path.replaceAll('&','&amp;').replaceAll('<','&lt;') + '</option>').join('');
181 files.value = body.workspace.path; files.disabled = false;
182 path.textContent = body.workspace.path;
183 editor.value = body.workspace.draftText || '';
184 editor.disabled = false;
185 setStatus('Draft محلی آماده ویرایش است؛ تا قبل از Safe Approval هیچ تغییری در GitHub انجام نمی‌شود.');
186 updateCounter();
187 }
188 editor.addEventListener('input', updateCounter);
189 files.addEventListener('change', () => { params.set('path', files.value); location.search = params.toString(); });
190 save.addEventListener('click', async () => {
191 save.disabled = true; setStatus('در حال ذخیره Draft…');
192 try {
193 await api('/workspace/api/editor', { method:'PUT', headers:{'content-type':'application/json'}, body:JSON.stringify({workspaceId, path:files.value, text:editor.value}) });
194 setStatus('Draft ذخیره شد. برای Diff و Commit به ربات برگردید.', 'ok');
195 updateCounter();
196 if (tg && tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success');
197 } catch (error) { setStatus(error.message || 'ذخیره Draft ناموفق بود.', 'error'); updateCounter(); }
198 });
199 close.addEventListener('click', () => { if (tg) tg.close(); else history.back(); });
200 load().catch(error => { editor.disabled = true; save.disabled = true; setStatus(error.message || 'Editor قابل استفاده نیست.', 'error'); });
201 })();
202 </script>
203 </body>
204 </html>`;
205 }
206
207 export function workspaceEditorPageResponse() {
208 return new Response(renderWorkspaceEditorPage(), {
209 status: 200,
210 headers: {
211 'content-type': 'text/html; charset=utf-8',
212 'cache-control': 'no-store',
213 'x-content-type-options': 'nosniff',
214 'referrer-policy': 'no-referrer',
215 'content-security-policy': "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'"
216 }
217 });
218 }