Personal Telegram developer console for GitHub

feat: add compact HMAC approval service

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