diff --git a/apps/server/scripts/kin-push-test.ts b/apps/server/scripts/kin-push-test.ts index 05fad0b38df10..2f6c45ed61e5d 100644 --- a/apps/server/scripts/kin-push-test.ts +++ b/apps/server/scripts/kin-push-test.ts @@ -1,14 +1,23 @@ #!/usr/bin/env node // Dev only: one test push through the server's own APNs transport. From apps/server, with the -// KIN_APNS_* variables set: node scripts/kin-push-test.ts [development|production] +// KIN_APNS_* variables set: +// node scripts/kin-push-test.ts [development|production] // The mobile spec's "Test push" step has the full runbook. import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import { KinApsEnvironment, KinPushData, KinPushToken } from "@t3tools/contracts"; +import { + EnvironmentId, + KinApsEnvironment, + KinChatId, + KinOrgId, + KinPushData, + KinPushToken, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { KinApnsTransport, layer } from "../src/kin/push/Apns.ts"; import { kinPushDeviceId } from "../src/kin/push/KinPushDevices.ts"; +import { kinPushChatLink } from "../src/kin/push/KinPushSender.ts"; class KinPushTestError extends Schema.TaggedError()("KinPushTestError", { message: Schema.String, @@ -16,19 +25,26 @@ class KinPushTestError extends Schema.TaggedError()("KinPushTe const decodeToken = Schema.decodeUnknownEffect(KinPushToken); const decodeEnvironment = Schema.decodeUnknownEffect(KinApsEnvironment); +const decodeEnvironmentId = Schema.decodeUnknownEffect(EnvironmentId); const decodeData = Schema.decodeEffect(KinPushData); const program = Effect.gen(function* () { - const [rawToken, rawEnvironment = "development"] = process.argv.slice(2); + const [rawToken, rawEnvironmentId, rawEnvironment = "development"] = process.argv.slice(2); + if (rawEnvironmentId === "development" || rawEnvironmentId === "production") + return yield* new KinPushTestError({ + message: "The second argument is the host environment id; the APNs environment is third.", + }); const token = yield* decodeToken(rawToken?.toLowerCase()); + const environmentId = yield* decodeEnvironmentId(rawEnvironmentId); const environment = yield* decodeEnvironment(rawEnvironment); const apns = yield* KinApnsTransport; if (apns.status === "unconfigured") return yield* new KinPushTestError({ message: "APNs isn't configured; see the log above." }); + const orgId = KinOrgId.make("kin-default"); const body = yield* decodeData({ kin: 1, - orgId: "kin-default", - deepLink: "/kin/kin-default/chats/test", + orgId, + deepLink: kinPushChatLink(environmentId, orgId, KinChatId.make("test")), }); const result = yield* apns.send({ token, diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts index a4c09c209f160..87336b6debfa0 100644 --- a/apps/server/src/kin/push/KinPushDevices.ts +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -124,7 +125,8 @@ const make = Effect.gen(function* () { return yield* sql.withTransaction( Effect.gen(function* () { // A phone re-registers on every connect, which also moves the row to its current session. - // Someone else's token moves only once reconcile would drop it, or its session is gone. + // Someone else's token moves only once reconcile would drop it, its session is gone, or + // the same proof key re-pairs after that session expired. `auth_sessions` keeps expired rows. const saved = yield* sql`INSERT INTO kin_push_devices ${sql.insert({ org_id: input.orgId, token: input.token, @@ -147,9 +149,15 @@ const make = Effect.gen(function* () { updated_at = excluded.updated_at WHERE kin_push_devices.person_id = excluded.person_id OR ${revoked} OR NOT EXISTS ( SELECT 1 FROM auth_sessions WHERE session_id = kin_push_devices.session_id) + OR (kin_push_devices.proof_key_thumbprint = excluded.proof_key_thumbprint AND NOT EXISTS ( + SELECT 1 FROM auth_sessions WHERE session_id = kin_push_devices.session_id + AND expires_at > ${DateTime.formatIso(DateTime.makeUnsafe(now))})) RETURNING token`; if (saved.length === 0) - return yield* fail("not_member", "This device is registered to someone else."); + return yield* fail( + "registered_to_someone_else", + "This device is registered to someone else.", + ); yield* sql`DELETE FROM kin_push_devices WHERE org_id = ${input.orgId} AND person_id = ${person.personId} AND token != ${input.token} AND token NOT IN ( diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index 3d035220a3b42..29dd76ce4bc6a 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -565,40 +565,71 @@ describe("KinPushDevices", () => { }).pipe(Effect.provide(build(apns))); }); - it.effect("hands a token to another person only once its session is revoked or gone", () => { - const apns = makeApns(); - return Effect.gen(function* () { - const { sql, devices } = yield* seed; - const takeover = devices.register(caller("sess-member", member), { - orgId, - token: ownerPhone, - platform: "ios", - apsEnvironment: "development", - }); - const owners = sql<{ person_id: string }>` + it.effect( + "hands a token to another person only once its session is revoked, gone, or expired and re-paired", + () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql, devices } = yield* seed; + const phoneKey = "p".repeat(43); + const registerFrom = (from: KinPushCaller) => + devices.register(from, { + orgId, + token: ownerPhone, + platform: "ios", + apsEnvironment: "development", + }); + const takeover = registerFrom(caller("sess-member", member)); + const repair = registerFrom( + caller("sess-member", member, { proofKeyThumbprint: phoneKey }), + ); + const owners = sql<{ person_id: string }>` SELECT person_id FROM kin_push_devices WHERE token = ${ownerPhone}`; - const refused = yield* Effect.exit(takeover); - assert.isTrue( - Exit.isFailure(refused) && - (refused.cause.reasons[0] as { error?: KinPushError }).error?.reason === "not_member", - ); - assert.deepStrictEqual(yield* owners, [{ person_id: owner }]); - for (const release of [ - sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-owner-phone'`, - sql`DELETE FROM auth_sessions WHERE session_id = 'sess-owner-phone'`, - ]) { - yield* sql`UPDATE kin_push_devices SET person_id = ${owner}, + const refuses = (attempt: typeof takeover) => + Effect.gen(function* () { + const refused = yield* Effect.exit(attempt); + assert.isTrue( + Exit.isFailure(refused) && + (refused.cause.reasons[0] as { error?: KinPushError }).error?.reason === + "registered_to_someone_else", + ); + assert.deepStrictEqual(yield* owners, [{ person_id: owner }]); + }); + yield* refuses(takeover); + // Two keyless callers never share a proof key, even after expiry. + yield* sql`UPDATE auth_sessions SET expires_at = ${T} WHERE session_id = 'sess-owner-phone'`; + yield* refuses(takeover); + yield* sql`UPDATE auth_sessions SET expires_at = '2026-12-07T00:00:00.000Z' + WHERE session_id = 'sess-owner-phone'`; + yield* sql`UPDATE kin_push_devices SET proof_key_thumbprint = ${phoneKey} + WHERE token = ${ownerPhone}`; + // The same proof key can't take a device whose session is still live. + yield* refuses(repair); + yield* sql`UPDATE auth_sessions SET expires_at = ${T} WHERE session_id = 'sess-owner-phone'`; + // Expiry alone doesn't free it for another key. + yield* refuses(takeover); + yield* refuses( + registerFrom(caller("sess-member", member, { proofKeyThumbprint: "q".repeat(43) })), + ); + yield* repair; + assert.deepStrictEqual(yield* owners, [{ person_id: member }]); + for (const release of [ + sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-owner-phone'`, + sql`DELETE FROM auth_sessions WHERE session_id = 'sess-owner-phone'`, + ]) { + yield* sql`UPDATE kin_push_devices SET person_id = ${owner}, session_id = 'sess-owner-phone' WHERE token = ${ownerPhone}`; - yield* sql`INSERT OR REPLACE INTO auth_sessions (session_id, subject, scopes, method, + yield* sql`INSERT OR REPLACE INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at) VALUES ('sess-owner-phone', 'x', '[]', 'bearer-access-token', ${T}, '2026-12-07T00:00:00.000Z')`; - yield* release; - yield* takeover; - assert.deepStrictEqual(yield* owners, [{ person_id: member }]); - } - }).pipe(Effect.provide(build(apns))); - }); + yield* release; + yield* takeover; + assert.deepStrictEqual(yield* owners, [{ person_id: member }]); + } + }).pipe(Effect.provide(build(apns))); + }, + ); /** A relay phone: a DPoP session that renews under a new id with the same proof key. */ const relay = (personId: KinPersonId, proofKeyThumbprint: string, ttl: Duration.Duration) => @@ -695,7 +726,8 @@ describe("KinPushDevices", () => { const refused = yield* Effect.exit(takeover); assert.isTrue( Exit.isFailure(refused) && - (refused.cause.reasons[0] as { error?: KinPushError }).error?.reason === "not_member", + (refused.cause.reasons[0] as { error?: KinPushError }).error?.reason === + "registered_to_someone_else", ); yield* sessions.revoke( (yield* relay(owner, "relay-a", Duration.hours(1))).session.sessionId, diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index dc9f979949f18..6b6dc205928e1 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -1,4 +1,5 @@ import type { + EnvironmentId, KinActionId, KinChatId, KinMessageId, @@ -61,6 +62,9 @@ const CONFIG_REASONS = new Set(["DeviceTokenNotForTopic", "TopicDisallowed"]); const SEND_CONCURRENCY = 4; const segment = encodeURIComponent; +/** Every Kin host shares org id `kin-default`, so links name the host too (mobile spec, routes). */ +export const kinPushChatLink = (environmentId: EnvironmentId, orgId: KinOrgId, chatId: KinChatId) => + `/kin/${segment(environmentId)}/${segment(orgId)}/chats/${segment(chatId)}`; /** Fits `apns-collapse-id`'s 64 bytes whatever the ids' length. */ const kinPushCollapseId = (orgId: KinOrgId, chatId: KinChatId) => `kin:${kinPushDeviceId(`${orgId}\u0000${chatId}`)}`; @@ -107,10 +111,10 @@ const make = Effect.gen(function* () { const presence = yield* KinPushPresence; const keys = yield* ApproverKeys; const actions = yield* KinPendingActions; - // Every Kin host shares org id `kin-default`, so links name the host too (mobile spec, routes). - const host = segment(yield* (yield* ServerEnvironment.ServerEnvironment).getEnvironmentId); + const environmentId = yield* (yield* ServerEnvironment.ServerEnvironment).getEnvironmentId; + const host = segment(environmentId); const chatLink = (orgId: KinOrgId, chatId: KinChatId) => - `/kin/${host}/${segment(orgId)}/chats/${segment(chatId)}`; + kinPushChatLink(environmentId, orgId, chatId); /** People in the chat now. Muting silences messages, not things waiting on you. */ const chatPeople = Effect.fn("KinPushSender.chatPeople")(function* ( diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 99e32c66eaaff..d68707bf6b52d 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -278,13 +278,13 @@ Hiding the buttons is a convenience, not the protection (DESIGN 9.3). The server - A relay phone's DPoP session renews hourly under a new id while its socket keeps the first one, so the proof key join is what reaches a revoked relay phone. "Sign out other devices" never marks the caller's own key, so the caller's phone keeps its pushes. Unlike approver keys, an owner's repair (`--repair-proof-key`) restores a phone's pushes, since the phone registers again on connect. - A 410 drops the token only when Apple's `timestamp` is later than the row's `updated_at`, since a phone that registered again since then has a working token. `BadDeviceToken` drops it with a warning naming the APNs environment it was sent to. `DeviceTokenNotForTopic` means `KIN_APNS_TOPIC` is wrong, so it's logged as an error and the token stays. `InvalidProviderToken` is a key or id misconfiguration: it's logged as an error and the provider token is kept. `ExpiredProviderToken` signs a new provider token and retries once, but only if the current one is at least 20 minutes old, since APNs throttles faster renewal. - Pushes go out four devices at a time. A request APNs doesn't answer within 10 seconds, or one that errors, ends that HTTP/2 connection. A connection idle for 5 minutes is replaced before use. No answer, a 500 or a 503 retries once on a new connection; a 429 is logged and the push dropped. -- A token registered by one person moves to another only once that revocation rule would remove its row, or the session that registered it is gone; otherwise `registerDevice` refuses with `not_member`. +- A token registered by one person moves to another only once that revocation rule would remove its row, the session that registered it is gone, or that session has expired and the new registration comes from the same proof key (the phone re-pairing); otherwise `registerDevice` refuses with `registered_to_someone_else`. "Expired" reads only the session stored on the row, so a relay phone that renewed under a new session id counts as expired while still connected; only a caller holding that proof key can use this. - The payload carries `aps.category` and `KinPushData` under the `body` key, which is what expo-notifications returns as `content.data` for a remote push. `chatId` is optional, because an approval such as adding a key has no chat. `deepLink` names the sending host, `/kin///chats/` or `/kin///actions/`, because every host shares org id `kin-default`. Its text is fixed per kind and contains no PR body or agent free text, for example "Merge #212 is waiting on you". - The sender skips a device whose session has a live `kin.push.watch({ chatId })` stream. Upstream owns the foreground handler, so this check has to happen on the server. MOB-11 opens it while a chat is on screen with `watchKinChatForPush` (`@t3tools/client-runtime/kin-push`) and ends it when the chat leaves the screen or the app the foreground. The stream sends a beat every 15 seconds, and each pull refreshes the mark. The RPC server pulls only after the client acks the last beat, so a half-open socket stops suppressing within 45 seconds, whatever the chat's traffic. Until a client opens it, nothing is suppressed: the failure mode is an extra push, not a lost one. - Approval pushes go only to the devices of people with an `active` approver key (DESIGN 9.3), read after session revocations. Approval cards in chat never push on their own. - Callers pass ids only, `notify({ _tag: "approval", actionId } | { _tag: "message", messageId } | { _tag: "widget", widgetId })`, after their transaction commits, because `notify` reads what the commit wrote. It sends in a fiber owned by the sender's layer, so a request handler can `yield*` it and return; the request ending doesn't cancel the push. The sender reads recipients from the database: approvers, the chat's people other than the author for messages (muted members skipped), and the widget's `awaiting` people who are still in the chat. Message pushes set `apns-collapse-id` per chat, so a busy chat shows one banner. Not wired yet: APPR-3's `request_action` and `registerKey` call `approval` after creating an action, and lane A calls `message` after a post and `widget` when a deferral changes phase or a card starts waiting on someone. -**Test push (dev only).** Nishchay creates an APNs auth key (Keys, Apple Push Notifications service) in the team that signs the Kin build, then, on the Kin host with a development build installed, runs `cd apps/server && KIN_APNS_KEY_FILE=… KIN_APNS_KEY_ID=… KIN_APNS_TEAM_ID=… KIN_APNS_TOPIC= node scripts/kin-push-test.ts development`. The token comes from `Notifications.getDevicePushTokenAsync()` on the phone. APNs answering 200 and the banner showing is MOB-10's last "done when". +**Test push (dev only).** Nishchay creates an APNs auth key (Keys, Apple Push Notifications service) in the team that signs the Kin build, then, on the Kin host with a development build installed, runs `cd apps/server && KIN_APNS_KEY_FILE=… KIN_APNS_KEY_ID=… KIN_APNS_TEAM_ID=… KIN_APNS_TOPIC= node scripts/kin-push-test.ts "$(cat ~/.t3/userdata/environment-id)" development`. The token comes from `Notifications.getDevicePushTokenAsync()` on the phone. APNs answering 200 and the banner showing is MOB-10's last "done when". **Receiving (`features/chats/notifications/installKinNotifications.ts`, new).** diff --git a/packages/contracts/src/kinPush.ts b/packages/contracts/src/kinPush.ts index 94e0f20bfd3a5..5198d1a9731b9 100644 --- a/packages/contracts/src/kinPush.ts +++ b/packages/contracts/src/kinPush.ts @@ -90,7 +90,7 @@ export const KinPushWatchBeat = Schema.Literal("beat"); export type KinPushWatchBeat = typeof KinPushWatchBeat.Type; export class KinPushError extends Schema.TaggedError()("KinPushError", { - reason: Schema.Literals(["not_member", "unavailable", "disabled"]), + reason: Schema.Literals(["not_member", "registered_to_someone_else", "unavailable", "disabled"]), message: Schema.String, }) {}