mirror of
https://github.com/OpenSquawk/OpenSquawk
synced 2026-07-31 05:45:35 +08:00
Phase 0 of the OpenSquawk repo separation. Everything happens inside the
monorepo so that the split itself becomes a mechanical path filter — filtering
first and repairing afterwards would leave two broken repos at once.
AUTH_MODE (0.1)
New server/utils/authMode.ts, session.ts and jwt.ts (the latter extracted
from auth.ts). requireUserSession now resolves in three steps: the app's own
session cookie, an app-minted bearer token, then the website access token.
Only the last one is transitional; it is marked PHASE 1 and disappears with
the User collection. The app's session is its own JWT in a host-only cookie
plus a short-lived bearer, so the existing Authorization call sites are
unchanged.
AUTH_MODE defaults to 'sso', not 'open' as the plan proposed: while the admin
and editor surface still lives here, an unset variable would otherwise serve
it to everyone as a local admin. requireAdmin additionally refuses in open
mode. Both are one-line removals in Phase 1 and marked as such.
SSO handoff (0.2)
Issuer: /api/service/auth/sso/{authorize,exchange}. Codes are stored as
SHA-256 hashes with a TTL index and claimed by a single atomic update, so
concurrent redemption cannot succeed twice. redirect_uri is matched against
SSO_REDIRECT_ORIGINS by exact origin — a prefix check would accept
app.opensquawk.de.evil.tld. There is no default and no wildcard: an empty
allowlist disables the handoff rather than opening a redirector.
Consumer: /api/auth/sso/callback plus app/pages/auth/callback.vue. The
browser only ever carries the code; it is redeemed server-to-server.
Hardcoded values and leaks (0.3)
Hotjar ID, the dome-light webhook URL and the bug-report recipient were
compiled in. All three are env-gated and off by default now, so a foreign
instance cannot ship analytics, cockpit telemetry or its users' bug reports
to us. Setting HOTJAR_ID, DOME_LIGHT_WEBHOOK_URL and BUG_REPORT_NOTIFY_EMAIL
restores the current behaviour on opensquawk.de.
Two databases, no shared Mongo (0.6)
AppUser mirrors an identity locally. Its _id is deliberately the SSO subject,
i.e. the website's User._id, so every existing LearnProfile, PilotProfile and
BridgeToken reference keeps resolving without a migration.
telemetry.ts mirrors records to the hosted service only when TELEMETRY_URL
and SERVICE_SECRET are both set — the self-host default is that nothing ever
leaves the instance. It writes locally first, buffers with a bound, drops on
overflow and never blocks the request path.
/api/service/user-deleted purges the app's half on account deletion. Unlike
telemetry this is deliberately loud: the admin delete aborts with the user
intact if the purge fails, because their id is the only handle for retrying.
?force=true overrides it and says so in the response.
Also here
/api/service/analytics/product-session was an unauthenticated public write
endpoint; it moves to /api/analytics/product-session behind the auth guard.
The bridge no longer populates against User but resolves through the mirror,
backfilling missing rows so live bridges never have to re-pair.
.claude/worktrees was tracked and would have reached the public repo.
scripts/split-paths.txt carries the filter list, verified by
scripts/verify-split-paths.mjs: every path exists, nothing website-only is
kept, and no kept file imports a dropped one. That check found real gaps —
tests/ cannot be taken wholesale, and two shared modules were missing. Ten
remaining edges are allowlisted, each annotated PHASE 1 in the code.
Open item, flagged and not resolved: flightlabTelemetryStore is an in-process
singleton written by the bridge (app) and read by FlightLab (website). Two
repos means two processes, so that read breaks regardless of which side it
lands on. FlightLab needs an HTTP path in Phase 2/3.
Verified: 609 tests pass, vue-tsc clean. Ran against two throwaway local
MongoDBs: open mode reaches /classroom and /live-atc with no login and
persists progress; the full SSO loop works and the mirror _id matches the
website User._id; lookalike origins, code reuse, forged codes and wrong
service secrets are all rejected; ingest is idempotent on bug-report code;
deletion purges all five collections; and with the app unreachable the admin
delete fails 502 with the user still present.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
267 lines
9.1 KiB
TypeScript
267 lines
9.1 KiB
TypeScript
import { createError, getHeader, H3Event, setCookie, deleteCookie } from 'h3'
|
||
import { useRuntimeConfig } from '#imports'
|
||
import { randomBytes, timingSafeEqual, scrypt as _scrypt } from 'node:crypto'
|
||
import { promisify } from 'node:util'
|
||
import type { UserDocument } from '../models/User'
|
||
import { User } from '../models/User'
|
||
import { AppUser } from '../models/AppUser'
|
||
import { createJwtToken, verifyJwtToken } from './jwt'
|
||
import { getAuthMode, getLocalAppUser, mirrorAppUser } from './authMode'
|
||
import { readAppSession, verifyAppAccessToken } from './session'
|
||
|
||
const scrypt = promisify(_scrypt) as (password: string | Buffer, salt: string | Buffer, keylen: number) => Promise<Buffer>
|
||
|
||
const ACCESS_TOKEN_TTL_SECONDS = 60 * 60 * 24
|
||
const REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 7
|
||
const REFRESH_COOKIE_NAME = 'os_refresh_token'
|
||
const PASSWORD_SALT_BYTES = 16
|
||
const PASSWORD_KEYLEN = 64
|
||
|
||
function getSecrets() {
|
||
const config = useRuntimeConfig()
|
||
if (!config.jwtSecret) {
|
||
throw new Error('JWT secret missing – bitte JWT_SECRET in .env setzen')
|
||
}
|
||
return {
|
||
accessSecret: config.jwtSecret as string,
|
||
refreshSecret: (config.jwtRefreshSecret as string) || (config.jwtSecret as string),
|
||
}
|
||
}
|
||
|
||
export async function hashPassword(password: string) {
|
||
const salt = randomBytes(PASSWORD_SALT_BYTES)
|
||
const derived = await scrypt(password, salt, PASSWORD_KEYLEN)
|
||
return `${salt.toString('hex')}.${derived.toString('hex')}`
|
||
}
|
||
|
||
export async function verifyPassword(password: string, stored: string) {
|
||
const [saltHex, hashHex] = stored.split('.')
|
||
if (!saltHex || !hashHex) return false
|
||
const salt = Buffer.from(saltHex, 'hex')
|
||
const expected = Buffer.from(hashHex, 'hex')
|
||
const derived = await scrypt(password, salt, expected.length)
|
||
if (derived.length !== expected.length) return false
|
||
return timingSafeEqual(derived, expected)
|
||
}
|
||
|
||
export function createAccessToken(user: UserDocument) {
|
||
const { accessSecret } = getSecrets()
|
||
return createJwtToken(
|
||
{
|
||
sub: String(user._id),
|
||
email: user.email,
|
||
version: user.tokenVersion,
|
||
},
|
||
accessSecret,
|
||
ACCESS_TOKEN_TTL_SECONDS,
|
||
)
|
||
}
|
||
|
||
export function createRefreshToken(user: UserDocument) {
|
||
const { refreshSecret } = getSecrets()
|
||
return createJwtToken(
|
||
{
|
||
sub: String(user._id),
|
||
type: 'refresh',
|
||
version: user.tokenVersion,
|
||
},
|
||
refreshSecret,
|
||
REFRESH_TOKEN_TTL_SECONDS,
|
||
)
|
||
}
|
||
|
||
export function setRefreshTokenCookie(event: H3Event, token: string) {
|
||
setCookie(event, REFRESH_COOKIE_NAME, token, {
|
||
httpOnly: true,
|
||
sameSite: 'lax',
|
||
path: '/',
|
||
maxAge: REFRESH_TOKEN_TTL_SECONDS,
|
||
secure: process.env.NODE_ENV === 'production',
|
||
})
|
||
}
|
||
|
||
export function clearRefreshTokenCookie(event: H3Event) {
|
||
deleteCookie(event, REFRESH_COOKIE_NAME, { path: '/' })
|
||
}
|
||
|
||
function parseAuthorizationHeader(event: H3Event) {
|
||
const header = getHeader(event, 'authorization')
|
||
if (!header) return null
|
||
const [scheme, token] = header.split(' ')
|
||
if (!token || scheme?.toLowerCase() !== 'bearer') return null
|
||
return token
|
||
}
|
||
|
||
// Local-dev-only bypass session (server/api/dev/login.post.ts): a fixed,
|
||
// entirely in-memory "user" that never touches MongoDB, so require-auth
|
||
// pages are reachable for local testing even when the dev DB is unreachable.
|
||
// This fixed ObjectId never resolves to a real User document: resolveUserFromToken
|
||
// below matches it BEFORE ever calling User.findById. It must nevertheless be a
|
||
// valid ObjectId because BridgeToken.user is stored as an ObjectId when WebSim
|
||
// connects to the real bridge endpoints.
|
||
export const DEV_BYPASS_USER_ID = '000000000000000000000001'
|
||
const DEV_BYPASS_EMAIL = 'dev-claude@localhost.test'
|
||
|
||
export function getDevBypassUser(): UserDocument {
|
||
return {
|
||
_id: DEV_BYPASS_USER_ID,
|
||
email: DEV_BYPASS_EMAIL,
|
||
name: 'Dev Test User',
|
||
role: 'user',
|
||
tokenVersion: 0,
|
||
createdAt: new Date(0),
|
||
invitationCodesIssued: 0,
|
||
acceptedTermsAt: new Date(0),
|
||
acceptedPrivacyAt: new Date(0),
|
||
} as unknown as UserDocument
|
||
}
|
||
|
||
/** Resolve an identity from the app's own mirror — no `User` lookup involved. */
|
||
async function resolveAppUser(sub: string) {
|
||
const appUser = await AppUser.findById(sub)
|
||
if (!appUser) return null
|
||
return appUser as unknown as UserDocument
|
||
}
|
||
|
||
export async function resolveUserFromToken(event: H3Event) {
|
||
// 1. The app's own session cookie — the only path that survives the split.
|
||
const session = readAppSession(event)
|
||
if (session) {
|
||
const appUser = await resolveAppUser(session.sub)
|
||
if (appUser) return appUser
|
||
}
|
||
|
||
const token = parseAuthorizationHeader(event)
|
||
if (!token) return null
|
||
|
||
// 2. An app-minted bearer token (same session, carried in the header).
|
||
const appToken = verifyAppAccessToken(token)
|
||
if (appToken) {
|
||
return await resolveAppUser(appToken.sub)
|
||
}
|
||
|
||
// 3. PHASE 1 (app repo): everything below goes away together with the `User`
|
||
// collection. While website and app share one deployment, a website access
|
||
// token is still a valid way in — it is how every existing user is logged in
|
||
// today. Each such request also refreshes the AppUser mirror (rate-limited
|
||
// internally), so app-side data is already keyed correctly when the split
|
||
// happens.
|
||
try {
|
||
const { accessSecret } = getSecrets()
|
||
const payload = verifyJwtToken(token, accessSecret)
|
||
if (!payload?.sub) return null
|
||
if (payload.sub === DEV_BYPASS_USER_ID && process.env.NODE_ENV !== 'production') {
|
||
const devUser = getDevBypassUser()
|
||
await mirrorAppUser({
|
||
subject: DEV_BYPASS_USER_ID,
|
||
email: devUser.email,
|
||
name: devUser.name,
|
||
role: 'user',
|
||
}).catch(() => null)
|
||
return devUser
|
||
}
|
||
const user = await User.findById(payload.sub)
|
||
if (!user) return null
|
||
if (typeof payload.version === 'number' && payload.version !== user.tokenVersion) {
|
||
return null
|
||
}
|
||
await mirrorAppUser({
|
||
subject: String(user._id),
|
||
email: user.email,
|
||
name: user.name,
|
||
role: user.role,
|
||
}).catch(() => null)
|
||
return user
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
export async function requireUserSession(event: H3Event) {
|
||
if (event.context?.user) {
|
||
return event.context.user as UserDocument
|
||
}
|
||
|
||
// AUTH_MODE=open: a self-hosted instance has no login. Every request is the
|
||
// one local identity, resolved without ever touching the `User` collection.
|
||
if (getAuthMode() === 'open') {
|
||
const localUser = await getLocalAppUser() as unknown as UserDocument
|
||
event.context.user = localUser
|
||
return localUser
|
||
}
|
||
|
||
const user = await resolveUserFromToken(event)
|
||
if (!user) {
|
||
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
||
}
|
||
event.context.user = user
|
||
return user
|
||
}
|
||
|
||
export async function getUserFromEvent(event: H3Event) {
|
||
if (event.context?.user) return event.context.user as UserDocument
|
||
if (getAuthMode() === 'open') {
|
||
const localUser = await getLocalAppUser() as unknown as UserDocument
|
||
event.context.user = localUser
|
||
return localUser
|
||
}
|
||
const user = await resolveUserFromToken(event)
|
||
if (user) {
|
||
event.context.user = user
|
||
}
|
||
return user
|
||
}
|
||
|
||
export function hasAdminRole(user: UserDocument | null | undefined) {
|
||
return user ? user.role === 'admin' || user.role === 'dev' : false
|
||
}
|
||
|
||
export async function requireAdmin(event: H3Event) {
|
||
// PHASE 1 (app repo): delete this guard together with the admin surface.
|
||
// The local AUTH_MODE=open identity is an admin *of its own instance*, which
|
||
// is correct once /api/admin/** no longer lives here. For as long as it does,
|
||
// an unauthenticated open-mode request must never reach it.
|
||
if (getAuthMode() === 'open') {
|
||
throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
||
}
|
||
const user = await requireUserSession(event)
|
||
if (!hasAdminRole(user)) {
|
||
throw createError({ statusCode: 403, statusMessage: 'Administratorrechte erforderlich' })
|
||
}
|
||
return user
|
||
}
|
||
|
||
export async function issueAuthTokens(event: H3Event, user: UserDocument) {
|
||
const accessToken = createAccessToken(user)
|
||
const refreshToken = createRefreshToken(user)
|
||
setRefreshTokenCookie(event, refreshToken)
|
||
return { accessToken }
|
||
}
|
||
|
||
export async function rotateRefreshToken(event: H3Event) {
|
||
const cookieHeader = event.node.req.headers?.cookie || ''
|
||
const match = cookieHeader.split(';').map((p) => p.trim()).find((p) => p.startsWith(`${REFRESH_COOKIE_NAME}=`))
|
||
if (!match) {
|
||
throw createError({ statusCode: 401, statusMessage: 'No refresh token present' })
|
||
}
|
||
const token = match.substring(REFRESH_COOKIE_NAME.length + 1)
|
||
try {
|
||
const { refreshSecret } = getSecrets()
|
||
const payload = verifyJwtToken(token, refreshSecret)
|
||
if (!payload?.sub || payload.type !== 'refresh') {
|
||
throw new Error('Invalid token payload')
|
||
}
|
||
const user = await User.findById(payload.sub)
|
||
if (!user) {
|
||
throw new Error('User missing')
|
||
}
|
||
if (typeof payload.version === 'number' && payload.version !== user.tokenVersion) {
|
||
throw new Error('Token version mismatch')
|
||
}
|
||
return issueAuthTokens(event, user)
|
||
} catch (err) {
|
||
clearRefreshTokenCookie(event)
|
||
throw createError({ statusCode: 401, statusMessage: 'Refresh token invalid' })
|
||
}
|
||
}
|