1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
|
import { sql } from "drizzle-orm";
import { db } from "../db";
export type Audience = "crontech" | "gatetest";
export const ALLOWED_AUDIENCES: readonly Audience[] = [
"crontech",
"gatetest",
] as const;
export const ALLOWED_SCOPES: readonly string[] = [
"deploy:read",
"deploy:write",
"test:run",
"test:heal",
"signals:write",
"signals:read",
"identity:read",
] as const;
export const DEFAULT_TTL_SECONDS: number = 15 * 60;
export const ISSUER = "gluecron" as const;
export interface CrossProductClaims {
sub: string;
email: string;
iss: typeof ISSUER;
aud: Audience;
exp: number;
iat: number;
jti: string;
scopes: string[];
}
export interface SignInput {
userId: string;
email: string;
audience: Audience;
scopes?: string[];
ttlSeconds?: number;
}
export interface SignResult {
token: string;
jti: string;
expiresAt: Date;
scopes: string[];
}
export type VerifyResult =
| {
valid: true;
sub: string;
email: string;
audience: Audience;
scopes: string[];
jti: string;
expiresAt: Date;
}
| { valid: false; reason: VerifyFailureReason };
export type VerifyFailureReason =
| "malformed"
| "bad_algorithm"
| "bad_signature"
| "expired"
| "unknown_audience"
| "revoked"
| "unknown_jti";
export interface ActiveCrossProductToken {
jti: string;
userId: string;
audience: Audience;
scopes: string[];
issuedAt: Date;
expiresAt: Date;
revokedAt: Date | null;
}
const DEV_FALLBACK_SEED = "gluecron-dev-secret-do-not-use-in-prod";
let cachedKey: Promise<CryptoKey> | null = null;
function resolveSecret(): string {
const envVar = process.env.CROSS_PRODUCT_SIGNING_SECRET;
if (envVar && envVar.length >= 16) return envVar;
if (process.env.NODE_ENV === "production") {
throw new Error(
"CROSS_PRODUCT_SIGNING_SECRET must be set (>=16 chars) in production"
);
}
return DEV_FALLBACK_SEED;
}
async function getSigningKey(): Promise<CryptoKey> {
if (!cachedKey) {
cachedKey = (async () => {
const secret = resolveSecret();
const raw = new TextEncoder().encode(secret);
return await crypto.subtle.importKey(
"raw",
raw,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"]
);
})();
}
return cachedKey;
}
function resetSigningKeyCache(): void {
cachedKey = null;
}
function b64urlEncode(bytes: Uint8Array): string {
let bin = "";
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function b64urlEncodeString(str: string): string {
return b64urlEncode(new TextEncoder().encode(str));
}
function b64urlDecode(input: string): Uint8Array {
const pad = input.length % 4 === 0 ? "" : "=".repeat(4 - (input.length % 4));
const b64 = input.replace(/-/g, "+").replace(/_/g, "/") + pad;
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
function b64urlDecodeString(input: string): string {
return new TextDecoder().decode(b64urlDecode(input));
}
function uuidV4(): string {
const b = crypto.getRandomValues(new Uint8Array(16));
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
const hex = Array.from(b).map((x) => x.toString(16).padStart(2, "0"));
return (
hex.slice(0, 4).join("") +
"-" +
hex.slice(4, 6).join("") +
"-" +
hex.slice(6, 8).join("") +
"-" +
hex.slice(8, 10).join("") +
"-" +
hex.slice(10, 16).join("")
);
}
export function validateScopes(requested: readonly string[] | undefined): string[] {
if (!requested || !Array.isArray(requested)) return [];
const seen = new Set<string>();
const out: string[] = [];
const allow = new Set<string>(ALLOWED_SCOPES);
for (const raw of requested) {
if (typeof raw !== "string") continue;
const s = raw.trim();
if (!s || seen.has(s)) continue;
if (allow.has(s)) {
out.push(s);
seen.add(s);
}
}
return out;
}
export function isAllowedAudience(value: unknown): value is Audience {
return (
typeof value === "string" &&
(ALLOWED_AUDIENCES as readonly string[]).includes(value)
);
}
async function hmacSign(signingInput: string): Promise<string> {
const key = await getSigningKey();
const sig = await crypto.subtle.sign(
"HMAC",
key,
new TextEncoder().encode(signingInput)
);
return b64urlEncode(new Uint8Array(sig));
}
async function hmacVerify(
signingInput: string,
signatureB64: string
): Promise<boolean> {
const key = await getSigningKey();
const sig = b64urlDecode(signatureB64);
return await crypto.subtle.verify(
"HMAC",
key,
sig,
new TextEncoder().encode(signingInput)
);
}
export async function signCrossProductToken(
input: SignInput
): Promise<SignResult> {
if (!input.userId || typeof input.userId !== "string") {
throw new Error("userId is required");
}
if (!isAllowedAudience(input.audience)) {
throw new Error(`unknown audience: ${String(input.audience)}`);
}
const ttl = Math.max(
60,
Math.min(input.ttlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS)
);
const scopes = validateScopes(input.scopes ?? []);
const jti = uuidV4();
const iat = Math.floor(Date.now() / 1000);
const exp = iat + ttl;
const expiresAt = new Date(exp * 1000);
const header = { alg: "HS256", typ: "JWT" } as const;
const payload: CrossProductClaims = {
sub: input.userId,
email: input.email,
iss: ISSUER,
aud: input.audience,
exp,
iat,
jti,
scopes,
};
const headerB = b64urlEncodeString(JSON.stringify(header));
const payloadB = b64urlEncodeString(JSON.stringify(payload));
const signingInput = `${headerB}.${payloadB}`;
const sigB = await hmacSign(signingInput);
const token = `${signingInput}.${sigB}`;
try {
await db.execute(sql`
INSERT INTO cross_product_tokens (jti, user_id, audience, scopes, issued_at, expires_at)
VALUES (
${jti},
${input.userId},
${input.audience},
${JSON.stringify(scopes)},
to_timestamp(${iat}),
to_timestamp(${exp})
)
`);
} catch (err) {
console.error("[cross-product-auth] failed to persist jti:", err);
}
return { token, jti, expiresAt, scopes };
}
export async function verifyCrossProductToken(
token: string
): Promise<VerifyResult> {
if (!token || typeof token !== "string") {
return { valid: false, reason: "malformed" };
}
const parts = token.split(".");
if (parts.length !== 3) return { valid: false, reason: "malformed" };
const [headerB, payloadB, sigB] = parts;
let header: { alg?: unknown; typ?: unknown };
let payload: Partial<CrossProductClaims> & Record<string, unknown>;
try {
header = JSON.parse(b64urlDecodeString(headerB));
payload = JSON.parse(b64urlDecodeString(payloadB));
} catch {
return { valid: false, reason: "malformed" };
}
if (header.alg !== "HS256" || header.typ !== "JWT") {
return { valid: false, reason: "bad_algorithm" };
}
const signingInput = `${headerB}.${payloadB}`;
let sigOk = false;
try {
sigOk = await hmacVerify(signingInput, sigB);
} catch {
sigOk = false;
}
if (!sigOk) return { valid: false, reason: "bad_signature" };
if (typeof payload.exp !== "number") {
return { valid: false, reason: "malformed" };
}
const now = Math.floor(Date.now() / 1000);
if (payload.exp <= now) return { valid: false, reason: "expired" };
if (!isAllowedAudience(payload.aud)) {
return { valid: false, reason: "unknown_audience" };
}
if (typeof payload.sub !== "string" || !payload.sub) {
return { valid: false, reason: "malformed" };
}
if (typeof payload.jti !== "string" || !payload.jti) {
return { valid: false, reason: "malformed" };
}
try {
const rows = (await db.execute(sql`
SELECT revoked_at FROM cross_product_tokens
WHERE jti = ${payload.jti}
LIMIT 1
`)) as unknown as Array<{ revoked_at: string | null }>;
const row = Array.isArray(rows) ? rows[0] : undefined;
if (row && row.revoked_at) {
return { valid: false, reason: "revoked" };
}
if (!row && process.env.CROSS_PRODUCT_STRICT_JTI === "1") {
return { valid: false, reason: "unknown_jti" };
}
} catch (err) {
console.error("[cross-product-auth] revocation lookup failed:", err);
}
const scopes = Array.isArray(payload.scopes)
? (payload.scopes as unknown[]).filter(
(s): s is string => typeof s === "string"
)
: [];
return {
valid: true,
sub: payload.sub,
email: typeof payload.email === "string" ? payload.email : "",
audience: payload.aud,
scopes,
jti: payload.jti,
expiresAt: new Date(payload.exp * 1000),
};
}
export async function revokeCrossProductToken(
jti: string,
userId: string
): Promise<boolean> {
if (!jti || !userId) return false;
try {
const rows = (await db.execute(sql`
UPDATE cross_product_tokens
SET revoked_at = now()
WHERE jti = ${jti}
AND user_id = ${userId}
AND revoked_at IS NULL
RETURNING jti
`)) as unknown as Array<{ jti: string }>;
return Array.isArray(rows) && rows.length > 0;
} catch (err) {
console.error("[cross-product-auth] revoke failed:", err);
return false;
}
}
export async function listActiveCrossProductTokens(
userId: string
): Promise<ActiveCrossProductToken[]> {
if (!userId) return [];
try {
const rows = (await db.execute(sql`
SELECT jti, user_id, audience, scopes, issued_at, expires_at, revoked_at
FROM cross_product_tokens
WHERE user_id = ${userId}
AND revoked_at IS NULL
AND expires_at > now()
ORDER BY issued_at DESC
LIMIT 50
`)) as unknown as Array<Record<string, unknown>>;
return (rows || []).map(rowToActive).filter(
(r): r is ActiveCrossProductToken => r !== null
);
} catch (err) {
console.error("[cross-product-auth] list failed:", err);
return [];
}
}
function rowToActive(row: Record<string, unknown>): ActiveCrossProductToken | null {
if (!row) return null;
const jti = row.jti;
const userId = row.user_id;
const audience = row.audience;
if (typeof jti !== "string" || typeof userId !== "string") return null;
if (!isAllowedAudience(audience)) return null;
let scopes: string[] = [];
if (typeof row.scopes === "string") {
try {
const parsed = JSON.parse(row.scopes);
if (Array.isArray(parsed)) {
scopes = parsed.filter((s): s is string => typeof s === "string");
}
} catch {
scopes = [];
}
}
const issuedAt = row.issued_at ? new Date(String(row.issued_at)) : new Date();
const expiresAt = row.expires_at
? new Date(String(row.expires_at))
: new Date();
const revokedAt = row.revoked_at ? new Date(String(row.revoked_at)) : null;
return { jti, userId, audience, scopes, issuedAt, expiresAt, revokedAt };
}
export const __test = {
resetSigningKeyCache,
b64urlEncode,
b64urlEncodeString,
b64urlDecode,
b64urlDecodeString,
uuidV4,
resolveSecret,
};
|