Personal Telegram developer console for GitHub

feat/github-advanced-read
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 251 lines 7.55 KB
Raw
1 const encoder = new TextEncoder();
2 const SIGNING_DOMAIN = 'nexa-approval-v1';
3
4 const DEFAULT_CODECS = new Map([
5 ['github.workflow.run.rerun_failed', {
6 code: 'r',
7 pluginId: 'github',
8 risk: 'WRITE'
9 }],
10 ['github.workflow.run.cancel', {
11 code: 'c',
12 pluginId: 'github',
13 risk: 'WRITE'
14 }]
15 ]);
16
17 const bytesToBase64Url = bytes => {
18 let binary = '';
19 for (const byte of bytes) binary += String.fromCharCode(byte);
20 return btoa(binary)
21 .replace(/\+/g, '-')
22 .replace(/\//g, '_')
23 .replace(/=+$/g, '');
24 };
25
26 const base64UrlToBytes = value => {
27 const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
28 const padding = '='.repeat((4 - (normalized.length % 4)) % 4);
29 const binary = atob(normalized + padding);
30 return Uint8Array.from(binary, char => char.charCodeAt(0));
31 };
32
33 const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
34 const base64UrlToText = value => new TextDecoder().decode(base64UrlToBytes(value));
35
36 const toBase36Int = value => {
37 const number = Number(value);
38 if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input');
39 return number.toString(36);
40 };
41
42 const fromBase36Int = value => {
43 if (!/^[0-9a-z]+$/i.test(value)) throw new Error('Invalid approval numeric input');
44 const number = Number.parseInt(value, 36);
45 if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input');
46 return number;
47 };
48
49 const constantTimeEqual = (left, right) => {
50 if (left.length !== right.length) return false;
51 let mismatch = 0;
52 for (let index = 0; index < left.length; index += 1) mismatch |= left[index] ^ right[index];
53 return mismatch === 0;
54 };
55
56 const compactCodecFor = actionId => DEFAULT_CODECS.get(actionId) || null;
57 const compactCodecByCode = code => {
58 for (const [actionId, codec] of DEFAULT_CODECS.entries()) {
59 if (codec.code === code) return { actionId, ...codec };
60 }
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 }
81 this.replayStore = replayStore;
82 this.keyPromise = null;
83 }
84
85 isReplayProtected() {
86 return Boolean(this.replayStore && typeof this.replayStore.consume === 'function');
87 }
88
89 async issue(payload = {}) {
90 this.#assertSecret();
91 const issuedAt = this.now();
92 const expiresAt = issuedAt + this.ttlMs;
93 const nonce = this.#nonce();
94 const normalized = {
95 v: 1,
96 pluginId: payload.pluginId,
97 actionId: payload.actionId,
98 risk: payload.risk,
99 ownerId: String(payload.ownerId ?? ''),
100 input: payload.input ?? {},
101 issuedAt,
102 expiresAt,
103 nonce
104 };
105
106 if (!normalized.ownerId) throw new Error('Approval owner is required');
107
108 const body = this.#encodeBody(normalized);
109 const signature = await this.#sign(normalized.ownerId, body);
110 const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
111 if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data');
112 return token;
113 }
114
115 async verify(token, expectations = {}) {
116 this.#assertSecret();
117 if (!token || typeof token !== 'string') throw new Error('Invalid approval token');
118 const ownerId = String(expectations.ownerId ?? '');
119 if (!ownerId) throw new Error('Approval owner is required');
120
121 const parts = token.split('.');
122 if (parts.length < 3) throw new Error('Invalid approval token');
123 const signaturePart = parts.pop();
124 const body = parts.join('.');
125
126 let suppliedSignature;
127 try {
128 suppliedSignature = base64UrlToBytes(signaturePart);
129 } catch {
130 throw new Error('Invalid approval signature');
131 }
132
133 const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes);
134 if (!constantTimeEqual(suppliedSignature, expectedSignature)) {
135 throw new Error('Invalid approval signature or owner mismatch');
136 }
137
138 const payload = this.#decodeBody(body, ownerId);
139 if (payload.expiresAt < this.now()) throw new Error('Approval token expired');
140 if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch');
141 if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch');
142 if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch');
143 return payload;
144 }
145
146 async consume(token, expectations = {}) {
147 const payload = await this.verify(token, expectations);
148 if (!this.isReplayProtected()) {
149 throw new Error('Durable approval replay protection is not configured');
150 }
151
152 const accepted = await this.replayStore.consume({
153 ownerId: payload.ownerId,
154 nonce: payload.nonce,
155 expiresAt: payload.expiresAt
156 });
157 if (!accepted) throw new Error('Approval token already used');
158 return payload;
159 }
160
161 #encodeBody(payload) {
162 const codec = compactCodecFor(payload.actionId);
163 const repoId = payload.input?.repoId;
164 const runId = payload.input?.runId;
165 if (
166 codec &&
167 codec.pluginId === payload.pluginId &&
168 codec.risk === payload.risk &&
169 Number.isSafeInteger(Number(repoId)) &&
170 Number.isSafeInteger(Number(runId))
171 ) {
172 return [
173 '1',
174 codec.code,
175 toBase36Int(repoId),
176 toBase36Int(runId),
177 toBase36Int(payload.expiresAt),
178 payload.nonce
179 ].join('.');
180 }
181
182 return `j.${textToBase64Url(JSON.stringify(payload))}`;
183 }
184
185 #decodeBody(body, ownerId) {
186 if (body.startsWith('j.')) {
187 let payload;
188 try {
189 payload = JSON.parse(base64UrlToText(body.slice(2)));
190 } catch {
191 throw new Error('Invalid approval payload');
192 }
193 if (String(payload.ownerId ?? '') !== ownerId) throw new Error('Approval owner mismatch');
194 return payload;
195 }
196
197 const parts = body.split('.');
198 if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload');
199 const [, code, repoPart, runPart, expiryPart, nonce] = parts;
200 const codec = compactCodecByCode(code);
201 if (!codec) throw new Error('Invalid approval action');
202 const expiresAt = fromBase36Int(expiryPart);
203 return {
204 v: 1,
205 pluginId: codec.pluginId,
206 actionId: codec.actionId,
207 risk: codec.risk,
208 ownerId,
209 input: {
210 repoId: fromBase36Int(repoPart),
211 runId: fromBase36Int(runPart)
212 },
213 issuedAt: expiresAt - this.ttlMs,
214 expiresAt,
215 nonce
216 };
217 }
218
219 async #sign(ownerId, body) {
220 const key = await this.#key();
221 const signature = await crypto.subtle.sign(
222 'HMAC',
223 key,
224 encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)
225 );
226 return new Uint8Array(signature);
227 }
228
229 async #key() {
230 if (!this.keyPromise) {
231 this.keyPromise = crypto.subtle.importKey(
232 'raw',
233 encoder.encode(this.secret),
234 { name: 'HMAC', hash: 'SHA-256' },
235 false,
236 ['sign']
237 );
238 }
239 return this.keyPromise;
240 }
241
242 #nonce() {
243 const bytes = new Uint8Array(6);
244 crypto.getRandomValues(bytes);
245 return bytesToBase64Url(bytes);
246 }
247
248 #assertSecret() {
249 if (!this.secret) throw new Error('Approval signing secret is required');
250 }
251 }