@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/play.ts ADDED
@@ -0,0 +1,152 @@
1
+ // The `beacon://play` deep-link contract.
2
+ //
3
+ // A beacon's "Play" button encodes a loadout *and the beacon's own origin* so
4
+ // the launcher (or `beacon play`) knows which beacon to fetch the loadout
5
+ // manifest from — loadouts live on each beacon's web app, not on Atlas. This
6
+ // is a bilateral wire contract: apps/web builds the link, the launcher/CLI
7
+ // parse it. It lives in `@thoughts-on-things/beacon-protocol` (not the launch engine) so the web
8
+ // side can build links without depending on the launcher.
9
+ //
10
+ // Format: `beacon://play/<loadoutId>?host=<url-encoded beacon origin>`
11
+ // e.g. `beacon://play/lo_8fa2c1?host=https%3A%2F%2Fplay.example`
12
+ //
13
+ // The link carries NO credential. Member-only access is authorized by the
14
+ // launcher's own first-party Beacon session — a silent, Atlas-brokered link the
15
+ // launcher establishes per beacon (see apps/launcher/src/lib/beacon-session.ts
16
+ // and apps/web/src/app/auth/launcher/*) and presents as `Authorization: Bearer`
17
+ // on the manifest fetch. So the same link works whether or not the loadout is
18
+ // public, and a stale link can never carry a dead token.
19
+
20
+ /** Where a play link points: a loadout on a specific beacon. */
21
+ export interface PlayTarget {
22
+ /** Full origin of the beacon's web app (scheme + host + port), normalized —
23
+ * e.g. `http://localhost:3000`, `https://play.example`. */
24
+ beaconOrigin: string;
25
+ /** The loadout to resolve from `<beaconOrigin>/i/<loadoutId>`. */
26
+ loadoutId: string;
27
+ }
28
+
29
+ /**
30
+ * What a beacon advertises at `GET /api/play`: its current (active) loadout and
31
+ * whether the launcher can one-click play it. Loadouts live on the beacon, not
32
+ * Atlas, so the launcher resolves this from a directory beacon's `publicUrl` to
33
+ * launch straight from Browse — no `beacon://play` deep link needed.
34
+ *
35
+ * This is the public, low-sensitivity descriptor (the same facts the beacon's
36
+ * own home page shows on its Play button); the heavy mod list still comes from
37
+ * the gated `/i/<loadoutId>/manifest.json` at launch time.
38
+ */
39
+ export interface ActivePlayTarget {
40
+ /** The active loadout's id — the deep-link target and the install-record key. */
41
+ loadoutId: string;
42
+ /** Display name of the client pack. */
43
+ name: string;
44
+ /** One-line summary, or null. */
45
+ summary: string | null;
46
+ /** Loader id (`fabric`/`quilt`/`vanilla`/…), for display. `vanilla` means
47
+ * nothing to install client-side — the stock client just connects. */
48
+ loader: string;
49
+ /** Minecraft version. */
50
+ mcVersion: string;
51
+ /** True when the launcher can resolve/install + boot the loadout (plain
52
+ * vanilla, Fabric/Quilt metadata, or Forge/NeoForge official installers). */
53
+ launchable: boolean;
54
+ /** True when the loadout's manifest is publicly fetchable (a `shared` loadout).
55
+ * A false value still may be playable: the launcher can authorize the gated
56
+ * manifest through its first-party Beacon session at launch time. */
57
+ shared: boolean;
58
+ }
59
+
60
+ /**
61
+ * Validate an untrusted `GET /api/play` payload into an {@link ActivePlayTarget},
62
+ * or null if it isn't one. Mirrors the defensive parsing the launcher applies to
63
+ * any beacon-served JSON.
64
+ */
65
+ export function parseActivePlayTarget(data: unknown): ActivePlayTarget | null {
66
+ if (typeof data !== "object" || data === null) return null;
67
+ const raw = data as Record<string, unknown>;
68
+ if (typeof raw.loadoutId !== "string" || !raw.loadoutId) return null;
69
+ if (typeof raw.name !== "string") return null;
70
+ if (typeof raw.loader !== "string") return null;
71
+ if (typeof raw.mcVersion !== "string") return null;
72
+ if (typeof raw.launchable !== "boolean") return null;
73
+ if (typeof raw.shared !== "boolean") return null;
74
+ return {
75
+ loadoutId: raw.loadoutId,
76
+ name: raw.name,
77
+ summary: typeof raw.summary === "string" ? raw.summary : null,
78
+ loader: raw.loader,
79
+ mcVersion: raw.mcVersion,
80
+ launchable: raw.launchable,
81
+ shared: raw.shared,
82
+ };
83
+ }
84
+
85
+ /** The `play` action segment — `beacon://play/...`. */
86
+ const PLAY_ACTION = "play";
87
+
88
+ /**
89
+ * Build a `beacon://play` deep link. Throws if `beaconOrigin` is not a valid
90
+ * http(s) origin or `loadoutId` is empty — both are programming errors at the
91
+ * call site (the web Play button always has a real origin + id).
92
+ */
93
+ export function buildPlayUri(target: PlayTarget): string {
94
+ const origin = normalizeOrigin(target.beaconOrigin);
95
+ if (!origin) {
96
+ throw new Error(`buildPlayUri: invalid beacon origin "${target.beaconOrigin}"`);
97
+ }
98
+ const id = target.loadoutId.trim();
99
+ if (!id) throw new Error("buildPlayUri: loadoutId is required");
100
+ const params = new URLSearchParams({ host: origin });
101
+ return `beacon://${PLAY_ACTION}/${encodeURIComponent(id)}?${params.toString()}`;
102
+ }
103
+
104
+ /**
105
+ * Parse a `beacon://play` deep link. Returns null for anything that isn't a
106
+ * well-formed play link carrying a loadout id and a valid http(s) `host`
107
+ * origin — a malformed or hostile link simply doesn't resolve.
108
+ */
109
+ export function parsePlayUri(uri: string): PlayTarget | null {
110
+ let url: URL;
111
+ try {
112
+ url = new URL(uri);
113
+ } catch {
114
+ return null;
115
+ }
116
+ if (url.protocol !== "beacon:") return null;
117
+ // `beacon://play/<id>` parses with hostname === "play".
118
+ if (url.hostname !== PLAY_ACTION) return null;
119
+
120
+ const firstSegment = url.pathname.split("/").filter(Boolean)[0];
121
+ if (!firstSegment) return null;
122
+ const loadoutId = safeDecode(firstSegment);
123
+ if (!loadoutId) return null;
124
+
125
+ const host = url.searchParams.get("host");
126
+ if (!host) return null;
127
+ const beaconOrigin = normalizeOrigin(host);
128
+ if (!beaconOrigin) return null;
129
+
130
+ return { beaconOrigin, loadoutId };
131
+ }
132
+
133
+ /** Validate + normalize an http(s) origin (drops any path/query/fragment).
134
+ * Returns null for anything that isn't http or https. */
135
+ function normalizeOrigin(value: string): string | null {
136
+ let url: URL;
137
+ try {
138
+ url = new URL(value);
139
+ } catch {
140
+ return null;
141
+ }
142
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
143
+ return url.origin;
144
+ }
145
+
146
+ function safeDecode(value: string): string {
147
+ try {
148
+ return decodeURIComponent(value);
149
+ } catch {
150
+ return "";
151
+ }
152
+ }
package/src/publish.ts ADDED
@@ -0,0 +1,237 @@
1
+ // Beacon-side publishing: the projector that turns a beacon's runtime state
2
+ // into a wire {@link Heartbeat}.
3
+ //
4
+ // This module is the *single* place a beacon decides what to publish about
5
+ // itself. The field allowlist is enforced by construction: `projectHeartbeat`
6
+ // reads only the explicit fields below, so a coordinate, an invite code, an
7
+ // operator account, or any operator-typed identity field simply has no path
8
+ // onto the wire — there is no field to carry it. Atlas owns every operator-
9
+ // typed identity (name, addresses, locations, profile copy, privacy, …); the
10
+ // beacon publishes only what its running server measures.
11
+ //
12
+ // Both sides of the beacon use this module: the `apps/web` settings card runs
13
+ // it to render the "what the world sees" preview, and the `apps/admin-rpc`
14
+ // publisher job runs it to build the heartbeat it POSTs. Because it is one
15
+ // pure function, the preview is byte-identical to what is published.
16
+
17
+ import {
18
+ buildHeartbeat,
19
+ heartbeatSchema,
20
+ type Heartbeat,
21
+ type Loader,
22
+ type RosterEntry,
23
+ type ActivityEntry,
24
+ type VantageStream,
25
+ } from "./index.js";
26
+
27
+ /** The `settings` table key the beacon stores its Atlas listing config under. */
28
+ export const ATLAS_LISTING_KEY = "atlas_listing";
29
+
30
+ /** The project-owned public Atlas a new beacon offers by default. */
31
+ export const CANONICAL_ATLAS_URL = "https://beacon-mc.io";
32
+
33
+ /**
34
+ * What the beacon stores LOCALLY about its Atlas listing. Identity, credentials,
35
+ * and every profile field live elsewhere: the single `client_id`/`client_secret`
36
+ * (env) is the beacon's identity for login, heartbeat, AND directory management,
37
+ * and Atlas is the authoritative source of profile content and visibility. So
38
+ * the beacon only needs two local facts: whether listing is on (the publisher's
39
+ * no-op gate) and the slug Atlas minted (for the `/b/<slug>` deep-link).
40
+ */
41
+ export interface AtlasListingSettings {
42
+ /** Operator opt-in to public listing. The publisher skips while false. */
43
+ enabled: boolean;
44
+ /** The public slug Atlas minted, for the `/b/<slug>` deep-link. Empty until known. */
45
+ slug: string;
46
+ /**
47
+ * Explicit opt-in to serving this world through the public Atlas profile.
48
+ * The stream stays on the Beacon; Atlas stores only the capability advertised
49
+ * in the heartbeat. Off by default because explored terrain is sensitive.
50
+ */
51
+ publishMap: boolean;
52
+ }
53
+
54
+ export const DEFAULT_ATLAS_LISTING: AtlasListingSettings = {
55
+ enabled: false,
56
+ slug: "",
57
+ publishMap: false,
58
+ };
59
+
60
+ /**
61
+ * Server-derived facts and live state the publisher gathers, passed to
62
+ * {@link projectHeartbeat}. Nothing here is operator-typed: it is read
63
+ * from the running server itself.
64
+ *
65
+ * `peak7d` and `uptimePct` are deliberately *not* here: rolling history is
66
+ * computed Atlas-side from the heartbeat stream so there is a single source
67
+ * of truth for the public profile's time-series panels. Vantage publishes only
68
+ * a tiny capability here; manifests, textures, and tiles stay on the Beacon.
69
+ */
70
+ export interface ProjectionInputs {
71
+ beaconId: string;
72
+ server: {
73
+ /** Minecraft version string. */
74
+ mcVersion: string;
75
+ /** Mod loader / server software. */
76
+ loader: Loader;
77
+ /** Installed mod / plugin names. */
78
+ mods: string[];
79
+ /** Server render distance, in chunks, when known. */
80
+ renderDistance?: number;
81
+ /** How long the current world has existed, in days, when known. */
82
+ worldAgeDays?: number;
83
+ /** On-disk world size, in mebibytes, when known. */
84
+ worldSizeMib?: number;
85
+ /** Federated Vantage stream, present only while public streaming is live.
86
+ * Typed off the wire schema so a new capability field lands here without
87
+ * a second declaration to keep in step — the allowlist stays by
88
+ * construction, it just names one shape instead of restating it. */
89
+ vantage?: VantageStream;
90
+ };
91
+ status: {
92
+ online: boolean;
93
+ playersOnline: number;
94
+ playersMax: number;
95
+ /** Ticks per second, when RCON answered. */
96
+ tps?: number;
97
+ /** Seconds since the Minecraft process started, when known. */
98
+ uptimeSeconds?: number;
99
+ };
100
+ /**
101
+ * Optional opt-in player data. Always forwarded when present; the Atlas
102
+ * applies the `consent_roster` / `consent_activity` listing toggles as a
103
+ * defense-in-depth filter so the publisher need only know whether it has
104
+ * data to send, not what the operator marked consent-wise on the Atlas
105
+ * dashboard. (A future beacon-side opt-in toggle is a separate change.)
106
+ */
107
+ consent?: {
108
+ roster?: RosterEntry[];
109
+ activity?: ActivityEntry[];
110
+ };
111
+ /** When the status was sampled. */
112
+ sampledAt: Date;
113
+ }
114
+
115
+ export type ProjectionResult =
116
+ | { ok: true; heartbeat: Heartbeat }
117
+ | { ok: false; error: string };
118
+
119
+ /**
120
+ * Project the beacon's runtime state into a validated {@link Heartbeat}.
121
+ *
122
+ * The result is run through `heartbeatSchema` before it is returned, so the
123
+ * heartbeat is sanitized and length-checked exactly as the Atlas will check
124
+ * it: a preview rendered from this is byte-identical to what the publisher
125
+ * sends, and a runtime value that violates the contract surfaces as an
126
+ * `ok: false` error the settings card can show: not a rejected POST later.
127
+ */
128
+ export function projectHeartbeat(inputs: ProjectionInputs): ProjectionResult {
129
+ const { server, status, consent } = inputs;
130
+
131
+ const manifest = {
132
+ mcVersion: server.mcVersion,
133
+ loader: server.loader,
134
+ mods: server.mods,
135
+ ...(server.renderDistance !== undefined
136
+ ? { renderDistance: server.renderDistance }
137
+ : {}),
138
+ ...(server.worldAgeDays !== undefined
139
+ ? { worldAgeDays: server.worldAgeDays }
140
+ : {}),
141
+ ...(server.worldSizeMib !== undefined
142
+ ? { worldSizeMib: server.worldSizeMib }
143
+ : {}),
144
+ ...(server.vantage !== undefined ? { vantage: server.vantage } : {}),
145
+ };
146
+
147
+ const profile =
148
+ consent && (consent.roster?.length || consent.activity?.length)
149
+ ? {
150
+ ...(consent.roster?.length ? { roster: consent.roster } : {}),
151
+ ...(consent.activity?.length ? { activity: consent.activity } : {}),
152
+ }
153
+ : undefined;
154
+
155
+ const built = buildHeartbeat(
156
+ inputs.beaconId,
157
+ manifest as Parameters<typeof buildHeartbeat>[1],
158
+ {
159
+ online: status.online,
160
+ playersOnline: status.playersOnline,
161
+ playersMax: status.playersMax,
162
+ ...(status.tps !== undefined ? { tps: status.tps } : {}),
163
+ ...(status.uptimeSeconds !== undefined
164
+ ? { uptimeSeconds: status.uptimeSeconds }
165
+ : {}),
166
+ sampledAt: inputs.sampledAt.toISOString(),
167
+ },
168
+ profile,
169
+ );
170
+
171
+ const parsed = heartbeatSchema.safeParse(built);
172
+ if (!parsed.success) {
173
+ const error = parsed.error.issues
174
+ .map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
175
+ .join("; ");
176
+ return { ok: false, error };
177
+ }
178
+ return { ok: true, heartbeat: parsed.data };
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Settings normalization
183
+ // ---------------------------------------------------------------------------
184
+
185
+ /**
186
+ * Coerce an untrusted `settings` JSON blob into a well-formed
187
+ * {@link AtlasListingSettings}. Every field defaults, so a partial or corrupt
188
+ * row never throws.
189
+ */
190
+ export function normalizeAtlasListing(input: unknown): AtlasListingSettings {
191
+ const r = isRecord(input) ? input : {};
192
+ return {
193
+ enabled: parseBool(r.enabled, false),
194
+ slug: cleanString(r.slug, "", 64),
195
+ publishMap: parseBool(r.publishMap, false),
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Whether the beacon should advertise its public Vantage stream: the listing
201
+ * must be enabled (publishing at all) and the operator must have opted the map
202
+ * in. Atlas applies `privacy.coords` as the final display gate.
203
+ */
204
+ export function shouldPublishMap(listing: AtlasListingSettings): boolean {
205
+ return listing.enabled && listing.publishMap;
206
+ }
207
+
208
+ /**
209
+ * Whether the operator opted into public listing. Local settings-level gate
210
+ * only; the publisher and dashboard additionally require the client credentials
211
+ * in env (a beacon with none can't authenticate to Atlas). Atlas's own `listed`
212
+ * flag is the authoritative directory-visibility source.
213
+ */
214
+ export function isPublishable(listing: AtlasListingSettings): boolean {
215
+ return listing.enabled;
216
+ }
217
+
218
+ function isRecord(value: unknown): value is Record<string, unknown> {
219
+ return typeof value === "object" && value !== null && !Array.isArray(value);
220
+ }
221
+
222
+ function parseBool(value: unknown, fallback: boolean): boolean {
223
+ if (typeof value === "boolean") return value;
224
+ if (typeof value === "string") {
225
+ const v = value.trim().toLowerCase();
226
+ if (["on", "true", "1", "yes"].includes(v)) return true;
227
+ if (["off", "false", "0", "no", ""].includes(v)) return false;
228
+ }
229
+ if (value === null || value === undefined) return fallback;
230
+ return Boolean(value);
231
+ }
232
+
233
+ function cleanString(value: unknown, fallback: string, max: number): string {
234
+ if (typeof value !== "string") return fallback;
235
+ const t = value.normalize("NFC").replace(/\s+/g, " ").trim();
236
+ return t.length > max ? t.slice(0, max) : t;
237
+ }