Personal Telegram developer console for GitHub

feat(approval): bind destructive PR merge to exact head

davoodmehraban89 committed Oct 5, 2026 at 05:03 UTC f592f8a63cc20e6261c605d47f2aae429f5119c2
1 file changed +46 -246
src/core/approval.js
+46 -246
@@ -1,276 +1,76 @@
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
6 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 - }]
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 + ['github.pull_request.merge', { code: 'm', pluginId: 'github', risk: 'DESTRUCTIVE', target: 'prhead' }]
11 ]);
12
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 -
13 +const bytesToBase64Url = bytes => { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); };
14 +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)); };
15 const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
16 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 -
17 +const toBase36Int = value => { const number = Number(value); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number.toString(36); };
18 +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; };
19 +const constantTimeEqual = (left, right) => { if (left.length !== right.length) return false; let mismatch = 0; for (let index = 0; index < left.length; index += 1) mismatch |= left[index] ^ right[index]; return mismatch === 0; };
20 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 -};
21 +const compactCodecByCode = code => { for (const [actionId, codec] of DEFAULT_CODECS.entries()) if (codec.code === code) return { actionId, ...codec }; return null; };
22
23 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');
24 + constructor({ secret = '', now = () => Date.now(), ttlMs = 120_000, maxTokenLength = 56, signatureBytes = 12, replayStore = null } = {}) {
25 + this.secret = String(secret || ''); this.now = now; this.ttlMs = ttlMs; this.maxTokenLength = maxTokenLength; this.signatureBytes = signatureBytes;
26 + if (replayStore && typeof replayStore.consume !== 'function') throw new Error('Approval replay store is invalid');
27 + this.replayStore = replayStore; this.keyPromise = null;
28 }
97 -
29 + isReplayProtected() { return Boolean(this.replayStore && typeof this.replayStore.consume === 'function'); }
30 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 -
31 + this.#assertSecret(); const issuedAt = this.now(); const expiresAt = issuedAt + this.ttlMs; const nonce = this.#nonce();
32 + const normalized = { v: 1, pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, ownerId: String(payload.ownerId ?? ''), input: payload.input ?? {}, issuedAt, expiresAt, nonce };
33 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;
34 + const body = this.#encodeBody(normalized); const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
35 + if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data'); return token;
36 }
123 -
37 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');
38 + 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');
39 + const parts = token.split('.'); if (parts.length < 3) throw new Error('Invalid approval token'); const signaturePart = parts.pop(); const body = parts.join('.'); let suppliedSignature;
40 + try { suppliedSignature = base64UrlToBytes(signaturePart); } catch { throw new Error('Invalid approval signature'); }
41 + const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes); if (!constantTimeEqual(suppliedSignature, expectedSignature)) throw new Error('Invalid approval signature or owner mismatch');
42 + const payload = this.#decodeBody(body, ownerId); if (payload.expiresAt < this.now()) throw new Error('Approval token expired');
43 if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch');
44 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;
45 + if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch'); return payload;
46 }
154 -
47 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;
48 + const payload = await this.verify(token, expectations); if (!this.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
49 + 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;
50 }
169 -
51 #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 - ) {
52 + const codec = compactCodecFor(payload.actionId); const repoId = payload.input?.repoId;
53 + if (codec && codec.pluginId === payload.pluginId && codec.risk === payload.risk && Number.isSafeInteger(Number(repoId))) {
54 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('.');
55 + if (codec.target === 'run') { const runId = payload.input?.runId; if (!Number.isSafeInteger(Number(runId))) return `j.${textToBase64Url(JSON.stringify(payload))}`; target = toBase36Int(runId); }
56 + 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; }
57 + else if (codec.target === 'prhead') { const prNumber = payload.input?.prNumber; const headSha = String(payload.input?.headSha || ''); if (!Number.isSafeInteger(Number(prNumber)) || !FULL_SHA_PATTERN.test(headSha)) throw new Error('Invalid pull request approval target'); target = `${toBase36Int(prNumber)}~${headSha}`; }
58 + else return `j.${textToBase64Url(JSON.stringify(payload))}`;
59 + return ['1', codec.code, toBase36Int(repoId), target, toBase36Int(payload.expiresAt), payload.nonce].join('.');
60 }
200 -
61 return `j.${textToBase64Url(JSON.stringify(payload))}`;
62 }
203 -
63 #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');
64 + 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; }
65 + 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) };
66 + if (codec.target === 'run') input.runId = fromBase36Int(targetPart);
67 + else if (codec.target === 'intent') { if (!INTENT_ID_PATTERN.test(targetPart)) throw new Error('Invalid approval intent ID'); input.intentId = targetPart; }
68 + else if (codec.target === 'prhead') { const [prPart, headSha, extra] = targetPart.split('~'); if (extra !== undefined || !FULL_SHA_PATTERN.test(headSha || '')) throw new Error('Invalid pull request approval target'); input.prNumber = fromBase36Int(prPart); input.headSha = headSha; }
69 + else throw new Error('Invalid approval target');
70 + return { v: 1, pluginId: codec.pluginId, actionId: codec.actionId, risk: codec.risk, ownerId, input, issuedAt: expiresAt - this.ttlMs, expiresAt, nonce };
71 }
72 + 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); }
73 + 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; }
74 + #nonce() { const bytes = new Uint8Array(6); crypto.getRandomValues(bytes); return bytesToBase64Url(bytes); }
75 + #assertSecret() { if (!this.secret) throw new Error('Approval signing secret is required'); }
76 }