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 d1bf1aed96

d1bf1aed964b3d237e2893702f3b5f83d323d61d

parent: 928d283ba0

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 04:51 UTC

Launches: push-to-start for followed rockets and providers (!139)

- Migration `0009_launch_starts.sql`: token, environment, rockets, providers (JSON), last_seen. Pruned after 180 days.
- `POST /v1/launch-starts` (App Attest checked like `/v1/devices`; empty lists delete), `DELETE /v1/launch-starts/:token`.
- `startLaunches` in the 5-minute tick: launches within the hour without an outcome; installs following the rocket or provider; `liveactivity` push to `sh.krz.moonrise.push-type.liveactivity` with `event: start`, `attributes-type: LaunchActivityAttributes`, `input-push-channel` set to the launch's channel. Deduplicated in `alerts_sent` by install, launch and NET date; 410 removes the token.
- `apns.send`/`sendAll` take a push type.
- App: `LaunchStarts` (token from `pushToStartTokenUpdates`, lists in UserDefaults, ends a second countdown for the same launch), toggles on the launch page, a Launch countdowns section in Settings.
- Tests: start window and payload; Worker sends to rocket and provider followers once with the channel; registration validation and removal.

Layout: unified · split

App/Sources/LaunchStarts.swift added +95
@@ -0,0 +1,95 @@
1import ActivityKit
2import Foundation
3import Observation
4
5/// Rockets and providers whose launches start a countdown on the Lock Screen an hour before liftoff, without opening
6/// the app. Sends the server ActivityKit's push-to-start token and these lists, nothing else.
7@MainActor
8@Observable
9final class LaunchStarts {
10 static let shared = LaunchStarts()
11
12 private static let rocketsKey = "followedRockets"
13 private static let providersKey = "followedProviders"
14 private static let tokenKey = "launchStartToken"
15
16 private(set) var rockets = UserDefaults.standard.stringArray(forKey: LaunchStarts.rocketsKey) ?? []
17 private(set) var providers = UserDefaults.standard.stringArray(forKey: LaunchStarts.providersKey) ?? []
18 private(set) var status: String?
19 private var started = false
20
21 #if DEBUG
22 private let environment = "sandbox"
23 #else
24 private let environment = "production"
25 #endif
26
27 private var token: String? { UserDefaults.standard.string(forKey: Self.tokenKey) }
28
29 /// At launch: watches for the push-to-start token and ends duplicate countdowns (one followed by hand and one
30 /// started by the server for the same launch).
31 func start() {
32 guard !started else { return }
33 started = true
34 Task {
35 for await data in Activity<LaunchActivityAttributes>.pushToStartTokenUpdates {
36 let hex = data.map { String(format: "%02x", $0) }.joined()
37 guard hex != token else { continue }
38 UserDefaults.standard.set(hex, forKey: Self.tokenKey)
39 await sync()
40 }
41 }
42 Task {
43 for await new in Activity<LaunchActivityAttributes>.activityUpdates {
44 await endIfDuplicate(id: new.id, launchID: new.attributes.launchID)
45 }
46 }
47 }
48
49 private func endIfDuplicate(id: String, launchID: String) async {
50 guard Activity<LaunchActivityAttributes>.activities.contains(where: { $0.attributes.launchID == launchID && $0.id != id }) else { return }
51 for a in Activity<LaunchActivityAttributes>.activities where a.id == id {
52 await a.end(nil, dismissalPolicy: .immediate)
53 }
54 }
55
56 func follows(rocket: String) -> Bool { rockets.contains(rocket) }
57 func follows(provider: String) -> Bool { providers.contains(provider) }
58
59 func set(rocket: String, _ on: Bool) async {
60 rockets = toggled(rockets, rocket, on)
61 UserDefaults.standard.set(rockets, forKey: Self.rocketsKey)
62 await sync()
63 }
64
65 func set(provider: String, _ on: Bool) async {
66 providers = toggled(providers, provider, on)
67 UserDefaults.standard.set(providers, forKey: Self.providersKey)
68 await sync()
69 }
70
71 private func toggled(_ list: [String], _ item: String, _ on: Bool) -> [String] {
72 on ? (list.contains(item) ? list : list + [item]) : list.filter { $0 != item }
73 }
74
75 /// Registers the lists with the token; empty lists remove it from the server.
76 func sync() async {
77 guard let apiBase else { return }
78 guard let token else {
79 if !(rockets.isEmpty && providers.isEmpty) { status = "Countdowns start once iOS hands Moonrise a token; open the app again shortly." }
80 return
81 }
82 let body: [String: Any] = ["token": token, "environment": environment, "rockets": rockets, "providers": providers]
83 var req = URLRequest(url: apiBase.appending(path: "v1/launch-starts"))
84 req.httpMethod = "POST"
85 req.setValue("application/json", forHTTPHeaderField: "content-type")
86 if let (data, headers) = await AppAttest.sign(body, base: apiBase) {
87 req.httpBody = data
88 for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) }
89 } else {
90 req.httpBody = try? JSONSerialization.data(withJSONObject: body)
91 }
92 let ok = ((try? await URLSession.shared.data(for: req))?.1 as? HTTPURLResponse)?.statusCode == 200
93 status = ok ? nil : "Couldn't reach the Moonrise server. Your choices will be sent next time."
94 }
95}
App/Sources/LaunchesScreen.swift +18
@@ -196,6 +196,7 @@ struct LaunchDetail: View {
196196 visibility.padding(.top, 8)
197197 followButton.padding(.top, 8)
198198 if let message { Text(message).font(.caption).dimmed(0.7) }
199 LaunchRuleToggles(rocket: launch.rocket, provider: launch.provider).padding(.top, 4)
199200 if let d = launch.missionDescription {
200201 Text(d).font(.subheadline).dimmed(0.85).padding(.top, 8)
201202 }
@@ -349,3 +350,20 @@ struct LaunchDetail: View {
349350 }
350351 }
351352}
353
354/// Follow every launch of this rocket or provider: the server starts each countdown an hour before liftoff.
355private struct LaunchRuleToggles: View {
356 var rocket: String
357 var provider: String
358 @State private var starts = LaunchStarts.shared
359
360 var body: some View {
361 VStack(alignment: .leading, spacing: 4) {
362 Toggle("Every \(rocket) launch", isOn: Binding(get: { starts.follows(rocket: rocket) }, set: { on in Task { await starts.set(rocket: rocket, on) } }))
363 Toggle("Every \(provider) launch", isOn: Binding(get: { starts.follows(provider: provider) }, set: { on in Task { await starts.set(provider: provider, on) } }))
364 Text("Starts the countdown on the Lock Screen an hour before each one, without opening Moonrise.").font(.caption).dimmed(0.7)
365 if let status = starts.status { Text(status).font(.caption).dimmed(0.7) }
366 }
367 .font(.subheadline)
368 }
369}
App/Sources/MoonriseApp.swift +1
@@ -46,6 +46,7 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
4646 ImageLoader.configureURLCache()
4747 UNUserNotificationCenter.current().delegate = self
4848 application.registerForRemoteNotifications()
49 Task { @MainActor in LaunchStarts.shared.start() }
4950 MoonriseShortcuts.updateAppShortcutParameters()
5051 Task.detached(priority: .utility) { Library.prepareSearch() }
5152 Task.detached(priority: .background) { await SpotlightIndexer.indexIfNeeded() }
App/Sources/SettingsScreen.swift +15
@@ -84,6 +84,7 @@ struct SettingsScreen: View {
8484 @AppStorage(SettingsKey.onboarded) private var onboarded = true
8585 @Environment(\.dismiss) private var dismiss
8686 @State private var alerts = AuroraAlerts.shared
87 @State private var starts = LaunchStarts.shared
8788 @AppStorage(SettingsKey.dailySummary) private var dailySummary = false
8889 @AppStorage(SettingsKey.issPasses) private var issPasses = false
8990 @AppStorage(SettingsKey.dailySummaryMinutes) private var dailySummaryMinutes = DailySummaryNotifications.defaultMinutes
@@ -126,6 +127,20 @@ struct SettingsScreen: View {
126127 } footer: {
127128 Text("Aurora alerts tell you when the aurora may be visible from your area at night. News alerts send three of the day's space headlines at 9 a.m. For these, Moonrise sends our server this device's notification token, a 5° band of geomagnetic latitude, your time zone offset and which alerts are on, not your location.")
128129 }
130 if !starts.rockets.isEmpty || !starts.providers.isEmpty {
131 Section {
132 ForEach(starts.rockets, id: \.self) { r in
133 Toggle(r, isOn: Binding(get: { true }, set: { on in Task { await starts.set(rocket: r, on) } }))
134 }
135 ForEach(starts.providers, id: \.self) { p in
136 Toggle(p, isOn: Binding(get: { true }, set: { on in Task { await starts.set(provider: p, on) } }))
137 }
138 } header: {
139 Text("Launch countdowns")
140 } footer: {
141 Text("Launches by these rockets and providers start a countdown on the Lock Screen an hour before liftoff. For this, Moonrise sends our server a Live Activity token and this list.")
142 }
143 }
129144 Section {
130145 Toggle("Daily summary", isOn: Binding(
131146 get: { dailySummary },
PLAN.org +5
@@ -581,6 +581,11 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled.
581581 minutes before dark to dawn.
582582- Push-to-start for followed launches: needs per-device tokens stored on the
583583 Worker, a privacy policy change and a matching App Store privacy label.
584 Done (5.8): follow every launch of a rocket or provider from the launch
585 page; =/v1/launch-starts= stores ActivityKit's push-to-start token and the
586 lists (App Attest signed, apart from devices); an hour before NET the
587 Worker starts the countdown on the launch's broadcast channel. Pending:
588 privacy policy and label.
584589
585590** v5.6: Observing
586591- Meteor radiant altitude (radiant coordinates for the major showers).
server/migrations/0009_launch_starts.sql added +9
@@ -0,0 +1,9 @@
1-- Push-to-start tokens for launch Live Activities and the rockets and providers each install follows (JSON arrays).
2-- Kept apart from devices: the token is ActivityKit's, not the APNs device token.
3CREATE TABLE launch_starts (
4 token TEXT PRIMARY KEY,
5 environment TEXT NOT NULL CHECK (environment IN ('sandbox', 'production')),
6 rockets TEXT NOT NULL,
7 providers TEXT NOT NULL,
8 last_seen TEXT NOT NULL
9);
server/src/activity.ts +35
@@ -72,3 +72,38 @@ export function activityPush(sent: ActivityState, current: ActivityState, now: D
7272 else aps["stale-date"] = unix(net + 60 * MINUTE);
7373 return { payload: { aps }, priority: sent.status === current.status ? 5 : 10, end };
7474}
75
76export interface StartLaunch extends ActivityState {
77 id: string;
78 rocket: string;
79 provider: string;
80 mission: string | null;
81 name: string;
82 location: string;
83}
84
85/** A followed launch is started on devices once it is within the hour and has no outcome. */
86export function startDue(l: ActivityState, now: Date): boolean {
87 const t = Date.parse(l.net);
88 return !OUTCOMES.includes(l.status) && now.getTime() < t && t - now.getTime() <= FOCUS_BEFORE;
89}
90
91/**
92 * Push-to-start payload: `attributes` match LaunchActivityAttributes and `content-state` its ContentState, as when
93 * the app starts the activity itself. With a channel the activity subscribes to the launch's broadcasts (iOS 18).
94 */
95export function startPayload(l: StartLaunch, channelId: string | null, now: Date): { aps: Record<string, unknown> } {
96 const net = Date.parse(l.net);
97 const mission = l.mission ?? l.name;
98 const aps: Record<string, unknown> = {
99 timestamp: unix(now.getTime()),
100 event: "start",
101 "attributes-type": "LaunchActivityAttributes",
102 attributes: { launchID: l.id, rocket: l.rocket, mission, location: l.location },
103 "content-state": { net: unix(net) - REFERENCE_DATE, status: l.status },
104 "stale-date": unix(net + 60 * MINUTE),
105 alert: { title: `${l.rocket} launches in an hour`, body: mission },
106 };
107 if (channelId) aps["input-push-channel"] = channelId;
108 return { aps };
109}
server/src/apns.ts +6 −5
@@ -58,14 +58,15 @@ function token(config: ApnsConfig): Promise<string> {
5858 return t;
5959}
6060
61export async function send(config: ApnsConfig, deviceToken: string, payload: unknown, sandbox: boolean): Promise<ApnsResult> {
61/** An alert to a device token, or with `liveactivity` a Live Activity push (push-to-start) to an ActivityKit token. */
62export async function send(config: ApnsConfig, deviceToken: string, payload: unknown, sandbox: boolean, type: "alert" | "liveactivity" = "alert"): Promise<ApnsResult> {
6263 const host = sandbox ? "api.sandbox.push.apple.com" : "api.push.apple.com";
6364 const res = await fetch(`https://${host}/3/device/${deviceToken}`, {
6465 method: "POST",
6566 headers: {
6667 authorization: `bearer ${await token(config)}`,
67 "apns-topic": config.topic,
68 "apns-push-type": "alert",
68 "apns-topic": type === "alert" ? config.topic : `${config.topic}.push-type.liveactivity`,
69 "apns-push-type": type,
6970 "apns-priority": "10",
7071 "content-type": "application/json",
7172 },
@@ -75,13 +76,13 @@ export async function send(config: ApnsConfig, deviceToken: string, payload: unk
7576}
7677
7778/** `send` to each device, at most `concurrency` at a time. Results are in input order; a network error is status 0. */
78export async function sendAll(config: ApnsConfig, sends: { token: string; payload: unknown; sandbox: boolean }[], concurrency: number): Promise<ApnsResult[]> {
79export async function sendAll(config: ApnsConfig, sends: { token: string; payload: unknown; sandbox: boolean; type?: "alert" | "liveactivity" }[], concurrency: number): Promise<ApnsResult[]> {
7980 const out: ApnsResult[] = new Array(sends.length);
8081 let next = 0;
8182 const worker = async () => {
8283 while (next < sends.length) {
8384 const i = next++;
84 out[i] = await send(config, sends[i].token, sends[i].payload, sends[i].sandbox).catch((e) => ({ status: 0, apnsId: null, reason: String(e) }));
85 out[i] = await send(config, sends[i].token, sends[i].payload, sends[i].sandbox, sends[i].type).catch((e) => ({ status: 0, apnsId: null, reason: String(e) }));
8586 }
8687 };
8788 await Promise.all(Array.from({ length: Math.min(concurrency, sends.length) }, worker));
server/src/index.ts +78 −1
@@ -1,4 +1,4 @@
1import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, type ActivityState } from "./activity";
1import { activityPush, startDue, startPayload, type StartLaunch, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, type ActivityState } from "./activity";
22import { AttestError, fromBase64, toBase64, verifyAssertion, verifyAttestation, type AttestedKey } from "./appattest";
33import { broadcast, createChannel, deleteChannel, retryable, send, sendAll, type ApnsConfig } from "./apns";
44import { actionableKp, alertBands, eventKey, isNight } from "./aurora";
@@ -191,6 +191,13 @@ export default {
191191 const test = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})\/test$/i);
192192 if (request.method === "POST" && test) return sendTest(env, test[1].toLowerCase(), now);
193193
194 if (request.method === "POST" && url.pathname === "/v1/launch-starts") return registerLaunchStarts(request, env, now);
195 const delStarts = url.pathname.match(/^\/v1\/launch-starts\/([0-9a-f]{64,200})$/i);
196 if (request.method === "DELETE" && delStarts) {
197 await env.DB.prepare("DELETE FROM launch_starts WHERE token = ?1").bind(delStarts[1].toLowerCase()).run();
198 return json({ ok: true });
199 }
200
194201 const del = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})$/i);
195202 if (request.method === "DELETE" && del) {
196203 await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(del[1]).run();
@@ -361,6 +368,75 @@ async function launchTick(env: Env, now: Date): Promise<void> {
361368 else if (pollList) await pollLaunches(env, now);
362369 // Channels are handed out with the launch's current state, so a poll means reading it again.
363370 if (env.APNS_KEY) await launchChannels(env, pollFocus || pollList ? await nearLaunches(env, now) : near, now);
371 if (env.APNS_KEY) await startLaunches(env, now);
372}
373
374const RULE = (v: unknown) => Array.isArray(v) && v.length <= 20 && v.every((x) => typeof x === "string" && x.length > 0 && x.length <= 100);
375
376/**
377 * POST /v1/launch-starts {token, environment, rockets, providers, challenge?}: the rockets and providers whose launches
378 * start a countdown on this install. Signed with App Attest like /v1/devices. No rules removes the token.
379 */
380async function registerLaunchStarts(request: Request, env: Env, now: Date): Promise<Response> {
381 const body = new Uint8Array(await request.arrayBuffer());
382 let d: { token?: unknown; environment?: unknown; rockets?: unknown; providers?: unknown; challenge?: string };
383 try {
384 d = JSON.parse(new TextDecoder().decode(body));
385 } catch {
386 d = {};
387 }
388 if (typeof d.token !== "string" || !/^[0-9a-f]{64,200}$/i.test(d.token) || (d.environment !== "sandbox" && d.environment !== "production") || !RULE(d.rockets) || !RULE(d.providers)) {
389 return json({ error: "invalid registration" }, 400);
390 }
391 const refused = await checkAssertion(env, request, body, d.challenge, now);
392 if (refused) return refused;
393 const rockets = d.rockets as string[], providers = d.providers as string[];
394 if (!rockets.length && !providers.length) {
395 await env.DB.prepare("DELETE FROM launch_starts WHERE token = ?1").bind(d.token.toLowerCase()).run();
396 } else {
397 await env.DB.prepare(
398 `INSERT INTO launch_starts (token, environment, rockets, providers, last_seen) VALUES (?1, ?2, ?3, ?4, ?5)
399 ON CONFLICT (token) DO UPDATE SET environment = ?2, rockets = ?3, providers = ?4, last_seen = ?5`,
400 ).bind(d.token.toLowerCase(), d.environment, JSON.stringify(rockets), JSON.stringify(providers), now.toISOString()).run();
401 }
402 return json({ ok: true });
403}
404
405/**
406 * Push-to-start for followed launches: an hour before NET, each install following the launch's rocket or provider
407 * gets the countdown, subscribed to the launch's broadcast channel. Once per install, launch and NET date, so a
408 * launch moved to another day starts again.
409 */
410async function startLaunches(env: Env, now: Date): Promise<void> {
411 const due = (await env.DB.prepare(
412 "SELECT id, name, net, status, rocket, provider, mission, location FROM launches WHERE net > ?1 AND net <= ?2",
413 // A minute either side: LL2 writes "…:00Z" and toISOString "…:00.000Z", which compare unequal as text. startDue decides.
414 ).bind(new Date(now.getTime() - 60_000).toISOString(), new Date(now.getTime() + 61 * 60_000).toISOString()).all<StartLaunch>()).results.filter((l) => startDue(l, now));
415 if (!due.length) return;
416 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
417 for (const l of due) {
418 const channels = Object.fromEntries((await env.DB.prepare("SELECT environment, channel_id FROM launch_channels WHERE launch_id = ?1 AND ended_at IS NULL")
419 .bind(l.id).all<{ environment: string; channel_id: string }>()).results.map((c) => [c.environment, c.channel_id]));
420 const event = `${l.id}:${l.net.slice(0, 10)}`;
421 const installs = (await env.DB.prepare(
422 `SELECT token, environment FROM launch_starts s
423 WHERE (EXISTS (SELECT 1 FROM json_each(s.rockets) WHERE value = ?1) OR EXISTS (SELECT 1 FROM json_each(s.providers) WHERE value = ?2))
424 AND NOT EXISTS (SELECT 1 FROM alerts_sent a WHERE a.kind = 'start' AND a.band = 0 AND a.event = s.token || ':' || ?3)
425 LIMIT ?4`,
426 ).bind(l.rocket, l.provider, event, PUSH_SLICE).all<{ token: string; environment: string }>()).results;
427 if (!installs.length) continue;
428 const results = await sendAll(config, installs.map((i) => ({
429 token: i.token, payload: startPayload(l, channels[i.environment] ?? null, now), sandbox: i.environment === "sandbox", type: "liveactivity" as const,
430 })), PUSH_CONCURRENCY);
431 const writes: D1PreparedStatement[] = [];
432 installs.forEach((i, k) => {
433 const { status, reason } = results[k];
434 if (status !== 200) console.error("apns start", status, reason);
435 if (status === 410) writes.push(env.DB.prepare("DELETE FROM launch_starts WHERE token = ?1").bind(i.token));
436 else if (!retryable(status)) writes.push(env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('start', 0, ?1, ?2)").bind(`${i.token}:${event}`, now.toISOString()));
437 });
438 if (writes.length) await env.DB.batch(writes);
439 }
364440}
365441
366442/** With an LL2 key: the launch in focus on the even minutes the 5-minute cron does not run on, and its broadcasts. */
@@ -750,5 +826,6 @@ async function prune(env: Env, now: Date): Promise<void> {
750826 env.DB.prepare("DELETE FROM app_keys WHERE last_used < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()),
751827 env.DB.prepare("DELETE FROM alerts_sent WHERE sent_at < ?1").bind(new Date(now.getTime() - 3 * 86400_000).toISOString()),
752828 env.DB.prepare("DELETE FROM devices WHERE last_seen < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()),
829 env.DB.prepare("DELETE FROM launch_starts WHERE last_seen < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()),
753830 ]);
754831}
server/test/activity.test.ts +19 −1
@@ -1,6 +1,6 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet } from "../src/activity.ts";
3import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, startDue, startPayload } from "../src/activity.ts";
44
55const now = new Date("2026-10-20T12:00:00Z");
66const unix = (iso: string) => Date.parse(iso) / 1000;
@@ -81,3 +81,21 @@ test("an outcome ends the activity and dismisses it 15 minutes later", () => {
8181 assert.equal(p.payload.aps["stale-date"], undefined);
8282 }
8383});
84
85test("push-to-start runs from an hour before NET until NET, without an outcome", () => {
86 assert.equal(startDue({ net: "2026-10-20T13:00:00Z", status: "Go" }, now), true);
87 assert.equal(startDue({ net: "2026-10-20T13:00:01Z", status: "Go" }, now), false);
88 assert.equal(startDue({ net: "2026-10-20T12:00:00Z", status: "Go" }, now), false);
89 assert.equal(startDue({ net: "2026-10-20T12:30:00Z", status: "Success" }, now), false);
90});
91
92test("the push-to-start payload matches LaunchActivityAttributes and subscribes to the channel", () => {
93 const l = { id: "x1", name: "Falcon 9 | Starlink", net: "2026-10-20T12:45:00Z", status: "Go", rocket: "Falcon 9 Block 5", provider: "SpaceX", mission: null, location: "Cape Canaveral" };
94 const { aps } = startPayload(l, "ch1", now);
95 assert.equal(aps.event, "start");
96 assert.equal(aps["attributes-type"], "LaunchActivityAttributes");
97 assert.deepEqual(aps.attributes, { launchID: "x1", rocket: "Falcon 9 Block 5", mission: "Falcon 9 | Starlink", location: "Cape Canaveral" });
98 assert.deepEqual(aps["content-state"], { net: unix("2026-10-20T12:45:00Z") - 978_307_200, status: "Go" });
99 assert.equal(aps["input-push-channel"], "ch1");
100 assert.equal("input-push-channel" in startPayload(l, null, now).aps, false);
101});
server/test/worker.test.ts +37
@@ -592,3 +592,40 @@ test("device registration checks an App Attest assertion over the body, with a o
592592 const { env: strict } = await setup({ APNS_TEAM_ID: "ZCNAX3VL9D", APP_ATTEST: "require" });
593593 assert.equal((await worker.fetch(new Request("https://moonrise.krz.sh/v1/devices", { method: "POST", body: plain }), strict as never)).status, 401);
594594});
595
596test("followers of a launch's rocket or provider get one push-to-start an hour out, on the launch's channel", async () => {
597 const { db, env } = await setup();
598 db.prepare("INSERT INTO launches (id, name, net, status, status_name, provider, rocket, pad, location, last_updated) VALUES ('L1', 'Falcon 9 | Starlink', '2026-10-20T12:50:00Z', 'Go', 'Go', 'SpaceX', 'Falcon 9', 'SLC-40', 'Cape', 'x')").run();
599 db.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES ('chP', 'production', 'L1', '2026-10-20T12:50:00Z', 'Go', 'x')").run();
600 const follow = (i: number, rockets: string[], providers: string[]) =>
601 db.prepare("INSERT INTO launch_starts (token, environment, rockets, providers, last_seen) VALUES (?, 'production', ?, ?, 'x')").run(token(i), JSON.stringify(rockets), JSON.stringify(providers));
602 follow(1, ["Falcon 9"], []);
603 follow(2, [], ["SpaceX"]);
604 follow(3, ["Electron"], ["Rocket Lab"]);
605 const pushes: { token: string; topic: string | null; type: string | null; body: string }[] = [];
606 const handler: Handler = (url, init) => {
607 const h = new Headers(init.headers);
608 pushes.push({ token: url.pathname.split("/").at(-1)!, topic: h.get("apns-topic"), type: h.get("apns-push-type"), body: String(init.body) });
609 return new Response(null, { status: 200 });
610 };
611 network({ "api.push.apple.com": handler });
612 await run(env, FIVE, "2026-10-20T11:45:00Z");
613 assert.equal(pushes.length, 0, "more than an hour out");
614 await run(env, FIVE, "2026-10-20T11:50:00Z");
615 assert.deepEqual(pushes.map((p) => p.token).sort(), [token(1), token(2)]);
616 assert.equal(pushes[0].topic, "sh.krz.moonrise.push-type.liveactivity");
617 assert.equal(pushes[0].type, "liveactivity");
618 assert.equal(JSON.parse(pushes[0].body).aps["input-push-channel"], "chP");
619 await run(env, FIVE, "2026-10-20T11:55:00Z");
620 assert.equal(pushes.length, 2, "once per install");
621});
622
623test("launch-start registration stores rules, and no rules removes the token", async () => {
624 const { db, env } = await setup();
625 const post = (body: object) => worker.fetch(new Request("https://moonrise.krz.sh/v1/launch-starts", { method: "POST", body: JSON.stringify(body) }), env as never);
626 assert.equal((await post({ token: token(1), environment: "production", rockets: ["Falcon Heavy"], providers: [] })).status, 200);
627 assert.equal((db.prepare("SELECT rockets FROM launch_starts").get() as { rockets: string }).rockets, '["Falcon Heavy"]');
628 assert.equal((await post({ token: token(1), environment: "production", rockets: "x", providers: [] })).status, 400);
629 assert.equal((await post({ token: token(1), environment: "production", rockets: [], providers: [] })).status, 200);
630 assert.equal(count(db, "SELECT COUNT(*) AS n FROM launch_starts"), 0);
631});