@thoughts-on-things/beacon-protocol 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,538 @@
1
+ // @thoughts-on-things/beacon-protocol: the wire contract between a self-hosted beacon and the
2
+ // Beacon Atlas directory.
3
+ //
4
+ // A beacon that opts into public listing POSTs a *heartbeat* to the Atlas on a
5
+ // timer. This module is the single source of truth for that shape: the
6
+ // beacon's publisher (`@beacon/shared/beacon-publish`) and the Atlas's ingest
7
+ // endpoint both validate against the schemas here, so a field is never defined
8
+ // in two places. `fixtures.ts` carries canonical heartbeats that the
9
+ // conformance tests in this package round-trip through `parseHeartbeat` and
10
+ // `invalidBodies` that must be rejected; both are exposed via the `./fixtures`
11
+ // subpath so downstream consumers can pin against the same baseline.
12
+ //
13
+ // ── The three buckets ─────────────────────────────────────────────────────
14
+ // A heartbeat is `{ schemaVersion, beaconId, manifest, profile?, status }`.
15
+ // The buckets are split by *who owns the data and how often it changes*.
16
+ // Atlas owns every operator-typed field (name, description, addresses,
17
+ // locations, tags, profile copy, privacy, consent flags): a beacon never
18
+ // publishes those over the wire. The heartbeat carries only what the
19
+ // running server itself knows or measures:
20
+ //
21
+ // manifest: slow-changing server-derived facts. Loader, MC version,
22
+ // installed mods, optional world stats. Always present.
23
+ //
24
+ // profile : optional consent-gated opt-in player-identity data
25
+ // (roster, activity). The Atlas listing row carries the consent
26
+ // toggles; the beacon refuses to publish a section the operator
27
+ // hasn't opted into.
28
+ //
29
+ // status : the live, machine-sampled snapshot, re-measured every
30
+ // heartbeat: online flag, player counts, TPS, uptime, peaks. The
31
+ // Atlas independently Server-List-Pings the listing's address and
32
+ // treats the ping as authoritative over these self-reported numbers.
33
+ //
34
+ // ── Versioning ────────────────────────────────────────────────────────────
35
+ // `SCHEMA_VERSION` is the current wire version. The Atlas is version-tolerant
36
+ // (see {@link parseHeartbeat}): a newer beacon's extra fields are stripped, an
37
+ // older beacon validates as long as it satisfies today's required fields.
38
+ // That tolerance only holds for *additive* change: every field added after a
39
+ // version's required core must be optional. Re-categorising a field across
40
+ // buckets, removing one, or adding a required one is a BREAKING change: it
41
+ // needs a `SCHEMA_VERSION` bump and an explicit normalise-on-parse shim, not a
42
+ // silent redefinition.
43
+ //
44
+ // ── Authentication ────────────────────────────────────────────────────────
45
+ // A heartbeat is authenticated by a per-listing bearer secret carried in the
46
+ // `Authorization: Bearer <beaconSecret>` header: never in this body. The
47
+ // Atlas stores only `SHA-256(secret)` and constant-time compares, so a Atlas
48
+ // database compromise yields no usable credential. (This is not HMAC: HMAC
49
+ // would force the Atlas to hold the raw key. TLS provides transport
50
+ // integrity; `status.sampledAt` + {@link checkHeartbeatFreshness} bounds
51
+ // replay value without needing a key.)
52
+ //
53
+ // Heartbeats are untrusted input on the Atlas side: every text field is
54
+ // sanitized (NFC, control chars stripped) and length-capped here, in the
55
+ // schema, so both sides agree on what is acceptable. Oversize input is
56
+ // rejected, never silently truncated.
57
+
58
+ import { z } from "zod";
59
+
60
+ /**
61
+ * Current wire-format version. Bumped only on a breaking change: see the
62
+ * versioning note above. Additive-optional fields do not bump it.
63
+ */
64
+ export const SCHEMA_VERSION = 1;
65
+
66
+ /**
67
+ * Hard cap on a heartbeat request body, in bytes. The ingest route rejects a
68
+ * larger body with 413 before parsing. A legitimate worst-case heartbeat: a
69
+ * full 300-entry roster, 300 mods, 50 activity rows: lands around 50 KiB;
70
+ * 64 KiB leaves headroom without letting a beacon flood the endpoint.
71
+ */
72
+ export const MAX_HEARTBEAT_BYTES = 64 * 1024;
73
+
74
+ /**
75
+ * Freshness window for `status.sampledAt`, relative to the Atlas's clock.
76
+ * A heartbeat sampled too far in the past is stale (or replayed); one too far
77
+ * in the future means a badly skewed beacon clock. Both are rejected. The
78
+ * past bound is generous enough to absorb publisher retry/backoff.
79
+ */
80
+ export const HEARTBEAT_MAX_AGE_MS = 15 * 60_000;
81
+ export const HEARTBEAT_MAX_SKEW_MS = 5 * 60_000;
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // Sanitization
85
+ // ---------------------------------------------------------------------------
86
+
87
+ // C0 and C1 control characters. Stripped from every text field so a beacon
88
+ // cannot smuggle terminal escapes or layout characters into a directory card.
89
+ // eslint-disable-next-line no-control-regex
90
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g;
91
+
92
+ /**
93
+ * Normalize a single-line text field: NFC-normalize, replace C0/C1 control
94
+ * characters with spaces, collapse runs of whitespace, and trim. Applied to
95
+ * every bounded text field before length validation, so the beacon and the
96
+ * Atlas treat input identically.
97
+ */
98
+ export function sanitizeText(value: string): string {
99
+ return value
100
+ .normalize("NFC")
101
+ .replace(CONTROL_CHARS, " ")
102
+ .replace(/\s+/g, " ")
103
+ .trim();
104
+ }
105
+
106
+ function isHttpsUrl(value: string): boolean {
107
+ try {
108
+ return new URL(value).protocol === "https:";
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+
114
+ // A non-empty, single-line text field, sanitized then capped. Sanitization
115
+ // runs first so an all-whitespace value collapses to "" and is rejected, and
116
+ // an oversize value is rejected (not truncated).
117
+ const boundedText = (max: number) =>
118
+ z
119
+ .string()
120
+ .transform(sanitizeText)
121
+ .pipe(z.string().min(1).max(max));
122
+
123
+ // An https:// URL, trimmed and capped. http:// is rejected: the Atlas is a
124
+ // public surface and only links to TLS origins.
125
+ const httpsUrl = (max: number) =>
126
+ z
127
+ .string()
128
+ .transform((value) => value.trim())
129
+ .pipe(
130
+ z
131
+ .string()
132
+ .min(1)
133
+ .max(max)
134
+ .refine(isHttpsUrl, { message: "must be a valid https:// URL" }),
135
+ );
136
+
137
+ // A strict ISO 8601 datetime: `YYYY-MM-DDThh:mm:ss(.sss)?(Z|±hh:mm)`. The
138
+ // previous schema accepted anything `Date.parse` tolerated: "2026", a bare
139
+ // date, a locale string: which let inconsistent timestamps onto the wire.
140
+ // This pins the format so both sides agree, then confirms it is a real,
141
+ // in-range instant.
142
+ const ISO_8601 =
143
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/;
144
+
145
+ const isoDatetime = () =>
146
+ z
147
+ .string()
148
+ .max(40)
149
+ .refine((value) => ISO_8601.test(value) && !Number.isNaN(Date.parse(value)), {
150
+ message: "must be a strict ISO 8601 datetime (YYYY-MM-DDThh:mm:ssZ)",
151
+ });
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Manifest: a beacon's core public identity
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /** Coarse geographic regions, used for directory filtering. */
158
+ export const REGIONS = [
159
+ "na",
160
+ "sa",
161
+ "eu",
162
+ "uk",
163
+ "africa",
164
+ "asia",
165
+ "oce",
166
+ "other",
167
+ ] as const;
168
+
169
+ export const regionSchema = z.enum(REGIONS);
170
+ export type Region = z.infer<typeof regionSchema>;
171
+
172
+ /** Granular public placement, still privacy-preserving by default. */
173
+ export const coordinateSchema = z.object({
174
+ /** Approximate latitude. Operators should not publish a home address. */
175
+ lat: z.number().min(-85).max(85),
176
+ /** Approximate longitude. Operators should not publish a home address. */
177
+ lon: z.number().min(-180).max(180),
178
+ /** Radius of uncertainty around the point, in kilometres. */
179
+ precisionKm: z.number().int().min(1).max(1000).optional(),
180
+ });
181
+ export type Coordinates = z.infer<typeof coordinateSchema>;
182
+
183
+ const publicLocationSchema = z.object({
184
+ /** Coarse region for filtering and fallback placement. */
185
+ region: regionSchema,
186
+ /** ISO 3166-1 alpha-2 country code, e.g. `US`, `CA`, `BR`. */
187
+ countryCode: z
188
+ .string()
189
+ .trim()
190
+ .toUpperCase()
191
+ .regex(/^[A-Z]{2}$/)
192
+ .optional(),
193
+ /** State/province/region code or label, e.g. `NY`, `ON`, `Scotland`. */
194
+ subdivisionCode: boundedText(32).optional(),
195
+ /** City/metro/nearest community label. */
196
+ locality: boundedText(80).optional(),
197
+ /**
198
+ * Optional approximate point. If omitted, Atlas places the beacon from the
199
+ * most specific available public geography above.
200
+ */
201
+ coordinates: coordinateSchema.optional(),
202
+ });
203
+ export const serverLocationSchema = publicLocationSchema;
204
+ export type ServerLocation = z.infer<typeof serverLocationSchema>;
205
+
206
+ export const communityLocationSchema = publicLocationSchema;
207
+ export type CommunityLocation = z.infer<typeof communityLocationSchema>;
208
+
209
+ /**
210
+ * How a player gets into the beacon, surfaced so the Atlas renders the right
211
+ * call to action: `gated` links to the beacon's own `/join` flow (the operator
212
+ * still approves), `open` means Atlas deep-links to a public Minecraft login
213
+ * flow that the beacon auto-approves after re-checking its Atlas profile.
214
+ */
215
+ export const joinPolicySchema = z.enum(["gated", "open"]);
216
+ export type JoinPolicy = z.infer<typeof joinPolicySchema>;
217
+
218
+ /**
219
+ * The mod loader / server software a beacon runs: part of core identity.
220
+ * These mirror `@beacon/shared`'s `LoaderId` exactly: a beacon publishes the
221
+ * loader it runs, so the publisher passes the value straight through with no
222
+ * mapping. Keep the two enums in lockstep.
223
+ */
224
+ export const loaderSchema = z.enum([
225
+ "vanilla",
226
+ "paper",
227
+ "purpur",
228
+ "folia",
229
+ "fabric",
230
+ "quilt",
231
+ "forge",
232
+ "neoforge",
233
+ ]);
234
+ export type Loader = z.infer<typeof loaderSchema>;
235
+
236
+ /**
237
+ * A Beacon-hosted Vantage protocol endpoint. Atlas never receives the tile
238
+ * tree: this capability tells the public profile that it may connect directly
239
+ * to the Beacon's public map boundary and speak Vantage protocol v1 there.
240
+ */
241
+ export const vantageStreamSchema = z.object({
242
+ protocolVersion: z.literal(1),
243
+ mode: z.literal("live"),
244
+ /**
245
+ * How many dimensions the endpoint serves, when it publishes a `world.json`
246
+ * index naming them. Absent means an older Beacon whose only entry point is
247
+ * `manifest.json` — so its presence, not its value, is what tells a viewer
248
+ * which URL to open. No coordinates ride on this: it is a count.
249
+ */
250
+ dimensions: z.number().int().min(1).max(64).optional(),
251
+ });
252
+ export type VantageStream = z.infer<typeof vantageStreamSchema>;
253
+
254
+ /**
255
+ * The slow-changing server-derived facts a beacon publishes about itself.
256
+ * These are values the running server measures or knows about its own
257
+ * runtime, not anything the operator typed. Operator-typed identity
258
+ * (name, description, addresses, locations, tags, …) lives on the Atlas
259
+ * listing row and never crosses this wire.
260
+ *
261
+ * Coordinates, invite codes, the audit log, and any operator account
262
+ * data have no field to ride on. Player identities leave a beacon only
263
+ * through the opt-in `profile.roster` / `profile.activity` fields.
264
+ */
265
+ export const manifestSchema = z.object({
266
+ /** Minecraft version string, e.g. "1.21.4". */
267
+ mcVersion: boundedText(32),
268
+ /** Server software / mod loader. */
269
+ loader: loaderSchema,
270
+ /** Installed mods / plugins, by name. */
271
+ mods: z.array(boundedText(64)).max(300).default([]),
272
+ /** Server render distance, in chunks. */
273
+ renderDistance: z.number().int().min(2).max(64).optional(),
274
+ /** How long the current world has existed, in days. */
275
+ worldAgeDays: z.number().int().min(0).max(40_000).optional(),
276
+ /** On-disk world size, in mebibytes. */
277
+ worldSizeMib: z.number().int().min(0).max(100_000_000).optional(),
278
+ /** Public, federated Vantage stream capability. No map bytes ride here. */
279
+ vantage: vantageStreamSchema.optional(),
280
+ });
281
+
282
+ export type BeaconManifest = z.infer<typeof manifestSchema>;
283
+
284
+ // ---------------------------------------------------------------------------
285
+ // Profile: opt-in consent-gated player-identity data
286
+ // ---------------------------------------------------------------------------
287
+ //
288
+ // Everything operator-typed (host name, vibe, rules, host note, events,
289
+ // difficulty, Discord invite, per-section privacy) lives on the Atlas
290
+ // listing row, not on the wire. The only thing the beacon publishes
291
+ // itself is *opt-in player data*: a roster of members and a recent-
292
+ // activity feed. Both are absent unless the operator flipped the
293
+ // matching consent toggle on the Atlas dashboard.
294
+
295
+ /** World difficulty: stored on the Atlas listing row, surfaced on `/b/[slug]`. */
296
+ export const difficultySchema = z.enum([
297
+ "peaceful",
298
+ "easy",
299
+ "normal",
300
+ "hard",
301
+ "hardcore",
302
+ ]);
303
+ export type Difficulty = z.infer<typeof difficultySchema>;
304
+
305
+ /**
306
+ * Per-section visibility the host configures on the Atlas dashboard.
307
+ * `public` shows the section to everyone; `members` restricts it to the
308
+ * beacon's members; `hidden` hides it from everyone but the host. The
309
+ * Atlas renders a `members`/`hidden` section as a locked placeholder for
310
+ * visitors. `coords` also gates the federated Vantage world; its bytes stay on
311
+ * the Beacon and never cross the heartbeat wire.
312
+ */
313
+ export const privacyLevelSchema = z.enum(["public", "members", "hidden"]);
314
+ export type PrivacyLevel = z.infer<typeof privacyLevelSchema>;
315
+
316
+ /** The profile sections whose visibility a host can configure. */
317
+ export const PRIVACY_SECTIONS = [
318
+ "coords",
319
+ "roster",
320
+ "activity",
321
+ "mods",
322
+ "perf",
323
+ ] as const;
324
+ export type PrivacySection = (typeof PRIVACY_SECTIONS)[number];
325
+
326
+ /** Visibility map, one level per gateable section. Defaults to `public`. */
327
+ export const privacySchema = z.object({
328
+ coords: privacyLevelSchema.default("public"),
329
+ roster: privacyLevelSchema.default("public"),
330
+ activity: privacyLevelSchema.default("public"),
331
+ mods: privacyLevelSchema.default("public"),
332
+ perf: privacyLevelSchema.default("public"),
333
+ });
334
+ export type ProfilePrivacy = z.infer<typeof privacySchema>;
335
+
336
+ /** A staff/member role, used to tally and badge the roster. */
337
+ export const rosterRoleSchema = z.enum([
338
+ "host",
339
+ "admin",
340
+ "mod",
341
+ "builder",
342
+ "member",
343
+ ]);
344
+ export type RosterRole = z.infer<typeof rosterRoleSchema>;
345
+
346
+ /** One entry in the published roster: opt-in player-identity data. */
347
+ export const rosterEntrySchema = z.object({
348
+ name: boundedText(32),
349
+ role: rosterRoleSchema,
350
+ /** Whether this player is connected as of the heartbeat. */
351
+ online: z.boolean().default(false),
352
+ });
353
+ export type RosterEntry = z.infer<typeof rosterEntrySchema>;
354
+
355
+ /** The kind of a recent-activity row. */
356
+ export const activityKindSchema = z.enum([
357
+ "join",
358
+ "leave",
359
+ "death",
360
+ "advancement",
361
+ "build",
362
+ "broadcast",
363
+ ]);
364
+ export type ActivityKind = z.infer<typeof activityKindSchema>;
365
+
366
+ /** One row in the published recent-activity feed: opt-in player data. */
367
+ export const activityEntrySchema = z.object({
368
+ kind: activityKindSchema,
369
+ /** The player the row is about. Absent for server-level rows. */
370
+ actor: boundedText(32).optional(),
371
+ /** Human-readable detail, e.g. "earned The End" or "was slain by a Warden". */
372
+ detail: boundedText(160),
373
+ /** When it happened, ISO 8601. */
374
+ at: isoDatetime(),
375
+ });
376
+ export type ActivityEntry = z.infer<typeof activityEntrySchema>;
377
+
378
+ /** An upcoming community event for the "Up next" panel. Stored on the
379
+ * Atlas listing row (operator-typed), not on the wire. */
380
+ export const eventEntrySchema = z.object({
381
+ at: isoDatetime(),
382
+ title: boundedText(80),
383
+ detail: boundedText(120).optional(),
384
+ });
385
+ export type EventEntry = z.infer<typeof eventEntrySchema>;
386
+
387
+ /** A pinned note from the host. Stored on the Atlas listing row. */
388
+ export const hostNoteSchema = z.object({
389
+ body: boundedText(600),
390
+ postedAt: isoDatetime(),
391
+ });
392
+ export type HostNote = z.infer<typeof hostNoteSchema>;
393
+
394
+ /**
395
+ * The optional opt-in player-data block on a heartbeat. Both fields are
396
+ * gated by the matching consent toggle on the Atlas listing row: the
397
+ * beacon must not publish them unless the operator opted in.
398
+ */
399
+ export const profileSchema = z.object({
400
+ /** Published member roster: opt-in player-identity data. */
401
+ roster: z.array(rosterEntrySchema).max(300).optional(),
402
+ /** Published recent-activity feed: opt-in player-identity data. */
403
+ activity: z.array(activityEntrySchema).max(50).optional(),
404
+ });
405
+ export type BeaconProfile = z.infer<typeof profileSchema>;
406
+
407
+ // ---------------------------------------------------------------------------
408
+ // Status: a beacon's live snapshot
409
+ // ---------------------------------------------------------------------------
410
+
411
+ /**
412
+ * The live, fast-changing slice of a heartbeat: re-measured every tick.
413
+ * Self-reported: the Atlas independently Server-List-Pings `manifest.mcAddress`
414
+ * and treats the ping result as authoritative over these numbers.
415
+ */
416
+ export const statusSchema = z.object({
417
+ /** Whether the beacon considers its Minecraft server reachable. */
418
+ online: z.boolean(),
419
+ /** Players currently connected. */
420
+ playersOnline: z.number().int().min(0).max(100_000),
421
+ /** Player slot capacity. */
422
+ playersMax: z.number().int().min(0).max(100_000),
423
+ /** Server ticks per second, 0–20. Drives the Performance panel. */
424
+ tps: z.number().min(0).max(20).optional(),
425
+ /** Seconds since the Minecraft process last started. */
426
+ uptimeSeconds: z.number().int().min(0).optional(),
427
+ /** Rolling uptime reliability, as a percentage 0–100. */
428
+ uptimePct: z.number().min(0).max(100).optional(),
429
+ /**
430
+ * Daily player peaks for the last 7 days, oldest first. Powers the
431
+ * profile's "players, last 7 days" sparkline.
432
+ */
433
+ playersPeak7d: z
434
+ .array(z.number().int().min(0).max(100_000))
435
+ .max(14)
436
+ .optional(),
437
+ /** When this status was sampled, ISO 8601. */
438
+ sampledAt: isoDatetime(),
439
+ });
440
+
441
+ export type BeaconStatusReport = z.infer<typeof statusSchema>;
442
+
443
+ // ---------------------------------------------------------------------------
444
+ // Heartbeat: the full POST body
445
+ // ---------------------------------------------------------------------------
446
+
447
+ // Opaque listing id minted by the Atlas at registration. The bearer secret
448
+ // that authenticates a heartbeat travels in an HTTP header, not in this body.
449
+ const beaconIdSchema = z
450
+ .string()
451
+ .min(1)
452
+ .max(64)
453
+ .regex(/^[A-Za-z0-9_-]+$/, "must be an opaque url-safe id");
454
+
455
+ export const heartbeatSchema = z.object({
456
+ /** Wire-format version the sending beacon was built against. */
457
+ schemaVersion: z.number().int().min(1),
458
+ /** The listing this heartbeat belongs to. */
459
+ beaconId: beaconIdSchema,
460
+ manifest: manifestSchema,
461
+ /** Optional operator-curated extended block: backs the profile page. */
462
+ profile: profileSchema.optional(),
463
+ status: statusSchema,
464
+ });
465
+
466
+ export type Heartbeat = z.infer<typeof heartbeatSchema>;
467
+
468
+ /**
469
+ * Stamp a heartbeat with the current {@link SCHEMA_VERSION}. The beacon-side
470
+ * publisher uses this so the version is set in exactly one place.
471
+ */
472
+ export function buildHeartbeat(
473
+ beaconId: string,
474
+ manifest: BeaconManifest,
475
+ status: BeaconStatusReport,
476
+ profile?: BeaconProfile,
477
+ ): Heartbeat {
478
+ return {
479
+ schemaVersion: SCHEMA_VERSION,
480
+ beaconId,
481
+ manifest,
482
+ ...(profile ? { profile } : {}),
483
+ status,
484
+ };
485
+ }
486
+
487
+ export type HeartbeatParseResult =
488
+ | { ok: true; heartbeat: Heartbeat; futureSchema: boolean }
489
+ | { ok: false; error: string };
490
+
491
+ /**
492
+ * Parse and validate an inbound heartbeat body on the Atlas side.
493
+ *
494
+ * Schema-version tolerant by design: a heartbeat is accepted regardless of its
495
+ * `schemaVersion`. A beacon on a newer version may send extra fields: zod
496
+ * strips unknown keys, so the known shape still validates. A beacon on an
497
+ * older version is fine as long as it satisfies the current required fields;
498
+ * future additive fields must therefore be optional. `futureSchema` flags a
499
+ * heartbeat newer than this build so callers can log or surface it.
500
+ */
501
+ export function parseHeartbeat(input: unknown): HeartbeatParseResult {
502
+ const result = heartbeatSchema.safeParse(input);
503
+ if (!result.success) {
504
+ const error = result.error.issues
505
+ .map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
506
+ .join("; ");
507
+ return { ok: false, error };
508
+ }
509
+ return {
510
+ ok: true,
511
+ heartbeat: result.data,
512
+ futureSchema: result.data.schemaVersion > SCHEMA_VERSION,
513
+ };
514
+ }
515
+
516
+ export type HeartbeatFreshness =
517
+ | { fresh: true }
518
+ | { fresh: false; reason: "stale" | "future" };
519
+
520
+ /**
521
+ * Check that a heartbeat's `status.sampledAt` sits inside the freshness
522
+ * window around the Atlas's clock. A too-old sample is `stale` (a delayed or
523
+ * replayed heartbeat); a too-far-ahead sample is `future` (a skewed beacon
524
+ * clock). The ingest route rejects either. This is a key-free replay bound:
525
+ * a captured heartbeat is worthless once it ages past {@link
526
+ * HEARTBEAT_MAX_AGE_MS}.
527
+ */
528
+ export function checkHeartbeatFreshness(
529
+ sampledAt: string,
530
+ now: Date = new Date(),
531
+ ): HeartbeatFreshness {
532
+ const sampled = Date.parse(sampledAt);
533
+ if (Number.isNaN(sampled)) return { fresh: false, reason: "future" };
534
+ const delta = now.getTime() - sampled;
535
+ if (delta > HEARTBEAT_MAX_AGE_MS) return { fresh: false, reason: "stale" };
536
+ if (delta < -HEARTBEAT_MAX_SKEW_MS) return { fresh: false, reason: "future" };
537
+ return { fresh: true };
538
+ }
@@ -0,0 +1,125 @@
1
+ // Atlas mod relay: the wire contract between a beacon and the Atlas's
2
+ // central mod-provider gateway.
3
+ //
4
+ // The Atlas fronts every provider's catalog API for registered beacons:
5
+ // one place holds upstream credentials (CurseForge's key never leaves
6
+ // the Atlas), responses are cached across ALL beacons, and per-beacon
7
+ // rate limits protect the shared upstream quota. A beacon calls
8
+ //
9
+ // {atlas}/api/mods/{provider}/{upstream path}?{query}
10
+ //
11
+ // with its registration credentials (`Authorization: Bearer <secret>` +
12
+ // `X-Beacon-Id`), and the relay forwards the allowlisted subset below to
13
+ // the provider's real API. The allowlist lives HERE — shared by the
14
+ // Atlas (enforcement) and admin-rpc (so a client change that needs a new
15
+ // route shows up as a contract change, not a mysterious 404).
16
+
17
+ export const MOD_RELAY_BASE_PATH = "/api/mods";
18
+ export const MOD_RELAY_STATUS_PATH = "/api/mods/status";
19
+
20
+ // Beacon identity header accompanying the bearer secret. The heartbeat
21
+ // carries its beacon id in the body; relay calls are mostly GETs, so the
22
+ // id rides a header instead.
23
+ export const MOD_RELAY_BEACON_ID_HEADER = "x-beacon-id";
24
+
25
+ // Upstream base URLs, owned by the relay — a beacon cannot point the
26
+ // Atlas at an arbitrary origin.
27
+ export const MOD_RELAY_UPSTREAMS = {
28
+ modrinth: "https://api.modrinth.com/v2",
29
+ curseforge: "https://api.curseforge.com/v1",
30
+ } as const;
31
+
32
+ export type ModRelayProvider = keyof typeof MOD_RELAY_UPSTREAMS;
33
+
34
+ export const MOD_RELAY_PROVIDERS = Object.keys(
35
+ MOD_RELAY_UPSTREAMS,
36
+ ) as readonly ModRelayProvider[];
37
+
38
+ export function isModRelayProvider(value: string): value is ModRelayProvider {
39
+ return Object.prototype.hasOwnProperty.call(MOD_RELAY_UPSTREAMS, value);
40
+ }
41
+
42
+ // The relay path a beacon-side client uses as its API base for one
43
+ // provider (append the provider client's usual upstream paths).
44
+ export function modRelayProviderBasePath(provider: ModRelayProvider): string {
45
+ return `${MOD_RELAY_BASE_PATH}/${provider}`;
46
+ }
47
+
48
+ // ---- Route allowlist ----
49
+ //
50
+ // Exactly the calls the shared provider clients make (see
51
+ // modrinth-client.ts / curseforge-client.ts): search, project lookup,
52
+ // version/file listing, and CurseForge's bulk file + category lookups.
53
+ // Patterns match the UPSTREAM subpath (no query string); id/slug
54
+ // segments tolerate percent-encoding.
55
+
56
+ export type ModRelayMethod = "GET" | "POST";
57
+
58
+ export type ModRelayRoute = {
59
+ method: ModRelayMethod;
60
+ pattern: RegExp;
61
+ };
62
+
63
+ // One URL-encoded path segment (slug, id, or percent-escaped bytes).
64
+ const SEG = "[A-Za-z0-9._%!\\-~]+";
65
+
66
+ export const MOD_RELAY_ROUTES: Record<
67
+ ModRelayProvider,
68
+ readonly ModRelayRoute[]
69
+ > = {
70
+ modrinth: [
71
+ { method: "GET", pattern: new RegExp(`^/search$`) },
72
+ { method: "GET", pattern: new RegExp(`^/project/${SEG}$`) },
73
+ { method: "GET", pattern: new RegExp(`^/project/${SEG}/version$`) },
74
+ { method: "GET", pattern: new RegExp(`^/version/${SEG}$`) },
75
+ ],
76
+ curseforge: [
77
+ { method: "GET", pattern: new RegExp(`^/mods/search$`) },
78
+ { method: "GET", pattern: new RegExp(`^/mods/\\d+$`) },
79
+ { method: "GET", pattern: new RegExp(`^/mods/\\d+/files$`) },
80
+ { method: "POST", pattern: new RegExp(`^/mods/files$`) },
81
+ { method: "GET", pattern: new RegExp(`^/categories$`) },
82
+ ],
83
+ };
84
+
85
+ export function isAllowedModRelayRoute(
86
+ provider: ModRelayProvider,
87
+ method: string,
88
+ upstreamPath: string,
89
+ ): boolean {
90
+ const normalizedMethod = method.toUpperCase();
91
+ return MOD_RELAY_ROUTES[provider].some(
92
+ (route) =>
93
+ route.method === normalizedMethod && route.pattern.test(upstreamPath),
94
+ );
95
+ }
96
+
97
+ // Cap for relayed POST bodies (CurseForge bulk file lookups are tiny;
98
+ // anything larger is not a legitimate relay call).
99
+ export const MOD_RELAY_MAX_BODY_BYTES = 16 * 1024;
100
+
101
+ // ---- Status ----
102
+ //
103
+ // What the relay can serve RIGHT NOW. Registration is static; CurseForge
104
+ // availability depends on the Atlas holding an API key. Beacons probe
105
+ // this (cached) to decide relay vs direct transport and what the picker
106
+ // should offer.
107
+
108
+ export type ModRelayStatus = {
109
+ providers: Record<ModRelayProvider, { available: boolean }>;
110
+ };
111
+
112
+ export function parseModRelayStatus(raw: unknown): ModRelayStatus | null {
113
+ if (!raw || typeof raw !== "object") return null;
114
+ const providers = (raw as { providers?: unknown }).providers;
115
+ if (!providers || typeof providers !== "object") return null;
116
+ const out = {} as ModRelayStatus["providers"];
117
+ for (const provider of MOD_RELAY_PROVIDERS) {
118
+ const entry = (providers as Record<string, unknown>)[provider];
119
+ if (!entry || typeof entry !== "object") return null;
120
+ const available = (entry as { available?: unknown }).available;
121
+ if (typeof available !== "boolean") return null;
122
+ out[provider] = { available };
123
+ }
124
+ return { providers: out };
125
+ }