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 | /**
* "Sign in with Google" routes.
*
* GET /admin/google-oauth — site-admin config page
* POST /admin/google-oauth — save Client ID + Secret + toggle
* GET /login/google — kick off OAuth (redirect to Google)
* GET /login/google/callback — exchange code, sign user in
*
* Mirrors the structure of `src/routes/github-oauth.tsx`. Reuses the
* existing `sso_user_links` table with `subject = "google:<sub>"` so it
* sits alongside the enterprise IdP (id='default') and the GitHub
* provider (id='github') without colliding.
*/
import { Hono } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
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 {
findOrCreateUserFromGoogle,
getGoogleOauthConfig,
googleOauthRedirectUri,
issueSsoSession,
randomToken,
upsertGoogleOauthConfig,
type GoogleProfile,
} from "../lib/sso";
import {
buildGoogleAuthorizeUrl,
exchangeGoogleCode,
fetchGoogleUserinfo,
} from "../lib/google-oauth";
import { sessionCookieOptions } from "../lib/auth";
const googleOauth = new Hono<AuthEnv>();
googleOauth.use("*", softAuth);
function stateCookieOpts(): {
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/google-oauth");
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 Google sign-in.</p>
</div>
</Layout>,
403
);
}
return { user };
}
googleOauth.get("/admin/google-oauth", requireAuth, async (c) => {
const g = await adminGate(c);
if (g instanceof Response) return g;
const { user } = g;
const cfg = await getGoogleOauthConfig();
const success = c.req.query("success");
const error = c.req.query("error");
const redirectUri = googleOauthRedirectUri();
return c.html(
<Layout title="Google sign-in — Admin" user={user}>
<div class="settings-container" style="max-width:780px">
<h2>Sign in with Google</h2>
<p style="color:var(--text-muted)">
Let any developer sign in to gluecron with their Google account in
one click. Create an OAuth 2.0 Client at{" "}
<a
href="https://console.cloud.google.com/apis/credentials"
target="_blank"
rel="noreferrer noopener"
>
console.cloud.google.com/apis/credentials
</a>{" "}
(set application type = Web), then paste the Client ID + Secret here.
</p>
<div class="panel" style="padding:12px;margin-bottom:16px">
<div
style="font-size:12px;text-transform:uppercase;color:var(--text-muted)"
>
Authorised redirect URI — paste this into Google Cloud Console
</div>
<code id="g-redirect-uri" style="font-size:13px">
{redirectUri}
</code>
<button
type="button"
class="btn"
style="margin-left:8px"
onclick={`navigator.clipboard.writeText(${JSON.stringify(redirectUri)});this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1500)`}
>
Copy
</button>
</div>
{success && (
<div class="auth-success">{decodeURIComponent(success)}</div>
)}
{error && <div class="auth-error">{decodeURIComponent(error)}</div>}
<form
method="post"
action="/admin/google-oauth"
class="panel"
style="padding:16px"
>
<label
style="display:flex;gap:8px;align-items:center;margin-bottom:12px"
>
<input
type="checkbox"
name="enabled"
value="1"
checked={!!cfg?.enabled}
aria-label="Enable Google sign-in on /login"
/>
<span>Enable Google sign-in on /login</span>
</label>
<div class="form-group">
<label for="g_client_id">Client ID</label>
<input
type="text"
id="g_client_id"
name="client_id"
value={cfg?.clientId || ""}
autocomplete="off"
placeholder="123456789-xxxxxxxxx.apps.googleusercontent.com"
/>
</div>
<div class="form-group">
<label for="g_client_secret">Client secret</label>
<input
type="password"
id="g_client_secret"
name="client_secret"
value={cfg?.clientSecret || ""}
autocomplete="off"
placeholder={
cfg?.clientSecret ? "(stored — leave blank to keep)" : ""
}
/>
</div>
<div class="form-group">
<label for="g_allowed_email_domains">
Allowed email domains (comma-separated, empty = any)
</label>
<input
type="text"
id="g_allowed_email_domains"
name="allowed_email_domains"
value={cfg?.allowedEmailDomains || ""}
placeholder="example.com, acme.io"
/>
</div>
<label
style="display:flex;gap:8px;align-items:center;margin:12px 0"
>
<input
type="checkbox"
name="auto_create_users"
value="1"
checked={cfg ? cfg.autoCreateUsers : true}
aria-label="Auto-create users on first Google sign-in"
/>
<span>Auto-create local accounts on first Google sign-in</span>
</label>
<button type="submit" class="btn btn-primary">
Save Google settings
</button>
</form>
</div>
</Layout>
);
});
googleOauth.post("/admin/google-oauth", 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 getGoogleOauthConfig();
const secretSubmitted = String(body.client_secret || "");
const result = await upsertGoogleOauthConfig({
enabled: String(body.enabled || "") === "1",
clientId: String(body.client_id || ""),
clientSecret:
secretSubmitted.trim().length === 0 && existing?.clientSecret
? existing.clientSecret
: secretSubmitted,
allowedEmailDomains: String(body.allowed_email_domains || ""),
autoCreateUsers: String(body.auto_create_users || "") === "1",
});
if (!result.ok) {
return c.redirect(
`/admin/google-oauth?error=${encodeURIComponent(result.error)}`
);
}
await audit({
userId: user.id,
action: "admin.google_oauth.configure",
metadata: {
enabled: String(body.enabled || "") === "1",
autoCreateUsers: String(body.auto_create_users || "") === "1",
allowedDomains: String(body.allowed_email_domains || "") || null,
},
});
return c.redirect(
`/admin/google-oauth?success=${encodeURIComponent("Google sign-in settings saved.")}`
);
});
// ----------------------------------------------------------------------------
// OAuth flow
// ----------------------------------------------------------------------------
googleOauth.get("/login/google", async (c) => {
const cfg = await getGoogleOauthConfig();
if (!cfg || !cfg.enabled) {
return c.redirect(
`/login?error=${encodeURIComponent("Google sign-in is not enabled")}`
);
}
if (!cfg.clientId || !cfg.clientSecret) {
return c.redirect(
`/login?error=${encodeURIComponent("Google sign-in is not fully configured")}`
);
}
const state = randomToken(16);
const nonce = randomToken(16);
const redirectUri = googleOauthRedirectUri();
let target: string;
try {
target = buildGoogleAuthorizeUrl(cfg, state, redirectUri, nonce);
} catch (err) {
return c.redirect(
`/login?error=${encodeURIComponent(
err instanceof Error ? err.message : "Google sign-in misconfigured"
)}`
);
}
setCookie(c, "g_oauth_state", state, stateCookieOpts());
setCookie(c, "g_oauth_nonce", nonce, stateCookieOpts());
return c.redirect(target);
});
googleOauth.get("/login/google/callback", async (c) => {
const cfg = await getGoogleOauthConfig();
if (!cfg || !cfg.enabled) {
return c.redirect(
`/login?error=${encodeURIComponent("Google sign-in 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(`Google error: ${errCode}`)}`
);
}
if (!code || !state) {
return c.redirect(
`/login?error=${encodeURIComponent("Missing code or state")}`
);
}
const expectedState = getCookie(c, "g_oauth_state");
if (!expectedState || expectedState !== state) {
return c.redirect(
`/login?error=${encodeURIComponent(
"Google state mismatch. Please try again."
)}`
);
}
// One-shot cookies — burn even on failure
deleteCookie(c, "g_oauth_state", { path: "/" });
deleteCookie(c, "g_oauth_nonce", { path: "/" });
try {
const { accessToken } = await exchangeGoogleCode(
cfg,
code,
googleOauthRedirectUri()
);
const userinfo = await fetchGoogleUserinfo(cfg, accessToken);
const profile: GoogleProfile = {
sub: userinfo.sub,
email: userinfo.email,
emailVerified: userinfo.emailVerified,
name: userinfo.name,
picture: userinfo.picture,
};
const result = await findOrCreateUserFromGoogle(profile, 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.google.login",
metadata: {
googleSub: profile.sub,
email: profile.email || null,
},
});
return c.redirect("/");
} catch (err) {
console.error("[google-oauth] callback error:", err);
return c.redirect(
`/login?error=${encodeURIComponent(
err instanceof Error
? `Google sign-in failed: ${err.message}`
: "Google sign-in failed"
)}`
);
}
});
export default googleOauth;
|