Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
google-oauth.ts5.1 KB · 156 lines
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
/**
 * "Sign in with Google" network helpers.
 *
 * Mirrors the structure of `src/lib/github-oauth.ts`. Google is OIDC-compliant
 * (unlike GitHub's plain OAuth 2.0) but we use it as plain OAuth here for
 * symmetry with the existing GitHub flow. The `userinfo_endpoint` returns
 * a stable subject (`sub`) which we use as the link key.
 *
 * Every function is pure: no database access, no global mutable state.
 * `fetchImpl` is injectable so tests don't hit the real Google API.
 */

import type { SsoConfig } from "../db/schema";

/** Override for tests — defaults to the global fetch. */
export type FetchImpl = typeof fetch;

/** Build the Google authorize URL the browser should be redirected to. */
export function buildGoogleAuthorizeUrl(
  cfg: Pick<SsoConfig, "authorizationEndpoint" | "clientId" | "scopes">,
  state: string,
  redirectUri: string,
  nonce: string
): string {
  if (!cfg.authorizationEndpoint || !cfg.clientId) {
    throw new Error(
      "Google OAuth config missing authorization_endpoint or client_id"
    );
  }
  const u = new URL(cfg.authorizationEndpoint);
  u.searchParams.set("client_id", cfg.clientId);
  u.searchParams.set("redirect_uri", redirectUri);
  u.searchParams.set("response_type", "code");
  u.searchParams.set("scope", cfg.scopes || "openid email profile");
  u.searchParams.set("state", state);
  u.searchParams.set("nonce", nonce);
  // `access_type=online` — we only need a one-shot sign-in, no offline refresh.
  u.searchParams.set("access_type", "online");
  // `prompt=select_account` — show Google's account picker so users with
  // multiple Google accounts can choose. Without this Google sometimes
  // silently uses the most-recent account, which surprises users.
  u.searchParams.set("prompt", "select_account");
  return u.toString();
}

/**
 * Exchange the authorization code for an access_token. Google returns
 * JSON natively, so this is simpler than GitHub's exchange.
 */
export async function exchangeGoogleCode(
  cfg: Pick<SsoConfig, "tokenEndpoint" | "clientId" | "clientSecret">,
  code: string,
  redirectUri: string,
  fetchImpl: FetchImpl = fetch
): Promise<{ accessToken: string; idToken: string | null }> {
  if (!cfg.tokenEndpoint || !cfg.clientId || !cfg.clientSecret) {
    throw new Error(
      "Google OAuth config missing token_endpoint or client credentials"
    );
  }
  const body = new URLSearchParams({
    grant_type: "authorization_code",
    code,
    redirect_uri: redirectUri,
    client_id: cfg.clientId,
    client_secret: cfg.clientSecret,
  });
  const res = await fetchImpl(cfg.tokenEndpoint, {
    method: "POST",
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      accept: "application/json",
    },
    body: body.toString(),
  });
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(
      `google token endpoint ${res.status}: ${text.slice(0, 200) || "no body"}`
    );
  }
  const json = (await res.json()) as {
    access_token?: string;
    id_token?: string;
    error?: string;
    error_description?: string;
  };
  if (json.error) {
    throw new Error(
      `google token endpoint: ${json.error}${json.error_description ? ` — ${json.error_description}` : ""}`
    );
  }
  if (!json.access_token) {
    throw new Error("google token endpoint response missing access_token");
  }
  return {
    accessToken: json.access_token,
    idToken: typeof json.id_token === "string" ? json.id_token : null,
  };
}

/** The minimal subset of Google userinfo we read. */
export interface GoogleUserinfo {
  /** Stable Google account id (the `sub` claim). */
  sub: string;
  /** Verified email address; Google always returns this for `email` scope. */
  email: string | null;
  /** Whether Google considers the email verified. We refuse to auto-create on false. */
  emailVerified: boolean;
  /** Full name from the Google profile. */
  name: string | null;
  /** Avatar URL. */
  picture: string | null;
}

/** Fetch the Google userinfo profile using a Bearer access token. */
export async function fetchGoogleUserinfo(
  cfg: Pick<SsoConfig, "userinfoEndpoint">,
  accessToken: string,
  fetchImpl: FetchImpl = fetch
): Promise<GoogleUserinfo> {
  if (!cfg.userinfoEndpoint) {
    throw new Error("Google OAuth config missing userinfo_endpoint");
  }
  const res = await fetchImpl(cfg.userinfoEndpoint, {
    headers: {
      authorization: `Bearer ${accessToken}`,
      accept: "application/json",
    },
  });
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(
      `google /userinfo ${res.status}: ${text.slice(0, 200) || "no body"}`
    );
  }
  const raw = (await res.json()) as {
    sub?: string;
    email?: string | null;
    email_verified?: boolean | string;
    name?: string | null;
    picture?: string | null;
  };
  if (typeof raw.sub !== "string" || !raw.sub) {
    throw new Error("google /userinfo response missing sub");
  }
  return {
    sub: raw.sub,
    email: raw.email ?? null,
    // Google sometimes serialises email_verified as a string "true"/"false".
    emailVerified:
      raw.email_verified === true || raw.email_verified === "true",
    name: raw.name ?? null,
    picture: raw.picture ?? null,
  };
}