~bigbes/lethe

ref: be6e43e7b0b449dcbb6d597f5fe243ba5235cf75 lethe/web/src/routes/auth.callback.tsx -rw-r--r-- 9.2 KiB
be6e43e7 — Eugene Blikh oidcstub: percent-encode authorize redirect query params (PC1) a month ago
                                                                                
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
// auth.callback.tsx — handles the OIDC authorization code callback.
//
// NOTE: This file uses raw `fetch` to POST to the OP token endpoint.
// This is the ONE allowed exception to the invariant "no raw fetch outside
// client.ts": the OP /token endpoint is a cross-origin request to the issuer
// host and is not part of the /api/v1/* surface that apiFetch serves.

import React, { useEffect, useRef } from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { tokenStore, countCallbackFailures } from '../lib/auth'
import { useAuth } from '../lib/authContext'
import { readConfig } from '../lib/config'

// ── Types ─────────────────────────────────────────────────────────────────────

interface PendingAuth {
  verifier: string
  state: string
  returnTo: string
  expiresAt: number
}

const PENDING_KEY   = 'lethe_auth_pending'
const FAILURES_KEY  = 'lethe_auth_failures'

// ── Route ─────────────────────────────────────────────────────────────────────

export const Route = createFileRoute('/auth/callback')({
  validateSearch: (s: Record<string, unknown>) => ({
    code:              typeof s['code']              === 'string' ? s['code']              : undefined,
    state:             typeof s['state']             === 'string' ? s['state']             : undefined,
    error:             typeof s['error']             === 'string' ? s['error']             : undefined,
    error_description: typeof s['error_description'] === 'string' ? s['error_description'] : undefined,
  }),
  component: CallbackRoute,
})

// ── Component ─────────────────────────────────────────────────────────────────

