Personal Telegram developer console for GitHub
audit/ops-actionability
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 | |
| 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/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 | return jsonResponse({ |
| 56 | workspace: { |
| 57 | id: workspace.id, |
| 58 | path: workspace.path, |
| 59 | state: workspace.state || 'DRAFT', |
| 60 | baseHeadSha: String(workspace.baseHeadSha || '').slice(0, 10), |
| 61 | draftText: String(workspace.draftText ?? '') |
| 62 | }, |
| 63 | limits: WORKSPACE_EDITOR_LIMITS |
| 64 | }); |
| 65 | } |
| 66 | |
| 67 | if (request.method === 'PUT') { |
| 68 | const contentLength = Number(request.headers.get('content-length')); |
| 69 | if (Number.isFinite(contentLength) && contentLength > WORKSPACE_EDITOR_LIMITS.maxBytes + 4096) { |
| 70 | return jsonResponse({ ok: false, error: 'Editor request body is too large' }, 413); |
| 71 | } |
| 72 | let body; |
| 73 | try { |
| 74 | body = await request.json(); |
| 75 | } catch { |
| 76 | throw new Error('Editor request body must be valid JSON'); |
| 77 | } |
| 78 | const workspaceId = safeWorkspaceId(body?.workspaceId); |
| 79 | const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId }); |
| 80 | if (!workspace) throw new Error('Workspace not found or expired'); |
| 81 | const policy = validateEditableFile({ path: workspace.path, text: body?.text }); |
| 82 | if (!policy.editable) return jsonResponse({ ok: false, error: policy.reason }, 422); |
| 83 | const digest = await digestText(policy.text); |
| 84 | const updated = await workspaces.updateDraft({ |
| 85 | ownerId: owner, |
| 86 | workspaceId, |
| 87 | text: policy.text, |
| 88 | digest |
| 89 | }); |
| 90 | return jsonResponse({ |
| 91 | ok: true, |
| 92 | workspace: { |
| 93 | id: updated?.id || workspaceId, |
| 94 | path: updated?.path || workspace.path, |
| 95 | state: updated?.state || 'DRAFT', |
| 96 | charLength: policy.charLength, |
| 97 | byteLength: policy.byteLength |
| 98 | } |
| 99 | }); |
| 100 | } |
| 101 | |
| 102 | return jsonResponse({ ok: false, error: 'Method not allowed' }, 405); |
| 103 | } catch (error) { |
| 104 | return jsonResponse({ ok: false, error: String(error?.message || 'Workspace editor request failed') }, statusForError(error)); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | export function renderWorkspaceEditorPage() { |
| 109 | return `<!doctype html> |
| 110 | <html lang="fa" dir="rtl"> |
| 111 | <head> |
| 112 | <meta charset="utf-8"> |
| 113 | <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"> |
| 114 | <meta name="color-scheme" content="light dark"> |
| 115 | <title>Nexa Workspace Editor</title> |
| 116 | <script src="https://telegram.org/js/telegram-web-app.js"></script> |
| 117 | <style> |
| 118 | :root{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color-scheme:light dark} |
| 119 | *{box-sizing:border-box}body{margin:0;background:var(--tg-theme-bg-color,#111827);color:var(--tg-theme-text-color,#f9fafb)} |
| 120 | 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))} |
| 121 | .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} |
| 122 | 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} |
| 123 | .status{min-height:22px;font-size:13px;color:var(--tg-theme-hint-color,#9ca3af)}.status.error{color:#ef4444}.status.ok{color:#22c55e} |
| 124 | .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)} |
| 125 | </style> |
| 126 | </head> |
| 127 | <body> |
| 128 | <main> |
| 129 | <div class="meta"><strong>🧑💻 Workspace Editor</strong><span id="counter">—</span></div> |
| 130 | <div id="path" class="path">در حال بارگذاری…</div> |
| 131 | <textarea id="editor" spellcheck="false" autocapitalize="off" autocomplete="off" disabled></textarea> |
| 132 | <div id="status" class="status">در حال اتصال امن به Workspace…</div> |
| 133 | <div class="actions"><button id="save" class="primary" disabled>💾 ذخیره Draft</button><button id="close" class="secondary">↩️ بازگشت به ربات</button></div> |
| 134 | </main> |
| 135 | <script> |
| 136 | (() => { |
| 137 | const tg = window.Telegram && window.Telegram.WebApp; |
| 138 | const editor = document.getElementById('editor'); |
| 139 | const status = document.getElementById('status'); |
| 140 | const path = document.getElementById('path'); |
| 141 | const counter = document.getElementById('counter'); |
| 142 | const save = document.getElementById('save'); |
| 143 | const close = document.getElementById('close'); |
| 144 | const params = new URLSearchParams(location.search); |
| 145 | const workspaceId = params.get('workspaceId') || ''; |
| 146 | const byteLength = value => new TextEncoder().encode(value).byteLength; |
| 147 | const codePoints = value => Array.from(value).length; |
| 148 | let limits = { maxChars: 20000, maxBytes: 65536 }; |
| 149 | |
| 150 | function setStatus(message, kind='') { status.textContent = message; status.className = 'status' + (kind ? ' ' + kind : ''); } |
| 151 | function updateCounter() { |
| 152 | const chars = codePoints(editor.value); const bytes = byteLength(editor.value); |
| 153 | counter.textContent = chars.toLocaleString() + ' / ' + limits.maxChars.toLocaleString() + ' · ' + bytes.toLocaleString() + ' B / ' + limits.maxBytes.toLocaleString() + ' B'; |
| 154 | const valid = chars <= limits.maxChars && bytes <= limits.maxBytes; |
| 155 | save.disabled = !valid || editor.disabled; |
| 156 | if (!valid) setStatus('محتوا از سقف امن Editor بیشتر است.', 'error'); |
| 157 | } |
| 158 | async function api(url, options={}) { |
| 159 | const headers = Object.assign({}, options.headers || {}, { 'x-telegram-init-data': tg ? tg.initData : '' }); |
| 160 | const response = await fetch(url, Object.assign({}, options, { headers })); |
| 161 | const body = await response.json().catch(() => ({})); |
| 162 | if (!response.ok) throw new Error(body.error || ('HTTP ' + response.status)); |
| 163 | return body; |
| 164 | } |
| 165 | async function load() { |
| 166 | if (!tg || !tg.initData) throw new Error('این Editor باید از داخل Telegram باز شود.'); |
| 167 | tg.ready(); tg.expand(); |
| 168 | if (!/^[A-Za-z0-9_-]{10}$/.test(workspaceId)) throw new Error('Workspace نامعتبر است.'); |
| 169 | const body = await api('/workspace/api/editor?workspaceId=' + encodeURIComponent(workspaceId)); |
| 170 | limits = body.limits || limits; |
| 171 | path.textContent = body.workspace.path; |
| 172 | editor.value = body.workspace.draftText || ''; |
| 173 | editor.disabled = false; |
| 174 | setStatus('Draft محلی آماده ویرایش است؛ تا قبل از Safe Approval هیچ تغییری در GitHub انجام نمیشود.'); |
| 175 | updateCounter(); |
| 176 | } |
| 177 | editor.addEventListener('input', updateCounter); |
| 178 | save.addEventListener('click', async () => { |
| 179 | save.disabled = true; setStatus('در حال ذخیره Draft…'); |
| 180 | try { |
| 181 | await api('/workspace/api/editor', { method:'PUT', headers:{'content-type':'application/json'}, body:JSON.stringify({workspaceId, text:editor.value}) }); |
| 182 | setStatus('Draft ذخیره شد. برای Diff و Commit به ربات برگردید.', 'ok'); |
| 183 | updateCounter(); |
| 184 | if (tg && tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success'); |
| 185 | } catch (error) { setStatus(error.message || 'ذخیره Draft ناموفق بود.', 'error'); updateCounter(); } |
| 186 | }); |
| 187 | close.addEventListener('click', () => { if (tg) tg.close(); else history.back(); }); |
| 188 | load().catch(error => { editor.disabled = true; save.disabled = true; setStatus(error.message || 'Editor قابل استفاده نیست.', 'error'); }); |
| 189 | })(); |
| 190 | </script> |
| 191 | </body> |
| 192 | </html>`; |
| 193 | } |
| 194 | |
| 195 | export function workspaceEditorPageResponse() { |
| 196 | return new Response(renderWorkspaceEditorPage(), { |
| 197 | status: 200, |
| 198 | headers: { |
| 199 | 'content-type': 'text/html; charset=utf-8', |
| 200 | 'cache-control': 'no-store', |
| 201 | 'x-content-type-options': 'nosniff', |
| 202 | 'referrer-policy': 'no-referrer', |
| 203 | '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'" |
| 204 | } |
| 205 | }); |
| 206 | } |