Personal Telegram developer console for GitHub

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