mirror of
https://github.com/OpenSquawk/OpenSquawk
synced 2026-07-30 21:38:45 +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>
136 lines
4.9 KiB
TypeScript
136 lines
4.9 KiB
TypeScript
import mongoose from 'mongoose'
|
|
import { AppUser, type AppUserDocument, type AppUserRole } from '../models/AppUser'
|
|
|
|
export type AuthMode = 'open' | 'sso'
|
|
|
|
/**
|
|
* How this deployment obtains an identity.
|
|
*
|
|
* - `open` — self-hosted, no login at all. Every request is the one local user.
|
|
* - `sso` — identity is handed over from the issuer (opensquawk.de) via a
|
|
* one-time code; the app then mints and verifies its own session.
|
|
*
|
|
* There is deliberately no third mode: the app never owns passwords, invites or
|
|
* password resets. Entitlement/feature-gating must NOT be mixed in here —
|
|
* AUTH_MODE is an *identity* concept (see Phase 5.2 of the split plan).
|
|
*/
|
|
|
|
// The single local identity used in AUTH_MODE=open. Fixed so that profiles,
|
|
// bridge tokens and progress survive restarts. Distinct from DEV_BYPASS_USER_ID
|
|
// in server/utils/auth.ts, which is a separate local-dev-only bypass.
|
|
export const LOCAL_USER_ID = '000000000000000000000010'
|
|
export const LOCAL_USER_SUBJECT = 'local'
|
|
const LOCAL_USER_EMAIL = 'local@opensquawk.invalid'
|
|
const LOCAL_USER_NAME = 'Local User'
|
|
|
|
export function getAuthMode(): AuthMode {
|
|
// PHASE 1 (app repo): flip this default to 'open' and delete the note below.
|
|
//
|
|
// The default is 'sso' for as long as the website surface (/api/admin/**,
|
|
// /api/editor/**, invitations, waitlist) still lives in this repo. Defaulting
|
|
// to 'open' here would mean that any deployment which simply forgets to set
|
|
// AUTH_MODE serves those endpoints to everyone as the local admin user.
|
|
// In the app repo that surface is gone and 'open' is the correct default.
|
|
const raw = (process.env.AUTH_MODE || 'sso').trim().toLowerCase()
|
|
return raw === 'open' ? 'open' : 'sso'
|
|
}
|
|
|
|
export function isOpenAuthMode() {
|
|
return getAuthMode() === 'open'
|
|
}
|
|
|
|
/**
|
|
* Where an unauthenticated user is sent in AUTH_MODE=sso. Empty in `open`.
|
|
*/
|
|
export function getAuthIssuer(): string {
|
|
return (process.env.NUXT_PUBLIC_AUTH_ISSUER || '').trim().replace(/\/+$/, '')
|
|
}
|
|
|
|
let localUserPromise: Promise<AppUserDocument> | null = null
|
|
|
|
/**
|
|
* The one identity of an AUTH_MODE=open instance. Persisted (rather than kept
|
|
* in memory) because BridgeToken/LearnProfile/PilotProfile reference it.
|
|
*/
|
|
export function getLocalAppUser(): Promise<AppUserDocument> {
|
|
if (!localUserPromise) {
|
|
localUserPromise = AppUser.findOneAndUpdate(
|
|
{ _id: LOCAL_USER_ID },
|
|
{
|
|
// _id is seeded from the filter's equality condition on insert.
|
|
$setOnInsert: {
|
|
ssoSubject: LOCAL_USER_SUBJECT,
|
|
email: LOCAL_USER_EMAIL,
|
|
name: LOCAL_USER_NAME,
|
|
role: 'admin',
|
|
},
|
|
},
|
|
{ upsert: true, new: true, setDefaultsOnInsert: true },
|
|
).exec().catch((err) => {
|
|
// Never cache a failed lookup — a transient DB outage must not disable
|
|
// the instance for the rest of the process lifetime.
|
|
localUserPromise = null
|
|
throw err
|
|
}) as Promise<AppUserDocument>
|
|
}
|
|
return localUserPromise
|
|
}
|
|
|
|
// Re-upserting the mirror on every single request would add a write to every
|
|
// authenticated call. Subjects seen recently are skipped.
|
|
const MIRROR_TTL_MS = 5 * 60 * 1000
|
|
const mirroredAt = new Map<string, number>()
|
|
|
|
export interface MirrorInput {
|
|
subject: string
|
|
email: string
|
|
name?: string
|
|
role?: AppUserRole
|
|
}
|
|
|
|
/**
|
|
* Write/refresh the local mirror of an SSO identity.
|
|
*
|
|
* When the subject is a valid ObjectId — which it is for every identity issued
|
|
* by opensquawk.de, where the subject *is* `User._id` — it is reused verbatim
|
|
* as the mirror's `_id`, so pre-existing `LearnProfile.user` / `PilotProfile.user`
|
|
* / `BridgeToken.user` references keep resolving without a migration
|
|
* (see server/models/AppUser.ts). A non-ObjectId subject from some future
|
|
* issuer simply gets a generated `_id` and is matched on `ssoSubject`.
|
|
*/
|
|
export async function mirrorAppUser(input: MirrorInput, options: { force?: boolean } = {}) {
|
|
const subject = String(input.subject || '').trim()
|
|
if (!subject) return null
|
|
|
|
const last = mirroredAt.get(subject)
|
|
if (!options.force && last && Date.now() - last < MIRROR_TTL_MS) {
|
|
return null
|
|
}
|
|
|
|
const update: Record<string, unknown> = {
|
|
ssoSubject: subject,
|
|
email: input.email,
|
|
role: input.role || 'user',
|
|
}
|
|
if (input.name !== undefined) update.name = input.name
|
|
|
|
// On insert, MongoDB seeds the document from the filter's equality
|
|
// conditions — so matching on _id is what carries the subject into _id.
|
|
const filter = mongoose.isValidObjectId(subject) ? { _id: subject } : { ssoSubject: subject }
|
|
|
|
const doc = await AppUser.findOneAndUpdate(
|
|
filter,
|
|
{ $set: update },
|
|
{ upsert: true, new: true, setDefaultsOnInsert: true },
|
|
).exec()
|
|
|
|
mirroredAt.set(subject, Date.now())
|
|
return doc
|
|
}
|
|
|
|
/** Test seam — the mirror cache is process-local and otherwise unreachable. */
|
|
export function resetAuthModeCaches() {
|
|
localUserPromise = null
|
|
mirroredAt.clear()
|
|
}
|