function CallbackRoute(): React.JSX.Element {
  const navigate = useNavigate()
  const { reportAuthError } = useAuth()
  const search = Route.useSearch()

  // Prevent double-execution in React StrictMode double-invoke.
  const ranRef = useRef(false)

  // blocked state: once set, render "please reload" card with no retry.
  const [blocked, setBlocked] = React.useState(false)
  const [authError, setAuthError] = React.useState<string | null>(null)

  useEffect(() => {
    if (ranRef.current) return
    ranRef.current = true

    void (async () => {
      // ── Helper: record a failure and check the anti-loop guard ──────────────
      function recordFailureAndCheck(): boolean {
        const raw = localStorage.getItem(FAILURES_KEY)
        let log: number[] = []
        try {
          if (raw != null) {
            log = JSON.parse(raw) as number[]
            if (!Array.isArray(log)) log = []
          }
        } catch {
          log = []
        }
        log.push(Date.now())
        localStorage.setItem(FAILURES_KEY, JSON.stringify(log))

        const { blocked: isBlocked } = countCallbackFailures(Date.now(), log)
        return isBlocked
      }

      // ── Helper: fail with a message ─────────────────────────────────────────
      function fail(msg: string): void {
        const isBlocked = recordFailureAndCheck()
        reportAuthError(msg)
        setAuthError(msg)
        if (isBlocked) {
          setBlocked(true)
        }
      }

      // ── 0. Check for OP-reported error in the callback URL ──────────────────
      if (search.error != null) {
        const desc = search.error_description ?? search.error
        fail(`Authorization error: ${desc}`)
        return
      }

      // ── 1. Validate that code and state are present ─────────────────────────
      if (search.code == null || search.state == null) {
        fail('Missing code or state in callback')
        return
      }

      // ── 2. Read and validate the pending auth entry from localStorage ────────
      const raw = localStorage.getItem(PENDING_KEY)
      if (raw == null) {
        fail('No pending authorization found (state may have expired)')
        return
      }

      let pending: PendingAuth
      try {
        pending = JSON.parse(raw) as PendingAuth
      } catch {
        fail('Corrupted pending authorization state')
        return
      }

      // State parameter must match.
      if (pending.state !== search.state) {
        fail('State mismatch — possible CSRF')
        return
      }

      // TTL check.
      if (Date.now() > pending.expiresAt) {
        fail('Authorization request expired — please try again')
        return
      }

      // Consume the pending entry immediately (single-use).
      localStorage.removeItem(PENDING_KEY)

      // ── 3. Read config ──────────────────────────────────────────────────────
      let cfg: ReturnType<typeof readConfig>
      try {
        cfg = readConfig()
      } catch (e) {
        fail('Auth config missing during token exchange')
        return
      }

      // ── 4. Exchange code for tokens via POST to OP /token ───────────────────
      const origin = window.location.origin
      const body = new URLSearchParams({
        grant_type:    'authorization_code',
        code:          search.code,
        code_verifier: pending.verifier,
        redirect_uri:  `${origin}/auth/callback`,
        client_id:     cfg.clientId,
      })

      let resp: Response
      try {
        resp = await fetch(`${cfg.issuer}/token`, {
          method:  'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body:    body.toString(),
        })
      } catch (e) {
        const msg = e instanceof Error ? e.message : String(e)
        fail(`Token endpoint unreachable: ${msg}`)
        return
      }

      if (!resp.ok) {
        let detail = resp.statusText
        try {
          const errBody = await resp.json() as Record<string, unknown>
          if (typeof errBody['error_description'] === 'string') {
            detail = errBody['error_description']
          } else if (typeof errBody['error'] === 'string') {
            detail = errBody['error']
          }
        } catch {
          // ignore JSON parse failure; use status text
        }
        fail(`Token exchange failed (${resp.status}): ${detail}`)
        return
      }

      // ── 5. Parse token response ─────────────────────────────────────────────
      let tokenResp: Record<string, unknown>
      try {
        tokenResp = await resp.json() as Record<string, unknown>
      } catch {
        fail('Token endpoint returned invalid JSON')
        return
      }

      const accessToken = tokenResp['access_token']
      if (typeof accessToken !== 'string' || accessToken === '') {
        fail('Token endpoint did not return an access_token')
        return
      }

      // ── 6. Store token and navigate to returnTo ─────────────────────────────
      // Clear anti-loop failures log on success.
      localStorage.removeItem(FAILURES_KEY)

      tokenStore.set(accessToken)
      await navigate({ to: pending.returnTo })
    })()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []) // mount-only

  // ── Render ──────────────────────────────────────────────────────────────────

  if (blocked) {
    return (
      <div
        className="body body-pad"
        style={{ display: 'flex', justifyContent: 'center', paddingTop: 60 }}
      >
        <div className="card" style={{ padding: '24px 32px', textAlign: 'center' }}>
          <div className="uppercase-mono" style={{ marginBottom: 8 }}>sign-in blocked</div>
          <div className="muted" style={{ marginBottom: 16 }}>
            Too many failed sign-in attempts. Please reload the page to try again.
          </div>
        </div>
      </div>
    )
  }

  if (authError != null) {
    return (
      <div
        className="body body-pad"
        style={{ display: 'flex', justifyContent: 'center', paddingTop: 60 }}
      >
        <div className="card" style={{ padding: '24px 32px', textAlign: 'center' }}>
          <div className="uppercase-mono" style={{ marginBottom: 8 }}>auth error</div>
          <div className="muted">{authError}</div>
        </div>
      </div>
    )
  }

  // Default: processing the callback.
  return (
    <div
      className="body body-pad"
      style={{ display: 'flex', justifyContent: 'center', paddingTop: 60 }}
    >
      <div className="card" style={{ padding: '24px 32px', textAlign: 'center' }}>
        <div className="uppercase-mono" style={{ marginBottom: 8 }}>completing sign-in</div>
        <div className="muted">Please wait.</div>
      </div>
    </div>
  )
}