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 321 lines 11 KB
Raw
1 const encoder = new TextEncoder();
2 const SIGNING_DOMAIN = 'nexa-approval-v1';
3 const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
4 const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
5 const VERSION_ID_PATTERN = /^[0-9a-f-]{36}$/i;
6 const DEFAULT_CODECS = new Map([
7 [
8 'github.workflow.run.rerun_failed',
9 { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }
10 ],
11 [
12 'github.workflow.run.cancel',
13 { code: 'c', pluginId: 'github', risk: 'WRITE', target: 'run' }
14 ],
15 [
16 'github.workspace.commit_branch',
17 { code: 'e', pluginId: 'github', risk: 'WRITE', target: 'intent' }
18 ]
19 ]);
20 const bytesToBase64Url = (bytes) => {
21 let binary = '';
22 for (const byte of bytes) binary += String.fromCharCode(byte);
23 return btoa(binary)
24 .replace(/\+/g, '-')
25 .replace(/\//g, '_')
26 .replace(/=+$/g, '');
27 };
28 const base64UrlToBytes = (value) => {
29 const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
30 const padding = '='.repeat((4 - (normalized.length % 4)) % 4);
31 const binary = atob(normalized + padding);
32 return Uint8Array.from(binary, (char) => char.charCodeAt(0));
33 };
34 const textToBase64Url = (value) => bytesToBase64Url(encoder.encode(value));
35 const base64UrlToText = (value) =>
36 new TextDecoder().decode(base64UrlToBytes(value));
37 const toBase36Int = (value) => {
38 const number = Number(value);
39 if (!Number.isSafeInteger(number) || number < 0)
40 throw new Error('Invalid approval numeric input');
41 return number.toString(36);
42 };
43 const fromBase36Int = (value) => {
44 if (!/^[0-9a-z]+$/i.test(value))
45 throw new Error('Invalid approval numeric input');
46 const number = Number.parseInt(value, 36);
47 if (!Number.isSafeInteger(number) || number < 0)
48 throw new Error('Invalid approval numeric input');
49 return number;
50 };
51 const constantTimeEqual = (left, right) => {
52 if (left.length !== right.length) return false;
53 let mismatch = 0;
54 for (let i = 0; i < left.length; i += 1) mismatch |= left[i] ^ right[i];
55 return mismatch === 0;
56 };
57 const compactCodecFor = (actionId) => DEFAULT_CODECS.get(actionId) || null;
58 const compactCodecByCode = (code) => {
59 for (const [actionId, codec] of DEFAULT_CODECS.entries())
60 if (codec.code === code) return { actionId, ...codec };
61 return null;
62 };
63
64 export class ApprovalService {
65 constructor({
66 secret = '',
67 now = () => Date.now(),
68 ttlMs = 120_000,
69 maxTokenLength = 56,
70 signatureBytes = 12,
71 replayStore = null
72 } = {}) {
73 this.secret = String(secret || '');
74 this.now = now;
75 this.ttlMs = ttlMs;
76 this.maxTokenLength = maxTokenLength;
77 this.signatureBytes = signatureBytes;
78 if (replayStore && typeof replayStore.consume !== 'function')
79 throw new Error('Approval replay store is invalid');
80 this.replayStore = replayStore;
81 this.keyPromise = null;
82 }
83 isReplayProtected() {
84 return Boolean(
85 this.replayStore && typeof this.replayStore.consume === 'function'
86 );
87 }
88 async issue(payload = {}) {
89 this.#assertSecret();
90 const issuedAt = this.now();
91 const expiresAt = issuedAt + this.ttlMs;
92 const nonce = this.#nonce();
93 const normalized = {
94 v: 1,
95 pluginId: payload.pluginId,
96 actionId: payload.actionId,
97 risk: payload.risk,
98 ownerId: String(payload.ownerId ?? ''),
99 input: payload.input ?? {},
100 issuedAt,
101 expiresAt,
102 nonce
103 };
104 if (!normalized.ownerId) throw new Error('Approval owner is required');
105 let body;
106 if (
107 normalized.actionId === 'github.pull_request.merge' ||
108 normalized.actionId === 'cloudflare.worker.deploy_version'
109 ) {
110 let code = '';
111 if (normalized.actionId === 'github.pull_request.merge') {
112 const { repoId, prNumber, headSha } = normalized.input || {};
113 if (
114 normalized.pluginId !== 'github' ||
115 normalized.risk !== 'DESTRUCTIVE' ||
116 !Number.isSafeInteger(Number(repoId)) ||
117 !Number.isSafeInteger(Number(prNumber)) ||
118 !FULL_SHA_PATTERN.test(String(headSha || ''))
119 )
120 throw new Error('Invalid pull request approval target');
121 code = 'm';
122 } else {
123 const { versionId } = normalized.input || {};
124 if (
125 normalized.pluginId !== 'cloudflare' ||
126 normalized.risk !== 'DESTRUCTIVE' ||
127 !VERSION_ID_PATTERN.test(String(versionId || ''))
128 )
129 throw new Error('Invalid Cloudflare approval target');
130 code = 'c';
131 }
132 if (
133 !this.replayStore ||
134 typeof this.replayStore.put !== 'function' ||
135 typeof this.replayStore.peek !== 'function'
136 )
137 throw new Error('Durable approval context storage is not configured');
138 await this.replayStore.put({
139 ownerId: normalized.ownerId,
140 nonce,
141 expiresAt,
142 payload: normalized
143 });
144 body = `s.${code}.${toBase36Int(expiresAt)}.${nonce}`;
145 } else body = this.#encodeBody(normalized);
146 const signature = await this.#sign(normalized.ownerId, body);
147 const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
148 if (token.length > this.maxTokenLength)
149 throw new Error('Approval token too large for callback data');
150 return token;
151 }
152 async verify(token, expectations = {}) {
153 this.#assertSecret();
154 if (!token || typeof token !== 'string')
155 throw new Error('Invalid approval token');
156 const ownerId = String(expectations.ownerId ?? '');
157 if (!ownerId) throw new Error('Approval owner is required');
158 const parts = token.split('.');
159 if (parts.length < 3) throw new Error('Invalid approval token');
160 const signaturePart = parts.pop();
161 const body = parts.join('.');
162 let suppliedSignature;
163 try {
164 suppliedSignature = base64UrlToBytes(signaturePart);
165 } catch {
166 throw new Error('Invalid approval signature');
167 }
168 const expectedSignature = (await this.#sign(ownerId, body)).slice(
169 0,
170 this.signatureBytes
171 );
172 if (!constantTimeEqual(suppliedSignature, expectedSignature))
173 throw new Error('Invalid approval signature or owner mismatch');
174 let payload;
175 if (body.startsWith('s.m.') || body.startsWith('s.c.')) {
176 const state = body.split('.');
177 if (state.length !== 4) throw new Error('Invalid approval payload');
178 const code = state[1];
179 const expiresAt = fromBase36Int(state[2]);
180 const nonce = state[3];
181 if (expiresAt < this.now()) throw new Error('Approval token expired');
182 if (!this.replayStore || typeof this.replayStore.peek !== 'function')
183 throw new Error('Durable approval context storage is not configured');
184 payload = await this.replayStore.peek({ ownerId, nonce });
185 if (!payload) throw new Error('Approval context is unavailable');
186 const expectedAction =
187 code === 'm'
188 ? 'github.pull_request.merge'
189 : code === 'c'
190 ? 'cloudflare.worker.deploy_version'
191 : '';
192 if (
193 !expectedAction ||
194 payload.expiresAt !== expiresAt ||
195 payload.nonce !== nonce ||
196 payload.ownerId !== ownerId ||
197 payload.actionId !== expectedAction
198 )
199 throw new Error('Approval context mismatch');
200 } else payload = this.#decodeBody(body, ownerId);
201 if (payload.expiresAt < this.now())
202 throw new Error('Approval token expired');
203 if (expectations.pluginId && payload.pluginId !== expectations.pluginId)
204 throw new Error('Approval plugin mismatch');
205 if (expectations.actionId && payload.actionId !== expectations.actionId)
206 throw new Error('Approval action mismatch');
207 if (expectations.risk && payload.risk !== expectations.risk)
208 throw new Error('Approval risk mismatch');
209 return payload;
210 }
211 async consume(token, expectations = {}) {
212 const payload = await this.verify(token, expectations);
213 if (!this.isReplayProtected())
214 throw new Error('Durable approval replay protection is not configured');
215 const accepted = await this.replayStore.consume({
216 ownerId: payload.ownerId,
217 nonce: payload.nonce,
218 expiresAt: payload.expiresAt
219 });
220 if (!accepted) throw new Error('Approval token already used');
221 return payload;
222 }
223 #encodeBody(payload) {
224 const codec = compactCodecFor(payload.actionId);
225 const repoId = payload.input?.repoId;
226 if (
227 codec &&
228 codec.pluginId === payload.pluginId &&
229 codec.risk === payload.risk &&
230 Number.isSafeInteger(Number(repoId))
231 ) {
232 let target;
233 if (codec.target === 'run') {
234 const runId = payload.input?.runId;
235 if (!Number.isSafeInteger(Number(runId)))
236 return `j.${textToBase64Url(JSON.stringify(payload))}`;
237 target = toBase36Int(runId);
238 } else if (codec.target === 'intent') {
239 const intentId = String(payload.input?.intentId || '');
240 if (!INTENT_ID_PATTERN.test(intentId))
241 throw new Error('Invalid approval intent ID');
242 target = intentId;
243 } else return `j.${textToBase64Url(JSON.stringify(payload))}`;
244 return [
245 '1',
246 codec.code,
247 toBase36Int(repoId),
248 target,
249 toBase36Int(payload.expiresAt),
250 payload.nonce
251 ].join('.');
252 }
253 return `j.${textToBase64Url(JSON.stringify(payload))}`;
254 }
255 #decodeBody(body, ownerId) {
256 if (body.startsWith('j.')) {
257 let payload;
258 try {
259 payload = JSON.parse(base64UrlToText(body.slice(2)));
260 } catch {
261 throw new Error('Invalid approval payload');
262 }
263 if (String(payload.ownerId ?? '') !== ownerId)
264 throw new Error('Approval owner mismatch');
265 return payload;
266 }
267 const parts = body.split('.');
268 if (parts.length !== 6 || parts[0] !== '1')
269 throw new Error('Invalid approval payload');
270 const [, code, repoPart, targetPart, expiryPart, nonce] = parts;
271 const codec = compactCodecByCode(code);
272 if (!codec) throw new Error('Invalid approval action');
273 const expiresAt = fromBase36Int(expiryPart);
274 const input = { repoId: fromBase36Int(repoPart) };
275 if (codec.target === 'run') input.runId = fromBase36Int(targetPart);
276 else if (codec.target === 'intent') {
277 if (!INTENT_ID_PATTERN.test(targetPart))
278 throw new Error('Invalid approval intent ID');
279 input.intentId = targetPart;
280 }
281 return {
282 v: 1,
283 pluginId: codec.pluginId,
284 actionId: codec.actionId,
285 risk: codec.risk,
286 ownerId,
287 input,
288 issuedAt: expiresAt - this.ttlMs,
289 expiresAt,
290 nonce
291 };
292 }
293 async #sign(ownerId, body) {
294 const key = await this.#key();
295 const signature = await crypto.subtle.sign(
296 'HMAC',
297 key,
298 encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)
299 );
300 return new Uint8Array(signature);
301 }
302 async #key() {
303 if (!this.keyPromise)
304 this.keyPromise = crypto.subtle.importKey(
305 'raw',
306 encoder.encode(this.secret),
307 { name: 'HMAC', hash: 'SHA-256' },
308 false,
309 ['sign']
310 );
311 return this.keyPromise;
312 }
313 #nonce() {
314 const bytes = new Uint8Array(6);
315 crypto.getRandomValues(bytes);
316 return bytesToBase64Url(bytes);
317 }
318 #assertSecret() {
319 if (!this.secret) throw new Error('Approval signing secret is required');
320 }
321 }