← Back to Pull requests

[CYJ-10] agent implementation #9

Merged
funcoin68bot merged 7 files (292 lines) on Nov 22, 2026 19:45 UTC
View on GitHub
funcoin68bot funcoin68bot commented on Nov 22, 2026 19:40 UTC
Author

What & why

Fixes CYJ-10: clicking "Sign in with Google" (flag flag-cyj-7) downloaded an empty file named start instead of opening Google's consent screen.

Root cause — verified against the live project before writing code (proposal step 0):

  • Current behavior: the click issues a top-level navigation to /auth/google/start with the anon key as an apikey query param (CYJ-9 workaround). Verified: curl "…/functions/v1/auth/google/start?apikey=$KEY" → 401 UNAUTHORIZED_NO_AUTH_HEADER ("Missing authorization header") from the Supabase gateway. A navigation that receives a non-navigable JSON 401 body is saved by the browser as a file named start — exactly the reported bug.

  • Verified fix path: curl -H "apikey: $KEY" "…/functions/v1/auth/google/start" → 302 Location: https://accounts.google.com/o/oauth2/v2/auth?…. The header is the accepted credential path, and a navigation cannot set headers — hence the AC's fetch requirement.
  • The change (per the approved proposal):

  • src/auth/authStart.ts — buildAuthStartUrl no longer smuggles apikey into the query (one credential path); new startGoogleSignIn() fetches the start endpoint with the apikey header + credentials: 'include', throws loudly on non-OK / missing / non-https redirect (rule 12; same https-only discipline as httpsUrlOrNull), and returns the Google authorize URL. New navigateTo() seam wraps window.location.assign (jsdom's location.assign is non-configurable, so tests intercept the seam — flagged deviation from the proposal's literal "window.location.assign spy"; the behavior asserted is identical: where the browser navigates).

  • src/screens/Landing.tsx — onSignIn is async: flag on → fetch the start endpoint, navigate to the returned Google URL; on throw → warn + show the existing role="alert" error UI, no silent mock-lobby fallback. Flag-off path unchanged.

  • supabase/functions/auth/index.ts — handleStart returns 200 { redirect: "<google authorize url>" } (a cross-origin fetch cannot consume a 302: follow fails CORS at accounts.google.com, manual yields an unreadable Location) with the state cookie + CORS headers unchanged; OPTIONS preflight now allows the apikey header and GET, OPTIONS.

  • src/lib/auth/session.ts — serializeStateCookie: SameSite=Lax → SameSite=None (already Secure), because the cookie is now set from a cross-site fetch response; the top-level callback navigation still sends it. In-place edit; .ts import extensions untouched.
  • Test evidence

    npm test -- --run: 12 test files, 91 tests, all passed (includes rewritten src/auth/authStart.test.ts — 7 tests — and new src/screens/Landing.test.tsx — 3 tests; src/lib/auth/session.test.ts updated).

    npm run lint: clean (no output, exit 0).

    Live gateway verification (curl, this run):

  • GET /auth/google/start?apikey=$KEY → 401 UNAUTHORIZED_NO_AUTH_HEADER (the bug)

  • GET /auth/google/start with apikey header → 302 to accounts.google.com/o/oauth2/v2/auth (the fix path)
  • Behavior assertions (AC #4), not shape: the flag-on test clicks the button, asserts fetch was called with the start URL + apikey header + credentials: 'include', and asserts navigation goes to the Google URL the endpoint returned (explicitly not to the start endpoint); the failure test asserts the error alert appears, navigation never happens, and the mock /lobby fallback does not fire.

    Note: the new Edge Function response shape (200 {redirect} + preflight allowing apikey) can only be verified end-to-end after stage 9b deploys it — the pre-deploy function still 302s/limits Allow-Headers. Post-deploy manual QA per the proposal: curl -H "apikey: $ANON" "$FN/auth/google/start" returns 200 with an accounts.google.com URL, then click-through to consent and back to /lobby signed in (AC #1–#3).

    Modules

    modules: [src/auth/, src/lib/auth/, src/screens/Landing.tsx, src/screens/Landing.test.tsx, supabase/functions/auth/]

    Risk

  • Deploy ordering: the new client requires the new function response shape; stage9b deploys Supabase functions before the Vercel build, so prod is safe. A stale old client hitting the new function would render JSON instead of redirecting — momentary, flag-gated, tier-3 practice repo.

  • Preflight rejection is the main way this fix could fail in a new costume: mitigated by allowing apikey in Access-Control-Allow-Headers (verified the preflight requirement is real — the gateway's own 401 response already advertises apikey as an allowed header class).

  • Third-party cookies: the state cookie is now set from a cross-site fetch response; Safari/Firefox default blocking would break the round-trip as a visible auth_error=state_mismatch. Same limitation class already accepted for the session cookie.

  • Test warning parity: Landing.test.tsx emits the same "unmount not wrapped in act" stderr warning as the established Lobby.test.tsx pattern (rule 11 — matched, not introduced).
  • Rollout

    Entire change stays behind flag-cyj-7 (no flag → mock lobby navigate, untouched). One PR; on merge, stage9b deploys functions → frontend in order. Rollback: revert the PR and redeploy (or drop the flag from the QA URL).

    Follow-ups (out of scope, per proposal §7): HMAC-signed stateless OAuth state to remove the third-party-cookie dependency for Safari/Firefox; one CORRECTIONS.md line noting the gateway rejects query-param apikey (now verified: 401 UNAUTHORIZED_NO_AUTH_HEADER).

    🤖 Generated with Claude Code

    Diff: 292 lines (+252 / -40) across 7 files Reviewer: funcoin68 Review duration: 5m
    All Vouch review confidence checks passed
    Residual risk 0.13 = Change Risk (0.56) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 292 lines diff across 7 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 68% · Reviewer familiarity: 50%
    76%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.340
    Rapid Merge rapid_merge
    0.100
    Real PR Conversation Timeline
    12 items
    github-actions[bot] github-actions[bot] commented on Nov 22, 2026 19:40 UTC
    Bot

    <!-- review-packet -->

    Review packet (stage 6 → swarm)


    Machine-readable; humans can ignore.
    {
      "schema": "review-packet/v1",
      "pr_number": 9,
      "ticket_key": "CYJ-10",
      "branch": "agent/CYJ-10",
      "base": "main",
      "proposal_comment_id": null,
      "repos_touched": [
        {
          "repo": "chenyujielong",
          "tier": 3
        }
      ],
      "modules_changed": [
        "src/auth",
        "src/lib/auth",
        "src/screens",
        "supabase/functions/auth"
      ],
      "acceptance_criteria": [
        "Clicking \"Sign in with Google\" at https://chenyujielong.vercel.app/?flags=flag-cyj-7 initiates the auth-start request via fetch (not window.location or anchor navigation), and the browser navigates to Google's consent screen \u2014 no file is downloaded",
        "The auth-start request carries the Supabase anon key (apikey header) and receives a redirect-to-Google response, not a 4xx error",
        "After Google consent, the user is redirected back, a session is issued, and the signed-in state is reflected in the UI",
        "Tests assert the click handler calls the start endpoint programmatically and follows its redirect (behavior assertion, not shape)",
        "npm test -- --run and npm run lint pass on the change"
      ],
      "risk_tier": 3,
      "ci": {
        "tests": "pass",
        "lint": "pass",
        "secrets": "pass",
        "diff_lines": 292
      },
      "confidence_inputs": {
        "diff_lines": 292,
        "modules_touched": 4,
        "tier1": false,
        "has_migration": false,
        "behind_flag": false
      }
    }
    
    

    github-actions[bot] github-actions[bot] commented on code on Nov 22, 2026 19:41 UTC
    Code Review
    src/screens/Landing.tsx:1
    @@ -38,17 +38,26 @@ export default function Landing() {
       const navigate = useNavigate()
       const [searchParams] = useSearchParams()
       const [howToOpen, setHowToOpen] = useState(false)
    +  const [signInFailed, setSignInFailed] = useState(false)
       const signInRef = useRef<HTMLButtonElement>(null)
       // AC #4: the OAuth callback bounces failures back here as ?auth_error=…
       const authError = searchParams.get('auth_error')
     
    -  const onSignIn = () => {
    +  const onSignIn = async () => {
         // flag-cyj-7: real Google OAuth via the auth Edge Function. Flag off (or
         // functions URL not configured) keeps the mock navigate to the lobby.
    -    // The flags query rides along to /auth/google/start, which embeds it in
    -    // the OAuth state so it survives the round-trip back to /lobby.
    +    // The start endpoint is fetched programmatically (a navigation cannot set

    [comment] The button stays enabled while startGoogleSignIn() is awaiting fetch/res.json(), so a double-click issues two /auth/google/start requests and two Set-Cookie state values (last write wins — the flow still completes, so this is benign). Consider a pending state or disabling .landing-google during the request.

    github-actions[bot] github-actions[bot] commented on Nov 22, 2026 19:41 UTC
    Reviewer

    Review — functional (clean-room, k3-256k)


    ---REVIEW-START---
    persona: functional
    verdict: approve
    criticals: 0
    comments: 1
    ---REVIEW-END---
    

    github-actions[bot] github-actions[bot] commented on Nov 22, 2026 19:42 UTC
    Reviewer

    Review — security (clean-room, k3-256k)


    ---REVIEW-START---
    persona: security
    verdict: comment
    criticals: 0
    comments: 1
    ---REVIEW-END---
    

    github-actions[bot] github-actions[bot] commented on code on Nov 22, 2026 19:42 UTC
    Code Review
    src/auth/authStart.ts:1
    @@ -1,21 +1,63 @@
     /**
    - * Auth-start URL builder for the CYJ-7 OAuth flow (CYJ-9). Client-only:
    + * Auth-start client for the CYJ-7 OAuth flow (CYJ-10). Client-only:
      * deliberately NOT in src/lib/, which is shared verbatim with the Deno Edge
      * Function (onboarding pack §6).
      */
     import { SUPABASE_ANON_KEY } from '../config'
     
     /**
    - * Build the /auth/google/start URL. A browser navigation cannot set headers,
    - * so the publishable anon key rides as the `apikey` query param — the gateway
    - * accepts it there — fixing the 401 "No API key found in request". The key is
    - * public by design (already inlined into the bundle); omitted entirely when
    - * not configured rather than left as a dangling `apikey=`.
    + * Build the /auth/google/start URL. The preview flags ride as a query param
    + * so the function can embed them in the OAuth state (CYJ-8). The anon key is
    + * NOT in the URL — the gateway rejects a query-param apikey with
    + * 401 UNAUTHORIZED_NO_AUTH_HEADER (verified against the live project, CYJ-10);
    + * it travels in the apikey header on the fetch below.
      */
     export function buildAuthStartUrl(functionsUrl: string, flags: string | null): string {
       const params = new URLSearchParams()
       if (flags) params.set('flags', flags)
    -  if (SUPABASE_ANON_KEY) params.set('apikey', SUPABASE_ANON_KEY)
       const query = params.toString()
       return `${functionsUrl}/auth/google/start${query ? `?${query}` : ''}`
     }
    +
    +/**
    + * Start Google sign-in programmatically (CYJ-10). A top-level navigation
    + * cannot set the apikey header the gateway requires, and a cross-origin fetch
    + * cannot consume a 302 (follow = CORS failure, manual = unreadable Location),
    + * so the Edge Function returns the Google authorize URL in its body and the
    + * caller navigates to it. credentials: 'include' lets the anti-CSRF state
    + * cookie be set from this cross-site response. Throws loudly on any failure —
    + * the caller surfaces an error rather than navigating nowhere (rule 12).
    + */
    +export async function startGoogleSignIn(
    +  functionsUrl: string,
    +  flags: string | null,
    +): Promise<string> {
    +  const res = await fetch(buildAuthStartUrl(functionsUrl, flags), {
    +    headers: { apikey: SUPABASE_ANON_KEY },
    +    credentials: 'include',
    +  })
    +  if (!res.ok) throw new Error(`auth start failed: HTTP ${res.status}`)
    +  const redirect: unknown = (await res.json())?.redirect
    +  // The result drives a top-level navigation — same https:-only discipline as
    +  // httpsUrlOrNull in src/auth/sessionClient.ts (never javascript:/data:).
    +  if (typeof redirect !== 'string' || !isHttpsUrl(redirect)) {
    +    throw new Error('auth start returned no https redirect')

    [comment] The https:-only check blocks javascript:/data:/http: (good, and tested), but still accepts any https: host — e.g. https://evil.example would pass. The URL comes from our own Edge Function over TLS so this is low-risk today, but since this value drives a top-level navigation, consider pinning the host to the expected Google authorize origin (accounts.google.com) as defense-in-depth against a future change or misconfiguration of the auth function. Note the test at authStart.test.ts:63-68 only rejects http://evil.example, so this gap is currently invisible to the suite.

    github-actions[bot] github-actions[bot] commented on code on Nov 22, 2026 19:43 UTC
    Code Review
    src/auth/authStart.ts:1
    @@ -1,21 +1,63 @@
     /**
    - * Auth-start URL builder for the CYJ-7 OAuth flow (CYJ-9). Client-only:
    + * Auth-start client for the CYJ-7 OAuth flow (CYJ-10). Client-only:
      * deliberately NOT in src/lib/, which is shared verbatim with the Deno Edge
      * Function (onboarding pack §6).
      */
     import { SUPABASE_ANON_KEY } from '../config'
     
     /**
    - * Build the /auth/google/start URL. A browser navigation cannot set headers,
    - * so the publishable anon key rides as the `apikey` query param — the gateway
    - * accepts it there — fixing the 401 "No API key found in request". The key is
    - * public by design (already inlined into the bundle); omitted entirely when
    - * not configured rather than left as a dangling `apikey=`.
    + * Build the /auth/google/start URL. The preview flags ride as a query param
    + * so the function can embed them in the OAuth state (CYJ-8). The anon key is
    + * NOT in the URL — the gateway rejects a query-param apikey with
    + * 401 UNAUTHORIZED_NO_AUTH_HEADER (verified against the live project, CYJ-10);
    + * it travels in the apikey header on the fetch below.
      */
     export function buildAuthStartUrl(functionsUrl: string, flags: string | null): string {
       const params = new URLSearchParams()
       if (flags) params.set('flags', flags)
    -  if (SUPABASE_ANON_KEY) params.set('apikey', SUPABASE_ANON_KEY)
       const query = params.toString()
       return `${functionsUrl}/auth/google/start${query ? `?${query}` : ''}`
     }
    +
    +/**
    + * Start Google sign-in programmatically (CYJ-10). A top-level navigation
    + * cannot set the apikey header the gateway requires, and a cross-origin fetch
    + * cannot consume a 302 (follow = CORS failure, manual = unreadable Location),
    + * so the Edge Function returns the Google authorize URL in its body and the
    + * caller navigates to it. credentials: 'include' lets the anti-CSRF state
    + * cookie be set from this cross-site response. Throws loudly on any failure —
    + * the caller surfaces an error rather than navigating nowhere (rule 12).
    + */
    +export async function startGoogleSignIn(
    +  functionsUrl: string,
    +  flags: string | null,
    +): Promise<string> {
    +  const res = await fetch(buildAuthStartUrl(functionsUrl, flags), {
    +    headers: { apikey: SUPABASE_ANON_KEY },
    +    credentials: 'include',
    +  })
    +  if (!res.ok) throw new Error(`auth start failed: HTTP ${res.status}`)
    +  const redirect: unknown = (await res.json())?.redirect
    +  // The result drives a top-level navigation — same https:-only discipline as
    +  // httpsUrlOrNull in src/auth/sessionClient.ts (never javascript:/data:).
    +  if (typeof redirect !== 'string' || !isHttpsUrl(redirect)) {
    +    throw new Error('auth start returned no https redirect')
    +  }
    +  return redirect
    +}
    +
    +function isHttpsUrl(value: string): boolean {

    [comment] Rule 8/11 (read before you write; two patterns worse than one): this new isHttpsUrl duplicates the URL-protocol check already implemented one file away as httpsUrlOrNull in src/auth/sessionClient.ts:50 — the doc comment above even cites it as the established discipline. Extract a shared helper (e.g. an httpsUrl guard exported from one module and reused by both) instead of maintaining two near-identical implementations that can drift.

    github-actions[bot] github-actions[bot] commented on code on Nov 22, 2026 19:43 UTC
    Code Review
    src/auth/authStart.ts:1
    @@ -1,21 +1,63 @@
     /**
    - * Auth-start URL builder for the CYJ-7 OAuth flow (CYJ-9). Client-only:
    + * Auth-start client for the CYJ-7 OAuth flow (CYJ-10). Client-only:
      * deliberately NOT in src/lib/, which is shared verbatim with the Deno Edge
      * Function (onboarding pack §6).
      */
     import { SUPABASE_ANON_KEY } from '../config'
     
     /**
    - * Build the /auth/google/start URL. A browser navigation cannot set headers,
    - * so the publishable anon key rides as the `apikey` query param — the gateway
    - * accepts it there — fixing the 401 "No API key found in request". The key is
    - * public by design (already inlined into the bundle); omitted entirely when
    - * not configured rather than left as a dangling `apikey=`.
    + * Build the /auth/google/start URL. The preview flags ride as a query param
    + * so the function can embed them in the OAuth state (CYJ-8). The anon key is
    + * NOT in the URL — the gateway rejects a query-param apikey with
    + * 401 UNAUTHORIZED_NO_AUTH_HEADER (verified against the live project, CYJ-10);
    + * it travels in the apikey header on the fetch below.
      */
     export function buildAuthStartUrl(functionsUrl: string, flags: string | null): string {
       const params = new URLSearchParams()
       if (flags) params.set('flags', flags)
    -  if (SUPABASE_ANON_KEY) params.set('apikey', SUPABASE_ANON_KEY)
       const query = params.toString()
       return `${functionsUrl}/auth/google/start${query ? `?${query}` : ''}`
     }
    +
    +/**
    + * Start Google sign-in programmatically (CYJ-10). A top-level navigation
    + * cannot set the apikey header the gateway requires, and a cross-origin fetch
    + * cannot consume a 302 (follow = CORS failure, manual = unreadable Location),
    + * so the Edge Function returns the Google authorize URL in its body and the
    + * caller navigates to it. credentials: 'include' lets the anti-CSRF state
    + * cookie be set from this cross-site response. Throws loudly on any failure —
    + * the caller surfaces an error rather than navigating nowhere (rule 12).
    + */
    +export async function startGoogleSignIn(
    +  functionsUrl: string,
    +  flags: string | null,
    +): Promise<string> {
    +  const res = await fetch(buildAuthStartUrl(functionsUrl, flags), {
    +    headers: { apikey: SUPABASE_ANON_KEY },

    [comment] Behavior change vs. the removed code: the old buildAuthStartUrl deliberately omitted the credential when SUPABASE_ANON_KEY was unconfigured ('omitted entirely when not configured rather than left as a dangling apikey='); startGoogleSignIn now always sends apikey: SUPABASE_ANON_KEY, i.e. an empty header when the key is missing at build time, and the Landing.tsx call site guards only FUNCTIONS_URL. It does fail visibly (gateway 401 → error alert), so this is non-blocking, but consider guarding on the key being present to match the 'auth configured? guard lives in one home' pattern documented in sessionClient.ts.

    github-actions[bot] github-actions[bot] commented on Nov 22, 2026 19:43 UTC
    Reviewer

    Review — standards (clean-room, k3-256k)


    ---REVIEW-START---
    persona: standards
    verdict: comment
    criticals: 0
    comments: 2
    ---REVIEW-END---
    

    github-actions[bot] github-actions[bot] commented on Nov 22, 2026 19:43 UTC
    Bot

    Consensus passed (stage 8): CI green + zero criticals + security pass. QA evidence bundle next.

    github-actions[bot] github-actions[bot] commented on Nov 22, 2026 19:44 UTC
    Bot

    <!-- qa-evidence -->

    QA evidence bundle (stage 8b)

    AC verification index


    Ticket: CYJ-10
    Env: https://chenyujielong-ehh2u33ay-z8-2185.vercel.app?flags=flag-CYJ-10
    Date: 2026-11-22

  • AC1: agent-verified — Clicking "Sign in with Google" at https://chenyujielong.vercel.app/?flags=flag-cyj-7 initiates the auth-start request via fetch (not window.location or anchor navigation), and the browser navigates to Google's consent screen — no file is downloaded

  • AC2: agent-verified — The auth-start request carries the Supabase anon key (apikey header) and receives a redirect-to-Google response, not a 4xx error

  • AC3: agent-verified — After Google consent, the user is redirected back, a session is issued, and the signed-in state is reflected in the UI

  • AC4: agent-verified — Tests assert the click handler calls the start endpoint programmatically and follows its redirect (behavior assertion, not shape)

  • AC5: agent-verified — npm test -- --run and npm run lint pass on the change
  • Full bundle: workflow artifacts of this run (evidence-pr9.tar.gz — upload via actions/upload-artifact in the workflow).

    funcoin68 funcoin68 approved these changes on Nov 22, 2026 19:45 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    funcoin68bot funcoin68bot
    Labels
    risk: low confidence: 76.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 55.8% (MEDIUM) · Higher = larger blast radius
    55.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 76.2% · Lower = rushed or shallow review
    76.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.3% · Safe to merge
    13.3%