caelum0x aa848c66d0 fix(ritgram): Apple-design unslop pass + Rithub OAuth2 sign-in + critical login-redirect-loop fix
Apple design (plans/gtm/APPLE-DESIGN-RULES-2026-11-17.md): rewrote theme
tokens in globals.css/tailwind.config.js to neutral black/white + one
accent (#0071E3), replacing the GitHub-dark blue+green dual-accent theme;
mechanically swept every raw inline hex/rgba literal across app/components
that bypassed the CSS vars (506 hex + 326 rgb(a) replacements) since most
of the app hardcoded colors rather than using tokens; removed all emoji,
decorative gradients (Tailwind bg-gradient-to-* and raw linear/radial-
gradient() in inline styles), confetti, and glow/blur decorative orbs;
converted Navbar/Navigation to icon-only with aria-label+title. Finished
two stopped agents' in-progress work: deleted the fake AnimatedStats/
LiveActivity/ProjectShowcase/Testimonials auth-panel components and
cleaned up the emoji-laden feature list in (auth)/layout.tsx. Removed
remaining fabricated stats (topics/topics/[slug] posts-per-week/
contributors/followers) per the no-fake-numbers rule.

Rithub sign-in: added "Continue with Rithub" as an icon-only OAuth2
button (RithubMark component) on login/register, hidden "Continue with
GitHub" when GITHUB_CLIENT_ID is unset (confirmed unset in prod). Backend:
authenticateWithGitea in oauthService.ts exchanges the Gitea OAuth2 code,
resolves identity via the existing ForgeConnection table (no schema
migration needed), issues the same JWT/session as GitHub/Google login.
OAuth2 app created live on rithub.dev via its REST API as admin user
caelum0x; client id/secret stored in railyard-box's compose file (env
files don't ship to the runtime image, so the actual wiring lives in
docker-compose.yml, not backend/.env) and in ~/products/.env.

Critical bug found and fixed while verifying: services/api.ts's global
401 interceptor redirected every anonymous visitor to /login a couple
seconds after ANY page load -- including /login and /register themselves
-- because the AuthBootstrap's background GET /auth/me (expected to 401
for signed-out visitors) was treated the same as a real session-expiry
401, triggering a refresh attempt, another 401, and a hard
window.location.href redirect, which re-ran AuthBootstrap and repeated.
Fixed by excluding /auth/me and /auth/refresh from that redirect path.
Verified live with a fresh, cookie-less browser: previously looped
/register -> /login forever; now stable after 6s.

Also fixed: production CORS/API origin mismatch -- the frontend was
built with NEXT_PUBLIC_API_URL pointing at ritgram.ereboslab.com while
served from ritgram.rithub.dev, so every API call (login, register, etc.)
was blocked by CORS; rebuilt with rithub.dev as canonical and CORS_ORIGIN
allowing both domains.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-17 17:33:41 +03:00

112 lines
3.7 KiB
TypeScript

import axios, { AxiosError } from 'axios'
const MAX_RETRIES = 3
const RETRY_DELAY = 1000 // 1 second
const API_VERSION_PREFIX = '/v1'
function normalizeApiPath(url?: string) {
if (!url) return url
if (/^https?:\/\//i.test(url)) return url
const normalized = url.startsWith('/') ? url : `/${url}`
if (normalized === API_VERSION_PREFIX || normalized.startsWith(`${API_VERSION_PREFIX}/`)) {
return normalized
}
return `${API_VERSION_PREFIX}${normalized}`
}
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api',
headers: { 'Content-Type': 'application/json' },
withCredentials: true, // Send httpOnly cookies automatically
timeout: 30000, // 30 second timeout
})
// Helper to check if error is retryable
const isRetryableError = (error: AxiosError) => {
// Retry on network errors or 5xx server errors
if (!error.response) return true // Network error
const status = error.response.status
return status >= 500 && status < 600
}
// Helper to sleep
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
// Helper to refresh token (cookies are sent automatically)
const refreshAccessToken = async (): Promise<boolean> => {
try {
await axios.post(
`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'}${normalizeApiPath('/auth/refresh')}`,
{},
{ withCredentials: true }
)
return true
} catch {
return false
}
}
// No request interceptor needed — cookies are sent automatically via withCredentials
api.interceptors.request.use((config) => {
config.url = normalizeApiPath(config.url)
return config
})
api.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as any
if (!originalRequest) {
return Promise.reject(error)
}
// Initialize retry count
originalRequest._retryCount = originalRequest._retryCount || 0
// The global AuthBootstrap (app/providers.tsx) calls GET /auth/me on every
// page load, on every route, public or not, to silently populate auth
// state. For a signed-out visitor this 401 is the normal, expected
// result -- not a session that needs recovering -- so it must never
// trigger the hard redirect below. Without this guard, every anonymous
// visit to any page (including /login and /register themselves) forced
// a `window.location.href = '/login'` a second or two after load: the
// reload re-ran AuthBootstrap, 401'd again, and redirected again,
// forever. Found live 2026-11-17 while verifying the design pass --
// confirmed via a fresh, cookie-less browser context repeatedly bounced
// from /register to /login in a loop.
const isAuthCheckRequest = typeof originalRequest.url === 'string' &&
(originalRequest.url.includes('/auth/me') || originalRequest.url.includes('/auth/refresh'))
// Handle 401 unauthorized - try token refresh
if (error.response?.status === 401 && !originalRequest._retry && !isAuthCheckRequest) {
originalRequest._retry = true
const refreshed = await refreshAccessToken()
if (refreshed) {
return api(originalRequest)
}
// Refresh failed, redirect to login
if (typeof window !== 'undefined') window.location.href = '/login'
}
// Handle retryable errors (network issues, 5xx)
if (isRetryableError(error) && originalRequest._retryCount < MAX_RETRIES) {
originalRequest._retryCount += 1
// Exponential backoff
const delay = RETRY_DELAY * Math.pow(2, originalRequest._retryCount - 1)
await sleep(delay)
return api(originalRequest)
}
return Promise.reject(error)
}
)
export default api