krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit ae13fc05cd

ae13fc05cd6db4946aa37871cc84b816b06df6d1

parent: e601dfc47e

Unsigned

cmc <hello@cleberg.net> · 2026-10-20 23:54 UTC

Push-updated launch Live Activities (!68)

Launch Live Activities get status and NET changes over APNs broadcast channels. Nothing per device is stored.

## Server
- `launch_channels` (migration 0005, not applied remotely): one channel per launch and APNs environment, handed out to launches within 24 h of NET. Channels come from a pool that `scripts/channels.ts` fills, or the Worker creates and deletes them itself when `APNS_MANAGE_CHANNELS` is `"1"`.
- `/v1/launches` returns `channelId`. `?environment=sandbox` gives the sandbox channel, for Debug builds; production is the default.
- LL2 polling now runs on the `*/5` cron. From T−60 to T+15 the launch is fetched on its own (`/launches/<id>/`) and the list poll pauses. Launches in focus at the same time take turns. Outside the window the list runs every 10 min and previous launches hourly. **At most 13 anonymous LL2 requests in any hour**: 12 five-minute ticks with one request each, plus the hourly previous-launches request. Before this change it was 7. The `*/10` cron now sends news digests only.
- On a change of status or NET, `apns.ts` `broadcast()` posts to `api[.sandbox].push.apple.com/4/broadcasts/apps/sh.krz.moonrise` with `apns-push-type: liveactivity`, `apns-channel-id`, `apns-expiration` +8 h, and priority 10 for a status change or 5 for a NET change alone. `content-state` is `{net, status}`, with `net` in seconds since 2001 (Swift's default `Date` decoding). The stale date is NET + 1 h. Success, Failure and Partial Failure send `event: end` with a dismissal 15 min later. The last state sent is stored on the channel row, so a failed send is retried on the next tick.
- Channels are retired 24 h after NET when there is no outcome, and deleted 8 h after the end message, either by the Worker in manage mode or with the script.
- Alert pushes (`send`) are unchanged.

## App
- When the launch has a `channelId`, Follow on Lock Screen requests the activity with `.channel(id)` and keeps the T−60 scheduled start. If that request throws, it falls back to the current behaviour. Launches without a `channelId` behave exactly as before.

## Trial
`spikes/apns-channels`: `/probe` lists channels from a deployed Worker on port 2195 (sandbox) or 2196 (production). It reuses the request code in `server/src/apns.ts`. Commands are in its README. It has not been deployed.

## Tests
- `npm test`: 40 pass
- `swift test`: all pass
- UI accessibility audit: 78 issues before and 78 after (Sky 4, Settings 7, System 16, Sun 3, News & launches 21, Library 14, Saturn 13).

## Before deploying
- `wrangler d1 migrations apply moonrise --remote`
- Turn on the Broadcast capability in the developer portal.
- Fill the pool, or set `APNS_MANAGE_CHANNELS` if the trial passes.

TODO before publishing: an LL2 API key.

Layout: unified · split

App/Sources/LaunchesScreen.swift +20 −4
@@ -8,6 +8,13 @@ import SwiftUI
88let apiBase: URL? = (Bundle.main.object(forInfoDictionaryKey: "MoonriseAPIURL") as? String)
99 .flatMap { $0.isEmpty ? nil : URL(string: $0) }
1010
11/// APNs environment of this build, which picks the launch broadcast channels it can listen on.
12#if DEBUG
13private let apnsEnvironment = "sandbox"
14#else
15private let apnsEnvironment = "production"
16#endif
17
1118/// Tab and News/Launches switch that a notification tap can change, and what Siri or Spotlight asked to show.
1219@MainActor
1320@Observable
@@ -91,7 +98,7 @@ struct LaunchesScreen: View {
9198 guard let apiBase else { error = "No backend configured for this build."; return }
9299 if !force, let cached: LaunchList = FeedMemo.get("launches", maxAge: 300) { list = cached; return }
93100 do {
94 list = try await LaunchFeed.fetch(base: apiBase)
101 list = try await LaunchFeed.fetch(base: apiBase, environment: apnsEnvironment)
95102 if let list {
96103 FeedMemo.set("launches", list)
97104 await LaunchPassNotifications.reschedule(list.launches + (list.recent ?? []))
@@ -300,15 +307,24 @@ struct LaunchDetail: View {
300307 let content = ActivityContent(state: state, staleDate: launch.net.addingTimeInterval(3600))
301308 // Live Activities end after 8 hours, so one for a later launch starts an hour before it.
302309 let start = launch.net.addingTimeInterval(-3600)
303 do {
310 // Status and NET changes arrive on the launch's broadcast channel; the server never sees who listens.
311 func request(_ pushType: PushType?) throws {
304312 if start > .now {
305313 let alert = AlertConfiguration(title: "\(attributes.rocket) launches in an hour", body: "\(attributes.mission)", sound: .default)
306 _ = try Activity.request(attributes: attributes, content: content, style: .standard, alertConfiguration: alert, start: start)
314 _ = try Activity.request(attributes: attributes, content: content, pushType: pushType, style: .standard, alertConfiguration: alert, start: start)
307315 message = "Countdown will appear on the Lock Screen an hour before launch."
308316 } else {
309 _ = try Activity.request(attributes: attributes, content: content)
317 _ = try Activity.request(attributes: attributes, content: content, pushType: pushType)
310318 message = "Countdown added to the Lock Screen."
311319 }
320 }
321 do {
322 if let channel = launch.channelId {
323 // An invalid channel stops the activity from starting, so fall back to a countdown without updates.
324 do { try request(.channel(channel)) } catch { try request(nil) }
325 } else {
326 try request(nil)
327 }
312328 following = true
313329 } catch {
314330 message = "Couldn't start the countdown: \(error.localizedDescription)"
Packages/MoonriseKit/Sources/Feeds/Launches.swift +11 −2
@@ -25,6 +25,8 @@ public struct Launch: Codable, Sendable, Identifiable, Hashable {
2525 public var elements: [OrbitalElements]?
2626 /// "supgp" (SpaceX data via CelesTrak, possibly predicted before launch) or "gp" (CelesTrak catalogue).
2727 public var elementsSource: String?
28 /// APNs broadcast channel for this launch's Live Activity updates, within a day of launch.
29 public var channelId: String?
2830}
2931
3032public struct LaunchList: Codable, Sendable {
@@ -50,7 +52,14 @@ public enum LaunchFeed {
5052 try decoder.decode(LaunchList.self, from: data)
5153 }
5254
53 public static func fetch(base: URL, session: URLSession = .shared) async throws -> LaunchList {
54 try decode(await session.data(from: base.appending(path: "v1/launches")).0)
55 /// `environment` ("sandbox" or "production") picks the APNs environment of each launch's `channelId`.
56 static func url(base: URL, environment: String?) -> URL {
57 let url = base.appending(path: "v1/launches")
58 guard let environment else { return url }
59 return url.appending(queryItems: [URLQueryItem(name: "environment", value: environment)])
60 }
61
62 public static func fetch(base: URL, environment: String? = nil, session: URLSession = .shared) async throws -> LaunchList {
63 try decode(await session.data(from: url(base: base, environment: environment)).0)
5564 }
5665}
Packages/MoonriseKit/Tests/FeedsTests/LaunchTests.swift +21
@@ -22,6 +22,27 @@ import Testing
2222 #expect(list.launches[0].elements == nil)
2323}
2424
25@Test func decodesBroadcastChannel() throws {
26 // Shape of GET /v1/launches?environment=sandbox with a launch channel, 2026-10-20.
27 let data = Data("""
28 {"fetchedAt":"2026-10-20T12:00:00.000Z","launches":[{"id":"fake-near","name":"Test | Near","net":"2026-10-20T22:46:46Z","windowStart":null,
29 "windowEnd":null,"status":"Go","statusName":"Go","provider":"X","rocket":"Rocket","mission":null,"missionType":null,"missionDescription":null,
30 "orbit":null,"pad":"Pad","location":"Loc","padLatitude":null,"padLongitude":null,"elements":[],"elementsSource":null,"channelId":"U0FOREJPWDE="},
31 {"id":"fake-far","name":"Test | Far","net":"2026-10-21T03:16:46Z","windowStart":null,"windowEnd":null,"status":"TBC","statusName":"TBC",
32 "provider":"X","rocket":"Rocket","mission":null,"missionType":null,"missionDescription":null,"orbit":null,"pad":"Pad","location":"Loc",
33 "padLatitude":null,"padLongitude":null,"elements":[],"elementsSource":null,"channelId":null}],"recent":[]}
34 """.utf8)
35 let list = try LaunchFeed.decode(data)
36 #expect(list.launches[0].channelId == "U0FOREJPWDE=")
37 #expect(list.launches[1].channelId == nil)
38}
39
40@Test func launchesURLNamesTheAPNsEnvironment() {
41 let base = URL(string: "https://example.com")!
42 #expect(LaunchFeed.url(base: base, environment: "sandbox").absoluteString == "https://example.com/v1/launches?environment=sandbox")
43 #expect(LaunchFeed.url(base: base, environment: "production").absoluteString == "https://example.com/v1/launches?environment=production")
44}
45
2546@Test func decodesRecentLaunchesWithElements() throws {
2647 // Shape of GET /v1/launches with launch element sets, 2026-10-19.
2748 let data = Data("""
server/README.org +26
@@ -32,10 +32,36 @@ so anonymous requests from Cloudflare often get HTTP 429. With an API key:
3232wrangler secret put LL2_API_KEY
3333#+end_src
3434
35* launch Live Activity channels
36Launch Live Activities get status and NET changes over APNs broadcast
37channels, one per launch and APNs environment, handed out a day before NET
38from the =launch_channels= table (migration =0005_launch_channels.sql=).
39Needs the Broadcast capability on for =sh.krz.moonrise= in the developer
40portal.
41
42With =APNS_MANAGE_CHANNELS= set to ="1"= (once =spikes/apns-channels= shows
43the Worker reaches the management ports), the Worker creates and deletes
44channels itself. Otherwise keep the pool filled from a computer; the log
45says =launch channel pool empty= when it runs out.
46
47#+begin_src sh
48export APNS_KEY_PATH=AuthKey_644XS4F2RG.p8
49node scripts/channels.ts create production 30 > pool.sql
50node scripts/channels.ts create sandbox 30 >> pool.sql
51wrangler d1 execute moonrise --remote --file pool.sql
52
53# Ended more than 8 hours ago: delete at APNs, then the rows.
54wrangler d1 execute moonrise --remote --command \
55 "SELECT environment, channel_id FROM launch_channels WHERE ended_at < strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-8 hours')"
56node scripts/channels.ts delete production <channel id>... > deleted.sql
57wrangler d1 execute moonrise --remote --file deleted.sql
58#+end_src
59
3560* API
3661| Method and path | Body / result |
3762|-
3863| =GET /v1/today= | ={spaceWeather: {kpNow, observedAt, kpNext24h, fetchedAt}}= |
64| =GET /v1/launches?environment=sandbox= | ={fetchedAt, launches, recent}=; each launch has =channelId= for that APNs environment (default production) |
3965| =POST /v1/devices= | ={token, environment, band, utcOffsetMinutes, aurora?}=; band is a 5° geomagnetic latitude band, south negative |
4066| =DELETE /v1/devices/{token}= | |
4167| =GET /healthz= | feed status |
server/migrations/0005_launch_channels.sql added +14
@@ -0,0 +1,14 @@
1-- APNs broadcast channels for launch Live Activities, one per launch and APNs environment.
2-- A row with no launch is in the pool (created by scripts/channels.ts or the Worker).
3-- net and status are the state last broadcast; ended_at is set once the activity is ended.
4CREATE TABLE launch_channels (
5 channel_id TEXT PRIMARY KEY,
6 environment TEXT NOT NULL,
7 launch_id TEXT,
8 net TEXT,
9 status TEXT,
10 created_at TEXT NOT NULL,
11 ended_at TEXT
12);
13
14CREATE UNIQUE INDEX launch_channels_launch ON launch_channels (launch_id, environment);
server/scripts/channels.ts added +73
@@ -0,0 +1,73 @@
1// Creates, lists and deletes APNs broadcast channels from a computer, over Node's HTTP/2 client.
2// create and delete print SQL for the launch_channels pool, to pipe into `wrangler d1 execute`.
3//
4// APNS_KEY_PATH=AuthKey_644XS4F2RG.p8 node scripts/channels.ts list sandbox
5// APNS_KEY_PATH=... node scripts/channels.ts create production 5 > pool.sql
6// APNS_KEY_PATH=... node scripts/channels.ts delete sandbox <channel id>... > deleted.sql
7
8import { readFileSync } from "node:fs";
9import { connect } from "node:http2";
10import { createChannel, deleteChannel, listChannels, type ApnsConfig } from "../src/apns.ts";
11
12/** Enough of fetch() for the channel calls in apns.ts, over HTTP/2. */
13const h2fetch = ((input: string, init: RequestInit = {}) =>
14 new Promise<Response>((resolve, reject) => {
15 const url = new URL(input);
16 const session = connect(url.origin);
17 session.on("error", reject);
18 const req = session.request({ ":method": init.method ?? "GET", ":path": url.pathname, ...(init.headers as Record<string, string>) });
19 let status = 0;
20 const headers = new Headers();
21 let body = "";
22 req.on("response", (h) => {
23 status = Number(h[":status"]);
24 for (const [k, v] of Object.entries(h)) if (!k.startsWith(":") && v !== undefined) headers.set(k, String(v));
25 });
26 req.setEncoding("utf8");
27 req.on("data", (chunk: string) => (body += chunk));
28 req.on("end", () => {
29 session.close();
30 resolve(new Response(body || null, { status, headers }));
31 });
32 req.on("error", reject);
33 req.end(init.body as string | undefined);
34 })) as typeof fetch;
35
36const [command, environment, ...rest] = process.argv.slice(2);
37if (!["create", "list", "delete"].includes(command) || !["sandbox", "production"].includes(environment) || !process.env.APNS_KEY_PATH) {
38 console.error("usage: APNS_KEY_PATH=<.p8> node scripts/channels.ts create|list|delete sandbox|production [count | channel id...]");
39 process.exit(2);
40}
41const config: ApnsConfig = {
42 keyId: process.env.APNS_KEY_ID ?? "644XS4F2RG",
43 teamId: process.env.APNS_TEAM_ID ?? "ZCNAX3VL9D",
44 privateKey: readFileSync(process.env.APNS_KEY_PATH, "utf8"),
45 topic: process.env.APNS_TOPIC ?? "sh.krz.moonrise",
46};
47const sandbox = environment === "sandbox";
48const base64 = /^[A-Za-z0-9+/=]+$/;
49
50if (command === "list") {
51 const r = await listChannels(config, sandbox, h2fetch);
52 if (r.status !== 200) fail(r.status, r.reason);
53 for (const id of r.channels) console.log(id);
54} else if (command === "create") {
55 const created = new Date().toISOString();
56 for (let i = 0; i < Number(rest[0] ?? 1); i++) {
57 const r = await createChannel(config, sandbox, h2fetch);
58 if (!r.channelId || !base64.test(r.channelId)) fail(r.status, r.reason);
59 console.log(`INSERT INTO launch_channels (channel_id, environment, created_at) VALUES ('${r.channelId}', '${environment}', '${created}');`);
60 }
61} else {
62 for (const id of rest) {
63 if (!base64.test(id)) fail(0, `not a channel id: ${id}`);
64 const r = await deleteChannel(config, id, sandbox, h2fetch);
65 if (r.status !== 204 && r.status !== 404) fail(r.status, r.reason);
66 console.log(`DELETE FROM launch_channels WHERE channel_id = '${id}';`);
67 }
68}
69
70function fail(status: number, reason: string | null): never {
71 console.error("apns", status, reason);
72 process.exit(1);
73}
server/src/activity.ts added +62
@@ -0,0 +1,62 @@
1// Launch Live Activity updates over APNs broadcast channels: one channel per launch and environment,
2// so the server never learns who follows a launch.
3
4const MINUTE = 60_000;
5/** A launch is polled on its own every 5 minutes from T−60 to T+15. */
6const FOCUS_BEFORE = 60 * MINUTE;
7const FOCUS_AFTER = 15 * MINUTE;
8/** Launch Library 2 status abbreviations that end the activity. */
9export const OUTCOMES = ["Success", "Failure", "Partial Failure"];
10/** Seconds between the Unix epoch and 2001-01-01, the reference date of Swift's default Date coding. */
11const REFERENCE_DATE = 978_307_200;
12
13export interface ActivityState {
14 net: string;
15 status: string;
16}
17
18export interface ActivityPush {
19 payload: { aps: Record<string, unknown> };
20 priority: 5 | 10;
21 end: boolean;
22}
23
24const unix = (ms: number) => Math.floor(ms / 1000);
25
26/** Earliest NET a launch can have and still be in focus or need a channel. */
27export const sinceNet = (now: Date) => new Date(now.getTime() - FOCUS_AFTER).toISOString();
28
29export function inFocus(l: ActivityState, now: Date): boolean {
30 const t = Date.parse(l.net);
31 return !OUTCOMES.includes(l.status) && t - FOCUS_BEFORE <= now.getTime() && now.getTime() <= t + FOCUS_AFTER;
32}
33
34/** One launch per 5-minute tick; launches in focus at the same time take turns. */
35export function focusPick(ids: string[], now: Date): string {
36 return ids[Math.floor(now.getTime() / (5 * MINUTE)) % ids.length];
37}
38
39/** Channels are handed out a day ahead, so a follow at any time before launch can subscribe. */
40export function needsChannel(l: ActivityState, now: Date): boolean {
41 const t = Date.parse(l.net);
42 return !OUTCOMES.includes(l.status) && now.getTime() - FOCUS_AFTER <= t && t <= now.getTime() + 24 * 60 * MINUTE;
43}
44
45/**
46 * The broadcast for a change from the last state sent to the current one, or null if nothing changed.
47 * `content-state` matches LaunchActivityAttributes.ContentState, decoded by ActivityKit with Swift's default strategies.
48 * The stale date matches the one the app sets when it starts the activity.
49 */
50export function activityPush(sent: ActivityState, current: ActivityState, now: Date): ActivityPush | null {
51 if (sent.net === current.net && sent.status === current.status) return null;
52 const end = OUTCOMES.includes(current.status);
53 const net = Date.parse(current.net);
54 const aps: Record<string, unknown> = {
55 timestamp: unix(now.getTime()),
56 event: end ? "end" : "update",
57 "content-state": { net: unix(net) - REFERENCE_DATE, status: current.status },
58 };
59 if (end) aps["dismissal-date"] = unix(now.getTime() + 15 * MINUTE);
60 else aps["stale-date"] = unix(net + 60 * MINUTE);
61 return { payload: { aps }, priority: sent.status === current.status ? 5 : 10, end };
62}
server/src/apns.ts +56 −1
@@ -65,6 +65,10 @@ export async function send(config: ApnsConfig, deviceToken: string, payload: unk
6565 },
6666 body: JSON.stringify(payload),
6767 });
68 return result(res, "apns-id");
69}
70
71async function result(res: Response, idHeader: string): Promise<ApnsResult> {
6872 let reason: string | null = null;
6973 if (!res.ok) {
7074 const text = await res.text();
@@ -74,5 +78,56 @@ export async function send(config: ApnsConfig, deviceToken: string, payload: unk
7478 reason = text;
7579 }
7680 }
77 return { status: res.status, apnsId: res.headers.get("apns-id"), reason };
81 return { status: res.status, apnsId: res.headers.get(idHeader), reason };
82}
83
84/** A Live Activity update to every device listening on a broadcast channel. `expiration` is in Unix seconds. */
85export async function broadcast(config: ApnsConfig, channelId: string, payload: unknown, sandbox: boolean, priority: 5 | 10, expiration: number): Promise<ApnsResult> {
86 const host = sandbox ? "api.sandbox.push.apple.com" : "api.push.apple.com";
87 const res = await fetch(`https://${host}/4/broadcasts/apps/${config.topic}`, {
88 method: "POST",
89 headers: {
90 authorization: `bearer ${await token(config)}`,
91 "apns-channel-id": channelId,
92 "apns-push-type": "liveactivity",
93 "apns-priority": String(priority),
94 "apns-expiration": String(expiration),
95 "content-type": "application/json",
96 },
97 body: JSON.stringify(payload),
98 });
99 return result(res, "apns-request-id");
100}
101
102// Channel management runs on its own host and ports. `fetcher` lets a Node script supply HTTP/2.
103
104const manageBase = (sandbox: boolean) =>
105 sandbox ? "https://api-manage-broadcast.sandbox.push.apple.com:2195" : "https://api-manage-broadcast.push.apple.com:2196";
106
107/** A channel that keeps its most recent message (up to 8 hours) for devices that were offline. */
108export async function createChannel(config: ApnsConfig, sandbox: boolean, fetcher: typeof fetch = fetch): Promise<ApnsResult & { channelId: string | null }> {
109 const res = await fetcher(`${manageBase(sandbox)}/1/apps/${config.topic}/channels`, {
110 method: "POST",
111 headers: { authorization: `bearer ${await token(config)}`, "content-type": "application/json" },
112 body: JSON.stringify({ "message-storage-policy": 1, "push-type": "LiveActivity" }),
113 });
114 return { ...(await result(res, "apns-request-id")), channelId: res.ok ? res.headers.get("apns-channel-id") : null };
115}
116
117export async function deleteChannel(config: ApnsConfig, channelId: string, sandbox: boolean, fetcher: typeof fetch = fetch): Promise<ApnsResult> {
118 const res = await fetcher(`${manageBase(sandbox)}/1/apps/${config.topic}/channels`, {
119 method: "DELETE",
120 headers: { authorization: `bearer ${await token(config)}`, "apns-channel-id": channelId },
121 });
122 return result(res, "apns-request-id");
123}
124
125export async function listChannels(config: ApnsConfig, sandbox: boolean, fetcher: typeof fetch = fetch): Promise<ApnsResult & { channels: string[] }> {
126 const res = await fetcher(`${manageBase(sandbox)}/1/apps/${config.topic}/all-channels`, {
127 method: "GET",
128 headers: { authorization: `bearer ${await token(config)}` },
129 });
130 if (!res.ok) return { ...(await result(res, "apns-request-id")), channels: [] };
131 const body = (await res.json()) as { channels?: string[] };
132 return { status: res.status, apnsId: res.headers.get("apns-request-id"), reason: null, channels: body.channels ?? [] };
78133}
server/src/index.ts +111 −13
@@ -1,8 +1,9 @@
1import { send, type ApnsConfig } from "./apns";
1import { activityPush, focusPick, inFocus, needsChannel, sinceNet } from "./activity";
2import { broadcast, createChannel, deleteChannel, send, type ApnsConfig } from "./apns";
23import { actionableKp, alertBands, eventKey, isNight } from "./aurora";
34import { compose, fetchGroups, fetchSupGP, fitsLaunch, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak";
45import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live";
5import { fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2";
6import { fetchLaunch, fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2";
67import { digestDue, digestPayload, fetchLatest, localDate, pickHeadlines } from "./news";
78import { PRIVACY_HTML } from "./privacy";
89import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc";
@@ -15,6 +16,8 @@ interface Env {
1516 APNS_KEY: string;
1617 /** Optional Launch Library 2 API key. */
1718 LL2_API_KEY?: string;
19 /** "1": the Worker creates and deletes launch channels itself. Otherwise scripts/channels.ts fills the pool. */
20 APNS_MANAGE_CHANNELS?: string;
1821}
1922
2023interface DeviceRequest {
@@ -26,7 +29,7 @@ interface DeviceRequest {
2629 news?: boolean;
2730}
2831
29const LAUNCH_CRON = "*/10 * * * *";
32const NEWS_CRON = "*/10 * * * *";
3033const SATELLITE_CRON = "7 */2 * * *";
3134/** Launches are kept this long after NET, so a launch page and its first pass outlive liftoff. */
3235const RETENTION_MS = 14 * 86400_000;
@@ -68,7 +71,7 @@ export default {
6871 if (request.method === "GET" && url.pathname === "/privacy")
6972 return new Response(PRIVACY_HTML, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=3600" } });
7073 if (request.method === "GET" && url.pathname === "/v1/today") return today(env, now);
71 if (request.method === "GET" && url.pathname === "/v1/launches") return launches(env, now);
74 if (request.method === "GET" && url.pathname === "/v1/launches") return launches(env, url, now);
7275 if (request.method === "GET" && url.pathname === "/v1/live") return live(env, url, now);
7376 if (request.method === "GET" && url.pathname === "/v1/satellites") {
7477 const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'celestrak' AND ok = 1").first<{ fetched_at: string; body: string }>();
@@ -99,10 +102,9 @@ export default {
99102
100103 async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
101104 const now = new Date(controller.scheduledTime);
102 // Upcoming launches every 10 minutes and previous launches hourly: 7 of the 15 anonymous Launch Library 2 requests per hour.
103 if (controller.cron === LAUNCH_CRON) ctx.waitUntil(Promise.all([pollLaunches(env, now), sendNewsDigests(env, now)]));
105 if (controller.cron === NEWS_CRON) ctx.waitUntil(sendNewsDigests(env, now));
104106 else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now));
105 else ctx.waitUntil(pollSpaceWeather(env, now));
107 else ctx.waitUntil(Promise.all([pollSpaceWeather(env, now), launchTick(env, now)]));
106108 },
107109} satisfies ExportedHandler<Env>;
108110
@@ -153,7 +155,8 @@ async function live(env: Env, url: URL, now: Date): Promise<Response> {
153155 return json({ event, at: at.toISOString(), points: points.filter((p) => p[0] * 1000 <= at.getTime()) }, 200, MAX_AGE.live);
154156}
155157
156async function launches(env: Env, now: Date): Promise<Response> {
158/** `?environment=sandbox` gives Debug builds the channels of the APNs sandbox. */
159async function launches(env: Env, url: URL, now: Date): Promise<Response> {
157160 const since = new Date(now.getTime() - 6 * 3600_000).toISOString();
158161 const rows = await env.DB.prepare("SELECT * FROM launches WHERE net >= ?1 ORDER BY net LIMIT 20").bind(since).all<Record<string, unknown>>();
159162 const recent = await env.DB.prepare("SELECT * FROM launches WHERE net < ?1 AND net >= ?2 ORDER BY net DESC LIMIT 20")
@@ -161,12 +164,16 @@ async function launches(env: Env, now: Date): Promise<Response> {
161164 const fetched = await env.DB.prepare("SELECT fetched_at FROM feed_snapshots WHERE feed = 'll2' AND ok = 1").first<{ fetched_at: string }>();
162165 const els = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'launch-elements' AND ok = 1").first<{ body: string }>();
163166 const elements: Record<string, LaunchElements> = els ? JSON.parse(els.body) : {};
167 const ch = await env.DB.prepare("SELECT launch_id, channel_id FROM launch_channels WHERE environment = ?1 AND launch_id IS NOT NULL AND ended_at IS NULL")
168 .bind(url.searchParams.get("environment") === "sandbox" ? "sandbox" : "production").all<{ launch_id: string; channel_id: string }>();
169 const channels = Object.fromEntries(ch.results.map((c) => [c.launch_id, c.channel_id]));
164170 const shape = (r: Record<string, unknown>) => ({
165171 id: r.id, name: r.name, net: r.net, windowStart: r.window_start, windowEnd: r.window_end,
166172 status: r.status, statusName: r.status_name, provider: r.provider, rocket: r.rocket,
167173 mission: r.mission, missionType: r.mission_type, missionDescription: r.mission_description, orbit: r.orbit,
168174 pad: r.pad, location: r.location, padLatitude: r.pad_latitude, padLongitude: r.pad_longitude,
169175 elements: elements[String(r.id)]?.elements ?? [], elementsSource: elements[String(r.id)]?.source ?? null,
176 channelId: channels[String(r.id)] ?? null,
170177 });
171178 return json({
172179 fetchedAt: fetched?.fetched_at ?? null,
@@ -175,6 +182,28 @@ async function launches(env: Env, now: Date): Promise<Response> {
175182 }, 200, MAX_AGE.launches);
176183}
177184
185/**
186 * Launch Library 2 within the anonymous 15 requests per hour. Every 5 minutes: the launch in focus (T−60 to T+15)
187 * on its own, with the list paused; otherwise the upcoming list every 10 minutes and previous launches hourly.
188 * At most 12 + 1 requests in any hour.
189 */
190async function launchTick(env: Env, now: Date): Promise<void> {
191 const near = await env.DB.prepare("SELECT id, net, status FROM launches WHERE net >= ?1 ORDER BY net").bind(sinceNet(now)).all<{ id: string; net: string; status: string }>();
192 const focus = near.results.filter((l) => inFocus(l, now)).map((l) => l.id);
193 if (focus.length) await pollLaunch(env, focusPick(focus, now), now);
194 else if (now.getUTCMinutes() % 10 === 0) await pollLaunches(env, now);
195 if (env.APNS_KEY) await launchChannels(env, now);
196}
197
198async function pollLaunch(env: Env, id: string, now: Date): Promise<void> {
199 try {
200 await env.DB.batch(upsertLaunches(env, [await fetchLaunch(id, env.LL2_API_KEY)]));
201 } catch (e) {
202 console.error("ll2 launch", String(e));
203 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('ll2:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()).run();
204 }
205}
206
178207// Failures are recorded under "<feed>:error" so the last good snapshot and its time survive.
179208async function pollLaunches(env: Env, now: Date): Promise<void> {
180209 let list: Launch[];
@@ -193,6 +222,14 @@ async function pollLaunches(env: Env, now: Date): Promise<void> {
193222 console.error("ll2 previous", String(e));
194223 }
195224 }
225 await env.DB.batch([
226 ...upsertLaunches(env, list),
227 env.DB.prepare("DELETE FROM launches WHERE net < ?1").bind(new Date(now.getTime() - RETENTION_MS).toISOString()),
228 env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('ll2', ?1, 1) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1").bind(now.toISOString()),
229 ]);
230}
231
232function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] {
196233 const upsert = env.DB.prepare(
197234 `INSERT INTO launches (id, name, net, window_start, window_end, status, status_name, provider, rocket, mission, mission_type, mission_description, orbit, pad, location, pad_latitude, pad_longitude, last_updated, launch_designator)
198235 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)
@@ -200,11 +237,72 @@ async function pollLaunches(env: Env, now: Date): Promise<void> {
200237 mission = ?10, mission_type = ?11, mission_description = ?12, orbit = ?13, pad = ?14, location = ?15, pad_latitude = ?16, pad_longitude = ?17, last_updated = ?18,
201238 launch_designator = COALESCE(?19, launch_designator)`,
202239 );
203 await env.DB.batch([
204 ...list.map((l) => upsert.bind(l.id, l.name, l.net, l.windowStart, l.windowEnd, l.status, l.statusName, l.provider, l.rocket, l.mission, l.missionType, l.missionDescription, l.orbit, l.pad, l.location, l.padLatitude, l.padLongitude, l.lastUpdated, l.designator)),
205 env.DB.prepare("DELETE FROM launches WHERE net < ?1").bind(new Date(now.getTime() - RETENTION_MS).toISOString()),
206 env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('ll2', ?1, 1) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1").bind(now.toISOString()),
207 ]);
240 return list.map((l) => upsert.bind(l.id, l.name, l.net, l.windowStart, l.windowEnd, l.status, l.statusName, l.provider, l.rocket, l.mission, l.missionType, l.missionDescription, l.orbit, l.pad, l.location, l.padLatitude, l.padLongitude, l.lastUpdated, l.designator));
241}
242
243/**
244 * Broadcast channels for launch Live Activities: hands one per APNs environment to each launch within 24 hours
245 * (from the pool, or created here with APNS_MANAGE_CHANNELS), broadcasts each change of status or NET, and
246 * retires a channel once its launch is over. Nothing about who follows a launch reaches the server.
247 */
248async function launchChannels(env: Env, now: Date): Promise<void> {
249 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
250 const manage = env.APNS_MANAGE_CHANNELS === "1";
251 const iso = now.toISOString();
252
253 const near = await env.DB.prepare("SELECT id, net, status FROM launches WHERE net >= ?1").bind(sinceNet(now)).all<{ id: string; net: string; status: string }>();
254 const assigned = await env.DB.prepare("SELECT launch_id, environment FROM launch_channels WHERE launch_id IS NOT NULL").all<{ launch_id: string; environment: string }>();
255 const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`));
256 for (const l of near.results.filter((l) => needsChannel(l, now))) {
257 for (const environment of ["sandbox", "production"]) {
258 if (has.has(`${l.id}:${environment}`)) continue;
259 const pooled = await env.DB.prepare(
260 `UPDATE launch_channels SET launch_id = ?1, net = ?2, status = ?3
261 WHERE channel_id = (SELECT channel_id FROM launch_channels WHERE launch_id IS NULL AND environment = ?4 ORDER BY created_at LIMIT 1)`,
262 ).bind(l.id, l.net, l.status, environment).run();
263 if (pooled.meta.changes) continue;
264 if (!manage) {
265 console.error("launch channel pool empty", environment);
266 continue;
267 }
268 const c = await createChannel(config, environment === "sandbox");
269 if (!c.channelId) {
270 console.error("apns channel", c.status, c.reason);
271 continue;
272 }
273 await env.DB.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
274 .bind(c.channelId, environment, l.id, l.net, l.status, iso).run();
275 }
276 }
277
278 const changed = await env.DB.prepare(
279 `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status
280 FROM launch_channels c JOIN launches l ON l.id = c.launch_id WHERE c.ended_at IS NULL AND (c.net != l.net OR c.status != l.status)`,
281 ).all<{ channel_id: string; environment: string; sent_net: string; sent_status: string; net: string; status: string }>();
282 for (const c of changed.results) {
283 const push = activityPush({ net: c.sent_net, status: c.sent_status }, c, now)!;
284 // APNs keeps the latest message for devices that are offline, for at most 8 hours.
285 const r = await broadcast(config, c.channel_id, push.payload, c.environment === "sandbox", push.priority, Math.floor(now.getTime() / 1000) + 8 * 3600)
286 .catch((e) => ({ status: 0, reason: String(e) }));
287 if (r.status !== 200) {
288 console.error("apns broadcast", r.status, r.reason);
289 continue;
290 }
291 await env.DB.prepare("UPDATE launch_channels SET net = ?2, status = ?3, ended_at = ?4 WHERE channel_id = ?1").bind(c.channel_id, c.net, c.status, push.end ? iso : null).run();
292 }
293
294 // A day past NET without an outcome, or gone from the table: ended without a push, as activities last 8 hours at most.
295 await env.DB.prepare("UPDATE launch_channels SET ended_at = ?1 WHERE launch_id IS NOT NULL AND ended_at IS NULL AND launch_id NOT IN (SELECT id FROM launches WHERE net >= ?2)")
296 .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run();
297 if (!manage) return;
298 // Deleted once the stored end message has expired.
299 const done = await env.DB.prepare("SELECT channel_id, environment FROM launch_channels WHERE ended_at < ?1")
300 .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>();
301 for (const c of done.results) {
302 const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox");
303 if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM launch_channels WHERE channel_id = ?1").bind(c.channel_id).run();
304 else console.error("apns channel delete", r.status, r.reason);
305 }
208306}
209307
210308async function pollSatellites(env: Env, now: Date): Promise<void> {
server/src/ll2.ts +12 −3
@@ -4,6 +4,8 @@
44export const UPCOMING_URL = "https://ll.thespacedevs.com/2.3.0/launches/upcoming/?limit=20&mode=normal";
55/** Recent launches, for the international designator, which is assigned only after liftoff. */
66export const PREVIOUS_URL = "https://ll.thespacedevs.com/2.3.0/launches/previous/?limit=10&mode=normal";
7/** One launch, polled on its own around liftoff. */
8export const launchURL = (id: string) => `https://ll.thespacedevs.com/2.3.0/launches/${encodeURIComponent(id)}/?mode=normal`;
79
810export interface Launch {
911 id: string;
@@ -70,11 +72,18 @@ export function normalize(r: Raw): Launch {
7072}
7173
7274/** `apiKey` lifts the anonymous per-IP limit, which Cloudflare's shared egress IPs often exhaust (HTTP 429). */
73export async function fetchLaunches(url: string, apiKey?: string): Promise<Launch[]> {
75async function get<T>(url: string, apiKey?: string): Promise<T> {
7476 const headers: Record<string, string> = { "user-agent": "moonrise-server (sh.krz.moonrise)" };
7577 if (apiKey) headers.authorization = `Token ${apiKey}`;
7678 const res = await fetch(url, { headers });
7779 if (!res.ok) throw new Error(`LL2 ${res.status}`);
78 const body = (await res.json()) as { results: Raw[] };
79 return body.results.map(normalize);
80 return (await res.json()) as T;
81}
82
83export async function fetchLaunches(url: string, apiKey?: string): Promise<Launch[]> {
84 return (await get<{ results: Raw[] }>(url, apiKey)).results.map(normalize);
85}
86
87export async function fetchLaunch(id: string, apiKey?: string): Promise<Launch> {
88 return normalize(await get<Raw>(launchURL(id), apiKey));
8089}
server/test/activity.test.ts added +67
@@ -0,0 +1,67 @@
1import assert from "node:assert/strict";
2import { test } from "node:test";
3import { activityPush, focusPick, inFocus, needsChannel, sinceNet } from "../src/activity.ts";
4
5const now = new Date("2026-10-20T12:00:00Z");
6const unix = (iso: string) => Date.parse(iso) / 1000;
7
8test("focus runs from an hour before NET to 15 minutes after, until an outcome", () => {
9 const at = (net: string, status = "Go") => inFocus({ net, status }, now);
10 assert.equal(at("2026-10-20T13:00:00Z"), true);
11 assert.equal(at("2026-10-20T13:00:01Z"), false);
12 assert.equal(at("2026-10-20T11:45:00Z", "In Flight"), true);
13 assert.equal(at("2026-10-20T11:44:59Z"), false);
14 assert.equal(at("2026-10-20T11:50:00Z", "Success"), false);
15 assert.equal(sinceNet(now), "2026-10-20T11:45:00.000Z");
16});
17
18test("overlapping launches take turns, one request per 5-minute tick", () => {
19 const ids = ["a", "b"];
20 assert.equal(focusPick(ids, new Date("2026-10-20T12:00:00Z")), "a");
21 assert.equal(focusPick(ids, new Date("2026-10-20T12:05:00Z")), "b");
22 assert.equal(focusPick(ids, new Date("2026-10-20T12:10:00Z")), "a");
23 assert.equal(focusPick(["a"], new Date("2026-10-20T12:05:00Z")), "a");
24});
25
26test("a launch needs a channel within 24 hours of NET until it has an outcome", () => {
27 assert.equal(needsChannel({ net: "2026-10-21T12:00:00Z", status: "Go" }, now), true);
28 assert.equal(needsChannel({ net: "2026-10-21T12:00:01Z", status: "Go" }, now), false);
29 assert.equal(needsChannel({ net: "2026-10-20T11:50:00Z", status: "In Flight" }, now), true);
30 assert.equal(needsChannel({ net: "2026-10-20T11:40:00Z", status: "Go" }, now), false);
31 assert.equal(needsChannel({ net: "2026-10-20T13:00:00Z", status: "Success" }, now), false);
32});
33
34test("no push without a change of status or NET", () => {
35 assert.equal(activityPush({ net: "2026-10-20T13:00:00Z", status: "Go" }, { net: "2026-10-20T13:00:00Z", status: "Go" }, now), null);
36});
37
38test("a status change is an update at priority 10, with content-state dates in seconds since 2001", () => {
39 const p = activityPush({ net: "2026-10-20T13:00:00Z", status: "Go" }, { net: "2026-10-20T13:00:00Z", status: "Hold" }, now)!;
40 assert.equal(p.priority, 10);
41 assert.equal(p.end, false);
42 assert.deepEqual(p.payload, {
43 aps: {
44 timestamp: unix("2026-10-20T12:00:00Z"),
45 event: "update",
46 "content-state": { net: unix("2026-10-20T13:00:00Z") - 978_307_200, status: "Hold" },
47 "stale-date": unix("2026-10-20T14:00:00Z"),
48 },
49 });
50});
51
52test("a NET change alone goes at priority 5", () => {
53 const p = activityPush({ net: "2026-10-20T13:00:00Z", status: "Go" }, { net: "2026-10-20T13:10:00Z", status: "Go" }, now)!;
54 assert.equal(p.priority, 5);
55 assert.equal((p.payload.aps["content-state"] as { net: number }).net, unix("2026-10-20T13:10:00Z") - 978_307_200);
56});
57
58test("an outcome ends the activity and dismisses it 15 minutes later", () => {
59 for (const status of ["Success", "Failure", "Partial Failure"]) {
60 const p = activityPush({ net: "2026-10-20T11:50:00Z", status: "In Flight" }, { net: "2026-10-20T11:50:00Z", status }, now)!;
61 assert.equal(p.end, true);
62 assert.equal(p.priority, 10);
63 assert.equal(p.payload.aps.event, "end");
64 assert.equal(p.payload.aps["dismissal-date"], unix("2026-10-20T12:15:00Z"));
65 assert.equal(p.payload.aps["stale-date"], undefined);
66 }
67});
server/test/apns.test.ts added +94
@@ -0,0 +1,94 @@
1import assert from "node:assert/strict";
2import { test } from "node:test";
3import { broadcast, createChannel, deleteChannel, listChannels, send, type ApnsConfig } from "../src/apns.ts";
4
5async function config(): Promise<ApnsConfig> {
6 const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
7 const der = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
8 const pem = `-----BEGIN PRIVATE KEY-----\n${btoa(String.fromCharCode(...der))}\n-----END PRIVATE KEY-----\n`;
9 return { keyId: "ABC123DEFG", teamId: "TEAM123456", privateKey: pem, topic: "sh.krz.moonrise" };
10}
11
12interface Seen {
13 url: string;
14 method: string;
15 headers: Record<string, string>;
16 body: string | undefined;
17}
18
19function recorder(response: () => Response): { seen: Seen[]; fetcher: typeof fetch } {
20 const seen: Seen[] = [];
21 const fetcher = (async (url: string, init: RequestInit) => {
22 seen.push({ url, method: init.method ?? "GET", headers: init.headers as Record<string, string>, body: init.body as string | undefined });
23 return response();
24 }) as typeof fetch;
25 return { seen, fetcher };
26}
27
28test("alert pushes keep their headers", async () => {
29 const { seen, fetcher } = recorder(() => new Response(null, { status: 200, headers: { "apns-id": "x" } }));
30 const real = globalThis.fetch;
31 globalThis.fetch = fetcher;
32 try {
33 const r = await send(await config(), "ab".repeat(32), { aps: { alert: "hi" } }, true);
34 assert.equal(r.apnsId, "x");
35 } finally {
36 globalThis.fetch = real;
37 }
38 assert.equal(seen[0].url, `https://api.sandbox.push.apple.com/3/device/${"ab".repeat(32)}`);
39 assert.equal(seen[0].headers["apns-push-type"], "alert");
40 assert.equal(seen[0].headers["apns-topic"], "sh.krz.moonrise");
41});
42
43test("broadcast goes to the standard host with the channel, Live Activity type, priority and expiration", async () => {
44 const { seen, fetcher } = recorder(() => new Response(null, { status: 200, headers: { "apns-request-id": "r" } }));
45 const real = globalThis.fetch;
46 globalThis.fetch = fetcher;
47 try {
48 const r = await broadcast(await config(), "dHN0LXNyY2gtY2hubA==", { aps: { event: "update" } }, false, 5, 1_792_230_000);
49 assert.deepEqual(r, { status: 200, apnsId: "r", reason: null });
50 } finally {
51 globalThis.fetch = real;
52 }
53 const s = seen[0];
54 assert.equal(s.url, "https://api.push.apple.com/4/broadcasts/apps/sh.krz.moonrise");
55 assert.equal(s.method, "POST");
56 assert.equal(s.headers["apns-channel-id"], "dHN0LXNyY2gtY2hubA==");
57 assert.equal(s.headers["apns-push-type"], "liveactivity");
58 assert.equal(s.headers["apns-priority"], "5");
59 assert.equal(s.headers["apns-expiration"], "1792230000");
60 assert.match(s.headers.authorization, /^bearer [\w-]+\.[\w-]+\.[\w-]+$/);
61 assert.deepEqual(JSON.parse(s.body!), { aps: { event: "update" } });
62});
63
64test("channels are created with most-recent-message storage on the management host", async () => {
65 const { seen, fetcher } = recorder(() => new Response(null, { status: 201, headers: { "apns-channel-id": "Y2hhbm5lbA==", "apns-request-id": "r" } }));
66 const r = await createChannel(await config(), true, fetcher);
67 assert.equal(r.channelId, "Y2hhbm5lbA==");
68 assert.equal(r.status, 201);
69 assert.equal(seen[0].url, "https://api-manage-broadcast.sandbox.push.apple.com:2195/1/apps/sh.krz.moonrise/channels");
70 assert.equal(seen[0].method, "POST");
71 assert.deepEqual(JSON.parse(seen[0].body!), { "message-storage-policy": 1, "push-type": "LiveActivity" });
72});
73
74test("channels are listed and deleted on the production management port", async () => {
75 const list = recorder(() => Response.json({ channels: ["YQ==", "Yg=="] }, { headers: { "apns-request-id": "r" } }));
76 const r = await listChannels(await config(), false, list.fetcher);
77 assert.deepEqual(r.channels, ["YQ==", "Yg=="]);
78 assert.equal(list.seen[0].url, "https://api-manage-broadcast.push.apple.com:2196/1/apps/sh.krz.moonrise/all-channels");
79
80 const del = recorder(() => new Response(null, { status: 204 }));
81 const d = await deleteChannel(await config(), "YQ==", false, del.fetcher);
82 assert.equal(d.status, 204);
83 assert.equal(del.seen[0].method, "DELETE");
84 assert.equal(del.seen[0].headers["apns-channel-id"], "YQ==");
85 assert.equal(del.seen[0].url, "https://api-manage-broadcast.push.apple.com:2196/1/apps/sh.krz.moonrise/channels");
86});
87
88test("errors report APNs' reason", async () => {
89 const { fetcher } = recorder(() => Response.json({ reason: "InvalidProviderToken" }, { status: 403 }));
90 const r = await listChannels(await config(), true, fetcher);
91 assert.equal(r.status, 403);
92 assert.equal(r.reason, "InvalidProviderToken");
93 assert.deepEqual(r.channels, []);
94});
server/test/ll2.test.ts +5 −1
@@ -1,6 +1,6 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3import { normalize, PREVIOUS_URL } from "../src/ll2.ts";
3import { launchURL, normalize, PREVIOUS_URL } from "../src/ll2.ts";
44
55// Trimmed from /2.3.0/launches/upcoming/?mode=normal on 2026-10-17.
66const raw = {
@@ -56,3 +56,7 @@ test("keeps the international designator once launched", () => {
5656test("previous launches are fetched ten at a time", () => {
5757 assert.match(PREVIOUS_URL, /\/launches\/previous\/\?limit=10&mode=normal$/);
5858});
59
60test("a single launch is fetched by id", () => {
61 assert.equal(launchURL(raw.id), `https://ll.thespacedevs.com/2.3.0/launches/${raw.id}/?mode=normal`);
62});
spikes/apns-channels/README.org added +32
@@ -0,0 +1,32 @@
1#+title: apns-channels spike
2
3Checks that a deployed Cloudflare Worker can reach APNs channel management,
4which runs on its own hosts and ports:
5=api-manage-broadcast.sandbox.push.apple.com:2195= and
6=api-manage-broadcast.push.apple.com:2196=. =/probe= lists the app's
7channels with the request code in =server/src/apns.ts=. Test deployed: =wrangler
8dev= has no HTTP/2.
9
10* run
11Needs the Broadcast capability on for =sh.krz.moonrise= in the developer
12portal.
13
14#+begin_src sh
15cd spikes/apns-channels
16wrangler deploy
17wrangler secret put APNS_KEY < AuthKey_644XS4F2RG.p8
18curl https://moonrise-apns-channels-spike.audit-labs.workers.dev/probe
19curl "https://moonrise-apns-channels-spike.audit-labs.workers.dev/probe?env=production"
20wrangler delete
21#+end_src
22
23* reading the result
24- =status= 200 and a =body= of ={"channels": [...]}=: the Worker can manage
25 channels. Set =APNS_MANAGE_CHANNELS= to ="1"= in
26 =server/wrangler.jsonc= =vars=.
27- Another =status= with a =requestId= and an APNs =reason= in =body= (for
28 example 403 =InvalidProviderToken=): the Worker reached APNs; fix the key,
29 team or capability and probe again.
30- =error=, or a body that is not APNs JSON: the Worker cannot reach the
31 port. Fill the channel pool with =server/scripts/channels.ts= (see
32 =server/README.org=).
spikes/apns-channels/package.json added +8
@@ -0,0 +1,8 @@
1{
2 "name": "moonrise-apns-channels-spike",
3 "private": true,
4 "type": "module",
5 "scripts": {
6 "deploy": "wrangler deploy"
7 }
8}
spikes/apns-channels/src/index.ts added +33
@@ -0,0 +1,33 @@
1// Spike: does a deployed Worker reach APNs channel management, on port 2195 (sandbox) and 2196 (production)?
2// Any APNs response with an apns-request-id answers yes.
3
4import { listChannels } from "../../../server/src/apns";
5
6interface Env {
7 APNS_KEY_ID: string;
8 APNS_TEAM_ID: string;
9 APNS_TOPIC: string;
10 APNS_KEY: string;
11}
12
13export default {
14 async fetch(request: Request, env: Env): Promise<Response> {
15 const url = new URL(request.url);
16 if (request.method !== "GET" || url.pathname !== "/probe") return new Response("not found", { status: 404 });
17 if (!env.APNS_KEY) return new Response("APNS_KEY not set", { status: 500 });
18
19 const sandbox = url.searchParams.get("env") !== "production";
20 let body = "";
21 const capture = (async (input: RequestInfo | URL, init?: RequestInit) => {
22 const res = await fetch(input, init);
23 body = await res.clone().text();
24 return res;
25 }) as typeof fetch;
26 try {
27 const r = await listChannels({ keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }, sandbox, capture);
28 return Response.json({ sandbox, status: r.status, requestId: r.apnsId, body });
29 } catch (e) {
30 return Response.json({ sandbox, error: String(e) }, { status: 502 });
31 }
32 },
33} satisfies ExportedHandler<Env>;
spikes/apns-channels/wrangler.jsonc added +11
@@ -0,0 +1,11 @@
1{
2 "name": "moonrise-apns-channels-spike",
3 "main": "src/index.ts",
4 "compatibility_date": "2026-10-01",
5 "vars": {
6 "APNS_KEY_ID": "644XS4F2RG",
7 "APNS_TEAM_ID": "ZCNAX3VL9D",
8 "APNS_TOPIC": "sh.krz.moonrise"
9 }
10 // Secret: APNS_KEY (.p8 contents). Set with `wrangler secret put`.
11}