Personal Telegram developer console for GitHub

docs/control-plane-2-7-design
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 195 lines 7.26 KB
Raw
1 const MAX_CHARS = 20000;
2 const MAX_BYTES = 65536;
3 const MAX_COMMIT_MESSAGE = 120;
4 const MAX_WORKSPACE_FILES = 8;
5 const MAX_WORKSPACE_BYTES = 131072;
6 const SAFE_HANDLE = /^[A-Za-z0-9_-]{10}$/;
7
8 export const WORKSPACE_EDITOR_LIMITS = Object.freeze({
9 maxChars: MAX_CHARS,
10 maxBytes: MAX_BYTES,
11 maxFiles: MAX_WORKSPACE_FILES,
12 maxAggregateBytes: MAX_WORKSPACE_BYTES
13 });
14
15 const encoder = new TextEncoder();
16
17 const sensitivePath = value => {
18 const path = String(value || '').replaceAll('\\', '/').toLowerCase();
19 const name = path.split('/').pop() || '';
20 if (name === '.env' || name.startsWith('.env.')) return true;
21 if (name === 'id_rsa' || name === 'id_ed25519') return true;
22 if (/\.(pem|key|p12|pfx)$/i.test(name)) return true;
23 if (name === 'credentials.json') return true;
24 if (/^service-account.*\.json$/i.test(name)) return true;
25 return false;
26 };
27
28 const codePointLength = value => Array.from(value).length;
29
30 export function validateEditableFile({ path, text, byteLength } = {}) {
31 const source = String(text ?? '');
32 const charLength = codePointLength(source);
33 const computedBytes = encoder.encode(source).byteLength;
34 const providerBytes = Number(byteLength);
35 const effectiveBytes = Number.isFinite(providerBytes) && providerBytes >= 0
36 ? Math.max(computedBytes, providerBytes)
37 : computedBytes;
38
39 let reason = '';
40 if (sensitivePath(path)) reason = 'Sensitive file path is not editable.';
41 else if (source.includes('\0')) reason = 'Binary-like content is not editable.';
42 else if (/^version https:\/\/git-lfs\.github\.com\/spec\/v1(?:\r?\n|$)/.test(source)) reason = 'Git LFS pointer files are not editable.';
43 else if (charLength > MAX_CHARS) reason = 'Editable text is limited to 20,000 Unicode characters.';
44 else if (effectiveBytes > MAX_BYTES) reason = 'Editable text is limited to 65,536 UTF-8 bytes.';
45
46 return {
47 editable: reason === '',
48 reason,
49 text: source,
50 charLength,
51 byteLength: effectiveBytes
52 };
53 }
54
55 export function normalizeCommitMessage(value) {
56 const normalized = String(value ?? '').trim().replace(/\s+/g, ' ');
57 if (!normalized) throw new Error('Commit message is required');
58 if (codePointLength(normalized) > MAX_COMMIT_MESSAGE) {
59 throw new Error('Commit message must be 120 characters or fewer');
60 }
61 return normalized;
62 }
63
64 export function makeTargetBranch(workspaceId) {
65 const id = String(workspaceId ?? '');
66 if (!SAFE_HANDLE.test(id)) throw new Error('Workspace ID must be a 10-character URL-safe handle');
67 return `nexa/edit-${id}`;
68 }
69
70 export async function digestText(value) {
71 const digest = await crypto.subtle.digest('SHA-256', encoder.encode(String(value ?? '')));
72 return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
73 }
74
75 function linesOf(value) {
76 return String(value ?? '').split('\n');
77 }
78
79 function diffOperations(beforeLines, afterLines) {
80 const rows = beforeLines.length + 1;
81 const cols = afterLines.length + 1;
82 const table = new Uint16Array(rows * cols);
83 const at = (i, j) => i * cols + j;
84
85 for (let i = beforeLines.length - 1; i >= 0; i -= 1) {
86 for (let j = afterLines.length - 1; j >= 0; j -= 1) {
87 table[at(i, j)] = beforeLines[i] === afterLines[j]
88 ? table[at(i + 1, j + 1)] + 1
89 : Math.max(table[at(i + 1, j)], table[at(i, j + 1)]);
90 }
91 }
92
93 const operations = [];
94 let i = 0;
95 let j = 0;
96 while (i < beforeLines.length || j < afterLines.length) {
97 if (i < beforeLines.length && j < afterLines.length && beforeLines[i] === afterLines[j]) {
98 operations.push({ kind: ' ', line: beforeLines[i] });
99 i += 1;
100 j += 1;
101 continue;
102 }
103 if (j < afterLines.length && (i >= beforeLines.length || table[at(i, j + 1)] >= table[at(i + 1, j)])) {
104 operations.push({ kind: '+', line: afterLines[j] });
105 j += 1;
106 continue;
107 }
108 operations.push({ kind: '-', line: beforeLines[i] });
109 i += 1;
110 }
111 return operations;
112 }
113
114 export function buildUnifiedDiff({ path, before, after, maxChars = 2600 } = {}) {
115 const safePath = String(path || 'file').replace(/[\r\n]/g, '');
116 const operations = diffOperations(linesOf(before), linesOf(after));
117 const additions = operations.reduce((count, op) => count + (op.kind === '+' ? 1 : 0), 0);
118 const deletions = operations.reduce((count, op) => count + (op.kind === '-' ? 1 : 0), 0);
119 const raw = [
120 `--- a/${safePath}`,
121 `+++ b/${safePath}`,
122 '@@',
123 ...operations.map(op => `${op.kind}${op.line}`)
124 ].join('\n');
125
126 const limit = Math.max(32, Math.min(10000, Number(maxChars) || 2600));
127 if (raw.length <= limit) {
128 return { text: raw, additions, deletions, truncated: false };
129 }
130 const marker = '\n…';
131 return {
132 text: `${raw.slice(0, Math.max(0, limit - marker.length))}${marker}`,
133 additions,
134 deletions,
135 truncated: true
136 };
137 }
138
139
140 export function validateWorkspaceFiles(files = []) {
141 if (!Array.isArray(files) || files.length === 0) throw new Error('Workspace files are required');
142 if (files.length > MAX_WORKSPACE_FILES) throw new Error(`Workspace is limited to ${MAX_WORKSPACE_FILES} files`);
143 const seen = new Set();
144 let totalBytes = 0;
145 const normalized = files.map(source => {
146 const path = String(source?.path || '').replaceAll('\\', '/');
147 if (!path) throw new Error('Workspace file path is required');
148 if (seen.has(path)) throw new Error(`Duplicate workspace path: ${path}`);
149 seen.add(path);
150 const original = validateEditableFile({ path, text: source?.originalText ?? '' });
151 if (!original.editable) throw new Error(original.reason);
152 const draft = validateEditableFile({ path, text: source?.draftText ?? source?.originalText ?? '' });
153 if (!draft.editable) throw new Error(draft.reason);
154 totalBytes += Math.max(original.byteLength, draft.byteLength);
155 return { ...source, path, originalText: original.text, draftText: draft.text };
156 });
157 if (totalBytes > MAX_WORKSPACE_BYTES) {
158 throw new Error('Workspace aggregate text is limited to 131,072 UTF-8 bytes');
159 }
160 return { valid: true, files: normalized, totalBytes };
161 }
162
163 export function buildWorkspaceDiff({ files = [], maxChars = 3000 } = {}) {
164 const validated = validateWorkspaceFiles(files);
165 const changed = [];
166 let additions = 0;
167 let deletions = 0;
168 for (const file of validated.files) {
169 if (file.originalText === file.draftText) continue;
170 const diff = buildUnifiedDiff({ path: file.path, before: file.originalText, after: file.draftText, maxChars: 10000 });
171 additions += diff.additions;
172 deletions += diff.deletions;
173 changed.push(diff.text);
174 }
175 const raw = changed.join('\n\n');
176 const limit = Math.max(32, Math.min(10000, Number(maxChars) || 3000));
177 const marker = '\n…';
178 const truncated = raw.length > limit;
179 const text = truncated ? `${raw.slice(0, Math.max(0, limit - marker.length))}${marker}` : raw;
180 return { text, additions, deletions, filesChanged: changed.length, truncated };
181 }
182
183 export async function digestWorkspaceFiles(files = []) {
184 const validated = validateWorkspaceFiles(files);
185 const canonical = validated.files
186 .map(file => ({
187 path: file.path,
188 blobSha: String(file.blobSha || ''),
189 originalDigest: String(file.originalDigest || ''),
190 draftText: file.draftText,
191 draftDigest: String(file.draftDigest || '')
192 }))
193 .sort((a, b) => a.path.localeCompare(b.path));
194 return digestText(JSON.stringify(canonical));
195 }