Personal Telegram developer console for GitHub
fix/editor-request-body-cap
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
| 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 | import { readBoundedJson } from './core/bounded-json.js'; |
| 8 | |
| 9 | const WORKSPACE_ID = /^[A-Za-z0-9_-]{10}$/; |
| 10 | |
| 11 | const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), { |
| 12 | status, |
| 13 | headers: { |
| 14 | 'content-type': 'application/json; charset=utf-8', |
| 15 | 'cache-control': 'no-store' |
| 16 | } |
| 17 | }); |
| 18 | |
| 19 | function safeWorkspaceId(value) { |
| 20 | const id = String(value || ''); |
| 21 | if (!WORKSPACE_ID.test(id)) throw new Error('Workspace ID is invalid'); |
| 22 | return id; |
| 23 | } |
| 24 | |
| 25 | function statusForError(error) { |
| 26 | const message = String(error?.message || ''); |
| 27 | if (/signature|hash|auth_date|owner|initData|user/i.test(message)) return 403; |
| 28 | if (/not found|expired/i.test(message)) return 404; |
| 29 | if (/limited|not editable|binary|LFS|sensitive/i.test(message)) return 422; |
| 30 | if (/invalid|required|JSON|body|path|member|Change Set/i.test(message)) return 400; |
| 31 | return 500; |
| 32 | } |
| 33 | |
| 34 | export async function handleWorkspaceEditorRequest(request, { |
| 35 | workspaces, |
| 36 | botToken, |
| 37 | ownerId, |
| 38 | now = () => Date.now() |
| 39 | } = {}) { |
| 40 | try { |
| 41 | if (!workspaces) throw new Error('Durable workspace store is not configured'); |
| 42 | const initData = request.headers.get('x-telegram-init-data') || ''; |
| 43 | const identity = await validateTelegramWebAppInitData(initData, { |
| 44 | botToken, |
| 45 | ownerId, |
| 46 | now, |
| 47 | maxAgeSeconds: 3600 |
| 48 | }); |
| 49 | const owner = identity.userId; |
| 50 | const url = new URL(request.url); |
| 51 | |
| 52 | if (request.method === 'GET') { |
| 53 | const workspaceId = safeWorkspaceId(url.searchParams.get('workspaceId')); |
| 54 | const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId }); |
| 55 | if (!workspace) throw new Error('Workspace not found or expired'); |
| 56 | const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }]; |
| 57 | const requestedPath = String(url.searchParams.get('path') || workspace.path || files[0].path); |
| 58 | const selected = files.find(file => file.path === requestedPath); |
| 59 | if (!selected) throw new Error('Editor path is not a member of this Change Set'); |
| 60 | return jsonResponse({ |
| 61 | workspace: { |
| 62 | id: workspace.id, |
| 63 | path: selected.path, |
| 64 | files: files.map(file => ({ path: file.path })), |
| 65 | state: workspace.state || 'DRAFT', |
| 66 | baseHeadSha: String(workspace.baseHeadSha || '').slice(0, 10), |
| 67 | draftText: String(selected.draftText ?? '') |
| 68 | }, |
| 69 | limits: WORKSPACE_EDITOR_LIMITS |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | if (request.method === 'PUT') { |
| 74 | let body; |
| 75 | try { |
| 76 | body = await readBoundedJson(request, WORKSPACE_EDITOR_LIMITS.maxBytes + 4096); |
| 77 | } catch (error) { |
| 78 | if (error instanceof RangeError) return jsonResponse({ ok: false, error: 'Editor request body is too large' }, 413); |
| 79 | if (error instanceof SyntaxError) return jsonResponse({ ok: false, error: 'Editor request body must be valid JSON' }, 400); |
| 80 | throw error; |
| 81 | } |
| 82 | const workspaceId = safeWorkspaceId(body?.workspaceId); |
| 83 | const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId }); |
| 84 | if (!workspace) throw new Error('Workspace not found or expired'); |
| 85 | const files = Array.isArray(workspace.files) && workspace.files.length ? workspace.files : [{ path: workspace.path, draftText: workspace.draftText }]; |
| 86 | const requestedPath = String(body?.path || workspace.path || files[0].path); |
| 87 | const selected = files.find(file => file.path === requestedPath); |
| 88 | if (!selected) throw new Error('Editor path is not a member of this Change Set'); |
| 89 | const policy = validateEditableFile({ path: selected.path, text: body?.text }); |
| 90 | if (!policy.editable) return jsonResponse({ ok: false, error: policy.reason }, 422); |
| 91 | const digest = await digestText(policy.text); |
| 92 | const updated = typeof workspaces.updateWorkspaceFileDraft === 'function' |
| 93 | ? await workspaces.updateWorkspaceFileDraft({ ownerId: owner, workspaceId, path: selected.path, text: policy.text, digest }) |
| 94 | : await workspaces.updateDraft({ ownerId: owner, workspaceId, text: policy.text, digest }); |
| 95 | return jsonResponse({ |
| 96 | ok: true, |
| 97 | workspace: { |
| 98 | id: updated?.id || workspaceId, |
| 99 | path: selected.path, |
| 100 | state: updated?.state || 'DRAFT', |
| 101 | charLength: policy.charLength, |
| 102 | byteLength: policy.byteLength |
| 103 | } |
| 104 | }); |
| 105 | } |
| 106 | |
| 107 | return jsonResponse({ ok: false, error: 'Method not allowed' }, 405); |
| 108 | } catch (error) { |
| 109 | const status = statusForError(error); |
| 110 | return jsonResponse({ ok: false, error: status === 500 ? 'Workspace editor request failed' : String(error?.message || 'Workspace editor request failed') }, status); |
| 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('&','&').replaceAll('"','"') + '">' + file.path.replaceAll('&','&').replaceAll('<','<') + '</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 | } |