CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* Block I10 — Enterprise SSO (OIDC) routes.
*
* GET /admin/sso — site-admin config page
* POST /admin/sso — save config
* GET /login/sso — begin OIDC flow (redirect to IdP)
* GET /login/sso/callback — handle IdP redirect, create session
* POST /settings/sso/unlink — user drops their SSO link
*/
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import { db } from "../db";
import { ssoUserLinks } from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { isSiteAdmin } from "../lib/admin";
import { audit } from "../lib/notify";
import {
buildAuthorizeUrl,
exchangeCode,
fetchUserinfo,
findOrCreateUserFromSso,
getSsoConfig,
issueSsoSession,
randomToken,
ssoRedirectUri,
upsertSsoConfig,
} from "../lib/sso";
import { sessionCookieOptions } from "../lib/auth";
const sso = new Hono<AuthEnv>();
sso.use("*", softAuth);
// Re-export the shared cookie options under the SSO namespace (buildable types)
// — defined here so we don't double-import under the same name.
function ssoStateCookieOpts(): {
httpOnly: boolean;
secure: boolean;
sameSite: "Lax";
path: string;
maxAge: number;
} {
return {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "Lax",
path: "/",
maxAge: 600, // 10 min to complete the flow
};
}
// ----------------------------------------------------------------------------
// Admin config page
// ----------------------------------------------------------------------------
async function adminGate(c: any): Promise<{ user: any } | Response> {
const user = c.get("user");
if (!user) return c.redirect("/login?next=/admin/sso");
if (!(await isSiteAdmin(user.id))) {
return c.html(
<Layout title="Forbidden" user={user}>
<div class="empty-state">
<h2>403 — Not a site admin</h2>
<p>You don't have permission to configure SSO.</p>
</div>
</Layout>,
403
);
}
return { user };
}
sso.get("/admin/sso", requireAuth, async (c) => {
const g = await adminGate(c);
if (g instanceof Response) return g;
const { user } = g;
const cfg = await getSsoConfig();
const success = c.req.query("success");
const error = c.req.query("error");
const redirectUri = ssoRedirectUri();
return c.html(
<Layout title="SSO — Admin" user={user}>
<div class="settings-container" style="max-width:780px">
<h2>Enterprise SSO (OpenID Connect)</h2>
<p style="color:var(--text-muted)">
Configure a single site-wide OIDC provider. Users will see a
"Sign in with{" "}
<code>{cfg?.providerName || "SSO"}</code>" button on /login.
</p>
<div class="panel" style="padding:12px;margin-bottom:16px">
<div
style="font-size:12px;text-transform:uppercase;color:var(--text-muted)"
>
Redirect URI — paste this into your IdP
</div>
<code style="font-size:13px">{redirectUri}</code>
</div>
{success && (
<div class="auth-success">{decodeURIComponent(success)}</div>
)}
{error && <div class="auth-error">{decodeURIComponent(error)}</div>}
<div
class="panel"
style="padding:14px 16px;margin-bottom:14px;display:flex;gap:10px;flex-wrap:wrap;align-items:center"
>
<span style="font-size:13px;color:var(--text-muted)">
Quick fill from a preset:
</span>
<button
type="button"
class="btn btn-sm"
onclick="window.gluecronSsoPreset('google')"
>
Google Workspace
</button>
<button
type="button"
class="btn btn-sm"
onclick="window.gluecronSsoPreset('okta')"
>
Okta
</button>
<button
type="button"
class="btn btn-sm"
onclick="window.gluecronSsoPreset('auth0')"
>
Auth0
</button>
<button
type="button"
class="btn btn-sm"
onclick="window.gluecronSsoPreset('azure')"
>
Microsoft Entra
</button>
</div>
<script
dangerouslySetInnerHTML={{
__html: /* js */ `
window.gluecronSsoPreset = function (provider) {
var P = {
google: {
provider_name: 'Google',
issuer: 'https://accounts.google.com',
authorization_endpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
token_endpoint: 'https://oauth2.googleapis.com/token',
userinfo_endpoint: 'https://openidconnect.googleapis.com/v1/userinfo',
scopes: 'openid email profile',
},
okta: {
provider_name: 'Okta',
issuer: 'https://YOUR-TENANT.okta.com',
authorization_endpoint: 'https://YOUR-TENANT.okta.com/oauth2/v1/authorize',
token_endpoint: 'https://YOUR-TENANT.okta.com/oauth2/v1/token',
userinfo_endpoint: 'https://YOUR-TENANT.okta.com/oauth2/v1/userinfo',
scopes: 'openid email profile',
},
auth0: {
provider_name: 'Auth0',
issuer: 'https://YOUR-TENANT.auth0.com',
authorization_endpoint: 'https://YOUR-TENANT.auth0.com/authorize',
token_endpoint: 'https://YOUR-TENANT.auth0.com/oauth/token',
userinfo_endpoint: 'https://YOUR-TENANT.auth0.com/userinfo',
scopes: 'openid email profile',
},
azure: {
provider_name: 'Microsoft',
issuer: 'https://login.microsoftonline.com/YOUR-TENANT-ID/v2.0',
authorization_endpoint: 'https://login.microsoftonline.com/YOUR-TENANT-ID/oauth2/v2.0/authorize',
token_endpoint: 'https://login.microsoftonline.com/YOUR-TENANT-ID/oauth2/v2.0/token',
userinfo_endpoint: 'https://graph.microsoft.com/oidc/userinfo',
scopes: 'openid email profile',
},
};
var p = P[provider];
if (!p) return;
for (var k in p) {
var el = document.getElementById(k);
if (el) el.value = p[k];
}
};
`,
}}
/>
);
});
sso.post("/admin/sso", requireAuth, async (c) => {
const g = await adminGate(c);
if (g instanceof Response) return g;
const { user } = g;
const body = await c.req.parseBody();
const existing = await getSsoConfig();
const secretSubmitted = String(body.client_secret || "");
const result = await upsertSsoConfig({
enabled: String(body.enabled || "") === "1",
providerName: String(body.provider_name || "SSO"),
issuer: String(body.issuer || ""),
authorizationEndpoint: String(body.authorization_endpoint || ""),
tokenEndpoint: String(body.token_endpoint || ""),
userinfoEndpoint: String(body.userinfo_endpoint || ""),
clientId: String(body.client_id || ""),
clientSecret:
secretSubmitted.trim().length === 0 && existing?.clientSecret
? existing.clientSecret
: secretSubmitted,
scopes: String(body.scopes || "openid profile email"),
allowedEmailDomains: String(body.allowed_email_domains || ""),
autoCreateUsers: String(body.auto_create_users || "") === "1",
});
if (!result.ok) {
return c.redirect(
`/admin/sso?error=${encodeURIComponent(result.error)}`
);
}
await audit({
userId: user.id,
action: "admin.sso.configure",
metadata: {
enabled: String(body.enabled || "") === "1",
provider: String(body.provider_name || "SSO"),
autoCreateUsers: String(body.auto_create_users || "") === "1",
allowedDomains: String(body.allowed_email_domains || "") || null,
},
});
return c.redirect(
`/admin/sso?success=${encodeURIComponent("SSO settings saved.")}`
);
});
// ----------------------------------------------------------------------------
// OIDC flow
// ----------------------------------------------------------------------------
sso.get("/login/sso", async (c) => {
const cfg = await getSsoConfig();
if (!cfg || !cfg.enabled) {
return c.redirect(
`/login?error=${encodeURIComponent("SSO is not enabled")}`
);
}
if (
!cfg.authorizationEndpoint ||
!cfg.tokenEndpoint ||
!cfg.userinfoEndpoint ||
!cfg.clientId ||
!cfg.clientSecret
) {
return c.redirect(
`/login?error=${encodeURIComponent("SSO is not fully configured")}`
);
}
const state = randomToken(16);
const nonce = randomToken(16);
const redirectUri = ssoRedirectUri();
let target: string;
try {
target = buildAuthorizeUrl(cfg, state, nonce, redirectUri);
} catch (err) {
return c.redirect(
`/login?error=${encodeURIComponent(
err instanceof Error ? err.message : "SSO misconfigured"
)}`
);
}
setCookie(c, "sso_state", state, ssoStateCookieOpts());
setCookie(c, "sso_nonce", nonce, ssoStateCookieOpts());
return c.redirect(target);
});
sso.get("/login/sso/callback", async (c) => {
const cfg = await getSsoConfig();
if (!cfg || !cfg.enabled) {
return c.redirect(
`/login?error=${encodeURIComponent("SSO is 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(
`SSO provider error: ${errCode}`
)}`
);
}
if (!code || !state) {
return c.redirect(
`/login?error=${encodeURIComponent("Missing code or state")}`
);
}
const expectedState = getCookie(c, "sso_state");
if (!expectedState || expectedState !== state) {
return c.redirect(
`/login?error=${encodeURIComponent(
"SSO state mismatch. Please try again."
)}`
);
}
// One-shot cookies — burn them even on failure
deleteCookie(c, "sso_state", { path: "/" });
deleteCookie(c, "sso_nonce", { path: "/" });
try {
const tokens = await exchangeCode(cfg, code, ssoRedirectUri());
const claims = await fetchUserinfo(cfg, tokens.access_token);
const result = await findOrCreateUserFromSso(claims, cfg);
if (!result.ok) {
return c.redirect(`/login?error=${encodeURIComponent(result.error)}`);
}
const token = await issueSsoSession(result.user.id);
setCookie(c, "session", token, sessionCookieOptions());
await audit({
userId: result.user.id,
action: "auth.sso.login",
metadata: {
provider: cfg.providerName,
sub: claims.sub,
email: claims.email || null,
},
});
return c.redirect("/");
} catch (err) {
console.error("[sso] callback error:", err);
const friendly = friendlySsoError(err);
return c.redirect(`/login?error=${encodeURIComponent(friendly)}`);
}
});
/**
* Map the raw OIDC failure shape to a one-sentence message safe to render
* inside an HTML <div>. We never surface the IdP's response body — those
* have been Google 404 HTML pages, Azure JSON blobs full of object IDs,
* etc. The raw `err.message` is logged via console.error above so admins
* can still diagnose from server logs.
*/
function friendlySsoError(err: unknown): string {
const raw = err instanceof Error ? err.message : String(err ?? "");
if (raw.includes("token_endpoint")) {
if (/\b40[01]\b/.test(raw)) {
return "SSO sign-in failed: the identity provider rejected our token request (HTTP 4xx). Check the Token endpoint URL and Client Secret at /admin/sso.";
}
if (/\b404\b/.test(raw)) {
return "SSO sign-in failed: the Token endpoint URL returned 404. Verify the URL at /admin/sso — for Google it's https://oauth2.googleapis.com/token.";
}
if (/\b5\d\d\b/.test(raw)) {
return "SSO sign-in failed: the identity provider returned a server error. Try again, or check the IdP's status page.";
}
return "SSO sign-in failed at the token exchange step. Check /admin/sso configuration.";
}
if (raw.includes("userinfo_endpoint")) {
return "SSO sign-in failed while fetching profile info. Verify the Userinfo endpoint URL at /admin/sso.";
}
if (raw.includes("state cookie") || raw.includes("nonce")) {
return "SSO sign-in expired before you returned to the site. Please try again.";
}
if (raw.includes("email") && raw.includes("not allowed")) {
return "SSO sign-in failed: your email domain is not on the allowlist for this site.";
}
return "SSO sign-in failed. Check /admin/sso configuration or try again.";
}
// ----------------------------------------------------------------------------
// User: unlink SSO
// ----------------------------------------------------------------------------
sso.post("/settings/sso/unlink", requireAuth, async (c) => {
const user = c.get("user")!;
const links = await db
.select({ id: ssoUserLinks.id })
.from(ssoUserLinks)
.where(eq(ssoUserLinks.userId, user.id));
if (links.length === 0) {
return c.redirect("/settings?error=" + encodeURIComponent("No SSO link"));
}
await db.delete(ssoUserLinks).where(eq(ssoUserLinks.userId, user.id));
await audit({
userId: user.id,
action: "auth.sso.unlink",
metadata: { removedLinks: links.length },
});
return c.redirect(
"/settings?success=" + encodeURIComponent("SSO link removed.")
);
});
export default sso;
|