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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
|
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import * as crypto from "crypto";
import { db } from "../db";
import { orgSsoConfigs, orgSsoSessions, organizations, users, sessions } from "../db/schema";
import { generateSessionToken, sessionCookieOptions, sessionExpiry } from "../lib/auth";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
const samlSso = new Hono<AuthEnv>();
samlSso.use("*", softAuth);
function getBaseUrl(): string {
return process.env.APP_URL || process.env.BASE_URL || "https://gluecron.com";
}
function generateId(len = 16): string {
return crypto.randomBytes(len).toString("hex");
}
async function getOrgBySlug(slug: string) {
const [org] = await db
.select()
.from(organizations)
.where(eq(organizations.slug, slug))
.limit(1);
return org ?? null;
}
async function getOrgSsoConfig(orgId: string) {
const [cfg] = await db
.select()
.from(orgSsoConfigs)
.where(eq(orgSsoConfigs.orgId, orgId))
.limit(1);
return cfg ?? null;
}
async function findOrCreateSsoUser(
email: string,
name: string | undefined,
preferredUsername: string | undefined,
orgId: string
): Promise<{ ok: true; userId: string } | { ok: false; error: string }> {
if (!email) return { ok: false, error: "No email returned from IdP" };
const [existing] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.email, email))
.limit(1);
if (existing) return { ok: true, userId: existing.id };
let username = (preferredUsername || email.split("@")[0])
.toLowerCase()
.replace(/[^a-z0-9_-]/g, "-")
.slice(0, 39);
if (!username) username = "user-" + generateId(4);
const [taken] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.username, username))
.limit(1);
if (taken) username = username + "-" + generateId(4);
const [created] = await db
.insert(users)
.values({
username,
email,
displayName: name || username,
passwordHash: await Bun.password.hash(generateId(32), {
algorithm: "bcrypt",
cost: 10,
}),
emailVerifiedAt: new Date(),
})
.returning({ id: users.id });
if (!created) return { ok: false, error: "Failed to create user account" };
return { ok: true, userId: created.id };
}
async function createUserSession(userId: string): Promise<string> {
const token = generateSessionToken();
await db.insert(sessions).values({
userId,
token,
expiresAt: sessionExpiry(),
});
return token;
}
samlSso.get("/sso/saml/:orgSlug/metadata", async (c) => {
const { orgSlug } = c.req.param();
const org = await getOrgBySlug(orgSlug);
if (!org) return c.text("Organization not found", 404);
const cfg = await getOrgSsoConfig(org.id);
if (!cfg || cfg.provider !== "saml") {
return c.text("SAML not configured for this organization", 404);
}
const base = getBaseUrl();
const spEntityId =
cfg.spEntityId || `${base}/sso/saml/${orgSlug}`;
const callbackUrl = `${base}/sso/saml/${orgSlug}/callback`;
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
entityID="${escapeXml(spEntityId)}">
<SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="true"
protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</NameIDFormat>
<AssertionConsumerService
Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
Location="${escapeXml(callbackUrl)}"
index="1"/>
</SPSSODescriptor>
</EntityDescriptor>`;
return c.body(xml, 200, {
"Content-Type": "application/xml; charset=utf-8",
"Cache-Control": "public, max-age=3600",
});
});
samlSso.get("/sso/saml/:orgSlug/login", async (c) => {
const { orgSlug } = c.req.param();
const org = await getOrgBySlug(orgSlug);
if (!org) return c.redirect(`/login?error=${encodeURIComponent("Organization not found")}`);
const cfg = await getOrgSsoConfig(org.id);
if (!cfg || !cfg.enabled || cfg.provider !== "saml") {
return c.redirect(`/login?error=${encodeURIComponent("SAML SSO not enabled for this organization")}`);
}
if (!cfg.idpSsoUrl) {
return c.redirect(`/login?error=${encodeURIComponent("SAML IdP SSO URL not configured")}`);
}
const base = getBaseUrl();
const spEntityId = cfg.spEntityId || `${base}/sso/saml/${orgSlug}`;
const acsUrl = `${base}/sso/saml/${orgSlug}/callback`;
const requestId = "_" + generateId(20);
const issueInstant = new Date().toISOString();
const relayState = generateId(16);
const authnRequest = `<samlp:AuthnRequest
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="${requestId}"
Version="2.0"
IssueInstant="${issueInstant}"
Destination="${escapeXml(cfg.idpSsoUrl)}"
AssertionConsumerServiceURL="${escapeXml(acsUrl)}"
ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST">
<saml:Issuer>${escapeXml(spEntityId)}</saml:Issuer>
</samlp:AuthnRequest>`;
const encoded = Buffer.from(authnRequest).toString("base64");
const params = new URLSearchParams({
SAMLRequest: encoded,
RelayState: relayState,
});
setCookie(c, "saml_relay_state", relayState, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
path: "/",
maxAge: 600,
});
setCookie(c, "saml_org", orgSlug, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
path: "/",
maxAge: 600,
});
return c.redirect(`${cfg.idpSsoUrl}?${params.toString()}`);
});
samlSso.post("/sso/saml/:orgSlug/callback", async (c) => {
const { orgSlug } = c.req.param();
const org = await getOrgBySlug(orgSlug);
if (!org) return c.redirect(`/login?error=${encodeURIComponent("Organization not found")}`);
const cfg = await getOrgSsoConfig(org.id);
if (!cfg || !cfg.enabled || cfg.provider !== "saml") {
return c.redirect(`/login?error=${encodeURIComponent("SAML SSO not enabled for this organization")}`);
}
const expectedRelay = getCookie(c, "saml_relay_state");
const expectedOrg = getCookie(c, "saml_org");
deleteCookie(c, "saml_relay_state", { path: "/" });
deleteCookie(c, "saml_org", { path: "/" });
if (!expectedRelay || expectedOrg !== orgSlug) {
return c.redirect(`/login?error=${encodeURIComponent("SAML relay state mismatch. Please try again.")}`);
}
const body = await c.req.parseBody();
const samlResponse = String(body.SAMLResponse || "");
if (!samlResponse) {
return c.redirect(`/login?error=${encodeURIComponent("No SAMLResponse received")}`);
}
try {
const claims = parseSamlResponse(samlResponse, cfg.idpCertificate || "", cfg);
if (!claims.ok) {
return c.redirect(`/login?error=${encodeURIComponent(claims.error)}`);
}
const result = await findOrCreateSsoUser(
claims.email,
claims.name,
claims.username,
org.id
);
if (!result.ok) {
return c.redirect(`/login?error=${encodeURIComponent(result.error)}`);
}
await db.insert(orgSsoSessions).values({
userId: result.userId,
orgId: org.id,
idpSessionId: claims.sessionIndex ?? null,
expiresAt: new Date(Date.now() + 8 * 60 * 60 * 1000),
});
const token = await createUserSession(result.userId);
setCookie(c, "session", token, sessionCookieOptions());
return c.redirect("/");
} catch (err) {
console.error("[saml-sso] callback error:", err);
return c.redirect(`/login?error=${encodeURIComponent("SAML authentication failed. Check IdP configuration.")}`);
}
});
samlSso.get("/sso/oidc/:orgSlug/login", async (c) => {
const { orgSlug } = c.req.param();
const org = await getOrgBySlug(orgSlug);
if (!org) return c.redirect(`/login?error=${encodeURIComponent("Organization not found")}`);
const cfg = await getOrgSsoConfig(org.id);
if (!cfg || !cfg.enabled || cfg.provider !== "oidc") {
return c.redirect(`/login?error=${encodeURIComponent("OIDC SSO not enabled for this organization")}`);
}
if (!cfg.oidcDiscoveryUrl || !cfg.oidcClientId) {
return c.redirect(`/login?error=${encodeURIComponent("OIDC not fully configured")}`);
}
let authorizationEndpoint: string;
try {
const discoveryUrl = cfg.oidcDiscoveryUrl.replace(/\/$/, "") + "/.well-known/openid-configuration";
const res = await fetch(discoveryUrl);
if (!res.ok) throw new Error(`Discovery returned ${res.status}`);
const doc = await res.json() as { authorization_endpoint: string };
authorizationEndpoint = doc.authorization_endpoint;
if (!authorizationEndpoint) throw new Error("No authorization_endpoint in discovery");
} catch (err) {
console.error("[oidc-sso] discovery error:", err);
return c.redirect(`/login?error=${encodeURIComponent("OIDC discovery failed")}`);
}
const base = getBaseUrl();
const redirectUri = `${base}/sso/oidc/${orgSlug}/callback`;
const state = generateId(16);
const nonce = generateId(16);
setCookie(c, "oidc_state", state, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
path: "/",
maxAge: 600,
});
setCookie(c, "oidc_nonce", nonce, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
path: "/",
maxAge: 600,
});
setCookie(c, "oidc_org", orgSlug, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
path: "/",
maxAge: 600,
});
const params = new URLSearchParams({
client_id: cfg.oidcClientId,
redirect_uri: redirectUri,
response_type: "code",
scope: "openid email profile",
state,
nonce,
});
return c.redirect(`${authorizationEndpoint}?${params.toString()}`);
});
samlSso.get("/sso/oidc/:orgSlug/callback", async (c) => {
const { orgSlug } = c.req.param();
const org = await getOrgBySlug(orgSlug);
if (!org) return c.redirect(`/login?error=${encodeURIComponent("Organization not found")}`);
const cfg = await getOrgSsoConfig(org.id);
if (!cfg || !cfg.enabled || cfg.provider !== "oidc") {
return c.redirect(`/login?error=${encodeURIComponent("OIDC SSO not enabled")}`);
}
const code = c.req.query("code");
const state = c.req.query("state");
const errCode = c.req.query("error");
if (errCode) {
return c.redirect(`/login?error=${encodeURIComponent(`IdP error: ${errCode}`)}`);
}
if (!code || !state) {
return c.redirect(`/login?error=${encodeURIComponent("Missing code or state")}`);
}
const expectedState = getCookie(c, "oidc_state");
const expectedOrg = getCookie(c, "oidc_org");
deleteCookie(c, "oidc_state", { path: "/" });
deleteCookie(c, "oidc_nonce", { path: "/" });
deleteCookie(c, "oidc_org", { path: "/" });
if (!expectedState || expectedState !== state || expectedOrg !== orgSlug) {
return c.redirect(`/login?error=${encodeURIComponent("OIDC state mismatch. Please try again.")}`);
}
try {
const discoveryUrl = cfg.oidcDiscoveryUrl!.replace(/\/$/, "") + "/.well-known/openid-configuration";
const discoveryRes = await fetch(discoveryUrl);
const discovery = await discoveryRes.json() as {
token_endpoint: string;
userinfo_endpoint: string;
};
const base = getBaseUrl();
const redirectUri = `${base}/sso/oidc/${orgSlug}/callback`;
const tokenRes = await fetch(discovery.token_endpoint, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
client_id: cfg.oidcClientId!,
client_secret: cfg.oidcClientSecret || "",
}).toString(),
});
if (!tokenRes.ok) {
throw new Error(`token_endpoint returned ${tokenRes.status}`);
}
const tokens = await tokenRes.json() as { access_token: string };
const userinfoRes = await fetch(discovery.userinfo_endpoint, {
headers: { Authorization: `Bearer ${tokens.access_token}` },
});
if (!userinfoRes.ok) {
throw new Error(`userinfo_endpoint returned ${userinfoRes.status}`);
}
const userinfo = await userinfoRes.json() as {
email?: string;
name?: string;
preferred_username?: string;
sub?: string;
};
const result = await findOrCreateSsoUser(
userinfo.email || "",
userinfo.name,
userinfo.preferred_username,
org.id
);
if (!result.ok) {
return c.redirect(`/login?error=${encodeURIComponent(result.error)}`);
}
await db.insert(orgSsoSessions).values({
userId: result.userId,
orgId: org.id,
idpSessionId: userinfo.sub ?? null,
expiresAt: new Date(Date.now() + 8 * 60 * 60 * 1000),
});
const token = await createUserSession(result.userId);
setCookie(c, "session", token, sessionCookieOptions());
return c.redirect("/");
} catch (err) {
console.error("[oidc-sso] callback error:", err);
return c.redirect(`/login?error=${encodeURIComponent("OIDC authentication failed.")}`);
}
});
function escapeXml(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
interface SamlClaims {
ok: true;
email: string;
name?: string;
username?: string;
sessionIndex?: string;
}
interface SamlError {
ok: false;
error: string;
}
function parseSamlResponse(
base64Response: string,
idpCertPem: string,
cfg: { attributeMapping?: Record<string, string> | null }
): SamlClaims | SamlError {
let xml: string;
try {
xml = Buffer.from(base64Response, "base64").toString("utf-8");
} catch {
return { ok: false, error: "Failed to decode SAMLResponse" };
}
if (!xml.includes("saml") && !xml.includes("SAML")) {
return { ok: false, error: "Invalid SAML response format" };
}
if (
xml.includes("urn:oasis:names:tc:SAML:2.0:status:Responder") ||
xml.includes("urn:oasis:names:tc:SAML:2.0:status:Requester")
) {
const statusMatch = xml.match(/<samlp?:StatusMessage[^>]*>([^<]*)</);
const msg = statusMatch ? statusMatch[1].trim() : "IdP rejected the request";
return { ok: false, error: `SAML error: ${msg}` };
}
if (idpCertPem && idpCertPem.trim()) {
const sigValid = verifySamlSignature(xml, idpCertPem);
if (!sigValid) {
return { ok: false, error: "SAML signature verification failed" };
}
}
const mapping = cfg.attributeMapping || {
email: "email",
name: "name",
username: "preferred_username",
};
const attrs = extractSamlAttributes(xml);
let email = attrs[mapping.email ?? "email"]
|| attrs["email"]
|| attrs["mail"]
|| attrs["emailAddress"]
|| extractNameId(xml)
|| "";
email = email.trim();
if (!email || !email.includes("@")) {
return { ok: false, error: "No email found in SAML assertion" };
}
const name =
attrs[mapping.name ?? "name"] ||
attrs["displayName"] ||
attrs["cn"] ||
attrs["givenName"] ||
undefined;
const username =
attrs[mapping.username ?? "preferred_username"] ||
attrs["uid"] ||
attrs["samaccountname"] ||
undefined;
const sessionIndex = extractSessionIndex(xml);
return { ok: true, email, name, username, sessionIndex };
}
function extractNameId(xml: string): string {
const m = xml.match(/<(?:saml|saml2):NameID[^>]*>([^<]+)<\/(?:saml|saml2):NameID>/);
return m ? m[1].trim() : "";
}
function extractSessionIndex(xml: string): string | undefined {
const m = xml.match(/SessionIndex="([^"]+)"/);
return m ? m[1] : undefined;
}
function extractSamlAttributes(xml: string): Record<string, string> {
const attrs: Record<string, string> = {};
const attrRe =
/<(?:saml|saml2):Attribute\s[^>]*(?:Name|FriendlyName)="([^"]+)"[^>]*>\s*<(?:saml|saml2):AttributeValue[^>]*>([^<]+)<\/(?:saml|saml2):AttributeValue>/gi;
let m: RegExpExecArray | null;
while ((m = attrRe.exec(xml)) !== null) {
const key = m[1].toLowerCase().replace(/^.*\//, "");
attrs[key] = m[2].trim();
}
return attrs;
}
function verifySamlSignature(xml: string, certPem: string): boolean {
try {
const sigValueMatch = xml.match(
/<(?:ds:)?SignatureValue[^>]*>([\s\S]*?)<\/(?:ds:)?SignatureValue>/
);
if (!sigValueMatch) return false;
const signatureValue = Buffer.from(
sigValueMatch[1].replace(/\s+/g, ""),
"base64"
);
const signedInfoMatch = xml.match(
/(<(?:ds:)?SignedInfo[\s\S]*?<\/(?:ds:)?SignedInfo>)/
);
if (!signedInfoMatch) return false;
const signedInfoXml = signedInfoMatch[1];
const algMatch = xml.match(/Algorithm="([^"]+)"/);
const alg = algMatch ? algMatch[1] : "";
let hashAlg: string;
if (alg.includes("sha256")) hashAlg = "SHA256";
else if (alg.includes("sha512")) hashAlg = "SHA512";
else hashAlg = "SHA1";
let pem = certPem.trim();
if (!pem.startsWith("-----BEGIN CERTIFICATE-----")) {
pem = `-----BEGIN CERTIFICATE-----\n${pem}\n-----END CERTIFICATE-----`;
}
const verifier = crypto.createVerify(`RSA-${hashAlg}`);
verifier.update(signedInfoXml, "utf8");
return verifier.verify(pem, signatureValue);
} catch (err) {
console.warn("[saml-sso] signature verification error:", err);
return false;
}
}
export default samlSso;
|