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 597 lines 19.4 KB
Raw
1 import { validateTelegramWebAppInitData } from './core/telegram-webapp-auth.js';
2 import { readBoundedJson } from './core/bounded-json.js';
3 import {
4 WORKSPACE_EDITOR_LIMITS,
5 buildWorkspaceDiff,
6 digestText,
7 normalizeCommitMessage,
8 validateEditableFile
9 } from './core/workspace-policy.js';
10 import { createWorkspaceController } from './plugins/github/workspace.js';
11 import { RELEASE_VERSION } from './version.js';
12
13 const PREFIX = '/api/v1/studio';
14 const HANDLE = /^[A-Za-z0-9_-]{10}$/;
15 const INTENT = /^[A-Za-z0-9_-]{8}$/;
16 const encoder = new TextEncoder();
17
18 class StudioError extends Error {
19 constructor(status, message) {
20 super(message);
21 this.status = status;
22 }
23 }
24
25 const response = (payload, status = 200) =>
26 Response.json(payload, {
27 status,
28 headers: {
29 'cache-control': 'no-store',
30 'x-content-type-options': 'nosniff'
31 }
32 });
33
34 function handle(value) {
35 if (typeof value !== 'string' || !HANDLE.test(value))
36 throw new StudioError(400, 'شناسه معتبر نیست.');
37 return value;
38 }
39
40 function repositoryId(value) {
41 if (
42 !/^[1-9][0-9]*$/.test(String(value ?? '')) ||
43 !Number.isSafeInteger(Number(value))
44 )
45 throw new StudioError(400, 'شناسه مخزن معتبر نیست.');
46 return String(value);
47 }
48
49 function filePath(value, { allowRoot = false } = {}) {
50 if (allowRoot && (value === '' || value === null)) return '';
51 if (
52 typeof value !== 'string' ||
53 value.length > 1024 ||
54 value.includes('\\') ||
55 Array.from(value).some((character) => {
56 const code = character.codePointAt(0);
57 return code < 32 || code === 127;
58 }) ||
59 value.startsWith('/') ||
60 value.split('/').some((part) => !part || part === '.' || part === '..')
61 )
62 throw new StudioError(400, 'مسیر فایل معتبر نیست.');
63 return value;
64 }
65
66 async function readBody(
67 request,
68 allowedKeys,
69 maxBytes = 4096,
70 allowEmpty = false
71 ) {
72 if (!request.body && allowEmpty) return {};
73 let body;
74 try {
75 body = await readBoundedJson(request, maxBytes);
76 } catch (error) {
77 if (error instanceof RangeError)
78 throw new StudioError(413, 'حجم درخواست بیش از حد مجاز است.');
79 if (error instanceof SyntaxError)
80 throw new StudioError(400, 'درخواست JSON معتبر نیست.');
81 throw error;
82 }
83 if (
84 !body ||
85 typeof body !== 'object' ||
86 Array.isArray(body) ||
87 Object.keys(body).some((key) => !allowedKeys.includes(key))
88 )
89 throw new StudioError(400, 'فیلدهای درخواست معتبر نیستند.');
90 return body;
91 }
92
93 function filesOf(workspace) {
94 return Array.isArray(workspace.files) && workspace.files.length
95 ? workspace.files
96 : [
97 {
98 path: workspace.path,
99 draftText: workspace.draftText,
100 originalText: workspace.originalText,
101 revision: workspace.revision ?? 0
102 }
103 ];
104 }
105
106 function workspaceDto(workspace) {
107 return {
108 id: workspace.id,
109 repoId: String(workspace.repoId),
110 repoFullName: workspace.repoFullName,
111 baseBranch: workspace.baseBranch,
112 baseHeadSha: workspace.baseHeadSha,
113 state: workspace.state || 'DRAFT',
114 path: workspace.path,
115 files: filesOf(workspace).map((file) => ({
116 path: file.path,
117 draftText: file.draftText,
118 revision: file.revision ?? 0
119 })),
120 commitMessage: workspace.commitMessage || '',
121 ...(workspace.commitSha && workspace.branch
122 ? { result: { commitSha: workspace.commitSha, branch: workspace.branch } }
123 : {})
124 };
125 }
126
127 const workspaceResponse = (workspace) =>
128 response({
129 ok: true,
130 workspace: workspaceDto(workspace),
131 limits: WORKSPACE_EDITOR_LIMITS
132 });
133
134 async function requireWorkspace(workspaces, ownerId, workspaceId) {
135 const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
136 if (!workspace)
137 throw new StudioError(404, 'فضای کار پیدا نشد یا منقضی شده است.');
138 return workspace;
139 }
140
141 function assertEditable(workspace) {
142 if (['COMMITTING', 'COMMITTED'].includes(workspace.state))
143 throw new StudioError(409, 'این فضای کار اکنون قابل ویرایش نیست.');
144 }
145
146 function expectedRevision(request) {
147 const value = request.headers.get('if-match');
148 if (value === null)
149 throw new StudioError(428, 'نسخه فایل برای ذخیره الزامی است.');
150 const match = value.match(/^(?:"(0|[1-9][0-9]*)"|(0|[1-9][0-9]*))$/);
151 const revision = match ? Number(match[1] ?? match[2]) : NaN;
152 if (!Number.isSafeInteger(revision))
153 throw new StudioError(400, 'نسخه فایل معتبر نیست.');
154 return revision;
155 }
156
157 function reviewOf(workspace) {
158 return {
159 baseHeadSha: workspace.baseHeadSha,
160 files: filesOf(workspace).map((file) => ({
161 path: file.path,
162 revision: file.revision ?? 0
163 }))
164 };
165 }
166
167 function validateReview(review) {
168 if (
169 !review ||
170 typeof review !== 'object' ||
171 Array.isArray(review) ||
172 Object.keys(review).some(
173 (key) => !['baseHeadSha', 'files'].includes(key)
174 ) ||
175 typeof review.baseHeadSha !== 'string' ||
176 !/^[a-f0-9]{40}$/i.test(review.baseHeadSha) ||
177 !Array.isArray(review.files) ||
178 !review.files.length ||
179 review.files.length > WORKSPACE_EDITOR_LIMITS.maxFiles
180 )
181 throw new StudioError(400, 'ابتدا Diff فعلی را بازبینی کنید.');
182 const paths = new Set();
183 for (const file of review.files) {
184 if (
185 !file ||
186 typeof file !== 'object' ||
187 Array.isArray(file) ||
188 Object.keys(file).some((key) => !['path', 'revision'].includes(key)) ||
189 !Number.isSafeInteger(file.revision) ||
190 file.revision < 0
191 )
192 throw new StudioError(400, 'نسخه بازبینی Diff معتبر نیست.');
193 filePath(file.path);
194 if (paths.has(file.path))
195 throw new StudioError(400, 'نسخه بازبینی Diff معتبر نیست.');
196 paths.add(file.path);
197 }
198 return review;
199 }
200
201 function assertAggregate(files) {
202 if (
203 files.length > WORKSPACE_EDITOR_LIMITS.maxFiles ||
204 files.reduce(
205 (total, file) =>
206 total +
207 Math.max(
208 encoder.encode(file.originalText ?? '').byteLength,
209 encoder.encode(file.draftText ?? '').byteLength
210 ),
211 0
212 ) > WORKSPACE_EDITOR_LIMITS.maxAggregateBytes
213 )
214 throw new StudioError(
215 422,
216 'حجم یا تعداد فایل‌های فضای کار بیش از حد مجاز است.'
217 );
218 }
219
220 async function provider(operation) {
221 try {
222 return await operation();
223 } catch {
224 throw new StudioError(
225 502,
226 'ارتباط با سرویس مخزن برقرار نشد. دوباره تلاش کنید.'
227 );
228 }
229 }
230
231 function controllerError(error) {
232 if (error instanceof StudioError) return error;
233 if (error?.code === 'REVISION_CONFLICT') return error;
234 if (error?.code === 'WORKSPACE_NOT_EDITABLE')
235 return new StudioError(409, 'این فضای کار اکنون قابل ویرایش نیست.');
236 if (error?.code === 'WORKSPACE_LIMIT_EXCEEDED')
237 return new StudioError(
238 422,
239 'حجم یا تعداد فایل‌های فضای کار بیش از حد مجاز است.'
240 );
241 const message = String(error?.message || '');
242 if (/reference.*(?:missing|expired)|not found or expired/i.test(message))
243 return new StudioError(404, 'مرجع یا فضای کار پیدا نشد یا منقضی شده است.');
244 if (/repository mismatch|reference mismatch|already exists/i.test(message))
245 return new StudioError(400, 'مرجع فایل با فضای کار مطابقت ندارد.');
246 if (/limited|not editable|binary|LFS|sensitive|aggregate size/i.test(message))
247 return new StudioError(422, 'این فایل یا اندازه آن برای ویرایش مجاز نیست.');
248 if (/No draft change|Commit message.*(?:required|120)/i.test(message))
249 return new StudioError(422, 'تغییر فایل و پیام Commit معتبر الزامی است.');
250 return new StudioError(502, 'عملیات فضای کار انجام نشد. دوباره تلاش کنید.');
251 }
252
253 async function controllerOperation(operation) {
254 try {
255 return await operation();
256 } catch (error) {
257 throw controllerError(error);
258 }
259 }
260
261 async function requestApproval({
262 ownerId,
263 workspaceId,
264 review,
265 controller,
266 bot
267 }) {
268 if (
269 !bot?.router?.dispatchCallback ||
270 !bot.approvals?.isReplayProtected?.() ||
271 !bot.telegram?.sendMessage
272 )
273 throw new StudioError(503, 'تأیید امن در دسترس نیست.');
274 const { workspace, intent } = await controllerOperation(() =>
275 controller.sealWorkspaceIntent({ ownerId, workspaceId, review })
276 );
277 if (
278 !intent ||
279 !INTENT.test(String(intent.id || '')) ||
280 intent.workspaceId !== workspaceId ||
281 intent.state !== 'READY' ||
282 Number(intent.repoId) !== Number(workspace.repoId)
283 )
284 throw new StudioError(409, 'فضای کار برای تأیید آماده نیست.');
285 const routed = await bot.router.dispatchCallback(
286 `wscommit:${workspace.repoId}:${intent.id}`,
287 { isOwner: true, ownerId }
288 );
289 if (
290 routed?.requiresApproval !== true ||
291 routed.pluginId !== 'github' ||
292 routed.actionId !== 'github.workspace.commit_branch' ||
293 routed.risk !== 'WRITE' ||
294 Number(routed.approval?.input?.repoId) !== Number(workspace.repoId) ||
295 routed.approval?.input?.intentId !== intent.id
296 )
297 throw new StudioError(503, 'درخواست تأیید امن پذیرفته نشد.');
298 const token = await bot.approvals.issue({
299 pluginId: routed.pluginId,
300 actionId: routed.actionId,
301 risk: routed.risk,
302 ownerId,
303 input: routed.approval.input
304 });
305 const approval = await bot.approvals.verify(token, {
306 ownerId,
307 pluginId: 'github',
308 actionId: 'github.workspace.commit_branch',
309 risk: 'WRITE'
310 });
311 await bot.telegram.sendMessage(
312 ownerId,
313 `⚠️ تأیید نهایی Commit روی شاخه جدید لازم است.\nBranch: <code>${intent.targetBranch}</code>\nBase: <code>${intent.baseHeadSha}</code>\n\nاین تأیید فقط برای نسخه بررسی‌شده و یک‌بار معتبر است.`,
314 {
315 inline_keyboard: [
316 [{ text: '✅ تأیید و Commit', callback_data: `approve:${token}` }],
317 [{ text: '↩️ انصراف', callback_data: `repo:${workspace.repoId}` }]
318 ]
319 }
320 );
321 return response({
322 ok: true,
323 approvalRequested: true,
324 workspaceId,
325 targetBranch: intent.targetBranch,
326 baseHeadSha: intent.baseHeadSha,
327 expiresAt: approval.expiresAt
328 });
329 }
330
331 export async function handleStudioApiRequest(
332 request,
333 { env = {}, github, workspaces, bot, now = () => Date.now() } = {}
334 ) {
335 const url = new URL(request.url);
336 if (url.pathname !== PREFIX && !url.pathname.startsWith(`${PREFIX}/`))
337 return null;
338 try {
339 const ownerId = String(env.OWNER_TELEGRAM_ID || '');
340 if (
341 !/^[1-9][0-9]*$/.test(ownerId) ||
342 !Number.isSafeInteger(Number(ownerId)) ||
343 !env.TELEGRAM_BOT_TOKEN
344 )
345 throw new StudioError(503, 'پیکربندی ورود امن کامل نیست.');
346 let identity;
347 try {
348 const initData = request.headers.get('x-telegram-init-data') || '';
349 if (initData.length > 8192) throw new Error('Invalid initData');
350 identity = await validateTelegramWebAppInitData(initData, {
351 botToken: env.TELEGRAM_BOT_TOKEN,
352 ownerId,
353 now,
354 maxAgeSeconds: 3600
355 });
356 } catch {
357 throw new StudioError(
358 403,
359 'این برنامه را از حساب مالک در تلگرام باز کنید.'
360 );
361 }
362
363 const route = url.pathname.slice(PREFIX.length);
364 if (request.method === 'GET' && route === '')
365 return response({
366 ok: true,
367 user: {
368 name: String(
369 identity.user.first_name || identity.user.username || 'مالک'
370 )
371 },
372 limits: WORKSPACE_EDITOR_LIMITS,
373 version: RELEASE_VERSION
374 });
375 if (request.method === 'GET' && route === '/repos') {
376 const repositories = await provider(() => github.listRepositories());
377 return response({
378 ok: true,
379 repositories: repositories.map((repo) => ({
380 id: String(repo.id),
381 name: repo.name,
382 fullName: repo.fullName,
383 defaultBranch: repo.defaultBranch,
384 private: Boolean(repo.private),
385 ...(repo.description ? { description: repo.description } : {})
386 }))
387 });
388 }
389 if (!github || !workspaces)
390 throw new StudioError(503, 'سرویس فضای کار در دسترس نیست.');
391 const controller = createWorkspaceController({ github, workspaces });
392 if (request.method === 'GET' && route === '/tree') {
393 const repoId = repositoryId(url.searchParams.get('repoId'));
394 const path = filePath(url.searchParams.get('path'), { allowRoot: true });
395 const workspaceId = url.searchParams.get('workspaceId');
396 let workspace;
397 if (workspaceId !== null) {
398 workspace = await requireWorkspace(
399 workspaces,
400 ownerId,
401 handle(workspaceId)
402 );
403 if (String(workspace.repoId) !== repoId)
404 throw new StudioError(400, 'مخزن با فضای کار مطابقت ندارد.');
405 }
406 const [repository, items] = await provider(() =>
407 Promise.all([
408 github.getRepository(repoId),
409 github.listFiles(
410 repoId,
411 path,
412 workspace ? { ref: workspace.baseHeadSha } : {}
413 )
414 ])
415 );
416 const refs = await workspaces.createNavigationRefs({
417 ownerId,
418 refs: items.map((item) => ({
419 repoId: Number(repoId),
420 path: item.path,
421 sha: item.sha,
422 type: workspace && item.type === 'file' ? 'workspace-add' : item.type,
423 ...(workspace && item.type === 'file'
424 ? { workspaceId: workspace.id }
425 : {})
426 }))
427 });
428 return response({
429 ok: true,
430 repository: {
431 id: String(repository.id),
432 fullName: repository.fullName,
433 defaultBranch: repository.defaultBranch
434 },
435 path,
436 items: items.map((item, i) => ({
437 refId: refs[i].refId,
438 name: item.name,
439 path: item.path,
440 type: item.type,
441 size: item.size ?? 0
442 }))
443 });
444 }
445 if (request.method === 'POST' && route === '/workspaces') {
446 const body = await readBody(request, ['refId']);
447 const workspace = await controllerOperation(() =>
448 controller.createWorkspaceFromRef({
449 ownerId,
450 refId: handle(body.refId)
451 })
452 );
453 return workspaceResponse(workspace);
454 }
455 const match = route.match(
456 /^\/workspaces\/([^/]+)(?:\/(files|diff|message|approval))?$/
457 );
458 if (!match) throw new StudioError(404, 'مسیر پیدا نشد.');
459 const workspaceId = handle(match[1]);
460 const action = match[2] || '';
461 const workspace = await requireWorkspace(workspaces, ownerId, workspaceId);
462 if (request.method === 'GET' && action === '')
463 return workspaceResponse(workspace);
464 if (request.method === 'GET' && action === 'diff')
465 return response({
466 ok: true,
467 diff: buildWorkspaceDiff({
468 files: filesOf(workspace),
469 maxChars: 10000
470 }),
471 review: reviewOf(workspace)
472 });
473 if (request.method === 'DELETE' && action === '') {
474 await workspaces.cancelWorkspace({ ownerId, workspaceId });
475 return response({ ok: true, cancelled: true, workspaceId });
476 }
477 assertEditable(workspace);
478 if (request.method === 'PUT' && action === 'files') {
479 const revision = expectedRevision(request);
480 const body = await readBody(
481 request,
482 ['path', 'text'],
483 WORKSPACE_EDITOR_LIMITS.maxBytes + 4096
484 );
485 const path = filePath(body.path);
486 const files = filesOf(workspace);
487 const selected = files.find((file) => file.path === path);
488 if (!selected || typeof body.text !== 'string')
489 throw new StudioError(400, 'فایل یا متن درخواست معتبر نیست.');
490 const policy = validateEditableFile({ path, text: body.text });
491 if (!policy.editable)
492 throw new StudioError(
493 422,
494 'متن فایل برای ویرایش مجاز نیست یا بیش از حد مجاز است.'
495 );
496 assertAggregate(
497 files.map((file) =>
498 file.path === path ? { ...file, draftText: policy.text } : file
499 )
500 );
501 const updated = await workspaces.updateWorkspaceFileDraft({
502 ownerId,
503 workspaceId,
504 path,
505 text: policy.text,
506 digest: await digestText(policy.text),
507 expectedRevision: revision
508 });
509 return workspaceResponse(updated);
510 }
511 if (request.method === 'POST' && action === 'files') {
512 const body = await readBody(request, ['refId']);
513 const updated = await controllerOperation(() =>
514 controller.addWorkspaceFileFromRef({
515 ownerId,
516 workspaceId,
517 refId: handle(body.refId)
518 })
519 );
520 return workspaceResponse(updated);
521 }
522 if (request.method === 'PUT' && action === 'message') {
523 const body = await readBody(request, ['message']);
524 if (typeof body.message !== 'string')
525 throw new StudioError(400, 'پیام Commit معتبر نیست.');
526 const message = await controllerOperation(() =>
527 normalizeCommitMessage(body.message)
528 );
529 return workspaceResponse(
530 await workspaces.setCommitMessage({
531 ownerId,
532 workspaceId,
533 message,
534 digest: await digestText(message)
535 })
536 );
537 }
538 if (request.method === 'POST' && action === 'approval') {
539 const body = await readBody(request, ['review', 'message'], 12288);
540 const review = validateReview(body.review);
541 if (typeof body.message !== 'string')
542 throw new StudioError(400, 'پیام Commit معتبر نیست.');
543 const message = await controllerOperation(() =>
544 normalizeCommitMessage(body.message)
545 );
546 const expectedReview = {
547 ...review,
548 commitMessageDigest: await digestText(message)
549 };
550 return await requestApproval({
551 ownerId,
552 workspaceId,
553 review: expectedReview,
554 controller,
555 bot
556 });
557 }
558 throw new StudioError(405, 'روش درخواست مجاز نیست.');
559 } catch (error) {
560 if (error instanceof StudioError)
561 return response({ ok: false, error: error.message }, error.status);
562 if (error?.code === 'WORKSPACE_NOT_EDITABLE')
563 return response(
564 { ok: false, error: 'این فضای کار اکنون قابل ویرایش نیست.' },
565 409
566 );
567 if (error?.code === 'REVISION_CONFLICT' || error?.status === 409)
568 return response(
569 {
570 ok: false,
571 error: 'نسخه فایل تغییر کرده است. آخرین نسخه را باز کنید.'
572 },
573 409
574 );
575 if (error?.code === 'DIFF_COMPLEXITY_LIMIT')
576 return response(
577 {
578 ok: false,
579 error:
580 'تغییرات برای محاسبه امن Diff پیچیده‌اند؛ تغییرها را کوچک‌تر کنید.'
581 },
582 422
583 );
584 if (error?.code === 'WORKSPACE_LIMIT_EXCEEDED')
585 return response(
586 {
587 ok: false,
588 error: 'حجم یا تعداد فایل‌های فضای کار بیش از حد مجاز است.'
589 },
590 422
591 );
592 return response(
593 { ok: false, error: 'عملیات انجام نشد. دوباره تلاش کنید.' },
594 502
595 );
596 }
597 }