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>
188 lines
8.1 KiB
TypeScript
188 lines
8.1 KiB
TypeScript
import {createError, defineEventHandler, readBody} from 'h3'
|
|
import {BridgeToken} from '../../models/BridgeToken'
|
|
import {getBridgeTokenFromHeader} from '../../utils/bridge'
|
|
import {logBridgeEvent} from '../../utils/bridgeLog'
|
|
import {flightlabTelemetryStore} from '../../utils/flightlabTelemetry'
|
|
import {simControlQueue} from '../../utils/simControlQueue'
|
|
import type {FlightLabTelemetryState} from '../../../shared/data/flightlab/types'
|
|
|
|
type DomeLightMode = 'off' | 'white' | 'amber'
|
|
|
|
const lastDomeLightModeByToken = new Map<string, DomeLightMode | null>()
|
|
|
|
/**
|
|
* Receives telemetry data from an external bridge application.
|
|
*
|
|
* The bridge sends raw SimConnect-style fields which are mapped to the
|
|
* FlightLabTelemetryState format before storage.
|
|
*
|
|
* POST /api/bridge/data
|
|
* x-bridge-token: <bridge-token>
|
|
*/
|
|
|
|
/** Map raw bridge field names to FlightLabTelemetryState keys */
|
|
function parseBooleanTelemetryValue(value: unknown): boolean | null {
|
|
if (typeof value === 'boolean') return value
|
|
if (typeof value === 'number') return value !== 0
|
|
if (typeof value === 'string') {
|
|
const normalized = value.trim().toLowerCase()
|
|
if (['1', 'true', 'on', 'yes'].includes(normalized)) return true
|
|
if (['0', 'false', 'off', 'no'].includes(normalized)) return false
|
|
}
|
|
return null
|
|
}
|
|
|
|
function mapBridgeTelemetry(raw: Record<string, any>): FlightLabTelemetryState {
|
|
const seatBeltSignsValue = parseBooleanTelemetryValue(
|
|
raw.seat_belt_signs ?? raw.SEAT_BELT_SIGNS ?? raw.seatbelt_signs ?? raw.seat_belts_signs,
|
|
)
|
|
|
|
return {
|
|
AIRSPEED_INDICATED: raw.ias_kt ?? raw.AIRSPEED_INDICATED ?? 0,
|
|
AIRSPEED_TRUE: raw.tas_kt ?? raw.AIRSPEED_TRUE ?? 0,
|
|
GROUND_VELOCITY: raw.groundspeed_kt ?? raw.GROUND_VELOCITY ?? 0,
|
|
VERTICAL_SPEED: raw.vertical_speed_fpm ?? raw.VERTICAL_SPEED ?? 0,
|
|
PLANE_ALTITUDE: raw.altitude_ft_indicated ?? raw.altitude_ft_true ?? raw.PLANE_ALTITUDE ?? 0,
|
|
PLANE_PITCH_DEGREES: raw.pitch_deg ?? raw.PLANE_PITCH_DEGREES ?? 0,
|
|
TURB_ENG_N1_1: raw.n1_pct ?? raw.TURB_ENG_N1_1 ?? 0,
|
|
TURB_ENG_N1_2: raw.n1_pct_2 ?? raw.TURB_ENG_N1_2 ?? 0,
|
|
ENG_COMBUSTION: !!(raw.eng_on ?? raw.ENG_COMBUSTION ?? false),
|
|
SIM_ON_GROUND: !!(raw.on_ground ?? raw.SIM_ON_GROUND ?? false),
|
|
GEAR_HANDLE_POSITION: !!(raw.gear_handle ?? raw.GEAR_HANDLE_POSITION ?? false),
|
|
FLAPS_HANDLE_INDEX: raw.flaps_index ?? raw.FLAPS_HANDLE_INDEX ?? 0,
|
|
BRAKE_PARKING_POSITION: !!(raw.parking_brake ?? raw.BRAKE_PARKING_POSITION ?? false),
|
|
...(seatBeltSignsValue === null ? {} : {SEAT_BELT_SIGNS: seatBeltSignsValue}),
|
|
AUTOPILOT_MASTER: !!(raw.autopilot_master ?? raw.AUTOPILOT_MASTER ?? false),
|
|
TRANSPONDER_CODE: raw.transponder_code ?? raw.TRANSPONDER_CODE ?? 0,
|
|
ADF_ACTIVE_FREQUENCY: raw.adf_active_freq ?? raw.ADF_ACTIVE_FREQUENCY ?? 0,
|
|
ADF_STANDBY_FREQUENCY: raw.adf_standby_freq_hz ?? raw.ADF_STANDBY_FREQUENCY ?? 0,
|
|
COM_ACTIVE_FREQUENCY: raw.com_active_frequency ?? raw.COM_ACTIVE_FREQUENCY ?? 0,
|
|
COM_STANDBY_FREQUENCY: raw.com_standby_frequency ?? raw.COM_STANDBY_FREQUENCY ?? 0,
|
|
PLANE_LATITUDE: raw.latitude_deg ?? raw.PLANE_LATITUDE ?? 0,
|
|
PLANE_LONGITUDE: raw.longitude_deg ?? raw.PLANE_LONGITUDE ?? 0,
|
|
PLANE_HEADING_DEGREES_TRUE: raw.heading_deg ?? raw.PLANE_HEADING_DEGREES_TRUE ?? 0,
|
|
}
|
|
}
|
|
|
|
function resolveBooleanValue(value: unknown): boolean | null {
|
|
if (typeof value === 'boolean') return value
|
|
if (typeof value === 'number') {
|
|
if (value === 1) return true
|
|
if (value === 0) return false
|
|
}
|
|
if (typeof value === 'string') {
|
|
const normalized = value.trim().toLowerCase()
|
|
if (normalized === 'true' || normalized === '1') return true
|
|
if (normalized === 'false' || normalized === '0') return false
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
function resolveDomeLightValue(raw: Record<string, any>): boolean | null {
|
|
return resolveBooleanValue(raw.dome_light ?? raw.DOME_LIGHT)
|
|
}
|
|
|
|
function resolveNavLogoLightsValue(raw: Record<string, any>): boolean | null {
|
|
return resolveBooleanValue(raw.nav_logo_lights ?? raw.NAV_LOGO_LIGHTS)
|
|
}
|
|
|
|
export function resolveDomeLightMode(raw: Record<string, any>): DomeLightMode | null {
|
|
const domeLight = resolveDomeLightValue(raw)
|
|
if (domeLight === null) return null
|
|
if (!domeLight) return 'off'
|
|
|
|
const navLogoLights = resolveNavLogoLightsValue(raw)
|
|
return navLogoLights ? 'white' : 'amber'
|
|
}
|
|
|
|
async function forwardDomeLightToWebhook(raw: Record<string, any>, webhookUrl: string, stateKey: string) {
|
|
const mode = resolveDomeLightMode(raw)
|
|
const lastMode = lastDomeLightModeByToken.get(stateKey) ?? null
|
|
|
|
if (mode === null) return
|
|
if (lastMode === mode) return
|
|
|
|
try {
|
|
const response = await fetch(webhookUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
},
|
|
body: JSON.stringify({mode}),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const responseBody = await response.text().catch(() => '')
|
|
console.error(
|
|
`\x1b[31m[bridge:dome]\x1b[0m webhook failed status=\x1b[91m${response.status}\x1b[0m mode=\x1b[93m${mode}\x1b[0m body=${responseBody.slice(0, 180)}`,
|
|
)
|
|
} else {
|
|
const domeLight = resolveDomeLightValue(raw)
|
|
const navLogoLights = resolveNavLogoLightsValue(raw)
|
|
console.info(
|
|
`\x1b[36m[bridge:dome]\x1b[0m dome_light=\x1b[92m${String(domeLight)}\x1b[0m nav_logo_lights=\x1b[92m${String(navLogoLights)}\x1b[0m mode=\x1b[93m${mode}\x1b[0m`,
|
|
)
|
|
}
|
|
} catch (error) {
|
|
console.error(
|
|
`\x1b[31m[bridge:dome]\x1b[0m webhook request failed mode=\x1b[93m${mode}\x1b[0m`,
|
|
error,
|
|
)
|
|
} finally {
|
|
lastDomeLightModeByToken.set(stateKey, mode)
|
|
}
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const bridgeToken = getBridgeTokenFromHeader(event)
|
|
if (!bridgeToken) {
|
|
throw createError({statusCode: 401, statusMessage: 'x-bridge-token header fehlt oder ist ungültig.'})
|
|
}
|
|
|
|
const bridgeDocument = await BridgeToken.findOne({token: bridgeToken}).select('user')
|
|
const userId = bridgeDocument?.user?.toString() ?? null
|
|
if (!userId) {
|
|
throw createError({statusCode: 401, statusMessage: 'Bridge-Token ist nicht mit einem Nutzer verknüpft.'})
|
|
}
|
|
|
|
const body = await readBody(event)
|
|
const telemetry = body && typeof body === 'object' ? (body as Record<string, any>) : {}
|
|
const telemetryKeys = Object.keys(telemetry)
|
|
console.info(`\x1b[35m[bridge:data]\x1b[0m token=\x1b[96m${bridgeToken.slice(0, 6)}...\x1b[0m user=\x1b[92m${userId}\x1b[0m telemetryKeys=\x1b[92m${telemetryKeys.length}\x1b[0m`)
|
|
console.table( telemetryKeys.reduce((acc, key) => { acc[key] = telemetry[key]; return acc }, {} as Record<string, any>) )
|
|
|
|
const runtimeConfig = useRuntimeConfig()
|
|
// Opt-in only: no DOME_LIGHT_WEBHOOK_URL, no outbound request. There is
|
|
// deliberately no fallback URL — a foreign instance must never post cockpit
|
|
// telemetry to somebody else's home automation.
|
|
const domeLightWebhookUrl = String(runtimeConfig.domeLightWebhookUrl || '').trim()
|
|
if (domeLightWebhookUrl) {
|
|
await forwardDomeLightToWebhook(telemetry, domeLightWebhookUrl, bridgeToken)
|
|
}
|
|
|
|
// Map raw bridge fields to FlightLab format and store
|
|
const mapped = mapBridgeTelemetry(telemetry)
|
|
flightlabTelemetryStore.update(userId, mapped)
|
|
|
|
logBridgeEvent(bridgeToken, {
|
|
endpoint: '/api/bridge/data',
|
|
method: 'POST',
|
|
statusCode: 200,
|
|
color: '#d946ef',
|
|
summary: `Telemetry ${telemetryKeys.length} keys — IAS ${mapped.AIRSPEED_INDICATED.toFixed(0)}kt ALT ${mapped.PLANE_ALTITUDE.toFixed(0)}ft`,
|
|
data: mapped as unknown as Record<string, unknown>,
|
|
})
|
|
|
|
return {
|
|
// n1_pct: (mapped.TURB_ENG_N1_1 ?? 0) + 10,
|
|
// n1_pct_2: (mapped.TURB_ENG_N1_2 ?? 0) + 10,
|
|
// gear und parking break togglen
|
|
// gear_handle: !mapped.GEAR_HANDLE_POSITION,
|
|
parking_brake: !mapped.BRAKE_PARKING_POSITION,
|
|
// frequency-sim-control (design §4): any commands queued for this bridge
|
|
// token since the last telemetry POST, piggybacked on this response.
|
|
commands: simControlQueue.drainPending(bridgeToken),
|
|
}
|
|
})
|