Personal Telegram developer console for GitHub

v3a/multifile
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 69 lines 9.71 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 ['github.workflow.run.rerun_failed', { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }],
8 ['github.workflow.run.cancel', { code: 'c', pluginId: 'github', risk: 'WRITE', target: 'run' }],
9 ['github.workspace.commit_branch', { code: 'e', pluginId: 'github', risk: 'WRITE', target: 'intent' }]
10 ]);
11 const bytesToBase64Url = bytes => { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); };
12 const base64UrlToBytes = value => { const normalized = value.replace(/-/g, '+').replace(/_/g, '/'); const padding = '='.repeat((4 - (normalized.length % 4)) % 4); const binary = atob(normalized + padding); return Uint8Array.from(binary, char => char.charCodeAt(0)); };
13 const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
14 const base64UrlToText = value => new TextDecoder().decode(base64UrlToBytes(value));
15 const toBase36Int = value => { const number = Number(value); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number.toString(36); };
16 const fromBase36Int = value => { if (!/^[0-9a-z]+$/i.test(value)) throw new Error('Invalid approval numeric input'); const number = Number.parseInt(value, 36); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number; };
17 const constantTimeEqual = (left, right) => { if (left.length !== right.length) return false; let mismatch = 0; for (let i = 0; i < left.length; i += 1) mismatch |= left[i] ^ right[i]; return mismatch === 0; };
18 const compactCodecFor = actionId => DEFAULT_CODECS.get(actionId) || null;
19 const compactCodecByCode = code => { for (const [actionId, codec] of DEFAULT_CODECS.entries()) if (codec.code === code) return { actionId, ...codec }; return null; };
20
21 export class ApprovalService {
22 constructor({ secret = '', now = () => Date.now(), ttlMs = 120_000, maxTokenLength = 56, signatureBytes = 12, replayStore = null } = {}) { this.secret = String(secret || ''); this.now = now; this.ttlMs = ttlMs; this.maxTokenLength = maxTokenLength; this.signatureBytes = signatureBytes; if (replayStore && typeof replayStore.consume !== 'function') throw new Error('Approval replay store is invalid'); this.replayStore = replayStore; this.keyPromise = null; }
23 isReplayProtected() { return Boolean(this.replayStore && typeof this.replayStore.consume === 'function'); }
24 async issue(payload = {}) {
25 this.#assertSecret(); const issuedAt = this.now(); const expiresAt = issuedAt + this.ttlMs; const nonce = this.#nonce();
26 const normalized = { v: 1, pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, ownerId: String(payload.ownerId ?? ''), input: payload.input ?? {}, issuedAt, expiresAt, nonce };
27 if (!normalized.ownerId) throw new Error('Approval owner is required');
28 let body;
29 if (normalized.actionId === 'github.pull_request.merge' || normalized.actionId === 'cloudflare.worker.deploy_version') {
30 let code = '';
31 if (normalized.actionId === 'github.pull_request.merge') {
32 const { repoId, prNumber, headSha } = normalized.input || {};
33 if (normalized.pluginId !== 'github' || normalized.risk !== 'DESTRUCTIVE' || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(prNumber)) || !FULL_SHA_PATTERN.test(String(headSha || ''))) throw new Error('Invalid pull request approval target');
34 code = 'm';
35 } else {
36 const { versionId } = normalized.input || {};
37 if (normalized.pluginId !== 'cloudflare' || normalized.risk !== 'DESTRUCTIVE' || !VERSION_ID_PATTERN.test(String(versionId || ''))) throw new Error('Invalid Cloudflare approval target');
38 code = 'c';
39 }
40 if (!this.replayStore || typeof this.replayStore.put !== 'function' || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
41 await this.replayStore.put({ ownerId: normalized.ownerId, nonce, expiresAt, payload: normalized });
42 body = `s.${code}.${toBase36Int(expiresAt)}.${nonce}`;
43 } else body = this.#encodeBody(normalized);
44 const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
45 if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data'); return token;
46 }
47 async verify(token, expectations = {}) {
48 this.#assertSecret(); if (!token || typeof token !== 'string') throw new Error('Invalid approval token'); const ownerId = String(expectations.ownerId ?? ''); if (!ownerId) throw new Error('Approval owner is required');
49 const parts = token.split('.'); if (parts.length < 3) throw new Error('Invalid approval token'); const signaturePart = parts.pop(); const body = parts.join('.'); let suppliedSignature;
50 try { suppliedSignature = base64UrlToBytes(signaturePart); } catch { throw new Error('Invalid approval signature'); }
51 const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes); if (!constantTimeEqual(suppliedSignature, expectedSignature)) throw new Error('Invalid approval signature or owner mismatch');
52 let payload;
53 if (body.startsWith('s.m.') || body.startsWith('s.c.')) {
54 const state = body.split('.'); if (state.length !== 4) throw new Error('Invalid approval payload'); const code = state[1]; const expiresAt = fromBase36Int(state[2]); const nonce = state[3]; if (expiresAt < this.now()) throw new Error('Approval token expired');
55 if (!this.replayStore || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
56 payload = await this.replayStore.peek({ ownerId, nonce }); if (!payload) throw new Error('Approval context is unavailable');
57 const expectedAction = code === 'm' ? 'github.pull_request.merge' : code === 'c' ? 'cloudflare.worker.deploy_version' : '';
58 if (!expectedAction || payload.expiresAt !== expiresAt || payload.nonce !== nonce || payload.ownerId !== ownerId || payload.actionId !== expectedAction) throw new Error('Approval context mismatch');
59 } else payload = this.#decodeBody(body, ownerId);
60 if (payload.expiresAt < this.now()) throw new Error('Approval token expired'); if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch'); if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch'); if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch'); return payload;
61 }
62 async consume(token, expectations = {}) { const payload = await this.verify(token, expectations); if (!this.isReplayProtected()) throw new Error('Durable approval replay protection is not configured'); const accepted = await this.replayStore.consume({ ownerId: payload.ownerId, nonce: payload.nonce, expiresAt: payload.expiresAt }); if (!accepted) throw new Error('Approval token already used'); return payload; }
63 #encodeBody(payload) { const codec = compactCodecFor(payload.actionId); const repoId = payload.input?.repoId; if (codec && codec.pluginId === payload.pluginId && codec.risk === payload.risk && Number.isSafeInteger(Number(repoId))) { let target; if (codec.target === 'run') { const runId = payload.input?.runId; if (!Number.isSafeInteger(Number(runId))) return `j.${textToBase64Url(JSON.stringify(payload))}`; target = toBase36Int(runId); } else if (codec.target === 'intent') { const intentId = String(payload.input?.intentId || ''); if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Invalid approval intent ID'); target = intentId; } else return `j.${textToBase64Url(JSON.stringify(payload))}`; return ['1', codec.code, toBase36Int(repoId), target, toBase36Int(payload.expiresAt), payload.nonce].join('.'); } return `j.${textToBase64Url(JSON.stringify(payload))}`; }
64 #decodeBody(body, ownerId) { if (body.startsWith('j.')) { let payload; try { payload = JSON.parse(base64UrlToText(body.slice(2))); } catch { throw new Error('Invalid approval payload'); } if (String(payload.ownerId ?? '') !== ownerId) throw new Error('Approval owner mismatch'); return payload; } const parts = body.split('.'); if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload'); const [, code, repoPart, targetPart, expiryPart, nonce] = parts; const codec = compactCodecByCode(code); if (!codec) throw new Error('Invalid approval action'); const expiresAt = fromBase36Int(expiryPart); const input = { repoId: fromBase36Int(repoPart) }; if (codec.target === 'run') input.runId = fromBase36Int(targetPart); else if (codec.target === 'intent') { if (!INTENT_ID_PATTERN.test(targetPart)) throw new Error('Invalid approval intent ID'); input.intentId = targetPart; } return { v: 1, pluginId: codec.pluginId, actionId: codec.actionId, risk: codec.risk, ownerId, input, issuedAt: expiresAt - this.ttlMs, expiresAt, nonce }; }
65 async #sign(ownerId, body) { const key = await this.#key(); const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)); return new Uint8Array(signature); }
66 async #key() { if (!this.keyPromise) this.keyPromise = crypto.subtle.importKey('raw', encoder.encode(this.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return this.keyPromise; }
67 #nonce() { const bytes = new Uint8Array(6); crypto.getRandomValues(bytes); return bytesToBase64Url(bytes); }
68 #assertSecret() { if (!this.secret) throw new Error('Approval signing secret is required'); }
69 }