Files
OpenSquawk/server/utils/telemetry.ts
itsrubberduck 110616bc23 refactor(split): decouple app from website in preparation for the repo split
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>
2026-07-27 18:46:34 +02:00

146 lines
4.4 KiB
TypeScript

/**
* Outbound telemetry mirror.
*
* The app always writes to its **own** database first — that is its data, and
* this channel must never be a dependency of anything. Only if both
* TELEMETRY_URL and SERVICE_SECRET are set is a copy additionally mirrored to
* the hosted service's ingest endpoint.
*
* Self-host default: both unset → nothing ever leaves the instance. That is the
* point, not a fallback.
*
* Design constraints, all of them deliberate:
* - fire-and-forget: emit() never awaits the network and never throws
* - bounded buffer: on overflow the oldest entries are dropped, so a dead sink
* can cost memory neither indefinitely nor unboundedly
* - no retries beyond the current batch: /api/atc/say must return 200 whether
* or not a log sink exists
*
* The wire contract below — {kind, payload} — is the interface between the two
* repos. Neither side shares a Mongoose schema with the other; each owns its
* own. That is what makes two independent databases possible.
*/
export type TelemetryKind =
| 'transmission-log'
| 'bug-report'
| 'llm-routing-decision'
| 'product-usage-session'
export interface TelemetryEnvelope {
kind: TelemetryKind
payload: Record<string, unknown>
emittedAt: string
}
const MAX_BUFFERED = 500
const MAX_BATCH = 50
const FLUSH_DELAY_MS = 2_000
const REQUEST_TIMEOUT_MS = 5_000
const buffer: TelemetryEnvelope[] = []
let flushTimer: ReturnType<typeof setTimeout> | null = null
let flushing = false
let droppedSinceLastWarning = 0
let warnedMissingConfig = false
interface TelemetryConfig {
url: string
secret: string
}
function getTelemetryConfig(): TelemetryConfig | null {
const url = (process.env.TELEMETRY_URL || '').trim()
const secret = (process.env.SERVICE_SECRET || '').trim()
if (!url || !secret) {
if (url && !secret && !warnedMissingConfig) {
console.warn('[telemetry] TELEMETRY_URL is set but SERVICE_SECRET is not — mirroring stays off.')
warnedMissingConfig = true
}
return null
}
return { url, secret }
}
export function isTelemetryEnabled() {
return getTelemetryConfig() !== null
}
/**
* Queue one record for mirroring. Returns immediately; callers do not await and
* do not handle errors, because a telemetry failure is not their problem.
*/
export function emit(kind: TelemetryKind, payload: Record<string, unknown>) {
if (!isTelemetryEnabled()) return
if (buffer.length >= MAX_BUFFERED) {
// Drop the oldest: a stalled sink must not push out fresh data forever.
buffer.shift()
droppedSinceLastWarning += 1
}
buffer.push({ kind, payload, emittedAt: new Date().toISOString() })
scheduleFlush()
}
function scheduleFlush() {
if (flushTimer || flushing) return
flushTimer = setTimeout(() => {
flushTimer = null
void flush()
}, FLUSH_DELAY_MS)
// Never hold the process open for a telemetry batch.
if (typeof flushTimer === 'object' && flushTimer && 'unref' in flushTimer) {
;(flushTimer as unknown as { unref: () => void }).unref()
}
}
export async function flush() {
const config = getTelemetryConfig()
if (!config || flushing || !buffer.length) return
flushing = true
try {
if (droppedSinceLastWarning > 0) {
console.warn(`[telemetry] dropped ${droppedSinceLastWarning} record(s): buffer full`)
droppedSinceLastWarning = 0
}
while (buffer.length) {
const batch = buffer.splice(0, MAX_BATCH)
try {
await $fetch(config.url, {
method: 'POST',
headers: { 'x-service-secret': config.secret },
body: { records: batch },
timeout: REQUEST_TIMEOUT_MS,
})
} catch (error: any) {
// The batch is gone. Re-queueing it would let an unreachable sink build
// an unbounded backlog, which is exactly what this must not do.
console.warn(`[telemetry] mirroring ${batch.length} record(s) failed:`, error?.message || error)
break
}
}
} finally {
flushing = false
if (buffer.length) scheduleFlush()
}
}
/** Test seam — the buffer is module-local and otherwise unreachable. */
export function __resetTelemetryBufferForTests() {
buffer.length = 0
droppedSinceLastWarning = 0
warnedMissingConfig = false
if (flushTimer) {
clearTimeout(flushTimer)
flushTimer = null
}
}
/** Test seam — inspect what is queued without flushing. */
export function __peekTelemetryBufferForTests(): readonly TelemetryEnvelope[] {
return buffer
}