Personal Telegram developer console for GitHub

fix(approval): keep exact PR head in durable approval context

davoodmehraban89 committed Oct 5, 2026 at 05:07 UTC d7dfa851992e322e075a5f5dd35086e67033109c
1 file changed +23 -40
src/core/approval.js
+23 -40
@@ -2,36 +2,37 @@ 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 -
5 const DEFAULT_CODECS = new Map([
6 ['github.workflow.run.rerun_failed', { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }],
7 ['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' }]
8 + ['github.workspace.commit_branch', { code: 'e', pluginId: 'github', risk: 'WRITE', target: 'intent' }]
9 ]);
12 -
10 const bytesToBase64Url = bytes => { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); };
11 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)); };
12 const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
13 const base64UrlToText = value => new TextDecoder().decode(base64UrlToBytes(value));
14 const toBase36Int = value => { const number = Number(value); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number.toString(36); };
15 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; };
16 +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; };
17 const compactCodecFor = actionId => DEFAULT_CODECS.get(actionId) || null;
18 const compactCodecByCode = code => { for (const [actionId, codec] of DEFAULT_CODECS.entries()) if (codec.code === code) return { actionId, ...codec }; return null; };
19
20 export class ApprovalService {
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 - }
21 + 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; }
22 isReplayProtected() { return Boolean(this.replayStore && typeof this.replayStore.consume === 'function'); }
23 async issue(payload = {}) {
24 this.#assertSecret(); const issuedAt = this.now(); const expiresAt = issuedAt + this.ttlMs; const nonce = this.#nonce();
25 const normalized = { v: 1, pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, ownerId: String(payload.ownerId ?? ''), input: payload.input ?? {}, issuedAt, expiresAt, nonce };
26 if (!normalized.ownerId) throw new Error('Approval owner is required');
34 - const body = this.#encodeBody(normalized); const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
27 + let body;
28 + if (normalized.actionId === 'github.pull_request.merge') {
29 + const { repoId, prNumber, headSha } = normalized.input || {};
30 + 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');
31 + if (!this.replayStore || typeof this.replayStore.put !== 'function' || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
32 + await this.replayStore.put({ ownerId: normalized.ownerId, nonce, expiresAt, payload: normalized });
33 + body = `s.m.${toBase36Int(expiresAt)}.${nonce}`;
34 + } else body = this.#encodeBody(normalized);
35 + const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
36 if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data'); return token;
37 }
38 async verify(token, expectations = {}) {
@@ -39,36 +40,18 @@ export class ApprovalService {
40 const parts = token.split('.'); if (parts.length < 3) throw new Error('Invalid approval token'); const signaturePart = parts.pop(); const body = parts.join('.'); let suppliedSignature;
41 try { suppliedSignature = base64UrlToBytes(signaturePart); } catch { throw new Error('Invalid approval signature'); }
42 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');
45 - if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch'); return payload;
46 - }
47 - async consume(token, expectations = {}) {
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 - }
51 - #encodeBody(payload) {
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;
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 - }
61 - return `j.${textToBase64Url(JSON.stringify(payload))}`;
62 - }
63 - #decodeBody(body, ownerId) {
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 };
43 + let payload;
44 + if (body.startsWith('s.m.')) {
45 + const state = body.split('.'); if (state.length !== 4) throw new Error('Invalid approval payload'); const expiresAt = fromBase36Int(state[2]); const nonce = state[3]; if (expiresAt < this.now()) throw new Error('Approval token expired');
46 + if (!this.replayStore || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
47 + payload = await this.replayStore.peek({ ownerId, nonce }); if (!payload) throw new Error('Approval context is unavailable');
48 + if (payload.expiresAt !== expiresAt || payload.nonce !== nonce || payload.ownerId !== ownerId || payload.actionId !== 'github.pull_request.merge') throw new Error('Approval context mismatch');
49 + } else payload = this.#decodeBody(body, ownerId);
50 + 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;
51 }
52 + 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; }
53 + #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))}`; }
54 + #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 }; }
55 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); }
56 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; }
57 #nonce() { const bytes = new Uint8Array(6); crypto.getRandomValues(bytes); return bytesToBase64Url(bytes); }