Public: anyone can read this; the crew can change it.
Push to Apple devices (APNs): device registration and a sender #17928
Merged 23h 39m ago, live in production
mason/forge:mason/17926-push-to-apple-devices-apns-device-regist → main 0 commits fork 1 thread · 1 unresolved
20 files
changed +1041
−8
- docs/features/push-apple.md
- forge.json
- src/contract/openapi/routes/deleteApiV1UserDevicesId.ts
- src/contract/openapi/routes/getApiV1UserDevices.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1UserDevices.ts
- src/core/migration-pins/20261203060000-push-devices.pin
- src/core/migrations/20261203060000-push-devices.ts
- src/core/push_devices.ts
- src/http/api.ts
- src/http/api/push_devices.ts
- src/http/lazy_lists.ts
- src/main.ts
- src/push/apns.ts
- src/push/payload.ts
- src/push/watch.ts
- test/job-slices.test.ts
- test/push-apns.test.ts
- test/route-timing-coverage.test.ts
- test/snapshot-stream.test.ts
docs/features/push-apple.md added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | --- | |
| 2 | topic: Every setting, by topic | |
| 3 | row: Push to Apple devices | |
| 4 | --- | |
| 5 | # Push to Apple devices | |
| 6 | ||
| 7 | The forge iOS app (`sh.open-platform.forge`) hears the forge while it is closed through Apple's push service (APNs). There is no page for it: the app registers itself, and a person never types a token. | |
| 8 | ||
| 9 | 1. **Keys.** A site admin seals three forge-scope secrets: `APNS_KEY` (the team's `.p8` key, PEM), `APNS_KEY_ID` and `APNS_TEAM_ID`. Until all three exist nothing is sent. | |
| 10 | 2. **Register.** `POST /api/v1/user/devices` with `{"token":"<hex>","platform":"apns","environment":"sandbox"|"production","kind":"alert"|"widget"|"liveactivity-start"|"liveactivity","activity":"run:<id>"}` (`activity` only for `liveactivity`). Needs a token of scope `rw` or a same-origin session; an agent is refused. The same token and kind again is the same device. `GET /api/v1/user/devices` lists yours (a token shows its last six characters); `DELETE /api/v1/user/devices/{id}` removes one. | |
| 11 | 3. **What is sent** (`src/push/watch.ts`, on the bus the home stream rides): | |
| 12 | - An **alert**, the only push that makes a sound: a review, look or handover ask newly waiting on you (told once), an ask of yours that was answered, a check you started that failed. Ten an hour at most; none while you are in focus. | |
| 13 | - A **silent widget reload** (`apns-push-type: background`) after a change in a repository you can read, at most one every 30 seconds. | |
| 14 | - A **Live Activity update or end** (`apns-push-type: liveactivity`, topic `sh.open-platform.forge.push-type.liveactivity`) for the run a registered activity follows; your own run starting also starts one on a `liveactivity-start` device. | |
| 15 | 4. **Private forges.** The call to Apple (`api.push.apple.com`, `api.sandbox.push.apple.com`, both under `*.push.apple.com` in `forge.json` `egress`) leaves from the forge's own process and the phone hears it over Apple's network, so a tailnet-only forge works. | |
| 16 | ||
| 17 | An alert names the app and the ask, and so reaches Apple's servers; register an `alert` device only if that is acceptable. A token Apple calls dead is forgotten. A payload is cut to short lines and stays under 4 KB. |
forge.json +2 −1
| @@ -30,7 +30,8 @@ | ||
| 30 | 30 | "api.first.org", |
| 31 | 31 | "api.modrinth.com", |
| 32 | 32 | "cdn.modrinth.com", |
| 33 | "api.mclo.gs" | |
| 33 | "api.mclo.gs", | |
| 34 | "*.push.apple.com" | |
| 34 | 35 | ], |
| 35 | 36 | "schedules": [ |
| 36 | 37 | { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" } |
src/contract/openapi/routes/deleteApiV1UserDevicesId.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "delete", | |
| 5 | path: "/api/v1/user/devices/{id}", | |
| 6 | summary: "Remove one of your registered Apple devices", | |
| 7 | auth: true, | |
| 8 | role: "member", | |
| 9 | status: 204, | |
| 10 | refusals: { unauthorized: "401: no valid credentials were sent", forbidden: "403: a token below scope rw, an agent, or a cross-origin browser request", not_found: "404: none of your devices has this id" }, | |
| 11 | refuses: [401, 404], | |
| 12 | }; |
src/contract/openapi/routes/getApiV1UserDevices.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/user/devices", | |
| 6 | summary: "List your registered Apple devices; each token shows its last six characters only", | |
| 7 | auth: true, | |
| 8 | role: "member", | |
| 9 | refusals: { unauthorized: "401: no valid credentials were sent", forbidden: "403: an agent has no devices" }, | |
| 10 | refuses: [401], | |
| 11 | }; |
src/contract/openapi/routes/index.ts +3
| @@ -39,6 +39,7 @@ export { route as deleteApiV1SecretsScopeName } from "./deleteApiV1SecretsScopeN | ||
| 39 | 39 | export { route as deleteApiV1Sessions } from "./deleteApiV1Sessions.ts"; |
| 40 | 40 | export { route as deleteApiV1TimersKey } from "./deleteApiV1TimersKey.ts"; |
| 41 | 41 | export { route as deleteApiV1TokensId } from "./deleteApiV1TokensId.ts"; |
| 42 | export { route as deleteApiV1UserDevicesId } from "./deleteApiV1UserDevicesId.ts"; | |
| 42 | 43 | export { route as deleteApiV1UserKeysId } from "./deleteApiV1UserKeysId.ts"; |
| 43 | 44 | export { route as deleteApiV1UserOriginAppsId } from "./deleteApiV1UserOriginAppsId.ts"; |
| 44 | 45 | export { route as deleteApiV1UserOriginsId } from "./deleteApiV1UserOriginsId.ts"; |
| @@ -260,6 +261,7 @@ export { route as getApiV1Tokens } from "./getApiV1Tokens.ts"; | ||
| 260 | 261 | export { route as getApiV1Usage } from "./getApiV1Usage.ts"; |
| 261 | 262 | export { route as getApiV1User } from "./getApiV1User.ts"; |
| 262 | 263 | export { route as getApiV1UserAssigned } from "./getApiV1UserAssigned.ts"; |
| 264 | export { route as getApiV1UserDevices } from "./getApiV1UserDevices.ts"; | |
| 263 | 265 | export { route as getApiV1UserExport } from "./getApiV1UserExport.ts"; |
| 264 | 266 | export { route as getApiV1UserKeys } from "./getApiV1UserKeys.ts"; |
| 265 | 267 | export { route as getApiV1UserNextSteps } from "./getApiV1UserNextSteps.ts"; |
| @@ -496,6 +498,7 @@ export { route as postApiV1Thoughts } from "./postApiV1Thoughts.ts"; | ||
| 496 | 498 | export { route as postApiV1Timers } from "./postApiV1Timers.ts"; |
| 497 | 499 | export { route as postApiV1TimersFinish } from "./postApiV1TimersFinish.ts"; |
| 498 | 500 | export { route as postApiV1Tokens } from "./postApiV1Tokens.ts"; |
| 501 | export { route as postApiV1UserDevices } from "./postApiV1UserDevices.ts"; | |
| 499 | 502 | export { route as postApiV1UserEmailVerify } from "./postApiV1UserEmailVerify.ts"; |
| 500 | 503 | export { route as postApiV1UserKeys } from "./postApiV1UserKeys.ts"; |
| 501 | 504 | export { route as postApiV1UserOriginApps } from "./postApiV1UserOriginApps.ts"; |
src/contract/openapi/routes/postApiV1UserDevices.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/user/devices", | |
| 6 | summary: "Register an Apple device to be pushed to (APNs); a person's own, scope rw", | |
| 7 | detail: "Register an APNs token for one purpose: an `alert`, a silent `widget` reload, a Live Activity's push-to-start token (`liveactivity-start`) or one running activity's update token (`liveactivity`, with `activity` naming `run:<id>`). Registering the same token and purpose again answers the device already kept. The token is never answered whole.", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | status: 201, | |
| 11 | body: { token: "string", platform: "string", environment: "string", kind: "string", activity: "string?" }, | |
| 12 | refusals: { unauthorized: "401: no valid credentials were sent", forbidden: "403: a token below scope rw, an agent, or a browser session sent a cross-origin request", invalid_token: "`token` is not 32 to 400 hex characters (422)", invalid_platform: "`platform` is not `apns` (422)", invalid_environment: "`environment` is not `sandbox` or `production` (422)", invalid_kind: "`kind` is not one of the four (422)", invalid_activity: "`activity` is malformed, or set for a kind that is not `liveactivity` (422)", too_many: "the account already keeps 20 devices (422)" }, | |
| 13 | refuses: [401, 422], | |
| 14 | }; |
src/core/migration-pins/20261203060000-push-devices.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 0e91582c2168367a5aeb21a4d5df1d90e0b3566689149e6275e2399585fe1e6c |
src/core/migrations/20261203060000-push-devices.ts added +18
| @@ -0,0 +1,18 @@ | ||
| 1 | // Apple devices a person registered to be pushed to (#17926). Additive: a new table. A token is | |
| 2 | // the device's APNs token; `kind` says what it is for (an alert, a widget reload, a Live Activity's | |
| 3 | // push-to-start token, or one running activity's update token, named by `activity`). A token Apple | |
| 4 | // says is dead is deleted on the spot. | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS push_device ( | |
| 7 | id TEXT PRIMARY KEY, | |
| 8 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 9 | token TEXT NOT NULL, | |
| 10 | platform TEXT NOT NULL, | |
| 11 | environment TEXT NOT NULL, | |
| 12 | kind TEXT NOT NULL, | |
| 13 | activity TEXT NOT NULL DEFAULT '', | |
| 14 | created_at TEXT NOT NULL, | |
| 15 | UNIQUE (user_id, token, kind, activity) | |
| 16 | ); | |
| 17 | CREATE INDEX IF NOT EXISTS push_device_user ON push_device (user_id); | |
| 18 | `; |
src/core/push_devices.ts added +137
| @@ -0,0 +1,137 @@ | ||
| 1 | /** | |
| 2 | * Apple devices a person registered to be pushed to (#17926): the rows only. A device is one APNs | |
| 3 | * token for one purpose (`kind`): an alert, a widget reload, a Live Activity's push-to-start | |
| 4 | * token, or the update token of one running activity (named by `activity`). Registering the same | |
| 5 | * token for the same purpose again is the same device. Pure data, no authz, no events; the route | |
| 6 | * is `http/api/push_devices.ts`, the sender `push/watch.ts`. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { id } from "../kernel/id.ts"; | |
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | ||
| 13 | export const PUSH_ENVIRONMENTS = ["sandbox", "production"] as const; | |
| 14 | export const PUSH_KINDS = ["alert", "widget", "liveactivity-start", "liveactivity"] as const; | |
| 15 | export type PushEnvironment = (typeof PUSH_ENVIRONMENTS)[number]; | |
| 16 | export type PushKind = (typeof PUSH_KINDS)[number]; | |
| 17 | ||
| 18 | /** The most devices one account keeps; a phone has a handful of tokens. */ | |
| 19 | export const DEVICES_MAX = 20; | |
| 20 | export const ACTIVITY_MAX = 80; | |
| 21 | ||
| 22 | export interface PushDevice { | |
| 23 | readonly id: string; | |
| 24 | readonly userId: string; | |
| 25 | readonly token: string; | |
| 26 | readonly environment: PushEnvironment; | |
| 27 | readonly kind: PushKind; | |
| 28 | /** What a Live Activity follows (`run:<id>`); empty for every other kind. */ | |
| 29 | readonly activity: string; | |
| 30 | readonly createdAt: string; | |
| 31 | } | |
| 32 | ||
| 33 | /** A request body: every field is checked here, none trusted. */ | |
| 34 | export type PushDeviceInput = Readonly<Record<string, unknown>>; | |
| 35 | ||
| 36 | export type PushDeviceError = | |
| 37 | | "invalid_token" | |
| 38 | | "invalid_platform" | |
| 39 | | "invalid_environment" | |
| 40 | | "invalid_kind" | |
| 41 | | "invalid_activity" | |
| 42 | | "too_many"; | |
| 43 | ||
| 44 | export const PUSH_DEVICE_ERRORS: Record<PushDeviceError, string> = { | |
| 45 | invalid_token: "`token` is the device's APNs token in hex, 32 to 400 characters.", | |
| 46 | invalid_platform: "`platform` is `apns`.", | |
| 47 | invalid_environment: "`environment` is `sandbox` or `production`.", | |
| 48 | invalid_kind: "`kind` is `alert`, `widget`, `liveactivity-start` or `liveactivity`.", | |
| 49 | invalid_activity: `\`activity\` names what a Live Activity follows (letters, digits, : . _ - /, up to ${ACTIVITY_MAX}), and only for \`liveactivity\`.`, | |
| 50 | too_many: `An account keeps at most ${DEVICES_MAX} devices; remove one first.`, | |
| 51 | }; | |
| 52 | ||
| 53 | interface Row { | |
| 54 | id: string; | |
| 55 | user_id: string; | |
| 56 | token: string; | |
| 57 | environment: PushEnvironment; | |
| 58 | kind: PushKind; | |
| 59 | activity: string; | |
| 60 | created_at: string; | |
| 61 | } | |
| 62 | ||
| 63 | const fromRow = (r: Row): PushDevice => ({ | |
| 64 | id: r.id, | |
| 65 | userId: r.user_id, | |
| 66 | token: r.token, | |
| 67 | environment: r.environment, | |
| 68 | kind: r.kind, | |
| 69 | activity: r.activity, | |
| 70 | createdAt: r.created_at, | |
| 71 | }); | |
| 72 | ||
| 73 | const TOKEN = /^[0-9a-fA-F]{32,400}$/; | |
| 74 | const ACTIVITY = /^[A-Za-z0-9:._/-]+$/; | |
| 75 | const oneOf = <T extends string>(list: readonly T[], v: unknown): v is T => | |
| 76 | typeof v === "string" && (list as readonly string[]).includes(v); | |
| 77 | ||
| 78 | /** Keep a device for `userId`; the same token and purpose again answers the one already kept. */ | |
| 79 | export function registerPushDevice( | |
| 80 | db: Database, | |
| 81 | userId: string, | |
| 82 | input: PushDeviceInput, | |
| 83 | ): Result<PushDevice, PushDeviceError> { | |
| 84 | const { token, platform, environment, kind, activity } = input; | |
| 85 | if (typeof token !== "string" || !TOKEN.test(token)) return err("invalid_token"); | |
| 86 | if (platform !== "apns") return err("invalid_platform"); | |
| 87 | if (!oneOf(PUSH_ENVIRONMENTS, environment)) return err("invalid_environment"); | |
| 88 | if (!oneOf(PUSH_KINDS, kind)) return err("invalid_kind"); | |
| 89 | const named = activity === undefined || activity === null ? "" : activity; | |
| 90 | if (typeof named !== "string" || named.length > ACTIVITY_MAX) return err("invalid_activity"); | |
| 91 | if (named !== "" && (kind !== "liveactivity" || !ACTIVITY.test(named))) return err("invalid_activity"); | |
| 92 | const lower = token.toLowerCase(); | |
| 93 | const held = db | |
| 94 | .query<Row, [string, string, string, string]>( | |
| 95 | "SELECT * FROM push_device WHERE user_id = ?1 AND token = ?2 AND kind = ?3 AND activity = ?4", | |
| 96 | ) | |
| 97 | .get(userId, lower, kind, named); | |
| 98 | if (held !== null) { | |
| 99 | // The same token may move between Apple's two worlds (a development build, then a store one). | |
| 100 | db.query("UPDATE push_device SET environment = ?2 WHERE id = ?1").run(held.id, environment); | |
| 101 | return ok({ ...fromRow(held), environment }); | |
| 102 | } | |
| 103 | if (listPushDevices(db, userId).length >= DEVICES_MAX) return err("too_many"); | |
| 104 | const row: Row = { | |
| 105 | id: id(), | |
| 106 | user_id: userId, | |
| 107 | token: lower, | |
| 108 | environment, | |
| 109 | kind, | |
| 110 | activity: named, | |
| 111 | created_at: new Date().toISOString(), | |
| 112 | }; | |
| 113 | db.query( | |
| 114 | "INSERT INTO push_device (id, user_id, token, platform, environment, kind, activity, created_at) VALUES (?1, ?2, ?3, 'apns', ?4, ?5, ?6, ?7)", | |
| 115 | ).run(row.id, userId, lower, environment, kind, named, row.created_at); | |
| 116 | return ok(fromRow(row)); | |
| 117 | } | |
| 118 | ||
| 119 | /** One account's devices, oldest first. */ | |
| 120 | export const listPushDevices = (db: Database, userId: string): PushDevice[] => | |
| 121 | db | |
| 122 | .query<Row, [string]>("SELECT * FROM push_device WHERE user_id = ?1 ORDER BY id") | |
| 123 | .all(userId) | |
| 124 | .map(fromRow); | |
| 125 | ||
| 126 | /** Every device of every account, for the sender: a forge holds few. */ | |
| 127 | export const allPushDevices = (db: Database): PushDevice[] => | |
| 128 | db.query<Row, []>("SELECT * FROM push_device ORDER BY id").all().map(fromRow); | |
| 129 | ||
| 130 | /** Remove one of `userId`'s devices; false when it is not theirs or not there. */ | |
| 131 | export const removePushDevice = (db: Database, userId: string, deviceId: string): boolean => | |
| 132 | db.query("DELETE FROM push_device WHERE id = ?1 AND user_id = ?2").run(deviceId, userId).changes > 0; | |
| 133 | ||
| 134 | /** Forget one device Apple said is dead: that row only, not the token under other accounts. */ | |
| 135 | export const forgetPushDevice = (db: Database, deviceId: string): void => { | |
| 136 | db.query("DELETE FROM push_device WHERE id = ?1").run(deviceId); | |
| 137 | }; |
src/http/api.ts +2
| @@ -361,6 +361,7 @@ import { chapterNames } from "../core/chapters.ts"; | ||
| 361 | 361 | import { takeOrder } from "../crew/take_order.ts"; |
| 362 | 362 | import { forgeCarries } from "../origins/words.ts"; |
| 363 | 363 | import { forgeOriginRoutes } from "./api/forge_origin.ts"; |
| 364 | import { pushDeviceRoutes } from "./api/push_devices.ts"; | |
| 364 | 365 | import { userRoutes } from "./api/user.ts"; |
| 365 | 366 | import { appRoutes } from "./api/app.ts"; |
| 366 | 367 | import { appPullsRoutes } from "./api/app_pulls.ts"; |
| @@ -1266,6 +1267,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1266 | 1267 | tokenRoutes(router); |
| 1267 | 1268 | |
| 1268 | 1269 | userRoutes(router); |
| 1270 | pushDeviceRoutes(router); | |
| 1269 | 1271 | forgeOriginRoutes(router); |
| 1270 | 1272 | adminRoutes(router); |
| 1271 | 1273 | runnerRoutes(router); |
src/http/api/push_devices.ts added +46
| @@ -0,0 +1,46 @@ | ||
| 1 | /** | |
| 2 | * The caller's Apple devices (#17926): `POST /api/v1/user/devices` registers an APNs token for one | |
| 3 | * purpose, `GET` lists them, `DELETE /api/v1/user/devices/:id` removes one. A person's own, never | |
| 4 | * an agent's. A token is never answered back whole: the list shows its last six characters. | |
| 5 | */ | |
| 6 | ||
| 7 | import { PUSH_DEVICE_ERRORS, type PushDevice, listPushDevices, registerPushDevice, removePushDevice } from "../../core/push_devices.ts"; | |
| 8 | import type { Handler } from "../context.ts"; | |
| 9 | import { apiError, body, json, notFound, requireScope, unauthorized } from "../respond.ts"; | |
| 10 | import type { Router } from "../router.ts"; | |
| 11 | ||
| 12 | const shown = (d: PushDevice) => ({ | |
| 13 | id: d.id, | |
| 14 | platform: "apns", | |
| 15 | environment: d.environment, | |
| 16 | kind: d.kind, | |
| 17 | activity: d.activity === "" ? null : d.activity, | |
| 18 | token_tail: d.token.slice(-6), | |
| 19 | created_at: d.createdAt, | |
| 20 | }); | |
| 21 | ||
| 22 | export function pushDeviceRoutes(router: Router<Handler>): void { | |
| 23 | router.add("GET", "/api/v1/user/devices", (ctx) => { | |
| 24 | const user = ctx.auth.user; | |
| 25 | if (!user) return unauthorized(); | |
| 26 | if (user.kind === "agent") return apiError("forbidden", 403, "push devices are a person's, not an agent's"); | |
| 27 | return json({ items: listPushDevices(ctx.app.db, user.id).map(shown), next_cursor: null }); | |
| 28 | }); | |
| 29 | router.add("POST", "/api/v1/user/devices", async (ctx) => { | |
| 30 | const denied = requireScope(ctx, "rw"); | |
| 31 | if (denied) return denied; | |
| 32 | const user = ctx.auth.user!; | |
| 33 | if (user.kind === "agent") return apiError("forbidden", 403, "push devices are a person's, not an agent's"); | |
| 34 | const input = await body(ctx.request); | |
| 35 | const made = registerPushDevice(ctx.app.db, user.id, input); | |
| 36 | if (!made.ok) return apiError(made.error, 422, PUSH_DEVICE_ERRORS[made.error]); | |
| 37 | return json(shown(made.value), 201); | |
| 38 | }); | |
| 39 | router.add("DELETE", "/api/v1/user/devices/:id", (ctx) => { | |
| 40 | const denied = requireScope(ctx, "rw"); | |
| 41 | if (denied) return denied; | |
| 42 | const user = ctx.auth.user!; | |
| 43 | if (user.kind === "agent") return apiError("forbidden", 403, "push devices are a person's, not an agent's"); | |
| 44 | return removePushDevice(ctx.app.db, user.id, ctx.params.id!) ? new Response(null, { status: 204 }) : notFound(); | |
| 45 | }); | |
| 46 | } |
src/http/lazy_lists.ts +3
| @@ -1218,6 +1218,9 @@ export const API_ROUTES = [ | ||
| 1218 | 1218 | ["GET", "/api/v1/user/assigned"], |
| 1219 | 1219 | ["GET", "/api/v1/user/next-steps"], |
| 1220 | 1220 | ["DELETE", "/api/v1/user/pins/:owner/:name"], |
| 1221 | ["GET", "/api/v1/user/devices"], | |
| 1222 | ["POST", "/api/v1/user/devices"], | |
| 1223 | ["DELETE", "/api/v1/user/devices/:id"], | |
| 1221 | 1224 | ["GET", "/api/v1/version"], |
| 1222 | 1225 | ["GET", "/api/v1/user/repos"], |
| 1223 | 1226 | ["GET", "/api/v1/admin/pinned"], |
src/main.ts +5 −2
| @@ -906,14 +906,16 @@ useSleepers(app, (name) => !childAwake(app, name)); | ||
| 906 | 906 | // that connected an account, the top comment on its latest Reel is told to |
| 907 | 907 | // the crew. A minute's clock; nothing leaves the box until a source exists. |
| 908 | 908 | // What newly asks a person reaches the phone they chose (docs/APPS.md). |
| 909 | const [prompts, notifier] = inert | |
| 910 | ? [inertHandle(), inertHandle()] | |
| 909 | const [prompts, notifier, pushWatch] = inert | |
| 910 | ? [inertHandle(), inertHandle(), inertHandle()] | |
| 911 | 911 | : await Promise.all([ |
| 912 | 912 | startService(app.log, "prompts", async () => |
| 913 | 913 | (await import("./crew/prompts.ts")).startPromptRoutine(app, { client: graphInstagram() })).then((h) => h ?? inertHandle()), |
| 914 | 914 | startService(app.log, "notifier", async () => (await import("./crew/notify.ts")).startNotifier(app, { forgeUrl })).then( |
| 915 | 915 | (h) => h ?? inertHandle(), |
| 916 | 916 | ), |
| 917 | // What blocks a person, and the silent refreshes, reach their Apple devices (#17926). | |
| 918 | startService(app.log, "push", async () => (await import("./push/watch.ts")).startPush(app)).then((h) => h ?? inertHandle()), | |
| 917 | 919 | ]); |
| 918 | 920 | |
| 919 | 921 | // The engine's duties (`engine/duties.ts`): webhook delivery, the estimates, the |
| @@ -1367,6 +1369,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> { | ||
| 1367 | 1369 | linger, |
| 1368 | 1370 | prompts.stop(), |
| 1369 | 1371 | notifier.stop(), |
| 1372 | pushWatch.stop(), | |
| 1370 | 1373 | crew?.stop({ drain: true, drainMs: drainBudgets(process.env).crewMs }), |
| 1371 | 1374 | // Routers still send this process requests for the linger's length; |
| 1372 | 1375 | // its apps answer them, and stop only after (#4496). |
src/push/apns.ts added +174
| @@ -0,0 +1,174 @@ | ||
| 1 | /** | |
| 2 | * The APNs sender (#17926): token-based auth with the team's .p8 key, one HTTP/2 request per | |
| 3 | * push to Apple's own host. The key, its id and the team id are forge secrets (`APNS_KEY`, | |
| 4 | * `APNS_KEY_ID`, `APNS_TEAM_ID`, sealed at the forge's scope), opened only here and never put | |
| 5 | * on an event, a log line or an answer. `fetch` speaks HTTP/1.1 only, which Apple refuses, so | |
| 6 | * the request goes through `node:http2`. The call leaves from the forge's own process: a private | |
| 7 | * or tailnet-only forge reaches Apple, and the phone hears it over Apple's network. | |
| 8 | * | |
| 9 | * `createApns` takes the transport and the clock as arguments, so a test sends to no one. | |
| 10 | */ | |
| 11 | ||
| 12 | import { connect } from "node:http2"; | |
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import type { EventBus } from "../core/events.ts"; | |
| 15 | import { resolveSecrets } from "../core/secret_store.ts"; | |
| 16 | import type { PushEnvironment } from "../core/push_devices.ts"; | |
| 17 | ||
| 18 | /** The app Apple knows this forge's phone app as. */ | |
| 19 | export const APNS_TOPIC = "sh.open-platform.forge"; | |
| 20 | export const APNS_HOSTS: Record<PushEnvironment, string> = { | |
| 21 | production: "api.push.apple.com", | |
| 22 | sandbox: "api.sandbox.push.apple.com", | |
| 23 | }; | |
| 24 | export const APNS_SECRETS = ["APNS_KEY", "APNS_KEY_ID", "APNS_TEAM_ID"] as const; | |
| 25 | /** A provider token is good for an hour; Apple refuses one refreshed more than every 20 minutes. */ | |
| 26 | const TOKEN_TTL_MS = 50 * 60_000; | |
| 27 | const SEND_TIMEOUT_MS = 8_000; | |
| 28 | /** Apple's limit on a payload; a Live Activity's is 4 KB too. */ | |
| 29 | export const PAYLOAD_MAX = 4096; | |
| 30 | ||
| 31 | export type PushType = "alert" | "background" | "liveactivity"; | |
| 32 | ||
| 33 | export interface ApnsRequest { | |
| 34 | readonly environment: PushEnvironment; | |
| 35 | readonly token: string; | |
| 36 | readonly pushType: PushType; | |
| 37 | readonly topic: string; | |
| 38 | /** 10 now, 5 when the system may choose its time (a silent push must say 5). */ | |
| 39 | readonly priority: 5 | 10; | |
| 40 | readonly collapseId?: string; | |
| 41 | /** The payload, already JSON text. */ | |
| 42 | readonly body: string; | |
| 43 | /** The provider token, a signed JWT. */ | |
| 44 | readonly authorization: string; | |
| 45 | } | |
| 46 | ||
| 47 | /** What Apple answered: its status and, for a refusal, its reason (`BadDeviceToken`). */ | |
| 48 | export interface ApnsAnswer { | |
| 49 | readonly status: number; | |
| 50 | readonly reason?: string; | |
| 51 | } | |
| 52 | export type ApnsTransport = (req: ApnsRequest) => Promise<ApnsAnswer>; | |
| 53 | ||
| 54 | export interface ApnsKey { | |
| 55 | readonly pem: string; | |
| 56 | readonly keyId: string; | |
| 57 | readonly teamId: string; | |
| 58 | } | |
| 59 | ||
| 60 | /** The forge's key, or undefined while any of the three secrets is missing (push is off). */ | |
| 61 | export function readApnsKey(db: Database, dataDir: string, bus: EventBus): ApnsKey | undefined { | |
| 62 | const got = resolveSecrets(db, dataDir, bus, APNS_SECRETS, { quiet: true, only: ["forge"] }); | |
| 63 | const [pem, keyId, teamId] = [got["APNS_KEY"], got["APNS_KEY_ID"], got["APNS_TEAM_ID"]]; | |
| 64 | return pem === undefined || keyId === undefined || teamId === undefined ? undefined : { pem, keyId, teamId }; | |
| 65 | } | |
| 66 | ||
| 67 | const b64url = (bytes: Uint8Array | string): string => | |
| 68 | Buffer.from(bytes).toString("base64url"); | |
| 69 | ||
| 70 | /** The provider token: an ES256 JWT of the key id and the team id, issued at `nowMs`. */ | |
| 71 | export async function providerToken(key: ApnsKey, nowMs: number): Promise<string> { | |
| 72 | const der = Buffer.from( | |
| 73 | key.pem.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, ""), | |
| 74 | "base64", | |
| 75 | ); | |
| 76 | const secret = await crypto.subtle.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, [ | |
| 77 | "sign", | |
| 78 | ]); | |
| 79 | const head = b64url(JSON.stringify({ alg: "ES256", kid: key.keyId })); | |
| 80 | const claims = b64url(JSON.stringify({ iss: key.teamId, iat: Math.floor(nowMs / 1000) })); | |
| 81 | // WebCrypto signs ECDSA as r||s, which is the form a JWT wants. | |
| 82 | const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, secret, Buffer.from(`${head}.${claims}`)); | |
| 83 | return `${head}.${claims}.${b64url(new Uint8Array(sig))}`; | |
| 84 | } | |
| 85 | ||
| 86 | /** The real transport: one HTTP/2 POST to Apple's host for the device's environment. */ | |
| 87 | export const http2Transport: ApnsTransport = (req) => | |
| 88 | new Promise((resolve, reject) => { | |
| 89 | const session = connect(`https://${APNS_HOSTS[req.environment]}`); | |
| 90 | const done = (fn: () => void): void => { | |
| 91 | session.close(); | |
| 92 | fn(); | |
| 93 | }; | |
| 94 | // A silent Apple ends the call at the deadline, with no timer of ours to keep. | |
| 95 | const deadline = AbortSignal.timeout(SEND_TIMEOUT_MS); | |
| 96 | deadline.addEventListener( | |
| 97 | "abort", | |
| 98 | () => { | |
| 99 | session.destroy(); | |
| 100 | reject(new Error("apns timed out")); | |
| 101 | }, | |
| 102 | { once: true }, | |
| 103 | ); | |
| 104 | session.on("error", (error) => done(() => reject(error))); | |
| 105 | const stream = session.request({ | |
| 106 | ":method": "POST", | |
| 107 | ":path": `/3/device/${req.token}`, | |
| 108 | authorization: `bearer ${req.authorization}`, | |
| 109 | "apns-push-type": req.pushType, | |
| 110 | "apns-topic": req.topic, | |
| 111 | "apns-priority": String(req.priority), | |
| 112 | ...(req.collapseId === undefined ? {} : { "apns-collapse-id": req.collapseId }), | |
| 113 | "content-type": "application/json", | |
| 114 | }); | |
| 115 | let status = 0; | |
| 116 | let text = ""; | |
| 117 | stream.on("response", (headers) => { | |
| 118 | status = Number(headers[":status"] ?? 0); | |
| 119 | }); | |
| 120 | stream.setEncoding("utf8"); | |
| 121 | stream.on("data", (chunk: string) => { | |
| 122 | if (text.length < 1024) text += chunk; | |
| 123 | }); | |
| 124 | stream.on("error", (error) => done(() => reject(error))); | |
| 125 | stream.on("end", () => | |
| 126 | done(() => { | |
| 127 | let reason: string | undefined; | |
| 128 | try { | |
| 129 | reason = (JSON.parse(text) as { reason?: string }).reason; | |
| 130 | } catch { | |
| 131 | reason = undefined; | |
| 132 | } | |
| 133 | resolve(reason === undefined ? { status } : { status, reason }); | |
| 134 | }), | |
| 135 | ); | |
| 136 | stream.end(req.body); | |
| 137 | }); | |
| 138 | ||
| 139 | /** What a refusal means for the token: Apple says it is gone or was never this app's. */ | |
| 140 | export const tokenIsDead = (answer: ApnsAnswer): boolean => | |
| 141 | answer.status === 410 || | |
| 142 | (answer.status === 400 && (answer.reason === "BadDeviceToken" || answer.reason === "DeviceTokenNotForTopic")); | |
| 143 | ||
| 144 | export interface Apns { | |
| 145 | /** Whether the forge holds a key: without one nothing is sent. */ | |
| 146 | readonly on: () => boolean; | |
| 147 | /** Send one push; undefined when push is off or the request cannot be made. */ | |
| 148 | readonly send: (req: Omit<ApnsRequest, "authorization" | "topic"> & { topic?: string }) => Promise<ApnsAnswer | undefined>; | |
| 149 | } | |
| 150 | ||
| 151 | export interface ApnsOptions { | |
| 152 | readonly key: () => ApnsKey | undefined; | |
| 153 | readonly transport?: ApnsTransport; | |
| 154 | readonly now?: () => number; | |
| 155 | } | |
| 156 | ||
| 157 | /** A sender that signs with the forge's key, keeping the provider token for most of its hour. */ | |
| 158 | export function createApns(options: ApnsOptions): Apns { | |
| 159 | const transport = options.transport ?? http2Transport; | |
| 160 | const now = options.now ?? Date.now; | |
| 161 | let cached: { readonly for: string; readonly at: number; readonly token: string } | undefined; | |
| 162 | return { | |
| 163 | on: () => options.key() !== undefined, | |
| 164 | async send(req) { | |
| 165 | const key = options.key(); | |
| 166 | if (key === undefined || Buffer.byteLength(req.body) > PAYLOAD_MAX) return undefined; | |
| 167 | const at = now(); | |
| 168 | const identity = `${key.keyId}:${key.teamId}:${key.pem.length}`; | |
| 169 | if (cached === undefined || cached.for !== identity || at - cached.at > TOKEN_TTL_MS) | |
| 170 | cached = { for: identity, at, token: await providerToken(key, at) }; | |
| 171 | return transport({ ...req, topic: req.topic ?? APNS_TOPIC, authorization: cached.token }); | |
| 172 | }, | |
| 173 | }; | |
| 174 | } |
src/push/payload.ts added +61
| @@ -0,0 +1,61 @@ | ||
| 1 | /** | |
| 2 | * What a push says (#17926): plain data in, the JSON text Apple is sent out. An alert is the only | |
| 3 | * push that makes a sound; a widget reload and a Live Activity update are silent. Every string is | |
| 4 | * cut to a short line first, so a payload stays well under Apple's 4 KB. | |
| 5 | */ | |
| 6 | ||
| 7 | import { APNS_TOPIC, PAYLOAD_MAX } from "./apns.ts"; | |
| 8 | ||
| 9 | /** The topic a Live Activity push goes to. */ | |
| 10 | export const LIVE_ACTIVITY_TOPIC = `${APNS_TOPIC}.push-type.liveactivity`; | |
| 11 | /** The Swift type of the activity the phone app starts from a push. */ | |
| 12 | export const ACTIVITY_ATTRIBUTES_TYPE = "ForgeRunAttributes"; | |
| 13 | const LINE_MAX = 140; | |
| 14 | ||
| 15 | const oneLine = (s: string): string => | |
| 16 | // eslint-disable-next-line no-control-regex | |
| 17 | s.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, LINE_MAX); | |
| 18 | ||
| 19 | /** What a Live Activity shows of a run. */ | |
| 20 | export interface RunState { | |
| 21 | readonly runId: string; | |
| 22 | readonly kind: string; | |
| 23 | readonly state: string; | |
| 24 | /** The app, as owner/name. */ | |
| 25 | readonly repo: string; | |
| 26 | } | |
| 27 | ||
| 28 | const unlessBig = (payload: object): string => { | |
| 29 | const text = JSON.stringify(payload); | |
| 30 | if (Buffer.byteLength(text) > PAYLOAD_MAX) throw new Error("push payload over 4 KB"); | |
| 31 | return text; | |
| 32 | }; | |
| 33 | ||
| 34 | /** A visible alert; `link` is the path the app opens. */ | |
| 35 | export const alertPayload = (title: string, body: string, link: string, thread: string): string => | |
| 36 | unlessBig({ | |
| 37 | aps: { alert: { title: oneLine(title), body: oneLine(body) }, sound: "default", "thread-id": oneLine(thread) }, | |
| 38 | link: oneLine(link), | |
| 39 | }); | |
| 40 | ||
| 41 | /** A silent push that lets the widget reload its timeline. */ | |
| 42 | export const widgetPayload = (): string => unlessBig({ aps: { "content-available": 1 } }); | |
| 43 | ||
| 44 | const contentState = (run: RunState) => ({ runId: run.runId, kind: run.kind, state: run.state, repo: oneLine(run.repo) }); | |
| 45 | ||
| 46 | /** An update (or the end) of a running Live Activity. */ | |
| 47 | export const activityPayload = (run: RunState, event: "update" | "end", nowSec: number): string => | |
| 48 | unlessBig({ aps: { timestamp: nowSec, event, "content-state": contentState(run) } }); | |
| 49 | ||
| 50 | /** The start of a Live Activity, by push-to-start. */ | |
| 51 | export const activityStartPayload = (run: RunState, nowSec: number): string => | |
| 52 | unlessBig({ | |
| 53 | aps: { | |
| 54 | timestamp: nowSec, | |
| 55 | event: "start", | |
| 56 | "content-state": contentState(run), | |
| 57 | "attributes-type": ACTIVITY_ATTRIBUTES_TYPE, | |
| 58 | attributes: { runId: run.runId, repo: oneLine(run.repo) }, | |
| 59 | alert: { title: oneLine(`${run.kind} started`), body: oneLine(run.repo) }, | |
| 60 | }, | |
| 61 | }); |
src/push/watch.ts added +198
| @@ -0,0 +1,198 @@ | ||
| 1 | /** | |
| 2 | * Pushing to Apple devices on what the forge's events say (#17926). The bus is the one the home | |
| 3 | * stream rides; only what blocks a person becomes an alert: a pull that needs their review (the | |
| 4 | * asks panel's own `review`, `look` and `handover` rows, told once each), an ask of theirs that | |
| 5 | * was answered, a check they started that failed. Everything else is silent: a widget reload for | |
| 6 | * whoever can read the repository the event is about, and a Live Activity update for the run an | |
| 7 | * activity follows (a person's own run may also start one, by push-to-start). | |
| 8 | * | |
| 9 | * Nothing here blocks the event: the work runs after it, in order, and a push that cannot be | |
| 10 | * sent is dropped, never queued. A person in focus (`crew/focus.ts`) hears no alert, at most | |
| 11 | * `HOURLY` an hour. A token Apple calls dead is forgotten. With no key in the forge's secrets | |
| 12 | * nothing is sent at all. | |
| 13 | */ | |
| 14 | ||
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { type PushDevice, allPushDevices, forgetPushDevice } from "../core/push_devices.ts"; | |
| 17 | import { type ForgeEvent } from "../core/events.ts"; | |
| 18 | import { canRead, getRepoById } from "../core/repos.ts"; | |
| 19 | import { getRun } from "../core/runs.ts"; | |
| 20 | import { getUserById, getUserByName } from "../core/users.ts"; | |
| 21 | import { inFocus } from "../crew/focus.ts"; | |
| 22 | import { background } from "../perf/jobs.ts"; | |
| 23 | import { askLinesFor } from "../web/studio/asks.ts"; | |
| 24 | import { type Apns, type ApnsAnswer, createApns, readApnsKey, tokenIsDead } from "./apns.ts"; | |
| 25 | import { | |
| 26 | LIVE_ACTIVITY_TOPIC, | |
| 27 | type RunState, | |
| 28 | activityPayload, | |
| 29 | activityStartPayload, | |
| 30 | alertPayload, | |
| 31 | widgetPayload, | |
| 32 | } from "./payload.ts"; | |
| 33 | ||
| 34 | const HOURLY = 10; | |
| 35 | const HOUR_MS = 3_600_000; | |
| 36 | const WIDGET_GAP_MS = 30_000; | |
| 37 | /** The asks that wait on a person's review. */ | |
| 38 | const REVIEW_ASKS = new Set(["review", "look", "handover"]); | |
| 39 | ||
| 40 | /** Events after which what a widget shows, or what asks a person, may have changed. */ | |
| 41 | const WAKES = new Set([ | |
| 42 | "run.finished", | |
| 43 | "pull.opened", | |
| 44 | "pull.pushed", | |
| 45 | "pull.ready", | |
| 46 | "pull.reviewed", | |
| 47 | "pull.merged", | |
| 48 | "pull.closed", | |
| 49 | "issue.closed", | |
| 50 | "issue.commented", | |
| 51 | "ask.done", | |
| 52 | "ask.put_aside", | |
| 53 | ]); | |
| 54 | ||
| 55 | export interface PushWatch { | |
| 56 | /** Resolves when the work queued so far is done. For tests and shutdown. */ | |
| 57 | settled(): Promise<void>; | |
| 58 | stop(): void; | |
| 59 | } | |
| 60 | ||
| 61 | export interface PushOptions { | |
| 62 | readonly apns?: Apns; | |
| 63 | readonly now?: () => number; | |
| 64 | } | |
| 65 | ||
| 66 | export function startPush(app: App, options: PushOptions = {}): PushWatch { | |
| 67 | const now = options.now ?? Date.now; | |
| 68 | const apns = | |
| 69 | options.apns ?? createApns({ key: () => readApnsKey(app.db, app.config.dataDir, app.bus) }); | |
| 70 | /** Per person: the review asks last seen, so only a new one is told. */ | |
| 71 | const seen = new Map<string, Set<string>>(); | |
| 72 | const told = new Map<string, number[]>(); | |
| 73 | const widgetAt = new Map<string, number>(); | |
| 74 | let queue: Promise<void> = Promise.resolve(); | |
| 75 | let stopped = false; | |
| 76 | ||
| 77 | /** Send and, when Apple says the token is gone, forget it. */ | |
| 78 | const deliver = async ( | |
| 79 | d: PushDevice, | |
| 80 | req: { pushType: "alert" | "background" | "liveactivity"; priority: 5 | 10; body: string; topic?: string; collapseId?: string }, | |
| 81 | ): Promise<ApnsAnswer | undefined> => { | |
| 82 | try { | |
| 83 | const answer = await apns.send({ environment: d.environment, token: d.token, ...req }); | |
| 84 | if (answer !== undefined && tokenIsDead(answer)) forgetPushDevice(app.db, d.id); | |
| 85 | else if (answer !== undefined && answer.status !== 200) | |
| 86 | app.log.warn("apns refused a push", { status: answer.status, reason: answer.reason ?? "" }); | |
| 87 | return answer; | |
| 88 | } catch (error) { | |
| 89 | // The key and the token are not in the message. | |
| 90 | app.log.warn("apns push failed", { error: String(error).slice(0, 200) }); | |
| 91 | return undefined; | |
| 92 | } | |
| 93 | }; | |
| 94 | ||
| 95 | const alert = async (devices: readonly PushDevice[], userId: string, title: string, body: string, link: string, thread: string) => { | |
| 96 | const mine = devices.filter((d) => d.userId === userId && d.kind === "alert"); | |
| 97 | if (mine.length === 0 || inFocus(app.db, userId, now())) return; | |
| 98 | const recent = (told.get(userId) ?? []).filter((at) => now() - at < HOUR_MS); | |
| 99 | if (recent.length >= HOURLY) return; | |
| 100 | told.set(userId, [...recent, now()]); | |
| 101 | const payload = alertPayload(title, body, link, thread); | |
| 102 | await Promise.all(mine.map((d) => deliver(d, { pushType: "alert", priority: 10, body: payload }))); | |
| 103 | }; | |
| 104 | ||
| 105 | const reviewAlerts = async (devices: readonly PushDevice[]) => { | |
| 106 | for (const userId of new Set(devices.filter((d) => d.kind === "alert").map((d) => d.userId))) { | |
| 107 | const user = getUserById(app.db, userId); | |
| 108 | if (user === undefined || user.kind !== "user") continue; | |
| 109 | const lines = askLinesFor(app.db, user).filter((l) => REVIEW_ASKS.has(l.kind)); | |
| 110 | const before = seen.get(userId); | |
| 111 | seen.set(userId, new Set(lines.map((l) => l.id))); | |
| 112 | // The first look only learns what already waits: a new device is no news. | |
| 113 | if (before === undefined) continue; | |
| 114 | for (const line of lines) | |
| 115 | if (!before.has(line.id)) await alert(devices, userId, "Needs your review", line.line, line.link, line.repo); | |
| 116 | } | |
| 117 | }; | |
| 118 | ||
| 119 | const widgets = async (devices: readonly PushDevice[], event: ForgeEvent) => { | |
| 120 | if (event.repoId === null) return; | |
| 121 | const repo = getRepoById(app.db, event.repoId); | |
| 122 | if (repo === undefined) return; | |
| 123 | for (const d of devices) { | |
| 124 | if (d.kind !== "widget" || now() - (widgetAt.get(d.userId) ?? 0) < WIDGET_GAP_MS) continue; | |
| 125 | const user = getUserById(app.db, d.userId); | |
| 126 | if (user === undefined || !canRead(app.db, repo, user)) continue; | |
| 127 | widgetAt.set(d.userId, now()); | |
| 128 | await deliver(d, { pushType: "background", priority: 5, body: widgetPayload(), collapseId: "widget" }); | |
| 129 | } | |
| 130 | }; | |
| 131 | ||
| 132 | const runState = (event: ForgeEvent): RunState | undefined => { | |
| 133 | const p = event.payload; | |
| 134 | const repo = event.repoId === null ? undefined : getRepoById(app.db, event.repoId); | |
| 135 | if (typeof p["runId"] !== "string" || typeof p["kind"] !== "string" || typeof p["state"] !== "string" || repo === undefined) return undefined; | |
| 136 | return { runId: p["runId"], kind: p["kind"], state: p["state"], repo: `${repo.ownerName}/${repo.name}` }; | |
| 137 | }; | |
| 138 | ||
| 139 | const activities = async (devices: readonly PushDevice[], event: ForgeEvent) => { | |
| 140 | const run = runState(event); | |
| 141 | if (run === undefined) return; | |
| 142 | const nowSec = Math.floor(now() / 1000); | |
| 143 | const ended = event.kind === "run.finished"; | |
| 144 | // Registration takes any `run:<id>` text, so the device's owner must still read the repository. | |
| 145 | const repo = event.repoId === null ? undefined : getRepoById(app.db, event.repoId); | |
| 146 | const mayRead = (userId: string): boolean => { | |
| 147 | const user = getUserById(app.db, userId); | |
| 148 | return repo !== undefined && user !== undefined && canRead(app.db, repo, user); | |
| 149 | }; | |
| 150 | for (const d of devices) | |
| 151 | if (d.kind === "liveactivity" && d.activity === `run:${run.runId}` && mayRead(d.userId)) | |
| 152 | await deliver(d, { pushType: "liveactivity", priority: 10, topic: LIVE_ACTIVITY_TOPIC, body: activityPayload(run, ended ? "end" : "update", nowSec) }); | |
| 153 | // A person's own run may start an activity on their phone. | |
| 154 | if (event.kind !== "run.started") return; | |
| 155 | const owner = getRun(app.db, run.runId)?.actorId; | |
| 156 | if (owner === null || owner === undefined) return; | |
| 157 | for (const d of devices) | |
| 158 | if (d.kind === "liveactivity-start" && d.userId === owner && mayRead(d.userId)) | |
| 159 | await deliver(d, { pushType: "liveactivity", priority: 10, topic: LIVE_ACTIVITY_TOPIC, body: activityStartPayload(run, nowSec) }); | |
| 160 | }; | |
| 161 | ||
| 162 | const handle = async (event: ForgeEvent): Promise<void> => { | |
| 163 | if (stopped || !(event.kind.startsWith("run.") || WAKES.has(event.kind))) return; | |
| 164 | const devices = allPushDevices(app.db); | |
| 165 | if (devices.length === 0 || !apns.on()) return; | |
| 166 | if (event.kind.startsWith("run.")) await activities(devices, event); | |
| 167 | if (!WAKES.has(event.kind)) return; | |
| 168 | const p = event.payload; | |
| 169 | if (event.kind === "run.finished" && p["kind"] === "check" && p["state"] === "failed" && typeof p["runId"] === "string") { | |
| 170 | const run = getRun(app.db, p["runId"]); | |
| 171 | const who = run?.actorId == null ? undefined : getUserById(app.db, run.actorId); | |
| 172 | const repo = event.repoId === null ? undefined : getRepoById(app.db, event.repoId); | |
| 173 | if (run !== undefined && who?.kind === "user" && repo !== undefined) { | |
| 174 | const name = `${repo.ownerName}/${repo.name}`; | |
| 175 | await alert(devices, who.id, "A check you started failed", name, `/${name}/runs/${run.id}`, name); | |
| 176 | } | |
| 177 | } | |
| 178 | if ((event.kind === "ask.done" || event.kind === "ask.put_aside") && typeof p["want"] === "string") { | |
| 179 | // `ask.done` is the asker's own; `ask.put_aside` names the asker, the actor is who answered. | |
| 180 | const asker = event.kind === "ask.done" ? (event.actorId === null ? undefined : getUserById(app.db, event.actorId)) : typeof p["who"] === "string" ? getUserByName(app.db, p["who"]) : undefined; | |
| 181 | if (asker?.kind === "user") | |
| 182 | await alert(devices, asker.id, "Your ask has an answer", event.kind === "ask.done" ? "It is done." : "Not now.", "/", "asks"); | |
| 183 | } | |
| 184 | await reviewAlerts(devices); | |
| 185 | await widgets(devices, event); | |
| 186 | }; | |
| 187 | ||
| 188 | const off = app.bus.subscribe((event) => { | |
| 189 | queue = queue.then(() => background("push", () => handle(event), undefined, app)); | |
| 190 | }); | |
| 191 | return { | |
| 192 | settled: () => queue, | |
| 193 | stop: () => { | |
| 194 | stopped = true; | |
| 195 | off(); | |
| 196 | }, | |
| 197 | }; | |
| 198 | } |
test/job-slices.test.ts +1
| @@ -300,6 +300,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 300 | 300 | * on. |
| 301 | 301 | */ |
| 302 | 302 | const UNTIMED: Record<string, string> = { |
| 303 | "push": "one event's pushes to Apple (push/watch.ts): a few indexed reads, at most one askLinesFor per person with an alert device, and network answers that are not timed here; push-apns.test.ts drives it with a recording transport", | |
| 303 | 304 | "decider-shadow": "one call to a second decider after a decision is recorded (crew/snap.ts): a few indexed reads, one insert and a network answer, at most two at once; decider-shadow.test.ts drives it with a fake", |
| 304 | 305 | "decider-replay": "an admin's replay of at most 500 past decisions (crew/snap.ts): network answers and one insert each, two at once; decider-shadow.test.ts drives it with a fake", |
| 305 | 306 | "snapshot-gc": "one full Bun.gc(true) while a snapshot is cut (snapshot/settle.ts), as long as the process's own heap makes it, which a fixture's heap does not; snapshot-settle.test.ts drives it", |
test/push-apns.test.ts added +322
| @@ -0,0 +1,322 @@ | ||
| 1 | /** | |
| 2 | * Push to Apple devices (#17926): the device routes, the provider token, and what each event | |
| 3 | * sends (an alert only for what blocks a person, a silent push for the rest) to a transport | |
| 4 | * that records instead of dialling Apple. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createAgent } from "../src/actions/crew.ts"; | |
| 12 | import { announceRun } from "../src/actions/runs.ts"; | |
| 13 | import { openPull } from "../src/actions/pulls.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { listPushDevices, registerPushDevice } from "../src/core/push_devices.ts"; | |
| 18 | import type { Repo } from "../src/core/repos.ts"; | |
| 19 | import { claimRun, createRun, finishRun } from "../src/core/runs.ts"; | |
| 20 | import { setSecret } from "../src/core/secret_store.ts"; | |
| 21 | import { createUser, type User } from "../src/core/users.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | import { type ApnsRequest, type ApnsAnswer, createApns, providerToken, readApnsKey } from "../src/push/apns.ts"; | |
| 24 | import { startPush, type PushWatch } from "../src/push/watch.ts"; | |
| 25 | import { quietLogs } from "./helpers/globals.ts"; | |
| 26 | ||
| 27 | quietLogs(); | |
| 28 | ||
| 29 | const hex = (c: string, n = 64): string => c.repeat(n); | |
| 30 | const TOKEN_ALERT = hex("a"); | |
| 31 | const TOKEN_WIDGET = hex("b"); | |
| 32 | const TOKEN_START = hex("c"); | |
| 33 | const TOKEN_ACTIVITY = hex("d"); | |
| 34 | ||
| 35 | let dataDir: string; | |
| 36 | let app: App; | |
| 37 | let servers: Servers; | |
| 38 | let alice: User; | |
| 39 | let bob: User; | |
| 40 | let repo: Repo; | |
| 41 | let rw = ""; | |
| 42 | let ro = ""; | |
| 43 | let agent = ""; | |
| 44 | let cookie = ""; | |
| 45 | let watch: PushWatch; | |
| 46 | let publicKey: CryptoKey; | |
| 47 | const sent: ApnsRequest[] = []; | |
| 48 | let answer: ApnsAnswer = { status: 200 }; | |
| 49 | let clock = 1_000_000_000_000; | |
| 50 | ||
| 51 | const mkUser = async (username: string, first = false): Promise<User> => { | |
| 52 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 53 | if (!made.ok) throw new Error(String(made.error)); | |
| 54 | return made.value; | |
| 55 | }; | |
| 56 | ||
| 57 | const call = (method: string, path: string, token: string, body?: unknown, extra: Record<string, string> = {}) => | |
| 58 | fetch(`${servers.url}${path}`, { | |
| 59 | method, | |
| 60 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...extra }, | |
| 61 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 62 | }); | |
| 63 | ||
| 64 | beforeAll(async () => { | |
| 65 | dataDir = await mkdtemp(join(tmpdir(), "forge-push-")); | |
| 66 | app = createApp({ dataDir, port: 0 }); | |
| 67 | servers = await serve(app); | |
| 68 | alice = await mkUser("alice", true); | |
| 69 | bob = await mkUser("bob"); | |
| 70 | rw = createToken(app.db, alice.id, "w", "rw").token; | |
| 71 | ro = createToken(app.db, alice.id, "r", "ro").token; | |
| 72 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 73 | const bot = await createAgent(app, alice, { username: "bot" }); | |
| 74 | if (!bot.ok) throw new Error(String(bot.error)); | |
| 75 | agent = createToken(app.db, bot.value.user.id, "b", "admin").token; | |
| 76 | const made = await createRepo(app, alice, { name: "garden", visibility: "private" }); | |
| 77 | if (!made.ok) throw new Error(String(made.error)); | |
| 78 | repo = made.value; | |
| 79 | await commitToBranch(app, alice, repo, { message: "seed", files: [{ path: "README.md", content: "# garden\n" }] }); | |
| 80 | ||
| 81 | // A real P-256 key, in the PEM form Apple hands out. | |
| 82 | const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); | |
| 83 | publicKey = pair.publicKey; | |
| 84 | const der = Buffer.from(await crypto.subtle.exportKey("pkcs8", pair.privateKey)).toString("base64"); | |
| 85 | const dashes = "-".repeat(5); | |
| 86 | const pem = `${dashes}BEGIN PRIVATE KEY${dashes}\n${der.match(/.{1,64}/g)!.join("\n")}\n${dashes}END PRIVATE KEY${dashes}\n`; | |
| 87 | setSecret(app.db, dataDir, "forge", "", "APNS_KEY", pem); | |
| 88 | setSecret(app.db, dataDir, "forge", "", "APNS_KEY_ID", "KEYID12345"); | |
| 89 | setSecret(app.db, dataDir, "forge", "", "APNS_TEAM_ID", "ZRNBD82TC2"); | |
| 90 | watch = startPush(app, { | |
| 91 | now: () => clock, | |
| 92 | apns: createApns({ | |
| 93 | key: () => readApnsKey(app.db, dataDir, app.bus), | |
| 94 | now: () => clock, | |
| 95 | transport: async (req) => { | |
| 96 | sent.push(req); | |
| 97 | return answer; | |
| 98 | }, | |
| 99 | }), | |
| 100 | }); | |
| 101 | }); | |
| 102 | afterAll(async () => { | |
| 103 | watch.stop(); | |
| 104 | await servers.stop(); | |
| 105 | app.close(); | |
| 106 | await rm(dataDir, { recursive: true, force: true }); | |
| 107 | }); | |
| 108 | ||
| 109 | const register = (userId: string, token: string, kind: string, activity?: string) => { | |
| 110 | const made = registerPushDevice(app.db, userId, { token, platform: "apns", environment: "sandbox", kind, ...(activity === undefined ? {} : { activity }) }); | |
| 111 | if (!made.ok) throw new Error(made.error); | |
| 112 | return made.value; | |
| 113 | }; | |
| 114 | ||
| 115 | describe("device routes", () => { | |
| 116 | test("register, list without the token, remove; the same token again is the same device", async () => { | |
| 117 | const body = { token: TOKEN_ALERT.toUpperCase(), platform: "apns", environment: "production", kind: "alert" }; | |
| 118 | const first = await call("POST", "/api/v1/user/devices", rw, body); | |
| 119 | expect(first.status).toBe(201); | |
| 120 | const made = (await first.json()) as { id: string; token_tail: string; environment: string }; | |
| 121 | expect(made.token_tail).toBe("aaaaaa"); | |
| 122 | const again = await call("POST", "/api/v1/user/devices", rw, { ...body, environment: "sandbox" }); | |
| 123 | expect(((await again.json()) as { id: string }).id).toBe(made.id); | |
| 124 | const listed = await call("GET", "/api/v1/user/devices", ro); | |
| 125 | const text = await listed.text(); | |
| 126 | expect(text).not.toContain(TOKEN_ALERT); | |
| 127 | expect((JSON.parse(text) as { items: { environment: string }[] }).items).toHaveLength(1); | |
| 128 | expect((JSON.parse(text) as { items: { environment: string }[] }).items[0]!.environment).toBe("sandbox"); | |
| 129 | // Someone else's device is not found; a read-only token cannot remove; the owner can. | |
| 130 | const bobs = register(bob.id, hex("e"), "widget"); | |
| 131 | expect((await call("DELETE", `/api/v1/user/devices/${bobs.id}`, rw)).status).toBe(404); | |
| 132 | expect((await call("DELETE", `/api/v1/user/devices/${made.id}`, ro)).status).toBe(403); | |
| 133 | expect((await call("DELETE", `/api/v1/user/devices/${made.id}`, rw)).status).toBe(204); | |
| 134 | expect(listPushDevices(app.db, alice.id)).toHaveLength(0); | |
| 135 | expect(listPushDevices(app.db, bob.id)).toHaveLength(1); | |
| 136 | }); | |
| 137 | ||
| 138 | test("every field is checked; an agent and a cross-origin browser are refused", async () => { | |
| 139 | const ok = { token: TOKEN_ALERT, platform: "apns", environment: "sandbox", kind: "alert" }; | |
| 140 | for (const [bad, error] of [ | |
| 141 | [{ ...ok, token: "not hex" }, "invalid_token"], | |
| 142 | [{ ...ok, platform: "fcm" }, "invalid_platform"], | |
| 143 | [{ ...ok, environment: "prod" }, "invalid_environment"], | |
| 144 | [{ ...ok, kind: "banner" }, "invalid_kind"], | |
| 145 | [{ ...ok, activity: "run:1" }, "invalid_activity"], | |
| 146 | [{ ...ok, kind: "liveactivity", activity: "a b" }, "invalid_activity"], | |
| 147 | ] as const) { | |
| 148 | const res = await call("POST", "/api/v1/user/devices", rw, bad); | |
| 149 | expect(res.status).toBe(422); | |
| 150 | expect(JSON.stringify(await res.json())).toContain(error); | |
| 151 | } | |
| 152 | expect((await call("POST", "/api/v1/user/devices", ro, ok)).status).toBe(403); | |
| 153 | expect((await call("POST", "/api/v1/user/devices", agent, ok)).status).toBe(403); | |
| 154 | const cross = await fetch(`${servers.url}/api/v1/user/devices`, { | |
| 155 | method: "POST", | |
| 156 | headers: { cookie, origin: "https://evil.example", "content-type": "application/json" }, | |
| 157 | body: JSON.stringify(ok), | |
| 158 | }); | |
| 159 | expect(cross.status).toBe(403); | |
| 160 | expect(listPushDevices(app.db, alice.id)).toHaveLength(0); | |
| 161 | }); | |
| 162 | }); | |
| 163 | ||
| 164 | describe("the provider token", () => { | |
| 165 | test("is an ES256 JWT of the key id and team, signed by the key", async () => { | |
| 166 | const key = readApnsKey(app.db, dataDir, app.bus)!; | |
| 167 | const jwt = await providerToken(key, 1_700_000_000_000); | |
| 168 | const [head, claims, sig] = jwt.split(".") as [string, string, string]; | |
| 169 | expect(JSON.parse(Buffer.from(head, "base64url").toString())).toEqual({ alg: "ES256", kid: "KEYID12345" }); | |
| 170 | expect(JSON.parse(Buffer.from(claims, "base64url").toString())).toEqual({ iss: "ZRNBD82TC2", iat: 1_700_000_000 }); | |
| 171 | const signature = Buffer.from(sig, "base64url"); | |
| 172 | expect(signature.length).toBe(64); | |
| 173 | const valid = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicKey, signature, Buffer.from(`${head}.${claims}`)); | |
| 174 | expect(valid).toBe(true); | |
| 175 | }); | |
| 176 | }); | |
| 177 | ||
| 178 | describe("what events send", () => { | |
| 179 | /** A green pull, announced the way the checks worker announces it. */ | |
| 180 | async function greenPull(n: number, title: string): Promise<void> { | |
| 181 | const branch = await commitToBranch(app, alice, repo, { branch: `feature/n${n}`, base: "main", message: title, files: [{ path: `N${n}.md`, content: `${n}\n` }] }); | |
| 182 | if (!branch.ok) throw new Error(JSON.stringify(branch.error)); | |
| 183 | const opened = await openPull(app, alice, repo, { title, body: "", baseBranch: "main", headBranch: `feature/n${n}` }); | |
| 184 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 185 | const run = createRun(app.db, { repoId: repo.id, kind: "check", issueId: opened.value.id, env: `pull-${opened.value.number}`, commitOid: opened.value.headOid, reason: "pull" }); | |
| 186 | claimRun(app.db, run.id); | |
| 187 | announceRun(app, finishRun(app.db, run.id, { state: "ok", summary: "ok" })!); | |
| 188 | await watch.settled(); | |
| 189 | } | |
| 190 | const alerts = () => sent.filter((s) => s.pushType === "alert"); | |
| 191 | const bodyOf = (s: ApnsRequest) => JSON.parse(s.body) as { aps: Record<string, unknown>; link?: string }; | |
| 192 | ||
| 193 | test("a new review ask is one alert, told once; a widget gets a silent reload", async () => { | |
| 194 | register(alice.id, TOKEN_ALERT, "alert"); | |
| 195 | register(alice.id, TOKEN_WIDGET, "widget"); | |
| 196 | // The first look only learns what already waits: a new device is no news. | |
| 197 | app.bus.append({ kind: "issue.closed", repoId: repo.id, actorId: alice.id, payload: { number: 1 } }); | |
| 198 | await watch.settled(); | |
| 199 | expect(alerts()).toHaveLength(0); | |
| 200 | ||
| 201 | await greenPull(1, "Add a bench"); | |
| 202 | expect(alerts()).toHaveLength(1); | |
| 203 | const alert = alerts()[0]!; | |
| 204 | expect(alert.token).toBe(TOKEN_ALERT); | |
| 205 | expect(alert.priority).toBe(10); | |
| 206 | expect(bodyOf(alert).aps["alert"]).toMatchObject({ title: "Needs your review" }); | |
| 207 | expect(bodyOf(alert).link).toStartWith("/alice/garden"); | |
| 208 | expect(alert.authorization.split(".")).toHaveLength(3); | |
| 209 | ||
| 210 | const silent = sent.filter((s) => s.pushType === "background"); | |
| 211 | expect(silent).toHaveLength(1); | |
| 212 | expect(silent[0]!.priority).toBe(5); | |
| 213 | expect(silent[0]!.token).toBe(TOKEN_WIDGET); | |
| 214 | expect(bodyOf(silent[0]!)).toEqual({ aps: { "content-available": 1 } }); | |
| 215 | expect(silent[0]!.topic).toBe("sh.open-platform.forge"); | |
| 216 | expect(silent[0]!.environment).toBe("sandbox"); | |
| 217 | ||
| 218 | // The next pull is one more alert, not two: the first is not told again. | |
| 219 | await greenPull(2, "Add a table"); | |
| 220 | expect(alerts()).toHaveLength(2); | |
| 221 | // Bob has no device, so nothing went to anyone but Alice's. | |
| 222 | expect(alerts().every((s) => s.token === TOKEN_ALERT)).toBe(true); | |
| 223 | }); | |
| 224 | ||
| 225 | test("a check you started that failed is an alert; a check that passed is not", async () => { | |
| 226 | const before = alerts().length; | |
| 227 | const pass = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "1".repeat(40), reason: "push", actorId: alice.id }); | |
| 228 | claimRun(app.db, pass.id); | |
| 229 | announceRun(app, finishRun(app.db, pass.id, { state: "ok", summary: "ok" })!); | |
| 230 | await watch.settled(); | |
| 231 | expect(alerts()).toHaveLength(before); | |
| 232 | const red = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "2".repeat(40), reason: "push", actorId: alice.id }); | |
| 233 | claimRun(app.db, red.id); | |
| 234 | announceRun(app, finishRun(app.db, red.id, { state: "failed", summary: "tests failed" })!); | |
| 235 | await watch.settled(); | |
| 236 | expect(alerts()).toHaveLength(before + 1); | |
| 237 | expect(bodyOf(alerts().at(-1)!).aps["alert"]).toMatchObject({ title: "A check you started failed", body: "alice/garden" }); | |
| 238 | expect(bodyOf(alerts().at(-1)!).link).toBe(`/alice/garden/runs/${red.id}`); | |
| 239 | }); | |
| 240 | ||
| 241 | test("an ask that was answered reaches whoever asked, and nobody else", async () => { | |
| 242 | const before = alerts().length; | |
| 243 | app.bus.append({ kind: "ask.done", actorId: alice.id, payload: { want: "crew_key", subject: "alice" } }); | |
| 244 | await watch.settled(); | |
| 245 | expect(alerts()).toHaveLength(before + 1); | |
| 246 | expect(bodyOf(alerts().at(-1)!).aps["alert"]).toMatchObject({ title: "Your ask has an answer" }); | |
| 247 | app.bus.append({ kind: "ask.done", actorId: bob.id, payload: { want: "crew_key", subject: "bob" } }); | |
| 248 | await watch.settled(); | |
| 249 | expect(alerts()).toHaveLength(before + 1); | |
| 250 | }); | |
| 251 | ||
| 252 | test("a run starts and updates a Live Activity, silently, to the activity topic", async () => { | |
| 253 | register(alice.id, TOKEN_START, "liveactivity-start"); | |
| 254 | const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "3".repeat(40), reason: "push", actorId: alice.id }); | |
| 255 | register(alice.id, TOKEN_ACTIVITY, "liveactivity", `run:${run.id}`); | |
| 256 | const before = sent.length; | |
| 257 | const running = claimRun(app.db, run.id)!; | |
| 258 | announceRun(app, running); | |
| 259 | await watch.settled(); | |
| 260 | const fresh = sent.slice(before).filter((s) => s.pushType === "liveactivity"); | |
| 261 | expect(fresh.map((s) => s.token).sort()).toEqual([TOKEN_START, TOKEN_ACTIVITY].sort()); | |
| 262 | for (const s of fresh) { | |
| 263 | expect(s.topic).toBe("sh.open-platform.forge.push-type.liveactivity"); | |
| 264 | expect(Buffer.byteLength(s.body)).toBeLessThan(4096); | |
| 265 | } | |
| 266 | const start = bodyOf(fresh.find((s) => s.token === TOKEN_START)!); | |
| 267 | expect(start.aps["event"]).toBe("start"); | |
| 268 | const update = bodyOf(fresh.find((s) => s.token === TOKEN_ACTIVITY)!); | |
| 269 | expect(update.aps["event"]).toBe("update"); | |
| 270 | expect(update.aps["content-state"]).toMatchObject({ runId: run.id, state: "running", repo: "alice/garden" }); | |
| 271 | const mid = sent.length; | |
| 272 | announceRun(app, finishRun(app.db, run.id, { state: "ok", summary: "ok" })!); | |
| 273 | await watch.settled(); | |
| 274 | const ended = sent.slice(mid).find((s) => s.token === TOKEN_ACTIVITY)!; | |
| 275 | expect(bodyOf(ended).aps["event"]).toBe("end"); | |
| 276 | }); | |
| 277 | ||
| 278 | test("a person who cannot read a run's repository hears nothing of it", async () => { | |
| 279 | const spy = hex("e"); | |
| 280 | const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "6".repeat(40), reason: "push", actorId: alice.id }); | |
| 281 | register(bob.id, spy, "liveactivity", `run:${run.id}`); | |
| 282 | const before = sent.length; | |
| 283 | announceRun(app, claimRun(app.db, run.id)!); | |
| 284 | await watch.settled(); | |
| 285 | expect(sent.slice(before).some((s) => s.token === spy)).toBe(false); | |
| 286 | }); | |
| 287 | ||
| 288 | test("a dead answer forgets the device sent to, not the token under another account", async () => { | |
| 289 | const shared = hex("f"); | |
| 290 | register(alice.id, shared, "widget"); | |
| 291 | register(bob.id, shared, "widget"); | |
| 292 | answer = { status: 400, reason: "BadDeviceToken" }; | |
| 293 | clock += 120_000; | |
| 294 | const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "7".repeat(40), reason: "push", actorId: alice.id }); | |
| 295 | claimRun(app.db, run.id); | |
| 296 | announceRun(app, finishRun(app.db, run.id, { state: "ok", summary: "ok" })!); | |
| 297 | await watch.settled(); | |
| 298 | answer = { status: 200 }; | |
| 299 | expect(listPushDevices(app.db, bob.id).some((d) => d.token === shared)).toBe(true); | |
| 300 | }); | |
| 301 | ||
| 302 | test("a token Apple calls dead is forgotten; with no key nothing is sent", async () => { | |
| 303 | answer = { status: 410, reason: "Unregistered" }; | |
| 304 | clock += 120_000; | |
| 305 | const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "4".repeat(40), reason: "push", actorId: alice.id }); | |
| 306 | claimRun(app.db, run.id); | |
| 307 | announceRun(app, finishRun(app.db, run.id, { state: "ok", summary: "ok" })!); | |
| 308 | await watch.settled(); | |
| 309 | expect(listPushDevices(app.db, alice.id).some((d) => d.token === TOKEN_WIDGET)).toBe(false); | |
| 310 | answer = { status: 200 }; | |
| 311 | ||
| 312 | app.db.query("DELETE FROM secret WHERE name = 'APNS_KEY'").run(); | |
| 313 | register(alice.id, TOKEN_WIDGET, "widget"); | |
| 314 | clock += 120_000; | |
| 315 | const before = sent.length; | |
| 316 | const quiet = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "5".repeat(40), reason: "push", actorId: alice.id }); | |
| 317 | claimRun(app.db, quiet.id); | |
| 318 | announceRun(app, finishRun(app.db, quiet.id, { state: "failed", summary: "red" })!); | |
| 319 | await watch.settled(); | |
| 320 | expect(sent).toHaveLength(before); | |
| 321 | }); | |
| 322 | }); |
test/route-timing-coverage.test.ts +1
| @@ -31,6 +31,7 @@ const UNTIMED: Record<string, string> = { | ||
| 31 | 31 | "/api/v1/repos/:owner/:name/app/registry/updates": "an app's items behind the registry, one indexed read and a catalogue compare; no page to phase", |
| 32 | 32 | "/api/v1/admin/plans": "an admin's plans with the measured median, two indexed reads; no page to phase", |
| 33 | 33 | "/api/v1/admin/infra/code": "each app's infra.json read from its repo's main branch (cached per tip) and diffed read-only; no page to phase", |
| 34 | "/api/v1/user/devices": "a person's own Apple devices, one indexed read; no page to phase", | |
| 34 | 35 | "/metrics": "Prometheus text exposition, scraped by token; not a page read", |
| 35 | 36 | }; |
| 36 | 37 |
test/snapshot-stream.test.ts +13 −5
| @@ -18,7 +18,7 @@ import { restoreHostedInto, restoreSnapshot } from "../src/snapshot/restore.ts"; | ||
| 18 | 18 | import { startCutter, type Cutter } from "../src/snapshot/cut.ts"; |
| 19 | 19 | import { startSnapshots } from "../src/snapshot/service.ts"; |
| 20 | 20 | import { CHUNK_PREFIX } from "../src/snapshot/chunks.ts"; |
| 21 | import { listSnapshots, pruneSnapshots, streamManifestKey, takeSnapshot, type ChunkView } from "../src/snapshot/snapshot.ts"; | |
| 21 | import { chunksNamed, listSnapshots, pruneSnapshots, storedChunk, streamManifestKey, takeSnapshot, type ChunkView, type Manifest } from "../src/snapshot/snapshot.ts"; | |
| 22 | 22 | import { readStream, STREAM_LATE_MS, streamLag, streamPass } from "../src/snapshot/stream.ts"; |
| 23 | 23 | import type { Ctx } from "../src/http/context.ts"; |
| 24 | 24 | import { tool as systemTool } from "../src/http/mcp/tools/system.ts"; |
| @@ -280,18 +280,26 @@ describe("the stream of hosted forges", () => { | ||
| 280 | 280 | test("a view that claims a chunk the store lost writes no manifest, and the next forge lists afresh (#17851)", async () => { |
| 281 | 281 | const store = dirStore(join(root, `store-${n++}`)); |
| 282 | 282 | await takeSnapshot({ ...shape(), stream: "kid" }, store); |
| 283 | // Some chunks change with every snapshot and are sent again regardless: lose only those two | |
| 284 | // passes both name, which a third pass names too. | |
| 285 | const named = async () => new Set(chunksNamed(JSON.parse(new TextDecoder().decode((await store.get(streamManifestKey("kid")))!)) as Manifest)); | |
| 286 | const first = await named(); | |
| 287 | await takeSnapshot({ ...shape(), stream: "kid" }, store); | |
| 283 | 288 | const before = await store.get(streamManifestKey("kid")); |
| 289 | const second = await named(); | |
| 284 | 290 | const keys = await store.list(CHUNK_PREFIX); |
| 285 | const gone = keys[0]!; | |
| 286 | const body = (await store.get(gone))!; | |
| 287 | await store.delete(gone); | |
| 291 | const lost = await Promise.all([...second].filter((id) => first.has(id)).map((id) => storedChunk(store, id))); | |
| 292 | expect(lost.length).toBeGreaterThan(0); | |
| 293 | const bodies = new Map<string, Uint8Array>(); | |
| 294 | for (const k of lost) bodies.set(k, (await store.get(k))!); | |
| 295 | for (const k of lost) await store.delete(k); | |
| 288 | 296 | // The view still names it, so the forge does not send it again: the fresh check finds it gone. |
| 289 | 297 | const chunks: ChunkView = { keys: new Set(keys) }; |
| 290 | 298 | await expect(takeSnapshot({ ...shape(), stream: "kid", chunks }, store)).rejects.toThrow("no manifest written"); |
| 291 | 299 | expect(new TextDecoder().decode((await store.get(streamManifestKey("kid")))!)).toBe(new TextDecoder().decode(before!)); |
| 292 | 300 | expect(chunks.keys).toBeUndefined(); |
| 293 | 301 | await takeSnapshot({ ...shape(), stream: "kid", chunks }, store); |
| 294 | expect(await store.get(gone)).toEqual(body); | |
| 302 | for (const [k, body] of bodies) expect(await store.get(k)).toEqual(body); | |
| 295 | 303 | expect((await restoreHostedInto(store, "stream", "kid", join(root, "after-lost"), { passphrase: PASS })).repos).toBe(1); |
| 296 | 304 | }); |
| 297 | 305 |
new above
offline
High: no check that
d.userIdmay read this run's repository. Any registeredrun:<id>receives the repo name and state of a private repo. Add thecanReadcheck here (and a test with a second user).