Skip to content

armgit / fx0

Public Imported from GitHub
0

A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.

TypeScript

Log the sign-in, renewal and sign-out trail with hashed tags

Esteban Suarez094fc6ed72ac
diff --git a/app/api/auth/callback/route.ts b/app/api/auth/callback/route.ts
index 2ae682c..2aff766 100644
--- a/app/api/auth/callback/route.ts
+++ b/app/api/auth/callback/route.ts
@@ -3,10 +3,11 @@ import { unsealData } from 'iron-session'
import { NextResponse, type NextRequest } from 'next/server'
import { AuthError, upsertAccount } from '@/lib/accounts'
import { getGrantedTeam, publicUser } from '@/lib/auth'
+import { logTag } from '@/lib/auth-crypto'
import { getSessionOptions, sealSessionCookie, selectorCookie, type SessionData } from '@/lib/secure-session'
import { signedInHintCookie, signOutPendingCookie } from '@/lib/session-cookies'
import {
- logAuthFailure, requestOrigin, SIGN_IN_UNAVAILABLE_PATH, FLOW_COOKIE_NAME, FLOW_COOKIE_OPTIONS, FLOW_TTL_SECONDS, TOKEN_ENDPOINT,
+ logAuth, logAuthFailure, requestOrigin, SIGN_IN_UNAVAILABLE_PATH, FLOW_COOKIE_NAME, FLOW_COOKIE_OPTIONS, FLOW_TTL_SECONDS, TOKEN_ENDPOINT,
isLoginId, SESSION_COOKIE_NAME, validOAuthFlow, validOAuthTokens, verifyVercelIdToken, type OAuthFlow,
} from '@/lib/auth-protocol'
@@ -56,6 +57,8 @@ export async function GET(request: NextRequest) {
sessionCookies.push(selectorCookie(session.loginId).setCookie, cookie.setCookie,
signedInHintCookie(true, process.env.NODE_ENV === 'production'),
signOutPendingCookie(false, process.env.NODE_ENV === 'production'))
+ logAuth('auth:login', { user: logTag(session.userId), login: logTag(session.loginId), rt: logTag(tokens.refresh_token),
+ replaced: isLoginId(previous) && previous !== session.loginId ? logTag(previous) : null })
} catch (error) {
logAuthFailure('auth:callback:failed', error)
response = origin
diff --git a/app/api/auth/signout/route.ts b/app/api/auth/signout/route.ts
index f7a3871..82d0c25 100644
--- a/app/api/auth/signout/route.ts
+++ b/app/api/auth/signout/route.ts
@@ -1,7 +1,8 @@
import { after, NextResponse, type NextRequest } from 'next/server'
import { AuthError } from '@/lib/accounts'
import { revokeAccessToken } from '@/lib/auth'
-import { assertSameOrigin, FLOW_COOKIE_NAME, FLOW_COOKIE_OPTIONS, isLoginId, SESSION_COOKIE_NAME } from '@/lib/auth-protocol'
+import { logTag } from '@/lib/auth-crypto'
+import { assertSameOrigin, logAuth, FLOW_COOKIE_NAME, FLOW_COOKIE_OPTIONS, isLoginId, SESSION_COOKIE_NAME } from '@/lib/auth-protocol'
import { getSessionForSignOut, sealSessionCookie, selectorCookie } from '@/lib/secure-session'
import { signedInHintCookie, signOutPendingCookie } from '@/lib/session-cookies'
import { revokeLoginCredentials } from '@/lib/turn-credential'
@@ -22,6 +23,7 @@ export async function POST(request: NextRequest) {
status: 503, headers: { 'Cache-Control': 'no-store', 'Retry-After': '5' },
})
}
+ if (userId && sessionLoginId) logAuth('auth:signout', { user: logTag(userId), login: logTag(sessionLoginId) })
// Workers reject the revoked login even if cleanup or provider revocation
// fails after the response. Neither needs to delay the browser.
after(() => Promise.all([
diff --git a/lib/auth-crypto.ts b/lib/auth-crypto.ts
index 86e8210..d0231cd 100644
--- a/lib/auth-crypto.ts
+++ b/lib/auth-crypto.ts
@@ -8,6 +8,11 @@ export function hashHandle(value: string): string {
return createHash('sha256').update(value).digest('hex')
}
+// Short one-way tag that links log lines for one user, login or refresh token.
+export function logTag(value: string): string {
+ return hashHandle(value).slice(0, 10)
+}
+
export function pkceChallenge(verifier: string): string {
return createHash('sha256').update(verifier).digest('base64url')
}
diff --git a/lib/auth-protocol.ts b/lib/auth-protocol.ts
index b535544..e6efcf9 100644
--- a/lib/auth-protocol.ts
+++ b/lib/auth-protocol.ts
@@ -17,6 +17,12 @@ export function logAuthFailure(event: string, error: unknown): void {
console.error(JSON.stringify({ at: new Date().toISOString(), event, error: message }))
}
+// Login, renewal and sign-out trail. Values are logTag hashes, statuses and
+// OAuth error codes, never credentials or provider bodies.
+export function logAuth(event: string, detail: Record<string, unknown> = {}, level: 'info' | 'error' = 'info'): void {
+ console[level](JSON.stringify({ at: new Date().toISOString(), event, ...detail }))
+}
+
// Without a trusted origin there is nothing safe to put in an absolute URL, so the
// browser resolves this against the address it already requested.
export const SIGN_IN_UNAVAILABLE_PATH = '/login?error=signin_unavailable'
diff --git a/lib/auth.ts b/lib/auth.ts
index e4555e1..25b310c 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -3,11 +3,11 @@ import { sealData, unsealData } from 'iron-session'
// @ts-expect-error Node strip-types tests require the source extension.
import { AuthError, type AccountUser } from './accounts.ts'
// @ts-expect-error Node strip-types tests require the source extension.
-import { hashHandle, randomHandle } from './auth-crypto.ts'
+import { hashHandle, logTag, randomHandle } from './auth-crypto.ts'
// @ts-expect-error Node strip-types tests require the source extension.
import { getSession, getSessionOptions, isAuthenticatedSession, type SessionData } from './secure-session.ts'
// @ts-expect-error Node strip-types tests require the source extension.
-import { MIN_GATEWAY_VALIDITY_MS, TOKEN_ENDPOINT, validOAuthTokens, type OAuthTokens } from './auth-protocol.ts'
+import { logAuth, MIN_GATEWAY_VALIDITY_MS, TOKEN_ENDPOINT, validOAuthTokens, type OAuthTokens } from './auth-protocol.ts'
// @ts-expect-error Node strip-types tests require the source extension.
import { loginRevoked } from './turn-credential.ts'
@@ -126,11 +126,6 @@ export interface RefreshCache {
release(key: string, owner: string): Promise<void>
}
-// Server log for renewal failures: HTTP status and the OAuth error code only.
-function logRefresh(event: string, detail: Record<string, unknown> = {}): void {
- console.error(JSON.stringify({ at: new Date().toISOString(), event, ...detail }))
-}
-
export function needsTokenRefresh(session: Partial<SessionData>, now = Date.now()): boolean {
return isAuthenticatedSession(session) && !!session.refreshToken && session.expiresAt <= now + MIN_GATEWAY_VALIDITY_MS
}
@@ -146,8 +141,9 @@ export function createRefreshCoordinator(boundary: { fetch: typeof fetch; cache:
async function exchange(refreshToken: string): Promise<RefreshResult> {
const clientId = process.env.VERCEL_OAUTH_CLIENT_ID
const clientSecret = process.env.VERCEL_OAUTH_CLIENT_SECRET
+ const rt = logTag(refreshToken)
if (!clientId || !clientSecret) {
- logRefresh('auth:refresh:unconfigured')
+ logAuth('auth:refresh:unconfigured', {}, 'error')
return { status: 'transient' }
}
try {
@@ -159,23 +155,26 @@ export function createRefreshCoordinator(boundary: { fetch: typeof fetch; cache:
const body: unknown = await response.json().catch(() => null)
if (!response.ok) {
const code = body && typeof body === 'object' && 'error' in body && typeof body.error === 'string' ? body.error.slice(0, 64) : null
- logRefresh('auth:refresh:rejected', { status: response.status, error: code })
+ logAuth('auth:refresh:rejected', { rt, status: response.status, error: code }, 'error')
return code === 'invalid_grant' && response.status === 400 ? { status: 'terminal' } : { status: 'transient' }
}
if (!validOAuthTokens(body)) {
- logRefresh('auth:refresh:malformed', { status: response.status })
+ logAuth('auth:refresh:malformed', { rt, status: response.status }, 'error')
return { status: 'transient' }
}
// ID tokens are not needed by refresh and must not inflate cached results.
const tokens = { access_token: body.access_token, refresh_token: body.refresh_token, expires_in: body.expires_in }
+ // rt -> next links a later rejection of rt to this exchange (a replayed token).
+ logAuth('auth:refresh:exchanged', { rt, next: logTag(tokens.refresh_token ?? refreshToken), expiresIn: tokens.expires_in })
return { status: 'ok', tokens, expiresAt: Date.now() + tokens.expires_in * 1000 }
} catch (error) {
- logRefresh('auth:refresh:error', { error: (error as Error)?.name ?? 'Error' })
+ logAuth('auth:refresh:error', { rt, error: (error as Error)?.name ?? 'Error' }, 'error')
return { status: 'transient' }
}
}
async function coordinated(refreshToken: string, key: string): Promise<RefreshResult> {
+ const rt = logTag(refreshToken)
try {
const password = getSessionOptions().password
async function cached(): Promise<RefreshResult | null> {
@@ -188,7 +187,9 @@ export function createRefreshCoordinator(boundary: { fetch: typeof fetch; cache:
throw new Error('Invalid refresh cache result')
}
// Older builds cached transient failures; one blip must not be replayed.
- return entry.result.status === 'transient' ? null : entry.result
+ if (entry.result.status === 'transient') return null
+ logAuth('auth:refresh:reused', { rt, status: entry.result.status })
+ return entry.result
}
const prior = await cached()
if (prior) return prior
@@ -201,6 +202,7 @@ export function createRefreshCoordinator(boundary: { fetch: typeof fetch; cache:
if (result) return result
} while (Date.now() < deadline)
// Do not exchange a stale token while another instance owns its lease.
+ logAuth('auth:refresh:wait_timeout', { rt }, 'error')
return { status: 'transient' }
}
// Another owner may have published between our first read and acquire.
@@ -214,15 +216,17 @@ export function createRefreshCoordinator(boundary: { fetch: typeof fetch; cache:
return result
}
const value = await sealData({ key, result, expiresAt: Date.now() + REFRESH_RESULT_SECONDS * 1000 }, { password, ttl: REFRESH_RESULT_SECONDS })
- try {
- await boundary.cache.publish(key, owner, value, REFRESH_RESULT_SECONDS)
- } catch {
- // A rotation already succeeded: still persist it in this browser rather
- // than discard its only live refresh token. The unreleased lease expires.
+ // A rotation already succeeded: still persist it in this browser rather
+ // than discard its only live refresh token. The unreleased lease expires.
+ // Unpublished, other instances holding rt will exchange it again and fail.
+ const published = await boundary.cache.publish(key, owner, value, REFRESH_RESULT_SECONDS)
+ .catch((error) => (error as Error)?.name ?? 'Error')
+ if (published !== true) {
+ logAuth('auth:refresh:unpublished', { rt, status: result.status, error: published || 'lease_lost' }, 'error')
}
return result
} catch (error) {
- logRefresh('auth:refresh:unavailable', { error: (error as Error)?.name ?? 'Error' })
+ logAuth('auth:refresh:unavailable', { rt, error: (error as Error)?.name ?? 'Error' }, 'error')
return { status: 'transient' }
}
}
diff --git a/lib/request-session.ts b/lib/request-session.ts
index d8c1685..ecbd8e5 100644
--- a/lib/request-session.ts
+++ b/lib/request-session.ts
@@ -2,7 +2,9 @@ import { NextRequest } from 'next/server.js'
// @ts-expect-error Node strip-types tests require the source extension.
import { needsTokenRefresh, refreshAccessToken, sessionWithRefresh } from './auth.ts'
// @ts-expect-error Node strip-types tests require the source extension.
-import { forwardSessionCookie, grantCookieName, GRANT_COOKIE_PREFIX, isLoginId, SESSION_COOKIE_NAME } from './auth-protocol.ts'
+import { forwardSessionCookie, grantCookieName, GRANT_COOKIE_PREFIX, isLoginId, logAuth, SESSION_COOKIE_NAME } from './auth-protocol.ts'
+// @ts-expect-error Node strip-types tests require the source extension.
+import { logTag } from './auth-crypto.ts'
// @ts-expect-error Node strip-types tests require the source extension.
import { getGrantFromRequest, getSessionFromRequest, isAuthenticatedSession, sealSessionCookie, type SessionCookie, type SessionData } from './secure-session.ts'
// @ts-expect-error Node strip-types tests require the source extension.
@@ -43,6 +45,15 @@ export function withRequestSession(body: SessionHandler) {
sealed = await sealSessionCookie(refreshed)
}
if (sealed) cookies.push(sealed)
+ if (result.status !== 'transient') {
+ // Session age separates a token that outlived its grant from a recent
+ // login whose rotated cookie never reached this browser.
+ const now = Date.now()
+ logAuth(result.status === 'ok' ? 'auth:session:renewed' : 'auth:session:ended', {
+ user: logTag(grant.userId), login: logTag(grant.loginId), rt: logTag(grant.refreshToken!),
+ sessionAgeS: Math.round((now - grant.loginAt) / 1000), accessExpiresInS: Math.round((grant.expiresAt - now) / 1000),
+ }, result.status === 'ok' ? 'info' : 'error')
+ }
}
if (!revoked && isAuthenticatedSession(grant) && expiresAt <= Date.now() && sealed?.value !== '') {
diff --git a/tests/auth.test.mjs b/tests/auth.test.mjs
index d3f9ccd..8a5c198 100644
--- a/tests/auth.test.mjs
+++ b/tests/auth.test.mjs
@@ -589,6 +589,25 @@ test('terminal invalid_grant clears current request and browser, without droppin
assert.ok(handledRequests.has(response))
})
+test('renewal logs link a rejected refresh token to the exchange that rotated it, without credentials', async (t) => {
+ const tag = (value) => createHash('sha256').update(value).digest('hex').slice(0, 10)
+ const logged = []
+ for (const level of ['info', 'error']) t.mock.method(console, level, (line) => logged.push(JSON.parse(line)))
+ const results = [() => Response.json(tokenResponse()), () => Response.json({ error: 'invalid_grant' }, { status: 400 })]
+ mockRefreshNetwork(t, () => results.shift()())
+ await requestSession(await requestWithSession('/api/prompt', session({ refreshToken: 'trail-refresh' })))
+ await requestSession(await requestWithSession('/api/prompt', session({ refreshToken: 'rotated-refresh' })))
+ const trail = logged.filter(({ event }) => event.startsWith('auth:')).map(({ at, sessionAgeS, accessExpiresInS, ...rest }) => rest)
+ const ids = { user: tag('verified-sub'), login: tag(session().loginId) }
+ assert.deepEqual(trail, [
+ { event: 'auth:refresh:exchanged', rt: tag('trail-refresh'), next: tag('rotated-refresh'), expiresIn: tokenResponse().expires_in },
+ { event: 'auth:session:renewed', ...ids, rt: tag('trail-refresh') },
+ { event: 'auth:refresh:rejected', rt: tag('rotated-refresh'), status: 400, error: 'invalid_grant' },
+ { event: 'auth:session:ended', ...ids, rt: tag('rotated-refresh') },
+ ])
+ assert.doesNotMatch(JSON.stringify(logged), /trail-refresh|rotated-refresh|rotated-access|verified-sub|user@example/)
+})
+
test('transient refresh preserves cookie; known-expired credentials do not reach the handler', async (t) => {
mockRefreshNetwork(t, () => Response.json({ error: 'temporarily_unavailable' }, { status: 503 }))
const live = await requestSession(await requestWithSession('/api/prompt', session({ refreshToken: 'proxy-transient-live' })))