From 65f0551f37b03c91717e8e7b8bbed492cd280a89 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 09:39:59 +0530 Subject: [PATCH 01/10] feat(kin): APNs push sender and device registration (MOB-10) Kin sends its own APNs pushes, since T3's relay can't carry categories or Kin's bundle id. Phones register tokens per org and person with kin.push.registerDevice (and unregisterDevice). The sender takes ids only and reads recipients from the database: approval pushes reach only people with an active approver key, and a device whose session has the chat open is skipped. Without a full APNs config, push stays off and Kin still starts. Co-Authored-By: Claude Opus 5.5 --- apps/server/scripts/kin-push-test.ts | 50 +++ apps/server/src/kin/KinServer.ts | 13 +- apps/server/src/kin/approvals/ApproverKeys.ts | 16 + apps/server/src/kin/approvals/layer.ts | 2 +- apps/server/src/kin/chat/rpcHandlers.ts | 12 +- apps/server/src/kin/layer.ts | 3 +- .../src/kin/persistence/KinMigrations.test.ts | 11 +- .../src/kin/persistence/KinMigrations.ts | 2 + .../migrations/K011_PushDevices.ts | 22 + apps/server/src/kin/push/Apns.test.ts | 93 +++++ apps/server/src/kin/push/Apns.ts | 213 ++++++++++ apps/server/src/kin/push/KinPushDevices.ts | 167 ++++++++ apps/server/src/kin/push/KinPushPresence.ts | 47 +++ .../server/src/kin/push/KinPushSender.test.ts | 388 ++++++++++++++++++ apps/server/src/kin/push/KinPushSender.ts | 281 +++++++++++++ apps/server/src/kin/push/layer.ts | 12 + apps/server/src/kin/push/rpcHandlers.ts | 44 ++ apps/server/src/ws.ts | 2 + docs/kin/specs/mobile.md | 23 +- knip.jsonc | 1 + .../src/state/commandPermissions.test.ts | 67 +-- packages/contracts/src/index.ts | 1 + packages/contracts/src/kinPush.ts | 117 ++++++ packages/contracts/src/kinRpcs.ts | 6 +- 24 files changed, 1543 insertions(+), 50 deletions(-) create mode 100644 apps/server/scripts/kin-push-test.ts create mode 100644 apps/server/src/kin/persistence/migrations/K011_PushDevices.ts create mode 100644 apps/server/src/kin/push/Apns.test.ts create mode 100644 apps/server/src/kin/push/Apns.ts create mode 100644 apps/server/src/kin/push/KinPushDevices.ts create mode 100644 apps/server/src/kin/push/KinPushPresence.ts create mode 100644 apps/server/src/kin/push/KinPushSender.test.ts create mode 100644 apps/server/src/kin/push/KinPushSender.ts create mode 100644 apps/server/src/kin/push/layer.ts create mode 100644 apps/server/src/kin/push/rpcHandlers.ts create mode 100644 packages/contracts/src/kinPush.ts diff --git a/apps/server/scripts/kin-push-test.ts b/apps/server/scripts/kin-push-test.ts new file mode 100644 index 0000000000000..05fad0b38df10 --- /dev/null +++ b/apps/server/scripts/kin-push-test.ts @@ -0,0 +1,50 @@ +#!/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] +// 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 * 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"; + +class KinPushTestError extends Schema.TaggedError()("KinPushTestError", { + message: Schema.String, +}) {} + +const decodeToken = Schema.decodeUnknownEffect(KinPushToken); +const decodeEnvironment = Schema.decodeUnknownEffect(KinApsEnvironment); +const decodeData = Schema.decodeEffect(KinPushData); + +const program = Effect.gen(function* () { + const [rawToken, rawEnvironment = "development"] = process.argv.slice(2); + const token = yield* decodeToken(rawToken?.toLowerCase()); + 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 body = yield* decodeData({ + kin: 1, + orgId: "kin-default", + deepLink: "/kin/kin-default/chats/test", + }); + const result = yield* apns.send({ + token, + environment, + payload: { + aps: { + alert: { title: "Kin", body: "Test push from the Kin host" }, + category: "kin.message", + sound: "default", + }, + body, + }, + }); + yield* Effect.log("APNs answered.", { deviceId: kinPushDeviceId(token), ...result }); + if (result.status !== 200) + return yield* new KinPushTestError({ message: "APNs refused the push." }); +}); + +program.pipe(Effect.provide(layer), Effect.scoped, NodeRuntime.runMain); diff --git a/apps/server/src/kin/KinServer.ts b/apps/server/src/kin/KinServer.ts index 937b6fcee7d26..fee8266826274 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -8,8 +8,19 @@ import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinBudget } from "./lead/KinBudget.ts"; import { KinEventQueue } from "./lead/KinEventQueue.ts"; import { ApproverKeys } from "./approvals/ApproverKeys.ts"; +import type { KinPushDevices } from "./push/KinPushDevices.ts"; +import type { KinPushPresence } from "./push/KinPushPresence.ts"; +import type { KinPushSender } from "./push/KinPushSender.ts"; -export type Services = KinIdentity | KinChatService | KinBudget | KinEventQueue | ApproverKeys; +export type Services = + | KinIdentity + | KinChatService + | KinBudget + | KinEventQueue + | ApproverKeys + | KinPushDevices + | KinPushPresence + | KinPushSender; export class KinServer extends Context.Service< KinServer, diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 10c7925abc694..fe19b47f8f995 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -20,6 +20,7 @@ import { type KinApprovalsRegisterKeyResult, type KinKeyThumbprint, type KinOrgId, + type KinPersonId, } from "@t3tools/contracts"; import { computeDpopJwkThumbprint } from "@t3tools/shared/dpop"; import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification"; @@ -175,6 +176,10 @@ export class ApproverKeys extends Context.Service< readonly activateByGrant: (ref: KeyRef) => Effect.Effect; /** Revokes keys whose T3 session was revoked. Returns how many. */ readonly reconcileSessions: () => Effect.Effect; + /** People holding an `active` key in the org: the only ones approval pushes reach. */ + readonly activeApprovers: ( + orgId: KinOrgId, + ) => Effect.Effect, KinApprovalError>; } >()("t3/kin/approvals/ApproverKeys") {} @@ -500,6 +505,16 @@ const make = Effect.gen(function* () { Effect.mapError(internal("ApproverKeys.activateByGrant")), ); + const activeApprovers = Effect.fn("ApproverKeys.activeApprovers")( + function* (orgId: KinOrgId) { + yield* reconcileSessions(); + const rows = yield* sql<{ human_id: KinPersonId }>`SELECT DISTINCT human_id + FROM kin_approver_keys WHERE org_id = ${orgId} AND state = 'active' ORDER BY human_id`; + return rows.map((row) => row.human_id); + }, + Effect.mapError(internal("ApproverKeys.activeApprovers")), + ); + yield* reconcileSessions().pipe( Effect.catch((error) => Effect.logError("Kin approver key reconciliation failed.", error)), ); @@ -514,6 +529,7 @@ const make = Effect.gen(function* () { requireActive, activateByGrant, reconcileSessions, + activeApprovers, }); }); diff --git a/apps/server/src/kin/approvals/layer.ts b/apps/server/src/kin/approvals/layer.ts index c60550d0c4559..c9234e7e07d16 100644 --- a/apps/server/src/kin/approvals/layer.ts +++ b/apps/server/src/kin/approvals/layer.ts @@ -7,7 +7,7 @@ import * as AttestationTrust from "./attestation/AttestationTrust.ts"; import * as PendingActions from "./PendingActions.ts"; export const layer = ApproverKeys.layer.pipe( - Layer.provide(PendingActions.layer), + Layer.provideMerge(PendingActions.layer), Layer.provide(AttestationTrust.layer.pipe(Layer.provide(FetchHttpClient.layer))), Layer.provide(KinPersistence.layer), ); diff --git a/apps/server/src/kin/chat/rpcHandlers.ts b/apps/server/src/kin/chat/rpcHandlers.ts index 1304d53b8ec7d..33ca78ed2c27f 100644 --- a/apps/server/src/kin/chat/rpcHandlers.ts +++ b/apps/server/src/kin/chat/rpcHandlers.ts @@ -8,6 +8,7 @@ import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinServer } from "../layer.ts"; import { KinBudget } from "../lead/KinBudget.ts"; +import { KinPushPresence } from "../push/KinPushPresence.ts"; import { KinIdentity } from "./KinIdentity.ts"; import { KinChatService } from "./KinChatService.ts"; @@ -29,11 +30,12 @@ export const makeKinChatHandlers = Effect.fn("makeKinChatHandlers")(function* ( identity: Context.get(kin.value.services.value, KinIdentity), budget: Context.get(kin.value.services.value, KinBudget), chat: Context.get(kin.value.services.value, KinChatService), + presence: Context.get(kin.value.services.value, KinPushPresence), }; }); const viewer = Effect.gen(function* () { - const { identity, chat } = yield* services; - return { chat, people: yield* identity.resolve(session) }; + const { identity, chat, presence } = yield* services; + return { chat, presence, people: yield* identity.resolve(session) }; }); return group.of({ "kin.budget.get": (input) => @@ -71,7 +73,11 @@ export const makeKinChatHandlers = Effect.fn("makeKinChatHandlers")(function* ( ).pipe(Stream.mapError(mapError)), "kin.chat.subscribe": (input) => Stream.unwrap( - viewer.pipe(Effect.map(({ chat, people }) => chat.subscribe(people, input))), + viewer.pipe( + // While this stream lives, pushes for the chat skip this session's device. + Effect.tap(({ presence }) => presence.watch(session.sessionId, input.chatId)), + Effect.map(({ chat, people }) => chat.subscribe(people, input)), + ), ).pipe(Stream.mapError(mapError)), "kin.chats.createDirect": (input) => viewer.pipe( diff --git a/apps/server/src/kin/layer.ts b/apps/server/src/kin/layer.ts index 1d6c9b645ed0a..aee8d171e629b 100644 --- a/apps/server/src/kin/layer.ts +++ b/apps/server/src/kin/layer.ts @@ -12,6 +12,7 @@ import * as HttpRouter from "effect/http/HttpRouter"; import * as Option from "effect/Option"; import * as KinChat from "./chat/layer.ts"; import * as KinApprovals from "./approvals/layer.ts"; +import * as KinPush from "./push/layer.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinServer, type Services } from "./KinServer.ts"; @@ -41,7 +42,7 @@ const enabled = Layer.effect( Layer.provide( Layer.merge( KinChat.layer.pipe(Layer.provide(JudgeShadow.layer.pipe(Layer.provide(NoopJudge.layer)))), - KinApprovals.layer, + KinPush.layer.pipe(Layer.provideMerge(KinApprovals.layer)), ), ), ); diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 129312c97bf81..63ddde004e7b6 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -39,6 +39,7 @@ const tableNames = [ "kin_ping_escalations", "kin_ping_items", "kin_ping_ledger", + "kin_push_devices", "kin_read_state", "kin_session_bindings", "kin_shadow_entries", @@ -101,6 +102,7 @@ describe("Kin migrations", () => { { migration_id: 8, name: "Floor" }, { migration_id: 9, name: "JudgeLog" }, { migration_id: 10, name: "Approvals" }, + { migration_id: 11, name: "PushDevices" }, ]); assert.deepStrictEqual( upstreamBefore.map((row) => [row.migration_id, row.name] as const), @@ -117,6 +119,7 @@ describe("Kin migrations", () => { ["kin_pending_actions", ["created_at", "updated_at", "expires_at"]], ["kin_grants", ["accepted_at", "consumed_at"]], ["kin_executions", ["started_at", "finished_at"]], + ["kin_push_devices", ["created_at", "updated_at"]], ] as const) { const columns = yield* sql<{ name: string; type: string }>` SELECT name, type FROM pragma_table_info(${table}) @@ -156,6 +159,7 @@ describe("Kin migrations", () => { { migration_id: 8, name: "Floor" }, { migration_id: 9, name: "JudgeLog" }, { migration_id: 10, name: "Approvals" }, + { migration_id: 11, name: "PushDevices" }, ]); assert.deepStrictEqual(yield* upstreamHistory, upstreamBefore); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_orgs`, [ @@ -186,6 +190,7 @@ describe("Kin migrations", () => { { name: "idx_kin_people_org_person" }, { name: "idx_kin_ping_items_item" }, { name: "idx_kin_ping_items_pending" }, + { name: "idx_kin_push_devices_person" }, { name: "idx_kin_shadow_entries_promotion" }, { name: "idx_kin_shadow_entries_review" }, { name: "idx_kin_trigger_fires_retention" }, @@ -235,6 +240,7 @@ describe("Kin migrations", () => { [8, "Floor"], [9, "JudgeLog"], [10, "Approvals"], + [11, "PushDevices"], ]); const before = yield* kinSchema; assert.deepStrictEqual( @@ -263,6 +269,7 @@ describe("Kin migrations", () => { yield* sql`DROP TABLE kin_budget_charges`; yield* sql`ALTER TABLE kin_events DROP COLUMN budget_deferred`; for (const table of [ + "kin_push_devices", "kin_executions", "kin_grants", "kin_pending_actions", @@ -279,6 +286,7 @@ describe("Kin migrations", () => { [8, "Floor"], [9, "JudgeLog"], [10, "Approvals"], + [11, "PushDevices"], ]); assert.deepStrictEqual( yield* sql`SELECT member_id FROM kin_chat_members WHERE org_id = 'org' ORDER BY member_id`, @@ -301,6 +309,7 @@ describe("Kin migrations", () => { { migration_id: 8, name: "Floor" }, { migration_id: 9, name: "JudgeLog" }, { migration_id: 10, name: "Approvals" }, + { migration_id: 11, name: "PushDevices" }, ]); assert.deepStrictEqual(yield* runKinMigrations(), []); assert.deepStrictEqual(yield* runMigrations(), []); @@ -318,7 +327,7 @@ describe("Kin migrations", () => { const exit = yield* Effect.exit(runKinMigrations()); assert.isTrue(Exit.isFailure(exit)); assert.include(String(exit), "5_OneChatOwner"); - assert.include(String(exit), "below the latest applied migration 10"); + assert.include(String(exit), "below the latest applied migration 11"); assert.deepStrictEqual(yield* kinHistory, history); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/kin/persistence/KinMigrations.ts b/apps/server/src/kin/persistence/KinMigrations.ts index d785239d8b20f..6e38ec52e2d4a 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -12,6 +12,7 @@ import Budget from "./migrations/K007_Budget.ts"; import Floor from "./migrations/K008_Floor.ts"; import JudgeLog from "./migrations/K009_JudgeLog.ts"; import Approvals from "./migrations/K010_Approvals.ts"; +import PushDevices from "./migrations/K011_PushDevices.ts"; const table = "kin_sql_migrations"; const run = Migrator.make({}); @@ -26,6 +27,7 @@ const loader = Migrator.fromRecord({ "8_Floor": Floor, "9_JudgeLog": JudgeLog, "10_Approvals": Approvals, + "11_PushDevices": PushDevices, }); // The Migrator skips every id at or below the latest applied one, so a migration that diff --git a/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts b/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts new file mode 100644 index 0000000000000..64ddb0ebe4752 --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts @@ -0,0 +1,22 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // One row per device token per org; the latest person and session to register it own it. + yield* sql` + CREATE TABLE kin_push_devices ( + org_id TEXT NOT NULL REFERENCES kin_orgs(org_id), + token TEXT NOT NULL, + person_id TEXT NOT NULL REFERENCES kin_people(person_id), + platform TEXT NOT NULL CHECK (platform IN ('ios')), + aps_environment TEXT NOT NULL CHECK (aps_environment IN ('development', 'production')), + device_label TEXT, + session_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (org_id, token) + ) + `; + yield* sql`CREATE INDEX idx_kin_push_devices_person ON kin_push_devices(org_id, person_id)`; +}); diff --git a/apps/server/src/kin/push/Apns.test.ts b/apps/server/src/kin/push/Apns.test.ts new file mode 100644 index 0000000000000..d382541977f50 --- /dev/null +++ b/apps/server/src/kin/push/Apns.test.ts @@ -0,0 +1,93 @@ +// @effect-diagnostics nodeBuiltinImport:off -- a throwaway P-256 key on disk, as Apple's .p8 is. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { assert, it } from "@effect/vitest"; +import type { KinPushToken } from "@t3tools/contracts"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; + +import { apnsProviderToken, apnsRequestHeaders, loadApnsCredentials } from "./Apns.ts"; + +const keyFile = Effect.acquireRelease( + Effect.sync(() => { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "kin-apns-")); + const pair = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" }); + const ec = NodePath.join(dir, "AuthKey_TEST.p8"); + NodeFS.writeFileSync(ec, pair.privateKey.export({ type: "pkcs8", format: "pem" })); + const rsa = NodePath.join(dir, "rsa.pem"); + NodeFS.writeFileSync( + rsa, + NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ + type: "pkcs8", + format: "pem", + }), + ); + return { dir, ec, rsa, publicKey: pair.publicKey }; + }), + ({ dir }) => Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), +); + +const load = (env: Record) => + Effect.result(loadApnsCredentials()).pipe( + Effect.provide(ConfigProvider.layer(ConfigProvider.fromUnknown(env))), + ); + +it.effect("loads the .p8 only when fully configured, and signs a token APNs can verify", () => + Effect.gen(function* () { + const file = yield* keyFile; + const full = { + KIN_APNS_KEY_FILE: file.ec, + KIN_APNS_KEY_ID: "ABC123DEFG", + KIN_APNS_TEAM_ID: "TEAM123456", + KIN_APNS_TOPIC: "codes.kin.app", + }; + const failures = [ + [{}, "no APNs key is configured"], + [{ KIN_APNS_KEY_ID: "ABC123DEFG" }, "set all of"], + [{ ...full, KIN_APNS_KEY_FILE: NodePath.join(file.dir, "missing.p8") }, "isn't a readable"], + [{ ...full, KIN_APNS_KEY_FILE: file.rsa }, "isn't an APNs (P-256) key"], + ] as const; + for (const [env, reason] of failures) { + const result = yield* load(env); + assert.isTrue(result._tag === "Failure" && result.failure.includes(reason), reason); + } + + const loaded = yield* load(full); + assert.strictEqual(loaded._tag, "Success"); + if (loaded._tag !== "Success") return; + const jwt = apnsProviderToken(loaded.success, Date.parse("2026-11-08T00:00:00Z")); + const [header, claims, signature] = jwt.split(".") as [string, string, string]; + assert.deepStrictEqual(JSON.parse(Buffer.from(header, "base64url").toString()), { + alg: "ES256", + kid: "ABC123DEFG", + }); + assert.deepStrictEqual(JSON.parse(Buffer.from(claims, "base64url").toString()), { + iss: "TEAM123456", + iat: 1_794_096_000, + }); + assert.isTrue( + NodeCrypto.verify( + "sha256", + Buffer.from(`${header}.${claims}`), + { key: file.publicKey, dsaEncoding: "ieee-p1363" }, + Buffer.from(signature, "base64url"), + ), + ); + const token = "a".repeat(64) as KinPushToken; + assert.deepStrictEqual( + apnsRequestHeaders(loaded.success, { token, environment: "development", payload: {} }, jwt), + { + ":method": "POST", + ":path": `/3/device/${token}`, + authorization: `bearer ${jwt}`, + "apns-topic": "codes.kin.app", + "apns-push-type": "alert", + "apns-priority": "10", + "content-type": "application/json", + }, + ); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/kin/push/Apns.ts b/apps/server/src/kin/push/Apns.ts new file mode 100644 index 0000000000000..3b40d8e9e1a34 --- /dev/null +++ b/apps/server/src/kin/push/Apns.ts @@ -0,0 +1,213 @@ +// @effect-diagnostics nodeBuiltinImport:off -- ES256 signing, the .p8 file and APNs' HTTP/2 API. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeHttp2 from "node:http2"; + +import type { KinApsEnvironment, KinPushSendingStatus, KinPushToken } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +const ORIGINS: Record = { + development: "https://api.sandbox.push.apple.com", + production: "https://api.push.apple.com", +}; +// APNs refuses tokens older than an hour and throttles ones renewed more often than every 20 minutes. +const JWT_TTL_MS = 40 * 60 * 1000; +const REQUEST_TIMEOUT = "10 seconds"; + +export type KinApnsCredentials = { + readonly keyId: string; + readonly teamId: string; + /** The Kin build's bundle id, sent as `apns-topic`. */ + readonly topic: string; + readonly key: NodeCrypto.KeyObject; +}; + +export type KinApnsPush = { + readonly token: KinPushToken; + readonly environment: KinApsEnvironment; + readonly payload: unknown; +}; + +/** `status` 0 means APNs never answered (network, timeout); nothing was delivered. */ +export type KinApnsResult = { readonly status: number; readonly reason: string | undefined }; + +export class KinApnsTransport extends Context.Service< + KinApnsTransport, + { + readonly status: KinPushSendingStatus; + readonly send: (push: KinApnsPush) => Effect.Effect; + } +>()("t3/kin/push/Apns/KinApnsTransport") {} + +const base64Url = (value: string | Buffer) => Buffer.from(value).toString("base64url"); + +/** APNs provider token: ES256 over `{alg, kid}.{iss, iat}`. */ +export const apnsProviderToken = (credentials: KinApnsCredentials, nowMs: number) => { + const signingInput = `${base64Url(JSON.stringify({ alg: "ES256", kid: credentials.keyId }))}.${base64Url( + JSON.stringify({ iss: credentials.teamId, iat: Math.floor(nowMs / 1000) }), + )}`; + const signature = NodeCrypto.sign("sha256", Buffer.from(signingInput), { + key: credentials.key, + dsaEncoding: "ieee-p1363", + }); + return `${signingInput}.${base64Url(signature)}`; +}; + +export const apnsRequestHeaders = ( + credentials: KinApnsCredentials, + push: KinApnsPush, + jwt: string, +) => ({ + ":method": "POST", + ":path": `/3/device/${push.token}`, + authorization: `bearer ${jwt}`, + "apns-topic": credentials.topic, + "apns-push-type": "alert", + "apns-priority": "10", + "content-type": "application/json", +}); + +/** + * Reads `KIN_APNS_KEY_FILE` (the `.p8` from Apple, kept outside the repo), `KIN_APNS_KEY_ID`, + * `KIN_APNS_TEAM_ID` and `KIN_APNS_TOPIC`. Anything missing or unreadable leaves push off; + * it never stops Kin from starting. + */ +export const loadApnsCredentials = Effect.fn("KinApns.loadCredentials")(function* () { + const config = yield* Config.all({ + keyFile: Config.String("KIN_APNS_KEY_FILE").pipe(Config.option), + keyId: Config.String("KIN_APNS_KEY_ID").pipe(Config.option), + teamId: Config.String("KIN_APNS_TEAM_ID").pipe(Config.option), + topic: Config.String("KIN_APNS_TOPIC").pipe(Config.option), + }).pipe(Effect.orElseSucceed(() => undefined)); + if (config === undefined) return yield* Effect.fail("invalid APNs configuration"); + const values = [config.keyFile, config.keyId, config.teamId, config.topic]; + if (values.every(Option.isNone)) return yield* Effect.fail("no APNs key is configured"); + if ( + Option.isNone(config.keyFile) || + Option.isNone(config.keyId) || + Option.isNone(config.teamId) || + Option.isNone(config.topic) + ) + return yield* Effect.fail( + "set all of KIN_APNS_KEY_FILE, KIN_APNS_KEY_ID, KIN_APNS_TEAM_ID and KIN_APNS_TOPIC", + ); + const path = config.keyFile.value; + const key = yield* Effect.try({ + try: () => NodeCrypto.createPrivateKey(NodeFS.readFileSync(path, "utf8")), + // The message would name the file's contents on a parse error; say only what failed. + catch: () => "KIN_APNS_KEY_FILE isn't a readable .p8 key", + }); + if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") + return yield* Effect.fail("KIN_APNS_KEY_FILE isn't an APNs (P-256) key"); + return { + keyId: config.keyId.value, + teamId: config.teamId.value, + topic: config.topic.value, + key, + } satisfies KinApnsCredentials; +}); + +const post = ( + session: NodeHttp2.ClientHttp2Session, + headers: NodeHttp2.OutgoingHttpHeaders, + body: string, +) => + Effect.callback((resume) => { + const request = session.request(headers); + let status = 0; + const chunks: Array = []; + request.on("response", (response) => { + status = Number(response[":status"] ?? 0); + }); + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + let reason: string | undefined; + try { + const parsed: unknown = text.length > 0 ? JSON.parse(text) : undefined; + if (typeof parsed === "object" && parsed !== null && "reason" in parsed) + reason = String(parsed.reason); + } catch { + reason = undefined; + } + resume(Effect.succeed({ status, reason })); + }); + request.on("error", (error: Error) => resume(Effect.fail(error))); + request.end(body); + return Effect.sync(() => request.close(NodeHttp2.constants.NGHTTP2_CANCEL)); + }); + +const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +const unconfigured = (reason: string) => + Effect.logInfo(`Kin push is off: ${reason}.`).pipe( + Effect.as( + KinApnsTransport.of({ + status: "unconfigured", + send: Effect.fn("KinApnsTransport.sendUnconfigured")(function* () { + return yield* Effect.succeed({ status: 0, reason: "unconfigured" }); + }), + }), + ), + ); + +const make = Effect.gen(function* () { + const loaded = yield* Effect.result(loadApnsCredentials()); + if (loaded._tag === "Failure") return yield* unconfigured(loaded.failure); + const credentials = loaded.success; + const sessions = new Map(); + let jwt: { readonly value: string; readonly at: number } | undefined; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + for (const session of sessions.values()) session.close(); + sessions.clear(); + }), + ); + + const sessionFor = (environment: KinApsEnvironment) => { + const open = sessions.get(environment); + if (open !== undefined && !open.closed && !open.destroyed) return open; + const session = NodeHttp2.connect(ORIGINS[environment]); + const drop = () => { + if (sessions.get(environment) === session) sessions.delete(environment); + }; + session.on("error", drop); + session.on("close", drop); + session.on("goaway", drop); + session.unref(); + sessions.set(environment, session); + return session; + }; + + const providerToken = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (jwt === undefined || now - jwt.at >= JWT_TTL_MS) + jwt = { value: apnsProviderToken(credentials, now), at: now }; + return jwt.value; + }); + + yield* Effect.logInfo("Kin push is on.", { topic: credentials.topic, keyId: credentials.keyId }); + return KinApnsTransport.of({ + status: "ready", + send: Effect.fn("KinApnsTransport.send")(function* (push: KinApnsPush) { + const headers = apnsRequestHeaders(credentials, push, yield* providerToken); + return yield* encodeJson(push.payload).pipe( + Effect.flatMap((body) => post(sessionFor(push.environment), headers, body)), + Effect.timeout(REQUEST_TIMEOUT), + Effect.catch((error) => + Effect.logWarning("Kin push couldn't reach APNs.", { error: String(error) }).pipe( + Effect.as({ status: 0, reason: "transport" }), + ), + ), + ); + }), + }); +}); + +export const layer = Layer.effect(KinApnsTransport, make); diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts new file mode 100644 index 0000000000000..968ab00a0316f --- /dev/null +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -0,0 +1,167 @@ +// @effect-diagnostics nodeBuiltinImport:off -- synchronous SHA-256 for device ids. +import * as NodeCrypto from "node:crypto"; + +import { + KinPushError, + type AuthSessionId, + type KinApsEnvironment, + type KinOrgId, + type KinPersonId, + type KinPushRegisterDeviceInput, + type KinPushToken, + type KinPushUnregisterDeviceInput, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import type { PersonIdentity } from "../chat/KinIdentity.ts"; + +export type KinPushCaller = { + readonly session: AuthenticatedSession; + readonly people: ReadonlyArray; +}; + +export type KinPushDevice = { + readonly orgId: KinOrgId; + readonly token: KinPushToken; + readonly personId: KinPersonId; + readonly apsEnvironment: KinApsEnvironment; + readonly sessionId: AuthSessionId; +}; + +/** What logs and clients see instead of a token: 12 hex characters of its SHA-256. */ +export const kinPushDeviceId = (token: string) => + NodeCrypto.createHash("sha256").update(token).digest("hex").slice(0, 12); + +const isKinPushError = Schema.is(KinPushError); +const fail = (reason: KinPushError["reason"], message: string) => + Effect.fail(new KinPushError({ reason, message })); + +export class KinPushDevices extends Context.Service< + KinPushDevices, + { + readonly register: ( + caller: KinPushCaller, + input: KinPushRegisterDeviceInput, + ) => Effect.Effect<{ readonly deviceId: string }, KinPushError>; + readonly unregister: ( + caller: KinPushCaller, + input: KinPushUnregisterDeviceInput, + ) => Effect.Effect<{ readonly removed: boolean }, KinPushError>; + /** Devices of these people in the org, after dropping those whose session was revoked. */ + readonly forPeople: ( + orgId: KinOrgId, + people: ReadonlyArray, + ) => Effect.Effect, KinPushError>; + /** APNs said the token is dead (410, BadDeviceToken). */ + readonly forget: (orgId: KinOrgId, token: KinPushToken) => Effect.Effect; + /** Removes devices registered from a revoked T3 session. Returns how many. */ + readonly reconcileSessions: () => Effect.Effect; + } +>()("t3/kin/push/KinPushDevices") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const internal = (operation: string) => (cause: unknown) => + isKinPushError(cause) + ? cause + : new KinPushError({ reason: "unavailable", message: `${operation} failed.` }); + + const personIn = (caller: KinPushCaller, orgId: KinOrgId) => { + const person = caller.people.find((candidate) => candidate.orgId === orgId); + return person === undefined + ? fail("not_member", "Only a person in this org can get its notifications.") + : Effect.succeed(person); + }; + + // T3 revokes sessions in SessionStore; reading its table keeps auth free of Kin hooks, + // as ApproverKeys does. Runs before every send. + const reconcileSessions = Effect.fn("KinPushDevices.reconcileSessions")( + function* () { + const removed = yield* sql`DELETE FROM kin_push_devices WHERE session_id IN ( + SELECT session_id FROM auth_sessions WHERE revoked_at IS NOT NULL) + RETURNING token`; + return removed.length; + }, + Effect.mapError(internal("KinPushDevices.reconcileSessions")), + ); + + const register = Effect.fn("KinPushDevices.register")( + function* (caller: KinPushCaller, input: KinPushRegisterDeviceInput) { + const person = yield* personIn(caller, input.orgId); + const now = yield* Clock.currentTimeMillis; + // A phone re-registers on every connect, which also moves the row to its current session. + yield* sql`INSERT INTO kin_push_devices ${sql.insert({ + org_id: input.orgId, + token: input.token, + person_id: person.personId, + platform: input.platform, + aps_environment: input.apsEnvironment, + device_label: input.deviceLabel ?? null, + session_id: caller.session.sessionId, + created_at: now, + updated_at: now, + })} + ON CONFLICT (org_id, token) DO UPDATE SET + person_id = excluded.person_id, + platform = excluded.platform, + aps_environment = excluded.aps_environment, + device_label = excluded.device_label, + session_id = excluded.session_id, + updated_at = excluded.updated_at`; + return { deviceId: kinPushDeviceId(input.token) }; + }, + Effect.mapError(internal("KinPushDevices.register")), + ); + + const unregister = Effect.fn("KinPushDevices.unregister")( + function* (caller: KinPushCaller, input: KinPushUnregisterDeviceInput) { + const person = yield* personIn(caller, input.orgId); + const removed = yield* sql`DELETE FROM kin_push_devices + WHERE org_id = ${input.orgId} AND token = ${input.token} AND person_id = ${person.personId} + RETURNING token`; + return { removed: removed.length > 0 }; + }, + Effect.mapError(internal("KinPushDevices.unregister")), + ); + + const forPeople = Effect.fn("KinPushDevices.forPeople")( + function* (orgId: KinOrgId, people: ReadonlyArray) { + if (people.length === 0) return []; + yield* reconcileSessions(); + const rows = yield* sql<{ + token: KinPushToken; + person_id: KinPersonId; + aps_environment: KinApsEnvironment; + session_id: AuthSessionId; + }>`SELECT token, person_id, aps_environment, session_id FROM kin_push_devices + WHERE org_id = ${orgId} AND person_id IN ${sql.in(people)} + ORDER BY person_id, token`; + return rows.map((row): KinPushDevice => ({ + orgId, + token: row.token, + personId: row.person_id, + apsEnvironment: row.aps_environment, + sessionId: row.session_id, + })); + }, + Effect.mapError(internal("KinPushDevices.forPeople")), + ); + + const forget = Effect.fn("KinPushDevices.forget")( + function* (orgId: KinOrgId, token: KinPushToken) { + yield* sql`DELETE FROM kin_push_devices WHERE org_id = ${orgId} AND token = ${token}`; + }, + Effect.mapError(internal("KinPushDevices.forget")), + ); + + return KinPushDevices.of({ register, unregister, forPeople, forget, reconcileSessions }); +}); + +export const layer = Layer.effect(KinPushDevices, make); diff --git a/apps/server/src/kin/push/KinPushPresence.ts b/apps/server/src/kin/push/KinPushPresence.ts new file mode 100644 index 0000000000000..407b90e63c278 --- /dev/null +++ b/apps/server/src/kin/push/KinPushPresence.ts @@ -0,0 +1,47 @@ +import type { AuthSessionId, KinChatId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; + +/** + * Which sessions have a chat open right now. Upstream owns the phone's foreground handler, + * so the server skips a push for a chat the device is already showing (mobile spec, correction 8). + * The phone ends its chat stream when it leaves the foreground, so a live stream means "on screen". + */ +export class KinPushPresence extends Context.Service< + KinPushPresence, + { + /** Marks the chat open for the session until the scope closes. */ + readonly watch: ( + sessionId: AuthSessionId, + chatId: KinChatId, + ) => Effect.Effect; + readonly isWatching: (sessionId: AuthSessionId, chatId: KinChatId) => boolean; + } +>()("t3/kin/push/KinPushPresence") {} + +const make = Effect.sync(() => { + const open = new Map(); + const slot = (sessionId: AuthSessionId, chatId: KinChatId) => `${sessionId}\u0000${chatId}`; + return KinPushPresence.of({ + watch: Effect.fn("KinPushPresence.watch")(function* (sessionId, chatId) { + yield* Effect.acquireRelease( + Effect.sync(() => { + const key = slot(sessionId, chatId); + open.set(key, (open.get(key) ?? 0) + 1); + return key; + }), + (key) => + Effect.sync(() => { + const left = (open.get(key) ?? 1) - 1; + if (left > 0) open.set(key, left); + else open.delete(key); + }), + ); + }), + isWatching: (sessionId, chatId) => open.has(slot(sessionId, chatId)), + }); +}); + +export const layer = Layer.effect(KinPushPresence, make); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts new file mode 100644 index 0000000000000..26101be321dd7 --- /dev/null +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -0,0 +1,388 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + KinEventId, + KinMessageId, + KinOrgId, + KinPersonId, + KinWidgetId, + type KinPushError, + type KinPushToken, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as ApproverKeys from "../approvals/ApproverKeys.ts"; +import { KinAttestationTrust } from "../approvals/attestation/AttestationTrust.ts"; +import * as PendingActions from "../approvals/PendingActions.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { KinApnsTransport, type KinApnsPush, type KinApnsResult } from "./Apns.ts"; +import { KinPushDevices, type KinPushCaller } from "./KinPushDevices.ts"; +import { KinPushPresence } from "./KinPushPresence.ts"; +import * as Devices from "./KinPushDevices.ts"; +import * as Presence from "./KinPushPresence.ts"; +import * as Sender from "./KinPushSender.ts"; + +const NOW = Date.parse("2026-11-08T00:00:00Z"); +const T = "2026-11-07T00:00:00.000Z"; +const orgId = Schema.decodeSync(KinOrgId)("org_01"); +const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const member = Schema.decodeSync(KinPersonId)("h_member"); +const token = (fill: string) => fill.repeat(64) as KinPushToken; +const ownerPhone = token("a"); +const ownerTablet = token("b"); +const memberPhone = token("c"); + +const caller = (session: string, personId: KinPersonId): KinPushCaller => ({ + session: { + sessionId: AuthSessionId.make(session), + subject: session, + method: "bearer-access-token", + scopes: [], + }, + people: [{ _tag: "person", orgId, personId }], +}); + +/** A fake APNs: records every push and answers each token as told (200 by default). */ +const makeApns = (status: "ready" | "unconfigured" = "ready") => { + const sent: Array = []; + const answers = new Map(); + const layer = Layer.succeed(KinApnsTransport, { + status, + send: (push) => + Effect.sync(() => { + sent.push(push); + return answers.get(push.token) ?? { status: 200, reason: undefined }; + }), + }); + return { sent, answers, layer }; +}; + +const build = (apns: ReturnType) => + Sender.layer.pipe( + Layer.provideMerge(Layer.mergeAll(Devices.layer, Presence.layer, apns.layer)), + Layer.provideMerge(ApproverKeys.layer), + Layer.provideMerge(PendingActions.layer), + Layer.provide(Layer.succeed(KinAttestationTrust, { load: () => Effect.die("unused") })), + Layer.provideMerge(Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory)), + ); + +const seed = Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES ('org_01', 'Kin', ${T})`; + for (const [person, handle] of [ + [owner, "owner"], + [member, "priya"], + ] as const) { + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) + VALUES (${person}, 'org_01', ${handle}, ${handle}, ${T})`; + } + for (const id of ["sess-owner-phone", "sess-owner-tablet", "sess-member", "sess-key"]) { + yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at) + VALUES (${id}, ${id}, '[]', 'bearer-access-token', ${T}, '2026-12-07T00:00:00.000Z')`; + } + // The owner holds the org's active approver key; Priya's key never got past pending. + for (const [thumbprint, person, state] of [ + ["k".repeat(43), owner, "active"], + ["m".repeat(43), member, "pending"], + ] as const) { + yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, + device_label, platform, hardware, attested, session_id, state, created_at) + VALUES (${thumbprint}, 'org_01', '{}', ${person}, 'Phone', 'ios', 'secure_enclave', 1, + 'sess-key', ${state}, ${NOW})`; + } + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, last_seq, created_at) + VALUES ('chat_team', 'org_01', 'project_group', 0, ${T})`; + for (const [memberId, person, role] of [ + ["m_owner", owner, "owner"], + ["m_priya", member, "member"], + ] as const) { + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, + role, joined_at) + VALUES (${memberId}, 'org_01', 'chat_team', 'person', ${person}, ${role}, ${T})`; + } + const devices = yield* KinPushDevices; + yield* devices.register(caller("sess-owner-phone", owner), { + orgId, + token: ownerPhone, + platform: "ios", + apsEnvironment: "development", + }); + yield* devices.register(caller("sess-owner-tablet", owner), { + orgId, + token: ownerTablet, + platform: "ios", + apsEnvironment: "production", + }); + yield* devices.register(caller("sess-member", member), { + orgId, + token: memberPhone, + platform: "ios", + apsEnvironment: "development", + }); + return { sql, devices, sender: yield* Sender.KinPushSender }; +}); + +const postMessage = ( + sql: SqlClient.SqlClient, + author: { readonly personId: KinPersonId; readonly memberId: string } | "system", + status = "posted", +) => + Effect.gen(function* () { + const [{ seq }] = (yield* sql<{ seq: number }>` + SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM kin_messages`) as [{ seq: number }]; + const messageId = KinMessageId.make(`msg_${seq}`); + const human = author !== "system"; + yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, + author_person_id, author_member_id, author_role, kind, body, mentions_json, status, created_at) + VALUES (${messageId}, 'org_01', 'chat_team', ${seq}, ${human ? "human" : "system"}, + ${human ? author.personId : null}, ${human ? author.memberId : null}, 'member', 'text', + 'Ship it before Friday, the secret is hunter2', '[]', ${status}, ${T})`; + return messageId; + }); + +const postWidget = ( + sql: SqlClient.SqlClient, + type: string, + state: object, + awaiting: ReadonlyArray, +) => + Effect.gen(function* () { + const messageId = yield* postMessage(sql, "system"); + const widgetId = KinWidgetId.make(`w_${messageId}`); + yield* sql`INSERT INTO kin_widgets (widget_id, org_id, chat_id, message_id, widget_class, type, + revision, state_json, awaiting_json, updated_at) + VALUES (${widgetId}, 'org_01', 'chat_team', ${messageId}, 'native', ${type}, 3, + ${JSON.stringify(state)}, ${JSON.stringify(awaiting)}, ${T})`; + return widgetId; + }); + +const categories = (sent: ReadonlyArray) => + sent.map((push) => (push.payload as { aps: { category: string } }).aps.category); + +describe("KinPushSender", () => { + it.effect("sends approval pushes only to approvers' devices, with ids and fixed text", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sender, sql } = yield* seed; + const actions = yield* PendingActions.KinPendingActions; + const { action } = yield* actions.create({ + orgId, + kind: "merge_pull_request", + target: { + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number: 212, + mergeMethod: "squash", + deleteBranchAfter: false, + }, + resolved: { + _tag: "pull_request", + headSha: "a".repeat(40), + base: "main", + head: "kin/fix-212", + title: "Fix the flaky payments test", + additions: 3, + deletions: 1, + files: 1, + checks: [], + }, + targetDigest: "1".repeat(64), + reason: "Approve now, the token is ghp_secret", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { startedBy: { humanId: member }, startedByRole: "member", chain: [] }, + source: KinEventId.make("evt-212"), + } as unknown as PendingActions.KinPendingActionCreateInput); + + const outcome = yield* sender.notify({ _tag: "approval", orgId, actionId: action.id }); + assert.deepStrictEqual(outcome, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); + assert.deepStrictEqual( + apns.sent.map((push) => [push.token, push.environment]), + [ + [ownerPhone, "development"], + [ownerTablet, "production"], + ], + ); + assert.deepStrictEqual(apns.sent[0]?.payload, { + aps: { + alert: { title: "Approval needed", body: "Merge #212 is waiting on you" }, + category: "kin.approval", + sound: "default", + }, + body: { + kin: 1, + orgId, + pendingActionId: action.id, + deepLink: `/kin/org_01/actions/${encodeURIComponent(action.id)}`, + }, + }); + const wire = JSON.stringify(apns.sent.map((push) => push.payload)); + for (const leaked of ["ghp_secret", "flaky payments", "a".repeat(40)]) + assert.notInclude(wire, leaked); + + // Once the approver's key session is revoked, nobody is an approver and nothing is sent. + yield* sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-key'`; + const after = yield* sender.notify({ _tag: "approval", orgId, actionId: action.id }); + assert.strictEqual(after.sent, 0); + assert.strictEqual(apns.sent.length, 2); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("picks the category from the widget and routes only to who it awaits", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sender, sql } = yield* seed; + const cases = [ + ["deferral", { phase: "confirmed" }, [member], ["kin.deferral.confirmed"]], + [ + "deferral", + { phase: "heads_up" }, + [owner], + ["kin.deferral.heads_up", "kin.deferral.heads_up"], + ], + ["deferral", { phase: "done" }, [owner], []], + ["task", { status: "needs_decision" }, [member], ["kin.message"]], + // Approval cards announce nothing themselves; the pending action does, to approvers. + ["approval", { pendingActionId: "act_1" }, [member], []], + ] as const; + for (const [type, state, awaiting, expected] of cases) { + apns.sent.length = 0; + const widgetId = yield* postWidget(sql, type, state, awaiting); + yield* sender.notify({ _tag: "widget", orgId, widgetId }); + assert.deepStrictEqual( + categories(apns.sent), + [...expected], + `${type} ${JSON.stringify(state)}`, + ); + } + apns.sent.length = 0; + const widgetId = yield* postWidget(sql, "deferral", { phase: "confirmed" }, [member]); + yield* sender.notify({ _tag: "widget", orgId, widgetId }); + assert.deepStrictEqual(apns.sent[0]?.payload, { + aps: { + alert: { title: "Deferred", body: "A deferral needs a look" }, + category: "kin.deferral.confirmed", + sound: "default", + "thread-id": "kin:org_01:chat_team", + }, + body: { + kin: 1, + orgId, + chatId: "chat_team", + widgetId, + revision: 3, + deepLink: "/kin/org_01/chats/chat_team", + }, + }); + + apns.sent.length = 0; + const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); + yield* sender.notify({ _tag: "message", orgId, messageId }); + // The author doesn't hear about their own message, and the text never leaves the server. + assert.deepStrictEqual( + apns.sent.map((push) => push.token), + [memberPhone], + ); + assert.deepStrictEqual(categories(apns.sent), ["kin.message"]); + assert.notInclude(JSON.stringify(apns.sent), "hunter2"); + // A suggestion only the owner can see isn't announced to anyone. + const suggested = yield* postMessage(sql, "system", "suggested"); + assert.strictEqual( + (yield* sender.notify({ _tag: "message", orgId, messageId: suggested })).sent, + 0, + ); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("skips a device while its session has the chat open", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sender, sql } = yield* seed; + const presence = yield* KinPushPresence; + const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + const watched = yield* Effect.scoped( + Effect.gen(function* () { + yield* presence.watch(AuthSessionId.make("sess-owner-phone"), "chat_team" as never); + return yield* sender.notify({ _tag: "message", orgId, messageId }); + }), + ); + assert.deepStrictEqual(watched, { status: "ready", sent: 1, suppressed: 1, failed: 0 }); + assert.deepStrictEqual( + apns.sent.map((push) => push.token), + [ownerTablet], + ); + // Closing the chat stream ends the suppression. + const closed = yield* sender.notify({ _tag: "message", orgId, messageId }); + assert.deepStrictEqual(closed, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("sends nothing without an APNs key", () => { + const apns = makeApns("unconfigured"); + return Effect.gen(function* () { + const { sender, sql } = yield* seed; + const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); + assert.deepStrictEqual(yield* sender.notify({ _tag: "message", orgId, messageId }), { + status: "unconfigured", + sent: 0, + suppressed: 0, + failed: 0, + }); + assert.strictEqual(apns.sent.length, 0); + }).pipe(Effect.provide(build(apns))); + }); +}); + +describe("KinPushDevices", () => { + const tokens = (sql: SqlClient.SqlClient) => + sql<{ token: string; person_id: string; session_id: string }>` + SELECT token, person_id, session_id FROM kin_push_devices ORDER BY token`; + + it.effect("removes devices on unregister, session revoke and a dead token", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sender, sql, devices } = yield* seed; + const outsider: KinPushCaller = { ...caller("sess-member", member), people: [] }; + const refused = yield* Effect.exit( + devices.register(outsider, { + orgId, + token: token("d"), + platform: "ios", + apsEnvironment: "production", + }), + ); + assert.isTrue( + Exit.isFailure(refused) && + (refused.cause.reasons[0] as { error?: KinPushError }).error?.reason === "not_member", + ); + // Someone else can't unregister your phone. + assert.isFalse( + (yield* devices.unregister(caller("sess-member", member), { orgId, token: ownerPhone })) + .removed, + ); + assert.isTrue( + (yield* devices.unregister(caller("sess-owner-tablet", owner), { + orgId, + token: ownerTablet, + })).removed, + ); + yield* sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-member'`; + assert.strictEqual(yield* devices.reconcileSessions(), 1); + assert.deepStrictEqual(yield* tokens(sql), [ + { token: ownerPhone, person_id: owner, session_id: "sess-owner-phone" }, + ]); + + apns.answers.set(ownerPhone, { status: 410, reason: "Unregistered" }); + const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + assert.strictEqual((yield* sender.notify({ _tag: "message", orgId, messageId })).failed, 1); + assert.deepStrictEqual(yield* tokens(sql), []); + }).pipe(Effect.provide(build(apns))); + }); +}); diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts new file mode 100644 index 0000000000000..54f64c1bea980 --- /dev/null +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -0,0 +1,281 @@ +import type { + KinActionId, + KinChatId, + KinMessageId, + KinOrgId, + KinPendingAction, + KinPersonId, + KinPushCategory, + KinPushData, + KinPushSendingStatus, + KinWidgetId, +} from "@t3tools/contracts"; +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 Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { ApproverKeys } from "../approvals/ApproverKeys.ts"; +import { KinPendingActions } from "../approvals/PendingActions.ts"; +import { KinApnsTransport } from "./Apns.ts"; +import { KinPushDevices, kinPushDeviceId } from "./KinPushDevices.ts"; +import { KinPushPresence } from "./KinPushPresence.ts"; + +/** + * What server code asks to announce. Only ids: the sender reads everything else, including + * who receives it, from the database, so nothing an agent wrote picks recipients or text. + */ +export type KinPushNotification = + | { readonly _tag: "approval"; readonly orgId: KinOrgId; readonly actionId: KinActionId } + | { readonly _tag: "message"; readonly orgId: KinOrgId; readonly messageId: KinMessageId } + | { readonly _tag: "widget"; readonly orgId: KinOrgId; readonly widgetId: KinWidgetId }; + +export type KinPushOutcome = { + readonly status: KinPushSendingStatus; + readonly sent: number; + /** Devices showing that chat right now. */ + readonly suppressed: number; + readonly failed: number; +}; + +type Push = { + readonly category: KinPushCategory; + readonly title: string; + readonly body: string; + readonly chatId: KinChatId | undefined; + readonly data: KinPushData; + readonly recipients: ReadonlyArray; +}; + +// APNs answers these when a token will never work again (APNs docs, "Handling notification responses"). +const DEAD_TOKEN_REASONS = new Set(["BadDeviceToken", "DeviceTokenNotForTopic", "Unregistered"]); + +const segment = encodeURIComponent; +const decodeAwaiting = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Array(Schema.String)), +); + +/** Fixed text per kind: ids and numbers from the action, never the agent's reason. */ +const approvalPushText = (action: KinPendingAction) => { + switch (action.target._tag) { + case "pull_request": + return action.kind === "merge_pull_request" + ? `Merge #${action.target.number} is waiting on you` + : `A pull request action is waiting on you`; + case "branch": + return "Deleting a branch is waiting on you"; + case "device_key": + return "Adding an approver key is waiting on you"; + case "level": + return "A level change is waiting on you"; + case "content": + return action.kind === "memory_purge" + ? "A memory purge is waiting on you" + : "A rules change is waiting on you"; + } +}; + +export class KinPushSender extends Context.Service< + KinPushSender, + { + readonly status: KinPushSendingStatus; + /** Never fails: a push is best effort, and a failure is logged without the token. */ + readonly notify: (notification: KinPushNotification) => Effect.Effect; + } +>()("t3/kin/push/KinPushSender") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const apns = yield* KinApnsTransport; + const devices = yield* KinPushDevices; + const presence = yield* KinPushPresence; + const keys = yield* ApproverKeys; + const actions = yield* KinPendingActions; + + /** People in the chat now. Muting silences messages, not things waiting on you. */ + const chatPeople = Effect.fn("KinPushSender.chatPeople")(function* ( + orgId: KinOrgId, + chatId: KinChatId, + options: { readonly respectMute: boolean }, + ) { + const now = DateTime.formatIso(yield* DateTime.now); + const rows = yield* sql<{ person_id: KinPersonId; muted_until: string | null }>` + SELECT person_id, muted_until FROM kin_chat_members + WHERE org_id = ${orgId} AND chat_id = ${chatId} AND principal_kind = 'person' + AND left_at IS NULL`; + return rows + .filter((row) => !options.respectMute || row.muted_until === null || row.muted_until <= now) + .map((row) => row.person_id); + }); + + const approvalPush = Effect.fn("KinPushSender.approvalPush")(function* ( + orgId: KinOrgId, + actionId: KinActionId, + ) { + const action = yield* actions.get({ orgId, actionId }); + if (Option.isNone(action) || action.value.state !== "awaiting_approval") return undefined; + const deepLink = `/kin/${segment(orgId)}/actions/${segment(actionId)}`; + return { + category: "kin.approval", + title: "Approval needed", + body: approvalPushText(action.value), + chatId: undefined, + data: { kin: 1, orgId, pendingActionId: actionId, deepLink }, + // DESIGN 9.3: approvers only, read from their keys, never from the request. + recipients: yield* keys.activeApprovers(orgId), + } satisfies Push; + }); + + const messagePush = Effect.fn("KinPushSender.messagePush")(function* ( + orgId: KinOrgId, + messageId: KinMessageId, + ) { + const [row] = yield* sql<{ chat_id: KinChatId; author_person_id: KinPersonId | null }>` + SELECT chat_id, author_person_id FROM kin_messages + WHERE org_id = ${orgId} AND message_id = ${messageId} AND status = 'posted'`; + if (row === undefined) return undefined; + const people = yield* chatPeople(orgId, row.chat_id, { respectMute: true }); + return { + category: "kin.message", + title: "Kin", + body: "New message", + chatId: row.chat_id, + data: { + kin: 1, + orgId, + chatId: row.chat_id, + deepLink: `/kin/${segment(orgId)}/chats/${segment(row.chat_id)}`, + }, + recipients: people.filter((person) => person !== row.author_person_id), + } satisfies Push; + }); + + const widgetPush = Effect.fn("KinPushSender.widgetPush")(function* ( + orgId: KinOrgId, + widgetId: KinWidgetId, + ) { + const [row] = yield* sql<{ + chat_id: KinChatId; + type: string; + revision: number; + phase: unknown; + awaiting_json: string; + }>`SELECT w.chat_id, w.type, w.revision, json_extract(w.state_json, '$.phase') AS phase, + w.awaiting_json + FROM kin_widgets w JOIN kin_messages m ON m.message_id = w.message_id + WHERE w.org_id = ${orgId} AND w.widget_id = ${widgetId} AND w.closed_at IS NULL + AND m.status = 'posted'`; + if (row === undefined) return undefined; + // An approval card can be posted by an agent and await anyone; its push comes from the + // pending action and goes to approvers. + if (row.type === "approval") return undefined; + const kind = + row.type !== "deferral" + ? ({ category: "kin.message", title: "Waiting on you", body: "A card needs you" } as const) + : row.phase === "confirmed" + ? ({ + category: "kin.deferral.confirmed", + title: "Deferred", + body: "A deferral needs a look", + } as const) + : row.phase === "heads_up" + ? ({ + category: "kin.deferral.heads_up", + title: "Starting soon", + body: "A deferred task starts soon", + } as const) + : undefined; + if (kind === undefined) return undefined; + const awaiting = new Set(yield* decodeAwaiting(row.awaiting_json)); + const people = yield* chatPeople(orgId, row.chat_id, { respectMute: false }); + return { + ...kind, + chatId: row.chat_id, + data: { + kin: 1, + orgId, + chatId: row.chat_id, + widgetId, + revision: row.revision, + deepLink: `/kin/${segment(orgId)}/chats/${segment(row.chat_id)}`, + }, + recipients: people.filter((person) => awaiting.has(person)), + } satisfies Push; + }); + + const deliver = Effect.fn("KinPushSender.deliver")(function* (orgId: KinOrgId, push: Push) { + const targets = yield* devices.forPeople(orgId, push.recipients); + let sent = 0; + let suppressed = 0; + let failed = 0; + for (const device of targets) { + if (push.chatId !== undefined && presence.isWatching(device.sessionId, push.chatId)) { + suppressed += 1; + continue; + } + const result = yield* apns.send({ + token: device.token, + environment: device.apsEnvironment, + payload: { + aps: { + alert: { title: push.title, body: push.body }, + category: push.category, + sound: "default", + ...(push.chatId === undefined ? {} : { "thread-id": `kin:${orgId}:${push.chatId}` }), + }, + // expo-notifications reads a remote push's `content.data` from `body`. + body: push.data, + }, + }); + if (result.status === 200) { + sent += 1; + continue; + } + failed += 1; + const deviceId = kinPushDeviceId(device.token); + if (result.status === 410 || DEAD_TOKEN_REASONS.has(result.reason ?? "")) { + yield* devices.forget(orgId, device.token); + yield* Effect.logInfo("Kin push device token is gone; removed it.", { deviceId }); + } else { + yield* Effect.logWarning("APNs refused a Kin push.", { + deviceId, + status: result.status, + reason: result.reason, + }); + } + } + return { sent, suppressed, failed }; + }); + + const nothing: KinPushOutcome = { status: apns.status, sent: 0, suppressed: 0, failed: 0 }; + + const notify = Effect.fn("KinPushSender.notify")( + function* (notification: KinPushNotification) { + if (apns.status === "unconfigured") return nothing; + const push = + notification._tag === "approval" + ? yield* approvalPush(notification.orgId, notification.actionId) + : notification._tag === "message" + ? yield* messagePush(notification.orgId, notification.messageId) + : yield* widgetPush(notification.orgId, notification.widgetId); + if (push === undefined || push.recipients.length === 0) return nothing; + const outcome: KinPushOutcome = { + status: apns.status, + ...(yield* deliver(notification.orgId, push)), + }; + return outcome; + }, + Effect.catch((error) => + Effect.logWarning("Kin push failed.", { error: error._tag }).pipe( + Effect.as({ ...nothing, failed: 1 }), + ), + ), + ); + + return KinPushSender.of({ status: apns.status, notify }); +}); + +export const layer = Layer.effect(KinPushSender, make); diff --git a/apps/server/src/kin/push/layer.ts b/apps/server/src/kin/push/layer.ts new file mode 100644 index 0000000000000..817274be6f129 --- /dev/null +++ b/apps/server/src/kin/push/layer.ts @@ -0,0 +1,12 @@ +import * as Layer from "effect/Layer"; + +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import * as Apns from "./Apns.ts"; +import * as Devices from "./KinPushDevices.ts"; +import * as Presence from "./KinPushPresence.ts"; +import * as Sender from "./KinPushSender.ts"; + +export const layer = Sender.layer.pipe( + Layer.provideMerge(Layer.mergeAll(Devices.layer, Presence.layer, Apns.layer)), + Layer.provide(KinPersistence.layer), +); diff --git a/apps/server/src/kin/push/rpcHandlers.ts b/apps/server/src/kin/push/rpcHandlers.ts new file mode 100644 index 0000000000000..8d68aa9549086 --- /dev/null +++ b/apps/server/src/kin/push/rpcHandlers.ts @@ -0,0 +1,44 @@ +import { KinPushError, KinPushRpcs } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as RpcGroup from "effect/rpc/RpcGroup"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import { KinServer } from "../KinServer.ts"; +import { KinPushDevices } from "./KinPushDevices.ts"; +import { KinPushSender } from "./KinPushSender.ts"; + +const group = RpcGroup.make(...KinPushRpcs); +const unavailable = Effect.fail( + new KinPushError({ reason: "unavailable", message: "Kin notifications are unavailable." }), +); + +export const makeKinPushHandlers = Effect.fn("makeKinPushHandlers")(function* ( + session: AuthenticatedSession, +) { + const kin = yield* Effect.serviceOption(KinServer); + const caller = Effect.gen(function* () { + if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; + const services = kin.value.services.value; + const people = yield* Context.get(services, KinIdentity).resolve(session); + return { + devices: Context.get(services, KinPushDevices), + sending: Context.get(services, KinPushSender).status, + caller: { session, people }, + }; + }); + return group.of({ + "kin.push.registerDevice": (input) => + caller.pipe( + Effect.flatMap(({ devices, sending, caller }) => + devices + .register(caller, input) + .pipe(Effect.map(({ deviceId }) => ({ deviceId, sending }))), + ), + ), + "kin.push.unregisterDevice": (input) => + caller.pipe(Effect.flatMap(({ devices, caller }) => devices.unregister(caller, input))), + }); +}); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 9bb173d00ed2c..7458f51b7638b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,5 +1,6 @@ import { makeKinApprovalHandlers } from "./kin/approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./kin/chat/rpcHandlers.ts"; +import { makeKinPushHandlers } from "./kin/push/rpcHandlers.ts"; import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -2044,6 +2045,7 @@ export const layerWsRpc = ( const handlers = ServerWsRpcGroup.of({ ...(yield* makeKinChatHandlers(currentSession)), ...(yield* makeKinApprovalHandlers(currentSession)), + ...(yield* makeKinPushHandlers(currentSession)), [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index eafd04114a6ee..06cab4b477bb8 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -128,7 +128,7 @@ export const kinClient = { }), registerPush: createEnvironmentRpcCommand(connectionAtomRuntime, { label: "kin:register-push", - tag: KIN_PUSH_METHODS.registerDevice, + tag: KIN_PUSH_WS_METHODS.registerDevice, }), }; ``` @@ -163,14 +163,14 @@ KinPendingAction (view) = { orgId, pendingActionId, kind: "merge" | ..., status: expiresAt? } ``` -Mobile-owned data (**new**, `features/chats/notifications/kinPushPayload.ts`, decoded with Effect Schema): +Push data, shared with the sender as `KinPushData` in `packages/contracts/src/kinPush.ts` and decoded by `features/chats/notifications/kinPushPayload.ts`: ```ts export const KinPushData = Schema.Struct({ kin: Schema.Literal(1), orgId: KinOrgId, - chatId: Schema.String, - widgetId: Schema.optional(Schema.String), + chatId: Schema.optional(KinChatId), // approvals with no chat have none + widgetId: Schema.optional(KinWidgetId), revision: Schema.optional(Schema.Number), pendingActionId: Schema.optional(Schema.String), deepLink: Schema.String, // must match /kin/... ; anything else is dropped @@ -258,12 +258,15 @@ Hiding the buttons is a convenience, not the protection (DESIGN 9.3). The server ### Notifications with action buttons -**Sending (backend, this spec).** T3's relay can't carry Kin's pushes (see Design corrections). `apps/server/src/kin/push/KinPushSender.ts` (**new**) sends APNs pushes directly from the Kin server, over HTTP/2 with token auth. The `.p8` key is in the Kin host's keychain via `ServerSecretStore` (`apps/server/src/auth/ServerSecretStore.ts`). +**Sending (backend, this spec).** T3's relay can't carry Kin's pushes (see Design corrections). `apps/server/src/kin/push/KinPushSender.ts` sends APNs pushes directly from the Kin server, over HTTP/2 with token auth. The `.p8` key is a file on the Kin host outside the repo, named by `KIN_APNS_KEY_FILE`, with `KIN_APNS_KEY_ID`, `KIN_APNS_TEAM_ID` and `KIN_APNS_TOPIC` (the Kin bundle id), in the same environment as `KIN_ENABLED`. If any is missing or the key won't load, push is off: Kin still starts, nothing is sent, the server logs why, and `registerDevice` answers `sending: "unconfigured"`. -- Device tokens are registered through `kin.push.registerDevice` (**new**, contracts in `packages/contracts/src/kinPush.ts`). -- The payload carries `aps.category` and `KinPushData`. Its text stays short and contains no PR body or agent free text, for example "Merge #212 is waiting on you". -- The sender skips a push when the device holds a live subscription to that chat and the app is in the foreground. Upstream owns the foreground handler, so this check has to happen on the server. -- Approval pushes go only to the approvers' devices (DESIGN 9.3). +- Device tokens are registered through `kin.push.registerDevice` and removed through `kin.push.unregisterDevice` (contracts in `packages/contracts/src/kinPush.ts`, `orchestration:read`). A row is per org and token, owned by the person and session that last registered it. The phone registers on every connect, which moves the row to its current session. Rows go away on unregister, when APNs says the token is dead, and when the registering T3 session is revoked (read from `auth_sessions`, as approver keys do). +- 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. 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.chat.subscribe` stream for that chat. Upstream owns the foreground handler, so this check has to happen on the server. MOB-11 must end the chat stream when the app leaves the foreground, so that a live stream means the chat is on screen. +- 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 })`. 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. 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". **Receiving (`features/chats/notifications/installKinNotifications.ts`, new).** @@ -327,7 +330,7 @@ Upstream files touched, one hook each: - No widget kind falls back to a WebView in phase 1. Generated widgets (phase 2) go through `makeMcpAppHost` with the existing outer-document check that a real person tapped. - Push payloads hold ids and short fixed text only. Apple sees them. - Deep links from notifications are checked (`/kin/` prefix, schema decode) before navigation. Route params are treated as untrusted: a `KinApproval` link for an action the viewer can't approve shows the read-only card. -- The `.p8` APNs key stays in the server secret store, never in the repo or logs. +- The `.p8` APNs key stays in a file on the Kin host, never in the repo or logs. Device tokens are never logged; logs use a 12-character hash. ## Tests and acceptance criteria diff --git a/knip.jsonc b/knip.jsonc index ed4bf19129645..f8e34af6cce89 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -50,6 +50,7 @@ "src/claude-history-worker.ts!", "scripts/cli.ts", "scripts/fetch-expo-schema.ts", + "scripts/kin-push-test.ts", "scripts/probe-claude-fork-local-rollback-replay.ts", "scripts/update-test-shard-weights.ts", "scripts/verify-background-live.ts", diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index a1413d5d20ead..d4cece0a5bfcb 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -17,6 +17,7 @@ import { AuthSourceControlWriteScope, ThreadId, EnvironmentId, + KIN_PUSH_WS_METHODS, ORCHESTRATION_V2_WS_METHODS, ScheduledTaskId, WS_METHODS, @@ -96,38 +97,40 @@ describe("command permissions", () => { }), ), ); - it.effect("requires the destination read grant to refresh providers", () => - Effect.scoped( - Effect.gen(function* () { - const registry = yield* setup; - const refresh = createCommandPermissions(runtime, WS_METHODS.serverRefreshProviders); - registry.set(sessions(env), AsyncResult.success(grant(true))); - expect(registry.get(refresh.permissionAtom(env))).toBe(false); - expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( - "EnvironmentAuthorizationError", - ); - registry.set( - sessions(env), - AsyncResult.success({ - ...grant(false), - scopes: [AuthOrchestrationReadScope], - permissions: [AuthOrchestrationReadScope], - }), - ); - expect(registry.get(refresh.permissionAtom(env))).toBe(true); - yield* refresh.authorize(registry, env); - registry.set(sessions(other), AsyncResult.success(grant(false))); - expect(registry.get(refresh.permissionAtom(other))).toBe(false); - expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe( - "EnvironmentAuthorizationError", - ); - registry.set(sessions(env), AsyncResult.success(grant(false))); - expect(registry.get(refresh.permissionAtom(env))).toBe(false); - expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( - "EnvironmentAuthorizationError", - ); - }), - ), + it.effect.each([WS_METHODS.serverRefreshProviders, ...Object.values(KIN_PUSH_WS_METHODS)])( + "requires the destination read grant for %s", + (method) => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + const refresh = createCommandPermissions(runtime, method); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(refresh.permissionAtom(env))).toBe(false); + expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthOrchestrationReadScope], + permissions: [AuthOrchestrationReadScope], + }), + ); + expect(registry.get(refresh.permissionAtom(env))).toBe(true); + yield* refresh.authorize(registry, env); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect(registry.get(refresh.permissionAtom(other))).toBe(false); + expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + registry.set(sessions(env), AsyncResult.success(grant(false))); + expect(registry.get(refresh.permissionAtom(env))).toBe(false); + expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + }), + ), ); it.effect("requires the destination preview grant to close a browser tab", () => diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7e37688b3a5b1..18a37f7c366ef 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -77,5 +77,6 @@ export * from "./kinChat.ts"; export * from "./kinLead.ts"; export * from "./kinTriggers.ts"; export * from "./kinApprovals.ts"; +export * from "./kinPush.ts"; export * from "./kinRpcs.ts"; diff --git a/packages/contracts/src/kinPush.ts b/packages/contracts/src/kinPush.ts new file mode 100644 index 0000000000000..9cbe68a4e03fb --- /dev/null +++ b/packages/contracts/src/kinPush.ts @@ -0,0 +1,117 @@ +import * as Schema from "effect/Schema"; +import * as Rpc from "effect/rpc/Rpc"; + +import { + AuthOrchestrationReadScope, + EnvironmentAuthorizationError, + type AuthEnvironmentScope, +} from "./auth.ts"; +import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { KinActionId } from "./kinApprovals.ts"; +import { KinChatId, KinOrgId, KinWidgetId } from "./kinChat.ts"; + +/** A native APNs device token in hex. Apple says not to fix the length; today it is 32 bytes. */ +export const KinPushToken = Schema.String.check( + Schema.makeFilter((value: string) => /^[0-9a-f]{64,400}$/.test(value), { + expected: "a lowercase hex APNs device token", + }), +); +export type KinPushToken = typeof KinPushToken.Type; + +/** Android (FCM) waits until someone uses Android (mobile spec, open questions). */ +export const KinPushPlatform = Schema.Literals(["ios"]); +export type KinPushPlatform = typeof KinPushPlatform.Type; +export const KinApsEnvironment = Schema.Literals(["development", "production"]); +export type KinApsEnvironment = typeof KinApsEnvironment.Type; + +/** `aps.category`; the phone registers the matching buttons (mobile spec, notifications). */ +export const KinPushCategory = Schema.Literals([ + "kin.approval", + "kin.deferral.confirmed", + "kin.deferral.heads_up", + "kin.message", +]); +export type KinPushCategory = typeof KinPushCategory.Type; + +/** + * What a Kin push carries besides `aps`, under the payload's `body` key, which is what + * expo-notifications exposes as `content.data` for a remote push. Ids and a `/kin/` link only. + */ +export const KinPushData = Schema.Struct({ + kin: Schema.Literal(1), + orgId: KinOrgId, + // Approvals that no chat asked for, such as adding a key, have none. + chatId: Schema.optional(KinChatId), + widgetId: Schema.optional(KinWidgetId), + revision: Schema.optional(NonNegativeInt), + pendingActionId: Schema.optional(KinActionId), + deepLink: Schema.String.check( + Schema.makeFilter((value: string) => /^\/kin\/[A-Za-z0-9._~%/-]+$/.test(value), { + expected: "a /kin/ app path", + }), + ), +}); +export type KinPushData = typeof KinPushData.Type; + +/** `sending` is `unconfigured` until the Kin host has an APNs key: tokens are kept, nothing is sent. */ +export const KinPushSendingStatus = Schema.Literals(["ready", "unconfigured"]); +export type KinPushSendingStatus = typeof KinPushSendingStatus.Type; + +export const KinPushRegisterDeviceInput = Schema.Struct({ + orgId: KinOrgId, + token: KinPushToken, + platform: KinPushPlatform, + apsEnvironment: KinApsEnvironment, + deviceLabel: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(80))), +}); +export type KinPushRegisterDeviceInput = typeof KinPushRegisterDeviceInput.Type; + +export const KinPushRegisterDeviceResult = Schema.Struct({ + /** A short hash of the token, safe to show and log. */ + deviceId: TrimmedNonEmptyString, + sending: KinPushSendingStatus, +}); +export type KinPushRegisterDeviceResult = typeof KinPushRegisterDeviceResult.Type; + +export const KinPushUnregisterDeviceInput = Schema.Struct({ + orgId: KinOrgId, + token: KinPushToken, +}); +export type KinPushUnregisterDeviceInput = typeof KinPushUnregisterDeviceInput.Type; + +export const KinPushUnregisterDeviceResult = Schema.Struct({ removed: Schema.Boolean }); +export type KinPushUnregisterDeviceResult = typeof KinPushUnregisterDeviceResult.Type; + +export class KinPushError extends Schema.TaggedError()("KinPushError", { + reason: Schema.Literals(["not_member", "unavailable"]), + message: Schema.String, +}) {} + +export const KIN_PUSH_WS_METHODS = { + registerDevice: "kin.push.registerDevice", + unregisterDevice: "kin.push.unregisterDevice", +} as const; + +const error = Schema.Union([KinPushError, EnvironmentAuthorizationError]); + +export const KinPushRpcs = [ + Rpc.make(KIN_PUSH_WS_METHODS.registerDevice, { + payload: KinPushRegisterDeviceInput, + success: KinPushRegisterDeviceResult, + error, + }), + Rpc.make(KIN_PUSH_WS_METHODS.unregisterDevice, { + payload: KinPushUnregisterDeviceInput, + success: KinPushUnregisterDeviceResult, + error, + }), +] as const; + +// A device only receives what its session can already read, so reading is the gate. +export const KIN_PUSH_RPC_SCOPES = { + [KIN_PUSH_WS_METHODS.registerDevice]: AuthOrchestrationReadScope, + [KIN_PUSH_WS_METHODS.unregisterDevice]: AuthOrchestrationReadScope, +} as const satisfies Record< + (typeof KIN_PUSH_WS_METHODS)[keyof typeof KIN_PUSH_WS_METHODS], + AuthEnvironmentScope +>; diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index cb0f3117836ae..c0fcf39f2a91f 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -3,6 +3,7 @@ import * as Schema from "effect/Schema"; import { KinBudget, KinBudgetGetInput, KinBudgetSetInput } from "./kinLead.ts"; import { KinApprovalRpcs, KIN_APPROVAL_RPC_SCOPES } from "./kinApprovals.ts"; import { KinChatError, KinChatRpcs, KIN_CHAT_RPC_SCOPES } from "./kinChat.ts"; +import { KinPushRpcs, KIN_PUSH_RPC_SCOPES } from "./kinPush.ts"; import { EnvironmentAuthorizationError, AuthOrchestrationReadScope, @@ -22,10 +23,11 @@ const KinBudgetRpcs = [ }), ] as const; export const KinChatAndBudgetRpcs = [...KinChatRpcs, ...KinBudgetRpcs] as const; -export const KinRpcs = [...KinChatAndBudgetRpcs, ...KinApprovalRpcs] as const; +export const KinRpcs = [...KinChatAndBudgetRpcs, ...KinApprovalRpcs, ...KinPushRpcs] as const; export const KIN_RPC_SCOPES = { ...KIN_CHAT_RPC_SCOPES, ...KIN_APPROVAL_RPC_SCOPES, + ...KIN_PUSH_RPC_SCOPES, "kin.budget.get": AuthOrchestrationReadScope, "kin.budget.set": AuthSettingsWriteScope, } as const; @@ -53,4 +55,6 @@ export const KIN_RPC_AGGREGATES = { "kin.approvals.revokeKey": "kin-approvals", "kin.audit.list": "kin-approvals", "kin.audit.verify": "kin-approvals", + "kin.push.registerDevice": "kin-push", + "kin.push.unregisterDevice": "kin-push", } as const; From 4e1403f5bc9c7ee6f6fb9b0faa15cf87d520c8bf Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 10:05:11 +0530 Subject: [PATCH 02/10] fix(kin): close push security review findings (MOB-10) - Store the registering DPoP key on device rows and spec the relay revocation join that waits on #54; expired sessions keep their rows. - Presence beats travel through the chat stream with a 90 s TTL, so a half-open socket stops suppressing pushes. - A timed-out or failed APNs request ends its HTTP/2 connection; sends run four at a time. - Cap tokens at 10 per person per org, keep tokens on DeviceTokenNotForTopic, honour the 410 timestamp, renew a refused provider token, parse mute times, collapse message pushes per chat. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/chat/rpcHandlers.ts | 5 +- .../migrations/K011_PushDevices.ts | 1 + apps/server/src/kin/push/Apns.test.ts | 108 ++++++++- apps/server/src/kin/push/Apns.ts | 76 +++++-- apps/server/src/kin/push/KinPushDevices.ts | 32 ++- .../src/kin/push/KinPushPresence.test.ts | 107 +++++++++ apps/server/src/kin/push/KinPushPresence.ts | 83 +++++-- .../server/src/kin/push/KinPushSender.test.ts | 212 ++++++++++++++++-- apps/server/src/kin/push/KinPushSender.ts | 120 ++++++---- docs/kin/specs/mobile.md | 9 +- 10 files changed, 639 insertions(+), 114 deletions(-) create mode 100644 apps/server/src/kin/push/KinPushPresence.test.ts diff --git a/apps/server/src/kin/chat/rpcHandlers.ts b/apps/server/src/kin/chat/rpcHandlers.ts index 33ca78ed2c27f..73a240b211e8a 100644 --- a/apps/server/src/kin/chat/rpcHandlers.ts +++ b/apps/server/src/kin/chat/rpcHandlers.ts @@ -75,8 +75,9 @@ export const makeKinChatHandlers = Effect.fn("makeKinChatHandlers")(function* ( Stream.unwrap( viewer.pipe( // While this stream lives, pushes for the chat skip this session's device. - Effect.tap(({ presence }) => presence.watch(session.sessionId, input.chatId)), - Effect.map(({ chat, people }) => chat.subscribe(people, input)), + Effect.map(({ chat, people, presence }) => + chat.subscribe(people, input).pipe(presence.watching(session.sessionId, input.chatId)), + ), ), ).pipe(Stream.mapError(mapError)), "kin.chats.createDirect": (input) => diff --git a/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts b/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts index 64ddb0ebe4752..b6f275ed6f5fe 100644 --- a/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts +++ b/apps/server/src/kin/persistence/migrations/K011_PushDevices.ts @@ -13,6 +13,7 @@ export default Effect.gen(function* () { aps_environment TEXT NOT NULL CHECK (aps_environment IN ('development', 'production')), device_label TEXT, session_id TEXT NOT NULL, + proof_key_thumbprint TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY (org_id, token) diff --git a/apps/server/src/kin/push/Apns.test.ts b/apps/server/src/kin/push/Apns.test.ts index d382541977f50..041bde48a4a10 100644 --- a/apps/server/src/kin/push/Apns.test.ts +++ b/apps/server/src/kin/push/Apns.test.ts @@ -1,6 +1,7 @@ -// @effect-diagnostics nodeBuiltinImport:off -- a throwaway P-256 key on disk, as Apple's .p8 is. +// @effect-diagnostics nodeBuiltinImport:off -- a throwaway P-256 key on disk, as Apple's .p8 is, and a local HTTP/2 APNs. import * as NodeCrypto from "node:crypto"; import * as NodeFS from "node:fs"; +import * as NodeHttp2 from "node:http2"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; @@ -8,8 +9,15 @@ import { assert, it } from "@effect/vitest"; import type { KinPushToken } from "@t3tools/contracts"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as TestClock from "effect/testing/TestClock"; -import { apnsProviderToken, apnsRequestHeaders, loadApnsCredentials } from "./Apns.ts"; +import { + apnsProviderToken, + apnsRequestHeaders, + loadApnsCredentials, + makeApnsTransport, +} from "./Apns.ts"; const keyFile = Effect.acquireRelease( Effect.sync(() => { @@ -89,5 +97,101 @@ it.effect("loads the .p8 only when fully configured, and signs a token APNs can "content-type": "application/json", }, ); + assert.include( + apnsRequestHeaders( + loaded.success, + { token, environment: "development", payload: {}, collapseId: "kin:abc" }, + jwt, + ), + { "apns-collapse-id": "kin:abc" }, + ); + }).pipe(Effect.scoped), +); + +type Answer = { readonly status: number; readonly body?: object } | "hang"; + +/** A local APNs over cleartext HTTP/2. Answers requests in order; "hang" never answers. */ +const fakeApns = (answers: ReadonlyArray) => + Effect.acquireRelease( + Effect.callback<{ + readonly origin: string; + readonly seen: Array<{ readonly session: number; readonly authorization: string }>; + readonly hung: Promise; + readonly server: NodeHttp2.Http2Server; + }>((resume) => { + const server = NodeHttp2.createServer(); + const seen: Array<{ session: number; authorization: string }> = []; + const sessions: Array = []; + let markHung = () => {}; + const hung = new Promise((resolve) => (markHung = resolve)); + server.on("session", (session) => sessions.push(session)); + server.on("stream", (stream, headers) => { + seen.push({ + session: sessions.indexOf(stream.session as NodeHttp2.ServerHttp2Session), + authorization: String(headers.authorization), + }); + const answer = answers[seen.length - 1] ?? { status: 200 }; + if (answer === "hang") return markHung(); + stream.respond({ ":status": answer.status }); + stream.end(answer.body === undefined ? undefined : JSON.stringify(answer.body)); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + resume(Effect.succeed({ origin: `http://127.0.0.1:${port}`, seen, hung, server })); + }); + }), + ({ server }) => Effect.sync(() => server.close()), + ); + +const push = { + token: "a".repeat(64) as KinPushToken, + environment: "production", + payload: {}, +} as const; + +it.effect("replaces a dead APNs connection and renews a refused provider token", () => + Effect.gen(function* () { + const apns = yield* fakeApns([ + "hang", + { status: 403, body: { reason: "ExpiredProviderToken" } }, + { status: 200 }, + { status: 200 }, + { status: 410, body: { reason: "Unregistered", timestamp: 1_794_000_000_000 } }, + ]); + const credentials = { + keyId: "ABC123DEFG", + teamId: "TEAM123456", + topic: "codes.kin.app", + key: NodeCrypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" }).privateKey, + }; + const transport = yield* makeApnsTransport(credentials, () => apns.origin); + + // The first connection takes the request and never answers. + const stalled = yield* Effect.forkChild(transport.send(push)); + yield* Effect.promise(() => apns.hung); + yield* TestClock.adjust("10 seconds"); + assert.deepStrictEqual(yield* Fiber.join(stalled), { status: 0, reason: "transport" }); + + // The next push opens a new connection instead of waiting on the dead one. + assert.deepStrictEqual(yield* transport.send(push), { + status: 403, + reason: "ExpiredProviderToken", + }); + assert.deepStrictEqual(yield* transport.send(push), { status: 200, reason: undefined }); + yield* transport.send(push); + assert.deepStrictEqual(yield* transport.send(push), { + status: 410, + reason: "Unregistered", + timestamp: 1_794_000_000_000, + }); + const [first, refused, renewed, cached] = apns.seen; + assert.deepStrictEqual( + apns.seen.map((request) => request.session), + [0, 1, 1, 1, 1], + ); + assert.strictEqual(refused?.authorization, first?.authorization); + assert.notStrictEqual(renewed?.authorization, refused?.authorization); + assert.strictEqual(cached?.authorization, renewed?.authorization); }).pipe(Effect.scoped), ); diff --git a/apps/server/src/kin/push/Apns.ts b/apps/server/src/kin/push/Apns.ts index 3b40d8e9e1a34..d2b370430d36a 100644 --- a/apps/server/src/kin/push/Apns.ts +++ b/apps/server/src/kin/push/Apns.ts @@ -32,10 +32,19 @@ export type KinApnsPush = { readonly token: KinPushToken; readonly environment: KinApsEnvironment; readonly payload: unknown; + /** `apns-collapse-id`: a newer push with the same id replaces the shown one. At most 64 bytes. */ + readonly collapseId?: string; }; -/** `status` 0 means APNs never answered (network, timeout); nothing was delivered. */ -export type KinApnsResult = { readonly status: number; readonly reason: string | undefined }; +/** + * `status` 0 means APNs never answered (network, timeout); nothing was delivered. + * `timestamp` is when APNs last knew the token was valid, sent with a 410. + */ +export type KinApnsResult = { + readonly status: number; + readonly reason: string | undefined; + readonly timestamp?: number; +}; export class KinApnsTransport extends Context.Service< KinApnsTransport, @@ -71,6 +80,7 @@ export const apnsRequestHeaders = ( "apns-push-type": "alert", "apns-priority": "10", "content-type": "application/json", + ...(push.collapseId === undefined ? {} : { "apns-collapse-id": push.collapseId }), }); /** @@ -128,15 +138,19 @@ const post = ( request.on("data", (chunk: Buffer) => chunks.push(chunk)); request.on("end", () => { const text = Buffer.concat(chunks).toString("utf8"); - let reason: string | undefined; + let parsed: unknown; try { - const parsed: unknown = text.length > 0 ? JSON.parse(text) : undefined; - if (typeof parsed === "object" && parsed !== null && "reason" in parsed) - reason = String(parsed.reason); + parsed = text.length > 0 ? JSON.parse(text) : undefined; } catch { - reason = undefined; + parsed = undefined; } - resume(Effect.succeed({ status, reason })); + const fields = typeof parsed === "object" && parsed !== null ? parsed : {}; + const reason = "reason" in fields ? String(fields.reason) : undefined; + const timestamp = + "timestamp" in fields && typeof fields.timestamp === "number" + ? fields.timestamp + : undefined; + resume(Effect.succeed({ status, reason, ...(timestamp === undefined ? {} : { timestamp }) })); }); request.on("error", (error: Error) => resume(Effect.fail(error))); request.end(body); @@ -157,10 +171,15 @@ const unconfigured = (reason: string) => ), ); -const make = Effect.gen(function* () { - const loaded = yield* Effect.result(loadApnsCredentials()); - if (loaded._tag === "Failure") return yield* unconfigured(loaded.failure); - const credentials = loaded.success; +const unreachable: KinApnsResult = { status: 0, reason: "transport" }; +// APNs answers these with 403 when the cached provider token stopped working. +const STALE_PROVIDER_TOKEN = new Set(["ExpiredProviderToken", "InvalidProviderToken"]); + +/** The ready transport. `origin` exists so tests can point it at a local HTTP/2 server. */ +export const makeApnsTransport = Effect.fn("KinApns.makeTransport")(function* ( + credentials: KinApnsCredentials, + origin: (environment: KinApsEnvironment) => string = (environment) => ORIGINS[environment], +) { const sessions = new Map(); let jwt: { readonly value: string; readonly at: number } | undefined; yield* Effect.addFinalizer(() => @@ -173,7 +192,7 @@ const make = Effect.gen(function* () { const sessionFor = (environment: KinApsEnvironment) => { const open = sessions.get(environment); if (open !== undefined && !open.closed && !open.destroyed) return open; - const session = NodeHttp2.connect(ORIGINS[environment]); + const session = NodeHttp2.connect(origin(environment)); const drop = () => { if (sessions.get(environment) === session) sessions.delete(environment); }; @@ -185,6 +204,13 @@ const make = Effect.gen(function* () { return session; }; + // A dead connection never errors on its own, so a timeout must end it or every push stalls. + const discard = (environment: KinApsEnvironment, session: NodeHttp2.ClientHttp2Session) => + Effect.sync(() => { + if (sessions.get(environment) === session) sessions.delete(environment); + session.destroy(); + }); + const providerToken = Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; if (jwt === undefined || now - jwt.at >= JWT_TTL_MS) @@ -192,22 +218,36 @@ const make = Effect.gen(function* () { return jwt.value; }); - yield* Effect.logInfo("Kin push is on.", { topic: credentials.topic, keyId: credentials.keyId }); return KinApnsTransport.of({ status: "ready", send: Effect.fn("KinApnsTransport.send")(function* (push: KinApnsPush) { const headers = apnsRequestHeaders(credentials, push, yield* providerToken); - return yield* encodeJson(push.payload).pipe( - Effect.flatMap((body) => post(sessionFor(push.environment), headers, body)), - Effect.timeout(REQUEST_TIMEOUT), + const result = yield* encodeJson(push.payload).pipe( + Effect.flatMap((body) => { + const session = sessionFor(push.environment); + return post(session, headers, body).pipe( + Effect.timeout(REQUEST_TIMEOUT), + Effect.tapError(() => discard(push.environment, session)), + ); + }), Effect.catch((error) => Effect.logWarning("Kin push couldn't reach APNs.", { error: String(error) }).pipe( - Effect.as({ status: 0, reason: "transport" }), + Effect.as(unreachable), ), ), ); + if (STALE_PROVIDER_TOKEN.has(result.reason ?? "")) jwt = undefined; + return result; }), }); }); +const make = Effect.gen(function* () { + const loaded = yield* Effect.result(loadApnsCredentials()); + if (loaded._tag === "Failure") return yield* unconfigured(loaded.failure); + const credentials = loaded.success; + yield* Effect.logInfo("Kin push is on.", { topic: credentials.topic, keyId: credentials.keyId }); + return yield* makeApnsTransport(credentials); +}); + export const layer = Layer.effect(KinApnsTransport, make); diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts index 968ab00a0316f..e180b099b0d86 100644 --- a/apps/server/src/kin/push/KinPushDevices.ts +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -38,6 +38,9 @@ export type KinPushDevice = { export const kinPushDeviceId = (token: string) => NodeCrypto.createHash("sha256").update(token).digest("hex").slice(0, 12); +/** Past this, registering a token drops the person's least recently registered one. */ +export const KIN_PUSH_DEVICES_PER_PERSON = 10; + const isKinPushError = Schema.is(KinPushError); const fail = (reason: KinPushError["reason"], message: string) => Effect.fail(new KinPushError({ reason, message })); @@ -58,8 +61,15 @@ export class KinPushDevices extends Context.Service< orgId: KinOrgId, people: ReadonlyArray, ) => Effect.Effect, KinPushError>; - /** APNs said the token is dead (410, BadDeviceToken). */ - readonly forget: (orgId: KinOrgId, token: KinPushToken) => Effect.Effect; + /** + * APNs said the token is dead. With `invalidSince` (a 410's timestamp), a row registered + * after it survives, because the phone has since handed it to us again. + */ + readonly forget: ( + orgId: KinOrgId, + token: KinPushToken, + invalidSince?: number, + ) => Effect.Effect; /** Removes devices registered from a revoked T3 session. Returns how many. */ readonly reconcileSessions: () => Effect.Effect; } @@ -81,7 +91,9 @@ const make = Effect.gen(function* () { }; // T3 revokes sessions in SessionStore; reading its table keeps auth free of Kin hooks, - // as ApproverKeys does. Runs before every send. + // as ApproverKeys does. Runs before every send. Relay sessions renew under new ids, so this + // misses a revoked relay phone until #54 joins on proof_key_thumbprint (mobile spec). + // Expired sessions stay: a live socket outlives the session it registered under. const reconcileSessions = Effect.fn("KinPushDevices.reconcileSessions")( function* () { const removed = yield* sql`DELETE FROM kin_push_devices WHERE session_id IN ( @@ -105,6 +117,7 @@ const make = Effect.gen(function* () { aps_environment: input.apsEnvironment, device_label: input.deviceLabel ?? null, session_id: caller.session.sessionId, + proof_key_thumbprint: caller.session.proofKeyThumbprint ?? null, created_at: now, updated_at: now, })} @@ -114,7 +127,15 @@ const make = Effect.gen(function* () { aps_environment = excluded.aps_environment, device_label = excluded.device_label, session_id = excluded.session_id, + proof_key_thumbprint = excluded.proof_key_thumbprint, updated_at = excluded.updated_at`; + 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 ( + SELECT token FROM kin_push_devices + WHERE org_id = ${input.orgId} AND person_id = ${person.personId} + AND token != ${input.token} + ORDER BY updated_at DESC, token LIMIT ${KIN_PUSH_DEVICES_PER_PERSON - 1})`; return { deviceId: kinPushDeviceId(input.token) }; }, Effect.mapError(internal("KinPushDevices.register")), @@ -155,8 +176,9 @@ const make = Effect.gen(function* () { ); const forget = Effect.fn("KinPushDevices.forget")( - function* (orgId: KinOrgId, token: KinPushToken) { - yield* sql`DELETE FROM kin_push_devices WHERE org_id = ${orgId} AND token = ${token}`; + function* (orgId: KinOrgId, token: KinPushToken, invalidSince?: number) { + yield* sql`DELETE FROM kin_push_devices WHERE org_id = ${orgId} AND token = ${token} + ${invalidSince === undefined ? sql`` : sql`AND updated_at < ${invalidSince}`}`; }, Effect.mapError(internal("KinPushDevices.forget")), ); diff --git a/apps/server/src/kin/push/KinPushPresence.test.ts b/apps/server/src/kin/push/KinPushPresence.test.ts new file mode 100644 index 0000000000000..cdccf3b10b028 --- /dev/null +++ b/apps/server/src/kin/push/KinPushPresence.test.ts @@ -0,0 +1,107 @@ +import { assert, it } from "@effect/vitest"; +import { AuthSessionId, AuthStandardClientScopes, KinAgentId, KinChatId } from "@t3tools/contracts"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import * as Sqlite from "../../persistence/Sqlite.ts"; +import { KinChatService } from "../chat/KinChatService.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import * as Repository from "../chat/KinChatRepository.ts"; +import * as Chat from "../chat/layer.ts"; +import { makeKinChatHandlers } from "../chat/rpcHandlers.ts"; +import { dormantLeadDependencies } from "../lead/layer.testkit.ts"; +import * as Kin from "../layer.ts"; +import * as Presence from "./KinPushPresence.ts"; + +const sessionId = AuthSessionId.make("sess-phone"); +const chatId = KinChatId.make("chat_team"); + +it.effect("counts a watcher only while its client keeps taking the stream", () => + Effect.gen(function* () { + const presence = yield* Presence.KinPushPresence; + const idleOpen = yield* Deferred.make(); + // An idle chat on a live client: nothing to send, and the stream keeps being pulled. + yield* Stream.fromEffect(Deferred.succeed(idleOpen, undefined)).pipe( + Stream.concat(Stream.never), + presence.watching(sessionId, chatId), + Stream.runDrain, + Effect.forkChild, + ); + yield* Deferred.await(idleOpen); + for (let minute = 0; minute < 10; minute += 1) yield* TestClock.adjust("1 minute"); + assert.isTrue(yield* presence.isWatching(sessionId, chatId)); + + // A half-open client: it never acks the first event, so the server stops pulling. + const stalledChat = KinChatId.make("chat_stalled"); + const received = yield* Deferred.make(); + const ack = yield* Deferred.make(); + yield* Stream.make("event").pipe( + Stream.concat(Stream.never), + presence.watching(sessionId, stalledChat), + Stream.runForEach(() => + Deferred.succeed(received, undefined).pipe(Effect.andThen(Deferred.await(ack))), + ), + Effect.forkChild, + ); + yield* Deferred.await(received); + yield* TestClock.adjust("89 seconds"); + assert.isTrue(yield* presence.isWatching(sessionId, stalledChat)); + yield* TestClock.adjust("1 second"); + assert.isFalse(yield* presence.isWatching(sessionId, stalledChat)); + }).pipe(Effect.provide(Presence.layer)), +); + +const session = { + sessionId, + subject: "phone", + method: "browser-session-cookie" as const, + scopes: AuthStandardClientScopes, +}; +const root = Kin.layer.pipe( + Layer.provide(dormantLeadDependencies), + Layer.provideMerge(Chat.layer), + Layer.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ KIN_ENABLED: true }))), + Layer.provideMerge(Sqlite.layerMemory), +); + +it.effect("marks the chat open for the subscribing session through the real handler", () => + Effect.gen(function* () { + const person = (yield* (yield* KinIdentity).resolve(session))[0]; + assert.isDefined(person); + const agentId = KinAgentId.make("lead"); + yield* (yield* Repository.KinChatRepository).insertAgent({ + ...person, + agentId, + ownerPersonId: person.personId, + displayName: "Lead", + role: "lead", + createdAt: "1970-01-01T00:00:00.000Z", + }); + const direct = yield* (yield* KinChatService).createDirect(person, { ...person, agentId }); + const services = Option.getOrThrow((yield* Kin.KinServer).services); + const presence = Context.get(services, Presence.KinPushPresence); + + const handlers = yield* makeKinChatHandlers(session); + const backlog = yield* Deferred.make(); + const subscription = yield* handlers["kin.chat.subscribe"]({ + chatId: direct.chatId, + afterSeq: 0, + }).pipe( + Stream.runForEach(() => Deferred.succeed(backlog, undefined)), + Effect.forkChild, + ); + yield* Deferred.await(backlog); + assert.isTrue(yield* presence.isWatching(sessionId, direct.chatId)); + assert.isFalse(yield* presence.isWatching(AuthSessionId.make("sess-other"), direct.chatId)); + + yield* Fiber.interrupt(subscription); + assert.isFalse(yield* presence.isWatching(sessionId, direct.chatId)); + }).pipe(Effect.provide(root)), +); diff --git a/apps/server/src/kin/push/KinPushPresence.ts b/apps/server/src/kin/push/KinPushPresence.ts index 407b90e63c278..7b19dea9f8b14 100644 --- a/apps/server/src/kin/push/KinPushPresence.ts +++ b/apps/server/src/kin/push/KinPushPresence.ts @@ -1,8 +1,15 @@ import type { AuthSessionId, KinChatId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +/** A watcher whose last beat is older than this no longer counts as on screen. */ +const KIN_PUSH_PRESENCE_TTL = Duration.seconds(90); +const BEAT_INTERVAL = Duration.seconds(30); +const BEAT: unique symbol = Symbol("KinPushPresence.beat"); /** * Which sessions have a chat open right now. Upstream owns the phone's foreground handler, @@ -12,35 +19,71 @@ import type * as Scope from "effect/Scope"; export class KinPushPresence extends Context.Service< KinPushPresence, { - /** Marks the chat open for the session until the scope closes. */ - readonly watch: ( + /** + * Marks the chat open for the session while the stream runs. Beats travel through the + * stream, and the RPC server pulls only after the client acks a chunk, so a half-open + * socket stops refreshing once a chunk goes unacked. + */ + readonly watching: ( sessionId: AuthSessionId, chatId: KinChatId, - ) => Effect.Effect; - readonly isWatching: (sessionId: AuthSessionId, chatId: KinChatId) => boolean; + ) => (stream: Stream.Stream) => Stream.Stream; + readonly isWatching: (sessionId: AuthSessionId, chatId: KinChatId) => Effect.Effect; } >()("t3/kin/push/KinPushPresence") {} const make = Effect.sync(() => { - const open = new Map(); + type Watcher = { refreshedAt: number }; + const open = new Map>(); const slot = (sessionId: AuthSessionId, chatId: KinChatId) => `${sessionId}\u0000${chatId}`; - return KinPushPresence.of({ - watch: Effect.fn("KinPushPresence.watch")(function* (sessionId, chatId) { - yield* Effect.acquireRelease( + const ttl = Duration.toMillis(KIN_PUSH_PRESENCE_TTL); + + const watch = Effect.fn("KinPushPresence.watch")(function* (key: string) { + const watcher: Watcher = { refreshedAt: yield* Clock.currentTimeMillis }; + yield* Effect.acquireRelease( + Effect.sync(() => { + const watchers = open.get(key) ?? new Set(); + watchers.add(watcher); + open.set(key, watchers); + }), + () => Effect.sync(() => { - const key = slot(sessionId, chatId); - open.set(key, (open.get(key) ?? 0) + 1); - return key; + const watchers = open.get(key); + watchers?.delete(watcher); + if (watchers?.size === 0) open.delete(key); }), - (key) => - Effect.sync(() => { - const left = (open.get(key) ?? 1) - 1; - if (left > 0) open.set(key, left); - else open.delete(key); - }), - ); + ); + return watcher; + }); + + return KinPushPresence.of({ + watching: + (sessionId, chatId) => + (stream: Stream.Stream) => + Stream.unwrap( + Effect.map(watch(slot(sessionId, chatId)), (watcher) => + stream.pipe( + Stream.merge(Stream.tick(BEAT_INTERVAL).pipe(Stream.as(BEAT)), { + haltStrategy: "left", + }), + Stream.tap((event) => + event === BEAT + ? Effect.map(Clock.currentTimeMillis, (now) => { + watcher.refreshedAt = now; + }) + : Effect.void, + ), + Stream.filter((event): event is A => event !== BEAT), + ), + ), + ), + isWatching: Effect.fn("KinPushPresence.isWatching")(function* (sessionId, chatId) { + const watchers = open.get(slot(sessionId, chatId)); + if (watchers === undefined) return false; + const now = yield* Clock.currentTimeMillis; + for (const watcher of watchers) if (now - watcher.refreshedAt < ttl) return true; + return false; }), - isWatching: (sessionId, chatId) => open.has(slot(sessionId, chatId)), }); }); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index 26101be321dd7..ef5bce8476550 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { AuthSessionId, + KinChatId, KinEventId, KinMessageId, KinOrgId, @@ -9,11 +10,14 @@ import { type KinPushError, type KinPushToken, } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as Sqlite from "../../persistence/Sqlite.ts"; @@ -38,27 +42,37 @@ const ownerPhone = token("a"); const ownerTablet = token("b"); const memberPhone = token("c"); -const caller = (session: string, personId: KinPersonId): KinPushCaller => ({ +const caller = ( + session: string, + personId: KinPersonId, + options: { readonly orgId?: KinOrgId; readonly proofKeyThumbprint?: string } = {}, +): KinPushCaller => ({ session: { sessionId: AuthSessionId.make(session), subject: session, method: "bearer-access-token", scopes: [], + ...(options.proofKeyThumbprint === undefined + ? {} + : { proofKeyThumbprint: options.proofKeyThumbprint }), }, - people: [{ _tag: "person", orgId, personId }], + people: [{ _tag: "person", orgId: options.orgId ?? orgId, personId }], }); /** A fake APNs: records every push and answers each token as told (200 by default). */ -const makeApns = (status: "ready" | "unconfigured" = "ready") => { +const makeApns = ( + status: "ready" | "unconfigured" = "ready", + respond: (push: KinApnsPush) => Effect.Effect = () => Effect.void, +) => { const sent: Array = []; const answers = new Map(); const layer = Layer.succeed(KinApnsTransport, { status, send: (push) => - Effect.sync(() => { - sent.push(push); - return answers.get(push.token) ?? { status: 200, reason: undefined }; - }), + Effect.sync(() => sent.push(push)).pipe( + Effect.andThen(respond(push)), + Effect.as(answers.get(push.token) ?? { status: 200, reason: undefined }), + ), }); return { sent, answers, layer }; }; @@ -281,6 +295,7 @@ describe("KinPushSender", () => { deepLink: "/kin/org_01/chats/chat_team", }, }); + assert.isUndefined(apns.sent[0]?.collapseId); apns.sent.length = 0; const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); @@ -292,6 +307,8 @@ describe("KinPushSender", () => { ); assert.deepStrictEqual(categories(apns.sent), ["kin.message"]); assert.notInclude(JSON.stringify(apns.sent), "hunter2"); + // Messages collapse per chat; cards don't, since each one waits on something different. + assert.match(apns.sent[0]?.collapseId ?? "", /^kin:[0-9a-f]{12}$/); // A suggestion only the owner can see isn't announced to anyone. const suggested = yield* postMessage(sql, "system", "suggested"); assert.strictEqual( @@ -307,23 +324,93 @@ describe("KinPushSender", () => { const { sender, sql } = yield* seed; const presence = yield* KinPushPresence; const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); - const watched = yield* Effect.scoped( - Effect.gen(function* () { - yield* presence.watch(AuthSessionId.make("sess-owner-phone"), "chat_team" as never); - return yield* sender.notify({ _tag: "message", orgId, messageId }); - }), + const open = yield* Deferred.make(); + const stream = yield* Stream.fromEffect(Deferred.succeed(open, undefined)).pipe( + Stream.concat(Stream.never), + presence.watching(AuthSessionId.make("sess-owner-phone"), KinChatId.make("chat_team")), + Stream.runDrain, + Effect.forkChild, ); + yield* Deferred.await(open); + const watched = yield* sender.notify({ _tag: "message", orgId, messageId }); assert.deepStrictEqual(watched, { status: "ready", sent: 1, suppressed: 1, failed: 0 }); assert.deepStrictEqual( apns.sent.map((push) => push.token), [ownerTablet], ); // Closing the chat stream ends the suppression. + yield* Fiber.interrupt(stream); const closed = yield* sender.notify({ _tag: "message", orgId, messageId }); assert.deepStrictEqual(closed, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); }).pipe(Effect.provide(build(apns))); }); + it.effect("reaches only people still in the chat, in this org, and not muted", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sender, sql, devices } = yield* seed; + // Someone in another org with a device there hears nothing about this org's chat. + const elsewhere = KinOrgId.make("org_02"); + const stranger = KinPersonId.make("h_stranger"); + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES ('org_02', 'Other', ${T})`; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) + VALUES (${stranger}, 'org_02', 'stranger', 'Stranger', ${T})`; + yield* devices.register(caller("sess-member", stranger, { orgId: elsewhere }), { + orgId: elsewhere, + token: token("e"), + platform: "ios", + apsEnvironment: "production", + }); + const recipients = (mutedUntil: string | null, left: string | null) => + Effect.gen(function* () { + yield* sql`UPDATE kin_chat_members SET muted_until = ${mutedUntil}, left_at = ${left} + WHERE member_id = 'm_priya'`; + apns.sent.length = 0; + const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); + yield* sender.notify({ _tag: "message", orgId, messageId }); + return apns.sent.map((push) => push.token); + }); + assert.deepStrictEqual(yield* recipients(null, null), [memberPhone]); + // 03:00 at +05:00 is 22:00Z yesterday: the mute is over, though the text sorts later. + assert.deepStrictEqual(yield* recipients("2026-11-08T03:00:00+05:00", null), [memberPhone]); + assert.deepStrictEqual(yield* recipients("2026-11-08T01:00:00Z", null), []); + assert.deepStrictEqual(yield* recipients(null, T), []); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("sends to several devices at once, at most four", () => { + let inFlight = 0; + let peak = 0; + const started: Array = []; + const gate = Deferred.makeUnsafe(); + // Each send waits until four are in flight, so sending one at a time never finishes. + const apns = makeApns("ready", (push) => + Effect.gen(function* () { + inFlight += 1; + peak = Math.max(peak, inFlight); + started.push(push.token); + if (inFlight === 4) yield* Deferred.succeed(gate, undefined); + yield* Deferred.await(gate); + inFlight -= 1; + }), + ); + return Effect.gen(function* () { + const { sender, sql, devices } = yield* seed; + for (const fill of ["d", "e", "f", "1"]) + yield* devices.register(caller("sess-owner-phone", owner), { + orgId, + token: token(fill), + platform: "ios", + apsEnvironment: "production", + }); + const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + const outcome = yield* sender.notify({ _tag: "message", orgId, messageId }); + assert.deepStrictEqual(outcome, { status: "ready", sent: 6, suppressed: 0, failed: 0 }); + assert.strictEqual(peak, 4); + assert.strictEqual(started.length, 6); + }).pipe(Effect.provide(build(apns))); + }); + it.effect("sends nothing without an APNs key", () => { const apns = makeApns("unconfigured"); return Effect.gen(function* () { @@ -345,10 +432,10 @@ describe("KinPushDevices", () => { sql<{ token: string; person_id: string; session_id: string }>` SELECT token, person_id, session_id FROM kin_push_devices ORDER BY token`; - it.effect("removes devices on unregister, session revoke and a dead token", () => { + it.effect("removes devices on unregister and session revoke", () => { const apns = makeApns(); return Effect.gen(function* () { - const { sender, sql, devices } = yield* seed; + const { sql, devices } = yield* seed; const outsider: KinPushCaller = { ...caller("sess-member", member), people: [] }; const refused = yield* Effect.exit( devices.register(outsider, { @@ -374,15 +461,104 @@ describe("KinPushDevices", () => { })).removed, ); yield* sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-member'`; + // An expired session isn't revoked: its socket can outlive it. + yield* sql`UPDATE auth_sessions SET expires_at = ${T} WHERE session_id = 'sess-owner-phone'`; assert.strictEqual(yield* devices.reconcileSessions(), 1); assert.deepStrictEqual(yield* tokens(sql), [ { token: ownerPhone, person_id: owner, session_id: "sess-owner-phone" }, ]); + }).pipe(Effect.provide(build(apns))); + }); - apns.answers.set(ownerPhone, { status: 410, reason: "Unregistered" }); - const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); - assert.strictEqual((yield* sender.notify({ _tag: "message", orgId, messageId })).failed, 1); - assert.deepStrictEqual(yield* tokens(sql), []); + it.effect("moves a re-registered device to the caller's session and DPoP key", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql, devices } = yield* seed; + const row = sql<{ + session_id: string; + proof_key_thumbprint: string | null; + updated_at: number; + }>` + SELECT session_id, proof_key_thumbprint, updated_at FROM kin_push_devices + WHERE token = ${ownerPhone}`; + assert.deepStrictEqual(yield* row, [ + { session_id: "sess-owner-phone", proof_key_thumbprint: null, updated_at: NOW }, + ]); + yield* TestClock.adjust("1 hour"); + yield* devices.register( + caller("sess-owner-relay", owner, { proofKeyThumbprint: "p".repeat(43) }), + { orgId, token: ownerPhone, platform: "ios", apsEnvironment: "development" }, + ); + assert.deepStrictEqual(yield* row, [ + { + session_id: "sess-owner-relay", + proof_key_thumbprint: "p".repeat(43), + updated_at: NOW + 3_600_000, + }, + ]); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("keeps the ten most recently registered devices per person", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql, devices } = yield* seed; + const fills = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]; + for (const fill of fills) { + yield* TestClock.adjust("1 minute"); + yield* devices.register(caller("sess-owner-phone", owner), { + orgId, + token: token(fill), + platform: "ios", + apsEnvironment: "production", + }); + } + const owned = sql<{ token: string }>`SELECT token FROM kin_push_devices + WHERE person_id = ${owner} ORDER BY updated_at, token`; + // The phone and tablet from the seed were the oldest two of twelve. + assert.deepStrictEqual( + (yield* owned).map((row) => row.token), + fills.map(token), + ); + assert.strictEqual(fills.length, Devices.KIN_PUSH_DEVICES_PER_PERSON); + // Someone else's devices don't count against the owner's. + assert.deepStrictEqual( + (yield* tokens(sql)).filter((row) => row.person_id === member).map((row) => row.token), + [memberPhone], + ); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("drops a dead token, unless the phone registered it again since", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sender, sql } = yield* seed; + const notifyOwner = Effect.gen(function* () { + const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + return yield* sender.notify({ _tag: "message", orgId, messageId }); + }); + // A wrong topic is our misconfiguration: the token stays. + apns.answers.set(ownerTablet, { status: 400, reason: "DeviceTokenNotForTopic" }); + // Apple saw the phone's token die before the phone registered it (at NOW). + apns.answers.set(ownerPhone, { status: 410, reason: "Unregistered", timestamp: NOW - 1 }); + assert.deepStrictEqual(yield* notifyOwner, { + status: "ready", + sent: 0, + suppressed: 0, + failed: 2, + }); + assert.deepStrictEqual( + (yield* tokens(sql)).map((row) => row.token), + [ownerPhone, ownerTablet, memberPhone], + ); + + apns.answers.set(ownerPhone, { status: 410, reason: "Unregistered", timestamp: NOW + 1 }); + apns.answers.set(ownerTablet, { status: 400, reason: "BadDeviceToken" }); + yield* notifyOwner; + assert.deepStrictEqual( + (yield* tokens(sql)).map((row) => row.token), + [memberPhone], + ); }).pipe(Effect.provide(build(apns))); }); }); diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index 54f64c1bea980..efcae54e61c0b 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -11,7 +11,7 @@ import type { KinWidgetId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import * as DateTime from "effect/DateTime"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -21,7 +21,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { ApproverKeys } from "../approvals/ApproverKeys.ts"; import { KinPendingActions } from "../approvals/PendingActions.ts"; import { KinApnsTransport } from "./Apns.ts"; -import { KinPushDevices, kinPushDeviceId } from "./KinPushDevices.ts"; +import { KinPushDevices, kinPushDeviceId, type KinPushDevice } from "./KinPushDevices.ts"; import { KinPushPresence } from "./KinPushPresence.ts"; /** @@ -46,14 +46,22 @@ type Push = { readonly title: string; readonly body: string; readonly chatId: KinChatId | undefined; + /** Message pushes collapse per chat, so a busy chat shows one banner. */ + readonly collapseId?: string; readonly data: KinPushData; readonly recipients: ReadonlyArray; }; -// APNs answers these when a token will never work again (APNs docs, "Handling notification responses"). -const DEAD_TOKEN_REASONS = new Set(["BadDeviceToken", "DeviceTokenNotForTopic", "Unregistered"]); +// APNs docs, "Handling notification responses". A 410 is handled by its timestamp instead. +const DEAD_TOKEN_REASONS = new Set(["BadDeviceToken"]); +// The token is fine; our `KIN_APNS_TOPIC` doesn't match the app that registered it. +const CONFIG_REASONS = new Set(["DeviceTokenNotForTopic", "TopicDisallowed"]); +const SEND_CONCURRENCY = 4; const segment = encodeURIComponent; +/** Fits `apns-collapse-id`'s 64 bytes whatever the ids' length. */ +const kinPushCollapseId = (orgId: KinOrgId, chatId: KinChatId) => + `kin:${kinPushDeviceId(`${orgId}\u0000${chatId}`)}`; const decodeAwaiting = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Array(Schema.String)), ); @@ -82,7 +90,10 @@ export class KinPushSender extends Context.Service< KinPushSender, { readonly status: KinPushSendingStatus; - /** Never fails: a push is best effort, and a failure is logged without the token. */ + /** + * Never fails: a push is best effort, and a failure is logged without the token. Callers run + * it after their transaction commits and fork it off the request, since APNs can take seconds. + */ readonly notify: (notification: KinPushNotification) => Effect.Effect; } >()("t3/kin/push/KinPushSender") {} @@ -101,13 +112,16 @@ const make = Effect.gen(function* () { chatId: KinChatId, options: { readonly respectMute: boolean }, ) { - const now = DateTime.formatIso(yield* DateTime.now); + const now = yield* Clock.currentTimeMillis; const rows = yield* sql<{ person_id: KinPersonId; muted_until: string | null }>` SELECT person_id, muted_until FROM kin_chat_members WHERE org_id = ${orgId} AND chat_id = ${chatId} AND principal_kind = 'person' AND left_at IS NULL`; return rows - .filter((row) => !options.respectMute || row.muted_until === null || row.muted_until <= now) + .filter( + (row) => + !options.respectMute || row.muted_until === null || !(Date.parse(row.muted_until) > now), + ) .map((row) => row.person_id); }); @@ -143,6 +157,7 @@ const make = Effect.gen(function* () { title: "Kin", body: "New message", chatId: row.chat_id, + collapseId: kinPushCollapseId(orgId, row.chat_id), data: { kin: 1, orgId, @@ -206,48 +221,61 @@ const make = Effect.gen(function* () { } satisfies Push; }); - const deliver = Effect.fn("KinPushSender.deliver")(function* (orgId: KinOrgId, push: Push) { - const targets = yield* devices.forPeople(orgId, push.recipients); - let sent = 0; - let suppressed = 0; - let failed = 0; - for (const device of targets) { - if (push.chatId !== undefined && presence.isWatching(device.sessionId, push.chatId)) { - suppressed += 1; - continue; - } - const result = yield* apns.send({ - token: device.token, - environment: device.apsEnvironment, - payload: { - aps: { - alert: { title: push.title, body: push.body }, - category: push.category, - sound: "default", - ...(push.chatId === undefined ? {} : { "thread-id": `kin:${orgId}:${push.chatId}` }), - }, - // expo-notifications reads a remote push's `content.data` from `body`. - body: push.data, + const sendTo = Effect.fn("KinPushSender.sendTo")(function* ( + orgId: KinOrgId, + push: Push, + device: KinPushDevice, + ) { + if (push.chatId !== undefined && (yield* presence.isWatching(device.sessionId, push.chatId))) + return "suppressed" as const; + const result = yield* apns.send({ + token: device.token, + environment: device.apsEnvironment, + ...(push.collapseId === undefined ? {} : { collapseId: push.collapseId }), + payload: { + aps: { + alert: { title: push.title, body: push.body }, + category: push.category, + sound: "default", + ...(push.chatId === undefined ? {} : { "thread-id": `kin:${orgId}:${push.chatId}` }), }, + // expo-notifications reads a remote push's `content.data` from `body`. + body: push.data, + }, + }); + if (result.status === 200) return "sent" as const; + const deviceId = kinPushDeviceId(device.token); + if (result.status === 410 || DEAD_TOKEN_REASONS.has(result.reason ?? "")) { + yield* devices.forget( + orgId, + device.token, + result.status === 410 ? result.timestamp : undefined, + ); + yield* Effect.logInfo("Kin push device token is gone.", { deviceId, reason: result.reason }); + } else if (CONFIG_REASONS.has(result.reason ?? "")) { + yield* Effect.logError("APNs refused a Kin push: check KIN_APNS_TOPIC.", { + deviceId, + reason: result.reason, + }); + } else { + yield* Effect.logWarning("APNs refused a Kin push.", { + deviceId, + status: result.status, + reason: result.reason, }); - if (result.status === 200) { - sent += 1; - continue; - } - failed += 1; - const deviceId = kinPushDeviceId(device.token); - if (result.status === 410 || DEAD_TOKEN_REASONS.has(result.reason ?? "")) { - yield* devices.forget(orgId, device.token); - yield* Effect.logInfo("Kin push device token is gone; removed it.", { deviceId }); - } else { - yield* Effect.logWarning("APNs refused a Kin push.", { - deviceId, - status: result.status, - reason: result.reason, - }); - } } - return { sent, suppressed, failed }; + return "failed" as const; + }); + + const deliver = Effect.fn("KinPushSender.deliver")(function* (orgId: KinOrgId, push: Push) { + const targets = yield* devices.forPeople(orgId, push.recipients); + // Bounded, so one slow device doesn't hold up the rest and a big org doesn't flood APNs. + const results = yield* Effect.forEach(targets, (device) => sendTo(orgId, push, device), { + concurrency: SEND_CONCURRENCY, + }); + const count = (outcome: (typeof results)[number]) => + results.filter((result) => result === outcome).length; + return { sent: count("sent"), suppressed: count("suppressed"), failed: count("failed") }; }); const nothing: KinPushOutcome = { status: apns.status, sent: 0, suppressed: 0, failed: 0 }; diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 06cab4b477bb8..394b3de7cb86b 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -260,11 +260,14 @@ Hiding the buttons is a convenience, not the protection (DESIGN 9.3). The server **Sending (backend, this spec).** T3's relay can't carry Kin's pushes (see Design corrections). `apps/server/src/kin/push/KinPushSender.ts` sends APNs pushes directly from the Kin server, over HTTP/2 with token auth. The `.p8` key is a file on the Kin host outside the repo, named by `KIN_APNS_KEY_FILE`, with `KIN_APNS_KEY_ID`, `KIN_APNS_TEAM_ID` and `KIN_APNS_TOPIC` (the Kin bundle id), in the same environment as `KIN_ENABLED`. If any is missing or the key won't load, push is off: Kin still starts, nothing is sent, the server logs why, and `registerDevice` answers `sending: "unconfigured"`. -- Device tokens are registered through `kin.push.registerDevice` and removed through `kin.push.unregisterDevice` (contracts in `packages/contracts/src/kinPush.ts`, `orchestration:read`). A row is per org and token, owned by the person and session that last registered it. The phone registers on every connect, which moves the row to its current session. Rows go away on unregister, when APNs says the token is dead, and when the registering T3 session is revoked (read from `auth_sessions`, as approver keys do). +- Device tokens are registered through `kin.push.registerDevice` and removed through `kin.push.unregisterDevice` (contracts in `packages/contracts/src/kinPush.ts`, `orchestration:read`). A row is per org and token, owned by the person, session and DPoP key (`proof_key_thumbprint`) that last registered it. The phone registers on every connect, which moves the row to its current session. A person keeps at most 10 tokens per org; registering an 11th drops the one registered longest ago. Rows go away on unregister, when APNs says the token is dead, and when the registering T3 session is revoked (read from `auth_sessions`, as approver keys do). An expired session doesn't remove its rows, because a live socket outlives the session it connected with. +- **Relay revocation waits on #54.** A relay phone's DPoP session renews hourly under a new id while its socket keeps the first one, so revoking the phone in Settings revokes a session no row names, and its pushes continue. Lane A's #54 adds `kin_auth_session_keys(session_id, proof_key_thumbprint, created_at)`, filled when a session is issued. Then reconciliation removes a row when its `proof_key_thumbprint` matches a `kin_auth_session_keys` row whose `auth_sessions` row has `revoked_at IS NOT NULL`. "Sign out other devices" revokes every session except the caller's, so the same join must skip rows carrying the caller's own thumbprint, or the caller's earlier sessions take its own phone with them. +- 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. `DeviceTokenNotForTopic` means `KIN_APNS_TOPIC` is wrong, so it's logged as an error and the token stays. `ExpiredProviderToken` and `InvalidProviderToken` make the next push sign a new provider token. +- 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, and the next push opens a new one. - 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. 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.chat.subscribe` stream for that chat. Upstream owns the foreground handler, so this check has to happen on the server. MOB-11 must end the chat stream when the app leaves the foreground, so that a live stream means the chat is on screen. +- The sender skips a device whose session has a live `kin.chat.subscribe` stream for that chat. Upstream owns the foreground handler, so this check has to happen on the server. MOB-11 must end the chat stream when the app leaves the foreground, so that a live stream means the chat is on screen. A half-open socket never closes the stream, so the stream carries a beat every 30 seconds that the RPC server only pulls after the client acks what it last sent; a watcher without a beat for 90 seconds no longer suppresses. - 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 })`. 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. 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. +- Callers pass ids only, `notify({ _tag: "approval", actionId } | { _tag: "message", messageId } | { _tag: "widget", widgetId })`, after their transaction commits and forked off the request, because APNs can take seconds and `notify` reads what the commit wrote. 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". From 4a6da7e41812688107f595f23842ac92fb55c8ee Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 10:41:49 +0530 Subject: [PATCH 03/10] fix(kin): presence from acked watch beats, APNs retries, token takeover (MOB-10) - Presence comes from a new lane-B `kin.push.watch({ chatId })` stream. It beats every 15 s, and each pull refreshes the mark. The RPC server pulls only after the client acks, so a half-open socket stops suppressing within the 45 s TTL. kin.chat.subscribe is back to origin/kin. `watchKinChatForPush` in @t3tools/client-runtime/kin-push opens the stream. - APNs: a connection idle 5 min is replaced before use. No answer, 500 and 503 retry once on a new connection. 429 is logged and dropped. InvalidProviderToken is logged as a config error and the token kept. ExpiredProviderToken re-signs (if the token is 20+ min old) and retries once. - A token moves to another person only once its registering session is revoked or gone. - BadDeviceToken logs a warning with the APNs environment it was sent to. - notify forks into the sender layer's scope, so the request ending doesn't cancel a push. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/chat/rpcHandlers.ts | 13 +- apps/server/src/kin/push/Apns.test.ts | 76 ++++++++--- apps/server/src/kin/push/Apns.ts | 88 +++++++++---- apps/server/src/kin/push/KinPushDevices.ts | 11 +- .../src/kin/push/KinPushPresence.test.ts | 87 +++++-------- apps/server/src/kin/push/KinPushPresence.ts | 49 +++---- .../server/src/kin/push/KinPushSender.test.ts | 120 +++++++++++++----- apps/server/src/kin/push/KinPushSender.ts | 38 ++++-- apps/server/src/kin/push/rpcHandlers.ts | 8 ++ docs/kin/specs/mobile.md | 9 +- packages/client-runtime/package.json | 4 + packages/client-runtime/src/kinPush.ts | 12 ++ packages/client-runtime/src/rpc/client.ts | 4 +- packages/contracts/src/kinPush.ts | 16 +++ packages/contracts/src/kinRpcs.ts | 1 + 15 files changed, 345 insertions(+), 191 deletions(-) create mode 100644 packages/client-runtime/src/kinPush.ts diff --git a/apps/server/src/kin/chat/rpcHandlers.ts b/apps/server/src/kin/chat/rpcHandlers.ts index d22c0c25cb87f..adfb83f5c1ac6 100644 --- a/apps/server/src/kin/chat/rpcHandlers.ts +++ b/apps/server/src/kin/chat/rpcHandlers.ts @@ -8,7 +8,6 @@ import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinServer } from "../layer.ts"; import { KinBudget } from "../lead/KinBudget.ts"; -import { KinPushPresence } from "../push/KinPushPresence.ts"; import { KinIdentity } from "./KinIdentity.ts"; import { KinChatService } from "./KinChatService.ts"; @@ -31,12 +30,11 @@ export const makeKinChatHandlers = Effect.fn("makeKinChatHandlers")(function* ( identity: Context.get(kin.value.services.value, KinIdentity), budget: Context.get(kin.value.services.value, KinBudget), chat: Context.get(kin.value.services.value, KinChatService), - presence: Context.get(kin.value.services.value, KinPushPresence), }; }); const viewer = Effect.gen(function* () { - const { identity, chat, presence } = yield* services; - return { chat, presence, people: yield* identity.resolve(session) }; + const { identity, chat } = yield* services; + return { chat, people: yield* identity.resolve(session) }; }); return group.of({ "kin.budget.get": (input) => @@ -84,12 +82,7 @@ export const makeKinChatHandlers = Effect.fn("makeKinChatHandlers")(function* ( ), "kin.chat.subscribe": (input) => Stream.unwrap( - viewer.pipe( - // While this stream lives, pushes for the chat skip this session's device. - Effect.map(({ chat, people, presence }) => - chat.subscribe(people, input).pipe(presence.watching(session.sessionId, input.chatId)), - ), - ), + viewer.pipe(Effect.map(({ chat, people }) => chat.subscribe(people, input))), ).pipe( Stream.tapError(logInfra), Stream.mapError(mapError), diff --git a/apps/server/src/kin/push/Apns.test.ts b/apps/server/src/kin/push/Apns.test.ts index 041bde48a4a10..c75afa72fd74f 100644 --- a/apps/server/src/kin/push/Apns.test.ts +++ b/apps/server/src/kin/push/Apns.test.ts @@ -150,48 +150,86 @@ const push = { payload: {}, } as const; -it.effect("replaces a dead APNs connection and renews a refused provider token", () => +const credentials = { + keyId: "ABC123DEFG", + teamId: "TEAM123456", + topic: "codes.kin.app", + key: NodeCrypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" }).privateKey, +}; + +it.effect("retries once on a new connection after no answer or a 5xx, never after a 429", () => Effect.gen(function* () { const apns = yield* fakeApns([ "hang", - { status: 403, body: { reason: "ExpiredProviderToken" } }, { status: 200 }, + { status: 500 }, + { status: 200 }, + { status: 503 }, + { status: 503 }, + { status: 429, body: { reason: "TooManyRequests" } }, { status: 200 }, - { status: 410, body: { reason: "Unregistered", timestamp: 1_794_000_000_000 } }, ]); - const credentials = { - keyId: "ABC123DEFG", - teamId: "TEAM123456", - topic: "codes.kin.app", - key: NodeCrypto.generateKeyPairSync("ec", { namedCurve: "prime256v1" }).privateKey, - }; const transport = yield* makeApnsTransport(credentials, () => apns.origin); - // The first connection takes the request and never answers. + // The first connection takes the request and never answers; the retry opens a new one. const stalled = yield* Effect.forkChild(transport.send(push)); yield* Effect.promise(() => apns.hung); yield* TestClock.adjust("10 seconds"); - assert.deepStrictEqual(yield* Fiber.join(stalled), { status: 0, reason: "transport" }); + assert.deepStrictEqual(yield* Fiber.join(stalled), { status: 200, reason: undefined }); + assert.deepStrictEqual(yield* transport.send(push), { status: 200, reason: undefined }); + // Only one retry: a second 503 is the answer. + assert.deepStrictEqual(yield* transport.send(push), { status: 503, reason: undefined }); + assert.deepStrictEqual(yield* transport.send(push), { + status: 429, + reason: "TooManyRequests", + }); + // A connection that answered 5xx is dropped too, and one idle five minutes is replaced. + yield* TestClock.adjust("5 minutes"); + yield* transport.send(push); + assert.deepStrictEqual( + apns.seen.map((request) => request.session), + [0, 1, 1, 2, 2, 3, 4, 5], + ); + }).pipe(Effect.scoped), +); - // The next push opens a new connection instead of waiting on the dead one. +it.effect("renews an expired provider token at most every 20 minutes and keeps a refused one", () => + Effect.gen(function* () { + const apns = yield* fakeApns([ + { status: 403, body: { reason: "ExpiredProviderToken" } }, + { status: 403, body: { reason: "ExpiredProviderToken" } }, + { status: 200 }, + { status: 403, body: { reason: "InvalidProviderToken" } }, + { status: 200 }, + { status: 410, body: { reason: "Unregistered", timestamp: 1_794_000_000_000 } }, + ]); + const transport = yield* makeApnsTransport(credentials, () => apns.origin); + + // A token APNs calls expired right after signing isn't renewed: that would be throttled. assert.deepStrictEqual(yield* transport.send(push), { status: 403, reason: "ExpiredProviderToken", }); + // Twenty minutes in, it is renewed and the push retried with the new one. + yield* TestClock.adjust("20 minutes"); assert.deepStrictEqual(yield* transport.send(push), { status: 200, reason: undefined }); + // A refused token is a configuration problem; signing again on every push won't fix it. + assert.deepStrictEqual(yield* transport.send(push), { + status: 403, + reason: "InvalidProviderToken", + }); yield* transport.send(push); assert.deepStrictEqual(yield* transport.send(push), { status: 410, reason: "Unregistered", timestamp: 1_794_000_000_000, }); - const [first, refused, renewed, cached] = apns.seen; - assert.deepStrictEqual( - apns.seen.map((request) => request.session), - [0, 1, 1, 1, 1], + const [first, expired, renewed, refused, kept] = apns.seen.map( + (request) => request.authorization, ); - assert.strictEqual(refused?.authorization, first?.authorization); - assert.notStrictEqual(renewed?.authorization, refused?.authorization); - assert.strictEqual(cached?.authorization, renewed?.authorization); + assert.strictEqual(expired, first); + assert.notStrictEqual(renewed, expired); + assert.strictEqual(refused, renewed); + assert.strictEqual(kept, renewed); }).pipe(Effect.scoped), ); diff --git a/apps/server/src/kin/push/Apns.ts b/apps/server/src/kin/push/Apns.ts index d2b370430d36a..40614c2c76cf3 100644 --- a/apps/server/src/kin/push/Apns.ts +++ b/apps/server/src/kin/push/Apns.ts @@ -18,6 +18,7 @@ const ORIGINS: Record = { }; // APNs refuses tokens older than an hour and throttles ones renewed more often than every 20 minutes. const JWT_TTL_MS = 40 * 60 * 1000; +const JWT_MIN_RENEW_MS = 20 * 60 * 1000; const REQUEST_TIMEOUT = "10 seconds"; export type KinApnsCredentials = { @@ -172,42 +173,53 @@ const unconfigured = (reason: string) => ); const unreachable: KinApnsResult = { status: 0, reason: "transport" }; -// APNs answers these with 403 when the cached provider token stopped working. -const STALE_PROVIDER_TOKEN = new Set(["ExpiredProviderToken", "InvalidProviderToken"]); +// No answer, or APNs' own trouble: worth one more try on a new connection. +const RETRY_STATUSES = new Set([0, 500, 503]); +// An idle HTTP/2 connection can be dead without erroring, so one unused this long is replaced. +const SESSION_IDLE_MS = 5 * 60 * 1000; /** The ready transport. `origin` exists so tests can point it at a local HTTP/2 server. */ export const makeApnsTransport = Effect.fn("KinApns.makeTransport")(function* ( credentials: KinApnsCredentials, origin: (environment: KinApsEnvironment) => string = (environment) => ORIGINS[environment], ) { - const sessions = new Map(); + type Open = { readonly session: NodeHttp2.ClientHttp2Session; usedAt: number }; + const sessions = new Map(); let jwt: { readonly value: string; readonly at: number } | undefined; yield* Effect.addFinalizer(() => Effect.sync(() => { - for (const session of sessions.values()) session.close(); + for (const open of sessions.values()) open.session.close(); sessions.clear(); }), ); - const sessionFor = (environment: KinApsEnvironment) => { + const sessionFor = Effect.fnUntraced(function* (environment: KinApsEnvironment) { + const now = yield* Clock.currentTimeMillis; const open = sessions.get(environment); - if (open !== undefined && !open.closed && !open.destroyed) return open; + if (open !== undefined && !open.session.closed && !open.session.destroyed) { + if (now - open.usedAt < SESSION_IDLE_MS) { + open.usedAt = now; + return open.session; + } + sessions.delete(environment); + open.session.close(); + } const session = NodeHttp2.connect(origin(environment)); const drop = () => { - if (sessions.get(environment) === session) sessions.delete(environment); + if (sessions.get(environment)?.session === session) sessions.delete(environment); }; session.on("error", drop); session.on("close", drop); session.on("goaway", drop); session.unref(); - sessions.set(environment, session); + sessions.set(environment, { session, usedAt: now }); return session; - }; + }); // A dead connection never errors on its own, so a timeout must end it or every push stalls. const discard = (environment: KinApsEnvironment, session: NodeHttp2.ClientHttp2Session) => Effect.sync(() => { - if (sessions.get(environment) === session) sessions.delete(environment); + if (sessions.get(environment)?.session === session) sessions.delete(environment); session.destroy(); }); @@ -215,28 +227,50 @@ export const makeApnsTransport = Effect.fn("KinApns.makeTransport")(function* ( const now = yield* Clock.currentTimeMillis; if (jwt === undefined || now - jwt.at >= JWT_TTL_MS) jwt = { value: apnsProviderToken(credentials, now), at: now }; - return jwt.value; + return jwt; + }); + + const attempt = Effect.fnUntraced(function* (push: KinApnsPush, body: string, token: string) { + const session = yield* sessionFor(push.environment); + const result = yield* post(session, apnsRequestHeaders(credentials, push, token), body).pipe( + Effect.timeout(REQUEST_TIMEOUT), + Effect.tapError(() => discard(push.environment, session)), + Effect.catch((error) => + Effect.logWarning("Kin push couldn't reach APNs.", { error: String(error) }).pipe( + Effect.as(unreachable), + ), + ), + ); + if (result.status === 500 || result.status === 503) yield* discard(push.environment, session); + return result; }); return KinApnsTransport.of({ status: "ready", + // At most one retry per push. A 429 isn't retried: the sender logs it and drops the push. send: Effect.fn("KinApnsTransport.send")(function* (push: KinApnsPush) { - const headers = apnsRequestHeaders(credentials, push, yield* providerToken); - const result = yield* encodeJson(push.payload).pipe( - Effect.flatMap((body) => { - const session = sessionFor(push.environment); - return post(session, headers, body).pipe( - Effect.timeout(REQUEST_TIMEOUT), - Effect.tapError(() => discard(push.environment, session)), - ); - }), - Effect.catch((error) => - Effect.logWarning("Kin push couldn't reach APNs.", { error: String(error) }).pipe( - Effect.as(unreachable), - ), - ), - ); - if (STALE_PROVIDER_TOKEN.has(result.reason ?? "")) jwt = undefined; + const body = yield* encodeJson(push.payload).pipe(Effect.option); + if (Option.isNone(body)) { + yield* Effect.logWarning("Kin push payload isn't JSON."); + return { status: 0, reason: "payload" }; + } + const token = yield* providerToken; + const result = yield* attempt(push, body.value, token.value); + if (RETRY_STATUSES.has(result.status)) return yield* attempt(push, body.value, token.value); + if (result.reason === "ExpiredProviderToken") { + const now = yield* Clock.currentTimeMillis; + // APNs throttles provider tokens renewed more often than every 20 minutes. + if (now - token.at < JWT_MIN_RENEW_MS) { + yield* Effect.logWarning("APNs called a fresh Kin provider token expired."); + return result; + } + jwt = { value: apnsProviderToken(credentials, now), at: now }; + return yield* attempt(push, body.value, jwt.value); + } + if (result.reason === "InvalidProviderToken") + yield* Effect.logError( + "APNs refused the Kin provider token: check KIN_APNS_KEY_ID, KIN_APNS_TEAM_ID and the key.", + ); return result; }), }); diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts index e180b099b0d86..730337a60b320 100644 --- a/apps/server/src/kin/push/KinPushDevices.ts +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -109,7 +109,8 @@ const make = Effect.gen(function* () { const person = yield* personIn(caller, input.orgId); const now = yield* Clock.currentTimeMillis; // A phone re-registers on every connect, which also moves the row to its current session. - yield* sql`INSERT INTO kin_push_devices ${sql.insert({ + // Someone else's token moves only once the session that registered it is revoked or gone. + const saved = yield* sql`INSERT INTO kin_push_devices ${sql.insert({ org_id: input.orgId, token: input.token, person_id: person.personId, @@ -128,7 +129,13 @@ const make = Effect.gen(function* () { device_label = excluded.device_label, session_id = excluded.session_id, proof_key_thumbprint = excluded.proof_key_thumbprint, - updated_at = excluded.updated_at`; + updated_at = excluded.updated_at + WHERE kin_push_devices.person_id = excluded.person_id OR NOT EXISTS ( + SELECT 1 FROM auth_sessions s + WHERE s.session_id = kin_push_devices.session_id AND s.revoked_at IS NULL) + RETURNING token`; + if (saved.length === 0) + return yield* fail("not_member", "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/KinPushPresence.test.ts b/apps/server/src/kin/push/KinPushPresence.test.ts index cdccf3b10b028..181294b8a5aa6 100644 --- a/apps/server/src/kin/push/KinPushPresence.test.ts +++ b/apps/server/src/kin/push/KinPushPresence.test.ts @@ -1,5 +1,5 @@ import { assert, it } from "@effect/vitest"; -import { AuthSessionId, AuthStandardClientScopes, KinAgentId, KinChatId } from "@t3tools/contracts"; +import { AuthSessionId, AuthStandardClientScopes, KinChatId } from "@t3tools/contracts"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -11,50 +11,44 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as Sqlite from "../../persistence/Sqlite.ts"; -import { KinChatService } from "../chat/KinChatService.ts"; -import { KinIdentity } from "../chat/KinIdentity.ts"; -import * as Repository from "../chat/KinChatRepository.ts"; import * as Chat from "../chat/layer.ts"; -import { makeKinChatHandlers } from "../chat/rpcHandlers.ts"; import { dormantLeadDependencies } from "../lead/layer.testkit.ts"; import * as Kin from "../layer.ts"; import * as Presence from "./KinPushPresence.ts"; +import { makeKinPushHandlers } from "./rpcHandlers.ts"; const sessionId = AuthSessionId.make("sess-phone"); const chatId = KinChatId.make("chat_team"); -it.effect("counts a watcher only while its client keeps taking the stream", () => +it.effect("counts a watcher only while its client keeps acking beats", () => Effect.gen(function* () { const presence = yield* Presence.KinPushPresence; - const idleOpen = yield* Deferred.make(); - // An idle chat on a live client: nothing to send, and the stream keeps being pulled. - yield* Stream.fromEffect(Deferred.succeed(idleOpen, undefined)).pipe( - Stream.concat(Stream.never), - presence.watching(sessionId, chatId), - Stream.runDrain, - Effect.forkChild, - ); - yield* Deferred.await(idleOpen); - for (let minute = 0; minute < 10; minute += 1) yield* TestClock.adjust("1 minute"); - assert.isTrue(yield* presence.isWatching(sessionId, chatId)); + // A live client on an idle chat: it acks every beat, so the stream keeps being pulled. + yield* presence + .watch(sessionId, chatId) + .pipe(Stream.runDrain, Effect.forkChild({ startImmediately: true })); - // A half-open client: it never acks the first event, so the server stops pulling. - const stalledChat = KinChatId.make("chat_stalled"); + // A half-open client: it takes the first beat and never acks it. + const stalled = KinChatId.make("chat_stalled"); const received = yield* Deferred.make(); - const ack = yield* Deferred.make(); - yield* Stream.make("event").pipe( - Stream.concat(Stream.never), - presence.watching(sessionId, stalledChat), + yield* presence.watch(sessionId, stalled).pipe( Stream.runForEach(() => - Deferred.succeed(received, undefined).pipe(Effect.andThen(Deferred.await(ack))), + Deferred.succeed(received, undefined).pipe(Effect.andThen(Effect.never)), ), - Effect.forkChild, + Effect.forkChild({ startImmediately: true }), ); + assert.isTrue(yield* presence.isWatching(sessionId, stalled)); + yield* TestClock.adjust("15 seconds"); yield* Deferred.await(received); - yield* TestClock.adjust("89 seconds"); - assert.isTrue(yield* presence.isWatching(sessionId, stalledChat)); + // Its last refresh was when it opened, so it stops counting one TTL after that. + yield* TestClock.adjust("29 seconds"); + assert.isTrue(yield* presence.isWatching(sessionId, stalled)); yield* TestClock.adjust("1 second"); - assert.isFalse(yield* presence.isWatching(sessionId, stalledChat)); + assert.isFalse(yield* presence.isWatching(sessionId, stalled)); + + for (let minute = 0; minute < 60; minute += 1) yield* TestClock.adjust("1 minute"); + assert.isTrue(yield* presence.isWatching(sessionId, chatId)); + assert.isFalse(yield* presence.isWatching(sessionId, stalled)); }).pipe(Effect.provide(Presence.layer)), ); @@ -71,37 +65,22 @@ const root = Kin.layer.pipe( Layer.provideMerge(Sqlite.layerMemory), ); -it.effect("marks the chat open for the subscribing session through the real handler", () => +it.effect("marks the chat open for the watching session through the real handler", () => Effect.gen(function* () { - const person = (yield* (yield* KinIdentity).resolve(session))[0]; - assert.isDefined(person); - const agentId = KinAgentId.make("lead"); - yield* (yield* Repository.KinChatRepository).insertAgent({ - ...person, - agentId, - ownerPersonId: person.personId, - displayName: "Lead", - role: "lead", - createdAt: "1970-01-01T00:00:00.000Z", - }); - const direct = yield* (yield* KinChatService).createDirect(person, { ...person, agentId }); const services = Option.getOrThrow((yield* Kin.KinServer).services); const presence = Context.get(services, Presence.KinPushPresence); - - const handlers = yield* makeKinChatHandlers(session); - const backlog = yield* Deferred.make(); - const subscription = yield* handlers["kin.chat.subscribe"]({ - chatId: direct.chatId, - afterSeq: 0, - }).pipe( - Stream.runForEach(() => Deferred.succeed(backlog, undefined)), + const handlers = yield* makeKinPushHandlers(session); + const beat = yield* Deferred.make(); + const watch = yield* handlers["kin.push.watch"]({ chatId }).pipe( + Stream.runForEach(() => Deferred.succeed(beat, undefined)), Effect.forkChild, ); - yield* Deferred.await(backlog); - assert.isTrue(yield* presence.isWatching(sessionId, direct.chatId)); - assert.isFalse(yield* presence.isWatching(AuthSessionId.make("sess-other"), direct.chatId)); + yield* TestClock.adjust("15 seconds"); + yield* Deferred.await(beat); + assert.isTrue(yield* presence.isWatching(sessionId, chatId)); + assert.isFalse(yield* presence.isWatching(AuthSessionId.make("sess-other"), chatId)); - yield* Fiber.interrupt(subscription); - assert.isFalse(yield* presence.isWatching(sessionId, direct.chatId)); + yield* Fiber.interrupt(watch); + assert.isFalse(yield* presence.isWatching(sessionId, chatId)); }).pipe(Effect.provide(root)), ); diff --git a/apps/server/src/kin/push/KinPushPresence.ts b/apps/server/src/kin/push/KinPushPresence.ts index 7b19dea9f8b14..f242490839fb2 100644 --- a/apps/server/src/kin/push/KinPushPresence.ts +++ b/apps/server/src/kin/push/KinPushPresence.ts @@ -1,4 +1,4 @@ -import type { AuthSessionId, KinChatId } from "@t3tools/contracts"; +import type { AuthSessionId, KinChatId, KinPushWatchBeat } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; @@ -6,28 +6,26 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; -/** A watcher whose last beat is older than this no longer counts as on screen. */ -const KIN_PUSH_PRESENCE_TTL = Duration.seconds(90); -const BEAT_INTERVAL = Duration.seconds(30); -const BEAT: unique symbol = Symbol("KinPushPresence.beat"); +/** A watcher not refreshed for this long no longer counts as on screen. */ +const KIN_PUSH_PRESENCE_TTL = Duration.seconds(45); +const KIN_PUSH_BEAT_INTERVAL = Duration.seconds(15); /** * Which sessions have a chat open right now. Upstream owns the phone's foreground handler, * so the server skips a push for a chat the device is already showing (mobile spec, correction 8). - * The phone ends its chat stream when it leaves the foreground, so a live stream means "on screen". */ export class KinPushPresence extends Context.Service< KinPushPresence, { /** - * Marks the chat open for the session while the stream runs. Beats travel through the - * stream, and the RPC server pulls only after the client acks a chunk, so a half-open - * socket stops refreshing once a chunk goes unacked. + * Marks the chat open for the session while the stream runs. Each pull refreshes the mark, + * and the RPC server pulls only after the client acks the last beat, so a half-open socket + * stops suppressing within the TTL whatever the chat's traffic. */ - readonly watching: ( + readonly watch: ( sessionId: AuthSessionId, chatId: KinChatId, - ) => (stream: Stream.Stream) => Stream.Stream; + ) => Stream.Stream; readonly isWatching: (sessionId: AuthSessionId, chatId: KinChatId) => Effect.Effect; } >()("t3/kin/push/KinPushPresence") {} @@ -38,7 +36,7 @@ const make = Effect.sync(() => { const slot = (sessionId: AuthSessionId, chatId: KinChatId) => `${sessionId}\u0000${chatId}`; const ttl = Duration.toMillis(KIN_PUSH_PRESENCE_TTL); - const watch = Effect.fn("KinPushPresence.watch")(function* (key: string) { + const mark = Effect.fn("KinPushPresence.mark")(function* (key: string) { const watcher: Watcher = { refreshedAt: yield* Clock.currentTimeMillis }; yield* Effect.acquireRelease( Effect.sync(() => { @@ -57,26 +55,21 @@ const make = Effect.sync(() => { }); return KinPushPresence.of({ - watching: - (sessionId, chatId) => - (stream: Stream.Stream) => - Stream.unwrap( - Effect.map(watch(slot(sessionId, chatId)), (watcher) => - stream.pipe( - Stream.merge(Stream.tick(BEAT_INTERVAL).pipe(Stream.as(BEAT)), { - haltStrategy: "left", + watch: (sessionId, chatId) => + Stream.unwrap( + Effect.map(mark(slot(sessionId, chatId)), (watcher) => + // Refresh first, then wait: the refresh marks the moment the previous beat was acked. + Stream.fromEffectRepeat( + Clock.currentTimeMillis.pipe( + Effect.map((now) => { + watcher.refreshedAt = now; }), - Stream.tap((event) => - event === BEAT - ? Effect.map(Clock.currentTimeMillis, (now) => { - watcher.refreshedAt = now; - }) - : Effect.void, - ), - Stream.filter((event): event is A => event !== BEAT), + Effect.andThen(Effect.sleep(KIN_PUSH_BEAT_INTERVAL)), + Effect.as("beat" as const), ), ), ), + ), isWatching: Effect.fn("KinPushPresence.isWatching")(function* (sessionId, chatId) { const watchers = open.get(slot(sessionId, chatId)); if (watchers === undefined) return false; diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index ef5bce8476550..6efb1d05d1701 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -140,7 +140,11 @@ const seed = Effect.gen(function* () { platform: "ios", apsEnvironment: "development", }); - return { sql, devices, sender: yield* Sender.KinPushSender }; + const sender = yield* Sender.KinPushSender; + // Waits for the background send so tests can read its outcome. + const notify = (notification: Sender.KinPushNotification) => + sender.notify(notification).pipe(Effect.flatMap(Fiber.join)); + return { sql, devices, sender, notify }; }); const postMessage = ( @@ -184,7 +188,7 @@ describe("KinPushSender", () => { it.effect("sends approval pushes only to approvers' devices, with ids and fixed text", () => { const apns = makeApns(); return Effect.gen(function* () { - const { sender, sql } = yield* seed; + const { sender, notify, sql } = yield* seed; const actions = yield* PendingActions.KinPendingActions; const { action } = yield* actions.create({ orgId, @@ -215,7 +219,16 @@ describe("KinPushSender", () => { source: KinEventId.make("evt-212"), } as unknown as PendingActions.KinPendingActionCreateInput); - const outcome = yield* sender.notify({ _tag: "approval", orgId, actionId: action.id }); + // The send outlives the request that asked for it. + const handed = yield* Deferred.make>(); + const request = yield* sender.notify({ _tag: "approval", orgId, actionId: action.id }).pipe( + Effect.flatMap((delivery) => Deferred.succeed(handed, delivery)), + Effect.andThen(Effect.never), + Effect.forkChild, + ); + const delivery = yield* Deferred.await(handed); + yield* Fiber.interrupt(request); + const outcome = yield* Fiber.join(delivery); assert.deepStrictEqual(outcome, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); assert.deepStrictEqual( apns.sent.map((push) => [push.token, push.environment]), @@ -243,7 +256,7 @@ describe("KinPushSender", () => { // Once the approver's key session is revoked, nobody is an approver and nothing is sent. yield* sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-key'`; - const after = yield* sender.notify({ _tag: "approval", orgId, actionId: action.id }); + const after = yield* notify({ _tag: "approval", orgId, actionId: action.id }); assert.strictEqual(after.sent, 0); assert.strictEqual(apns.sent.length, 2); }).pipe(Effect.provide(build(apns))); @@ -252,7 +265,7 @@ describe("KinPushSender", () => { it.effect("picks the category from the widget and routes only to who it awaits", () => { const apns = makeApns(); return Effect.gen(function* () { - const { sender, sql } = yield* seed; + const { notify, sql } = yield* seed; const cases = [ ["deferral", { phase: "confirmed" }, [member], ["kin.deferral.confirmed"]], [ @@ -269,7 +282,7 @@ describe("KinPushSender", () => { for (const [type, state, awaiting, expected] of cases) { apns.sent.length = 0; const widgetId = yield* postWidget(sql, type, state, awaiting); - yield* sender.notify({ _tag: "widget", orgId, widgetId }); + yield* notify({ _tag: "widget", orgId, widgetId }); assert.deepStrictEqual( categories(apns.sent), [...expected], @@ -278,7 +291,7 @@ describe("KinPushSender", () => { } apns.sent.length = 0; const widgetId = yield* postWidget(sql, "deferral", { phase: "confirmed" }, [member]); - yield* sender.notify({ _tag: "widget", orgId, widgetId }); + yield* notify({ _tag: "widget", orgId, widgetId }); assert.deepStrictEqual(apns.sent[0]?.payload, { aps: { alert: { title: "Deferred", body: "A deferral needs a look" }, @@ -299,7 +312,7 @@ describe("KinPushSender", () => { apns.sent.length = 0; const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); - yield* sender.notify({ _tag: "message", orgId, messageId }); + yield* notify({ _tag: "message", orgId, messageId }); // The author doesn't hear about their own message, and the text never leaves the server. assert.deepStrictEqual( apns.sent.map((push) => push.token), @@ -311,44 +324,48 @@ describe("KinPushSender", () => { assert.match(apns.sent[0]?.collapseId ?? "", /^kin:[0-9a-f]{12}$/); // A suggestion only the owner can see isn't announced to anyone. const suggested = yield* postMessage(sql, "system", "suggested"); - assert.strictEqual( - (yield* sender.notify({ _tag: "message", orgId, messageId: suggested })).sent, - 0, - ); + assert.strictEqual((yield* notify({ _tag: "message", orgId, messageId: suggested })).sent, 0); }).pipe(Effect.provide(build(apns))); }); - it.effect("skips a device while its session has the chat open", () => { + it.effect("skips a device while its session watches the chat and acks", () => { const apns = makeApns(); return Effect.gen(function* () { - const { sender, sql } = yield* seed; + const { notify, sql } = yield* seed; const presence = yield* KinPushPresence; + const phone = AuthSessionId.make("sess-owner-phone"); + const chat = KinChatId.make("chat_team"); const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); - const open = yield* Deferred.make(); - const stream = yield* Stream.fromEffect(Deferred.succeed(open, undefined)).pipe( - Stream.concat(Stream.never), - presence.watching(AuthSessionId.make("sess-owner-phone"), KinChatId.make("chat_team")), - Stream.runDrain, - Effect.forkChild, - ); - yield* Deferred.await(open); - const watched = yield* sender.notify({ _tag: "message", orgId, messageId }); + const watching = yield* presence + .watch(phone, chat) + .pipe(Stream.runDrain, Effect.forkChild({ startImmediately: true })); + const watched = yield* notify({ _tag: "message", orgId, messageId }); assert.deepStrictEqual(watched, { status: "ready", sent: 1, suppressed: 1, failed: 0 }); assert.deepStrictEqual( apns.sent.map((push) => push.token), [ownerTablet], ); - // Closing the chat stream ends the suppression. - yield* Fiber.interrupt(stream); - const closed = yield* sender.notify({ _tag: "message", orgId, messageId }); + // Closing the watch ends the suppression. + yield* Fiber.interrupt(watching); + const closed = yield* notify({ _tag: "message", orgId, messageId }); assert.deepStrictEqual(closed, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); + + // A phone that dropped off without closing its socket stops acking. After an idle hour, + // the next message reaches it. + yield* presence.watch(phone, chat).pipe( + Stream.runForEach(() => Effect.never), + Effect.forkChild({ startImmediately: true }), + ); + for (let minute = 0; minute < 60; minute += 1) yield* TestClock.adjust("1 minute"); + const idle = yield* notify({ _tag: "message", orgId, messageId }); + assert.deepStrictEqual(idle, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); }).pipe(Effect.provide(build(apns))); }); it.effect("reaches only people still in the chat, in this org, and not muted", () => { const apns = makeApns(); return Effect.gen(function* () { - const { sender, sql, devices } = yield* seed; + const { notify, sql, devices } = yield* seed; // Someone in another org with a device there hears nothing about this org's chat. const elsewhere = KinOrgId.make("org_02"); const stranger = KinPersonId.make("h_stranger"); @@ -367,7 +384,7 @@ describe("KinPushSender", () => { WHERE member_id = 'm_priya'`; apns.sent.length = 0; const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); - yield* sender.notify({ _tag: "message", orgId, messageId }); + yield* notify({ _tag: "message", orgId, messageId }); return apns.sent.map((push) => push.token); }); assert.deepStrictEqual(yield* recipients(null, null), [memberPhone]); @@ -395,7 +412,7 @@ describe("KinPushSender", () => { }), ); return Effect.gen(function* () { - const { sender, sql, devices } = yield* seed; + const { notify, sql, devices } = yield* seed; for (const fill of ["d", "e", "f", "1"]) yield* devices.register(caller("sess-owner-phone", owner), { orgId, @@ -404,7 +421,7 @@ describe("KinPushSender", () => { apsEnvironment: "production", }); const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); - const outcome = yield* sender.notify({ _tag: "message", orgId, messageId }); + const outcome = yield* notify({ _tag: "message", orgId, messageId }); assert.deepStrictEqual(outcome, { status: "ready", sent: 6, suppressed: 0, failed: 0 }); assert.strictEqual(peak, 4); assert.strictEqual(started.length, 6); @@ -414,9 +431,9 @@ describe("KinPushSender", () => { it.effect("sends nothing without an APNs key", () => { const apns = makeApns("unconfigured"); return Effect.gen(function* () { - const { sender, sql } = yield* seed; + const { notify, sql } = yield* seed; const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); - assert.deepStrictEqual(yield* sender.notify({ _tag: "message", orgId, messageId }), { + assert.deepStrictEqual(yield* notify({ _tag: "message", orgId, messageId }), { status: "unconfigured", sent: 0, suppressed: 0, @@ -499,6 +516,41 @@ 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 }>` + 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}, + session_id = 'sess-owner-phone' WHERE token = ${ownerPhone}`; + 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))); + }); + it.effect("keeps the ten most recently registered devices per person", () => { const apns = makeApns(); return Effect.gen(function* () { @@ -532,10 +584,10 @@ describe("KinPushDevices", () => { it.effect("drops a dead token, unless the phone registered it again since", () => { const apns = makeApns(); return Effect.gen(function* () { - const { sender, sql } = yield* seed; + const { notify, sql } = yield* seed; const notifyOwner = Effect.gen(function* () { const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); - return yield* sender.notify({ _tag: "message", orgId, messageId }); + return yield* notify({ _tag: "message", orgId, messageId }); }); // A wrong topic is our misconfiguration: the token stays. apns.answers.set(ownerTablet, { status: 400, reason: "DeviceTokenNotForTopic" }); diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index efcae54e61c0b..f85d194d1040f 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -13,6 +13,7 @@ import type { import * as Context from "effect/Context"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import type * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -90,15 +91,15 @@ export class KinPushSender extends Context.Service< KinPushSender, { readonly status: KinPushSendingStatus; - /** - * Never fails: a push is best effort, and a failure is logged without the token. Callers run - * it after their transaction commits and fork it off the request, since APNs can take seconds. - */ - readonly notify: (notification: KinPushNotification) => Effect.Effect; + /** Call after the commit; it sends in the background, outliving the request, and never fails. */ + readonly notify: ( + notification: KinPushNotification, + ) => Effect.Effect>; } >()("t3/kin/push/KinPushSender") {} const make = Effect.gen(function* () { + const scope = yield* Effect.scope; const sql = yield* SqlClient.SqlClient; const apns = yield* KinApnsTransport; const devices = yield* KinPushDevices; @@ -245,13 +246,22 @@ const make = Effect.gen(function* () { }); if (result.status === 200) return "sent" as const; const deviceId = kinPushDeviceId(device.token); - if (result.status === 410 || DEAD_TOKEN_REASONS.has(result.reason ?? "")) { - yield* devices.forget( - orgId, - device.token, - result.status === 410 ? result.timestamp : undefined, - ); + if (result.status === 410) { + yield* devices.forget(orgId, device.token, result.timestamp); yield* Effect.logInfo("Kin push device token is gone.", { deviceId, reason: result.reason }); + } else if (DEAD_TOKEN_REASONS.has(result.reason ?? "")) { + yield* devices.forget(orgId, device.token); + // Often a token sent to the wrong APNs environment, so say which one it went to. + yield* Effect.logWarning("APNs called a Kin push device token bad; it was removed.", { + deviceId, + reason: result.reason, + environment: device.apsEnvironment, + }); + } else if (result.status === 429) { + yield* Effect.logWarning("APNs is throttling Kin pushes; this one was dropped.", { + deviceId, + reason: result.reason, + }); } else if (CONFIG_REASONS.has(result.reason ?? "")) { yield* Effect.logError("APNs refused a Kin push: check KIN_APNS_TOPIC.", { deviceId, @@ -280,7 +290,7 @@ const make = Effect.gen(function* () { const nothing: KinPushOutcome = { status: apns.status, sent: 0, suppressed: 0, failed: 0 }; - const notify = Effect.fn("KinPushSender.notify")( + const run = Effect.fn("KinPushSender.run")( function* (notification: KinPushNotification) { if (apns.status === "unconfigured") return nothing; const push = @@ -303,6 +313,10 @@ const make = Effect.gen(function* () { ), ); + const notify = Effect.fn("KinPushSender.notify")(function* (notification: KinPushNotification) { + return yield* Effect.forkIn(run(notification), scope); + }); + return KinPushSender.of({ status: apns.status, notify }); }); diff --git a/apps/server/src/kin/push/rpcHandlers.ts b/apps/server/src/kin/push/rpcHandlers.ts index 8d68aa9549086..a7660f3558387 100644 --- a/apps/server/src/kin/push/rpcHandlers.ts +++ b/apps/server/src/kin/push/rpcHandlers.ts @@ -3,11 +3,13 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as RpcGroup from "effect/rpc/RpcGroup"; +import * as Stream from "effect/Stream"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { KinServer } from "../KinServer.ts"; import { KinPushDevices } from "./KinPushDevices.ts"; +import { KinPushPresence } from "./KinPushPresence.ts"; import { KinPushSender } from "./KinPushSender.ts"; const group = RpcGroup.make(...KinPushRpcs); @@ -26,6 +28,7 @@ export const makeKinPushHandlers = Effect.fn("makeKinPushHandlers")(function* ( return { devices: Context.get(services, KinPushDevices), sending: Context.get(services, KinPushSender).status, + presence: Context.get(services, KinPushPresence), caller: { session, people }, }; }); @@ -40,5 +43,10 @@ export const makeKinPushHandlers = Effect.fn("makeKinPushHandlers")(function* ( ), "kin.push.unregisterDevice": (input) => caller.pipe(Effect.flatMap(({ devices, caller }) => devices.unregister(caller, input))), + // Only ever quiets this session's own pushes, so it needs no access check on the chat. + "kin.push.watch": (input) => + Stream.unwrap( + caller.pipe(Effect.map(({ presence }) => presence.watch(session.sessionId, input.chatId))), + ), }); }); diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 394b3de7cb86b..ccff9c65814c5 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -262,12 +262,13 @@ Hiding the buttons is a convenience, not the protection (DESIGN 9.3). The server - Device tokens are registered through `kin.push.registerDevice` and removed through `kin.push.unregisterDevice` (contracts in `packages/contracts/src/kinPush.ts`, `orchestration:read`). A row is per org and token, owned by the person, session and DPoP key (`proof_key_thumbprint`) that last registered it. The phone registers on every connect, which moves the row to its current session. A person keeps at most 10 tokens per org; registering an 11th drops the one registered longest ago. Rows go away on unregister, when APNs says the token is dead, and when the registering T3 session is revoked (read from `auth_sessions`, as approver keys do). An expired session doesn't remove its rows, because a live socket outlives the session it connected with. - **Relay revocation waits on #54.** A relay phone's DPoP session renews hourly under a new id while its socket keeps the first one, so revoking the phone in Settings revokes a session no row names, and its pushes continue. Lane A's #54 adds `kin_auth_session_keys(session_id, proof_key_thumbprint, created_at)`, filled when a session is issued. Then reconciliation removes a row when its `proof_key_thumbprint` matches a `kin_auth_session_keys` row whose `auth_sessions` row has `revoked_at IS NOT NULL`. "Sign out other devices" revokes every session except the caller's, so the same join must skip rows carrying the caller's own thumbprint, or the caller's earlier sessions take its own phone with them. -- 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. `DeviceTokenNotForTopic` means `KIN_APNS_TOPIC` is wrong, so it's logged as an error and the token stays. `ExpiredProviderToken` and `InvalidProviderToken` make the next push sign a new provider token. -- 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, and the next push opens a new one. +- 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 the session that registered it is revoked or gone; otherwise `registerDevice` refuses with `not_member`. - 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. 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.chat.subscribe` stream for that chat. Upstream owns the foreground handler, so this check has to happen on the server. MOB-11 must end the chat stream when the app leaves the foreground, so that a live stream means the chat is on screen. A half-open socket never closes the stream, so the stream carries a beat every 30 seconds that the RPC server only pulls after the client acks what it last sent; a watcher without a beat for 90 seconds no longer suppresses. +- 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 and forked off the request, because APNs can take seconds and `notify` reads what the commit wrote. 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. +- 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". diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index f52115577f108..96af3de706bbc 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -538,6 +538,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./kin-push": { + "types": "./src/kinPush.ts", + "default": "./src/kinPush.ts" } }, "scripts": { diff --git a/packages/client-runtime/src/kinPush.ts b/packages/client-runtime/src/kinPush.ts new file mode 100644 index 0000000000000..25cc7b8298c0d --- /dev/null +++ b/packages/client-runtime/src/kinPush.ts @@ -0,0 +1,12 @@ +import { KIN_PUSH_WS_METHODS, type KinChatId } from "@t3tools/contracts"; +import * as Stream from "effect/Stream"; + +import { subscribe } from "./rpc/client.ts"; + +/** + * Run while a Kin chat is on screen, and stop when it leaves the screen or the app the + * foreground: until then the host skips this device's pushes for the chat. + * @public MOB-11's chat screen, on the mobile stack, is its first caller. + */ +export const watchKinChatForPush = (chatId: KinChatId) => + subscribe(KIN_PUSH_WS_METHODS.watch, { chatId }).pipe(Stream.runDrain); diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index e74abde6a2c59..a36117c6a6da9 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -4,6 +4,7 @@ import { authScopeRequiredResponse, type EnvironmentId, type ClientGuardedRpcTag, + KIN_PUSH_WS_METHODS, ORCHESTRATION_V2_WS_METHODS, WS_METHODS, } from "@t3tools/contracts"; @@ -71,7 +72,8 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribeWorktreeSetup | typeof WS_METHODS.subscribeProjectClones | typeof WS_METHODS.terminalAttach - | typeof WS_METHODS.terminalObserve; + | typeof WS_METHODS.terminalObserve + | typeof KIN_PUSH_WS_METHODS.watch; export type EnvironmentStreamCommandRpcTag = | typeof WS_METHODS.chatGptHandoffSubscribe diff --git a/packages/contracts/src/kinPush.ts b/packages/contracts/src/kinPush.ts index 9cbe68a4e03fb..12537adbe3761 100644 --- a/packages/contracts/src/kinPush.ts +++ b/packages/contracts/src/kinPush.ts @@ -82,6 +82,13 @@ export type KinPushUnregisterDeviceInput = typeof KinPushUnregisterDeviceInput.T export const KinPushUnregisterDeviceResult = Schema.Struct({ removed: Schema.Boolean }); export type KinPushUnregisterDeviceResult = typeof KinPushUnregisterDeviceResult.Type; +export const KinPushWatchInput = Schema.Struct({ chatId: KinChatId }); +export type KinPushWatchInput = typeof KinPushWatchInput.Type; + +/** One per beat interval; the server counts a beat as presence only once the client acks it. */ +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"]), message: Schema.String, @@ -90,6 +97,7 @@ export class KinPushError extends Schema.TaggedError()("KinPushErr export const KIN_PUSH_WS_METHODS = { registerDevice: "kin.push.registerDevice", unregisterDevice: "kin.push.unregisterDevice", + watch: "kin.push.watch", } as const; const error = Schema.Union([KinPushError, EnvironmentAuthorizationError]); @@ -105,12 +113,20 @@ export const KinPushRpcs = [ success: KinPushUnregisterDeviceResult, error, }), + // Open while a chat is on screen: that session's device gets no pushes for the chat. + Rpc.make(KIN_PUSH_WS_METHODS.watch, { + payload: KinPushWatchInput, + success: KinPushWatchBeat, + error, + stream: true, + }), ] as const; // A device only receives what its session can already read, so reading is the gate. export const KIN_PUSH_RPC_SCOPES = { [KIN_PUSH_WS_METHODS.registerDevice]: AuthOrchestrationReadScope, [KIN_PUSH_WS_METHODS.unregisterDevice]: AuthOrchestrationReadScope, + [KIN_PUSH_WS_METHODS.watch]: AuthOrchestrationReadScope, } as const satisfies Record< (typeof KIN_PUSH_WS_METHODS)[keyof typeof KIN_PUSH_WS_METHODS], AuthEnvironmentScope diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index c0fcf39f2a91f..735159e80eafc 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -57,4 +57,5 @@ export const KIN_RPC_AGGREGATES = { "kin.audit.verify": "kin-approvals", "kin.push.registerDevice": "kin-push", "kin.push.unregisterDevice": "kin-push", + "kin.push.watch": "kin-push", } as const; From b8597ec770475f3bc7ef4fb5dc5e7bbf077d02fa Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:21:36 +0530 Subject: [PATCH 04/10] fix(kin): drop push devices of revoked relay phones A relay phone's session renews under a new id while its socket keeps the first, so revoking it in Settings never removed its push device. Reconcile and the takeover check now use the approver keys' revocation rule: the registering session revoked before expiry, or any individually revoked session of the device's proof key. Signing out other devices keeps the caller's own phone, revocations after expiry don't count, and an owner's repair restores a phone's pushes. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/push/KinPushDevices.ts | 26 ++-- .../server/src/kin/push/KinPushSender.test.ts | 117 +++++++++++++++++- docs/kin/specs/mobile.md | 6 +- 3 files changed, 134 insertions(+), 15 deletions(-) diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts index 730337a60b320..ada2e6630fa92 100644 --- a/apps/server/src/kin/push/KinPushDevices.ts +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -19,6 +19,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { revokedBySession } from "../auth/ProofKeySessions.ts"; import type { PersonIdentity } from "../chat/KinIdentity.ts"; export type KinPushCaller = { @@ -91,14 +92,20 @@ const make = Effect.gen(function* () { }; // T3 revokes sessions in SessionStore; reading its table keeps auth free of Kin hooks, - // as ApproverKeys does. Runs before every send. Relay sessions renew under new ids, so this - // misses a revoked relay phone until #54 joins on proof_key_thumbprint (mobile spec). - // Expired sessions stay: a live socket outlives the session it registered under. + // as ApproverKeys does. Runs before every send. Expired sessions stay: a live socket outlives + // the session it registered under. A repaired proof key keeps its pushes; the phone + // re-registers on connect anyway (mobile spec). + const revoked = revokedBySession( + sql, + { + sessionId: sql`kin_push_devices.session_id`, + proofKey: sql`kin_push_devices.proof_key_thumbprint`, + }, + { honorRepairs: true }, + ); const reconcileSessions = Effect.fn("KinPushDevices.reconcileSessions")( function* () { - const removed = yield* sql`DELETE FROM kin_push_devices WHERE session_id IN ( - SELECT session_id FROM auth_sessions WHERE revoked_at IS NOT NULL) - RETURNING token`; + const removed = yield* sql`DELETE FROM kin_push_devices WHERE ${revoked} RETURNING token`; return removed.length; }, Effect.mapError(internal("KinPushDevices.reconcileSessions")), @@ -109,7 +116,7 @@ const make = Effect.gen(function* () { const person = yield* personIn(caller, input.orgId); const now = yield* Clock.currentTimeMillis; // A phone re-registers on every connect, which also moves the row to its current session. - // Someone else's token moves only once the session that registered it is revoked or gone. + // Someone else's token moves only once reconcile would drop it, or its session is gone. const saved = yield* sql`INSERT INTO kin_push_devices ${sql.insert({ org_id: input.orgId, token: input.token, @@ -130,9 +137,8 @@ const make = Effect.gen(function* () { session_id = excluded.session_id, proof_key_thumbprint = excluded.proof_key_thumbprint, updated_at = excluded.updated_at - WHERE kin_push_devices.person_id = excluded.person_id OR NOT EXISTS ( - SELECT 1 FROM auth_sessions s - WHERE s.session_id = kin_push_devices.session_id AND s.revoked_at IS NULL) + 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) RETURNING token`; if (saved.length === 0) return yield* fail("not_member", "This device is registered to someone else."); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index 6efb1d05d1701..d2e813b08e5c1 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -11,6 +11,7 @@ import { type KinPushToken, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -20,10 +21,12 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as SessionStore from "../../auth/SessionStore.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; import * as ApproverKeys from "../approvals/ApproverKeys.ts"; import { KinAttestationTrust } from "../approvals/attestation/AttestationTrust.ts"; import * as PendingActions from "../approvals/PendingActions.ts"; +import { layerKinAuthTest, repairProofKey } from "../auth/ProofKeySessions.testkit.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { KinApnsTransport, type KinApnsPush, type KinApnsResult } from "./Apns.ts"; import { KinPushDevices, type KinPushCaller } from "./KinPushDevices.ts"; @@ -77,14 +80,18 @@ const makeApns = ( return { sent, answers, layer }; }; -const build = (apns: ReturnType) => +const buildOn = (apns: ReturnType, database: Layer.Layer) => Sender.layer.pipe( Layer.provideMerge(Layer.mergeAll(Devices.layer, Presence.layer, apns.layer)), Layer.provideMerge(ApproverKeys.layer), Layer.provideMerge(PendingActions.layer), Layer.provide(Layer.succeed(KinAttestationTrust, { load: () => Effect.die("unused") })), - Layer.provideMerge(Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory)), + Layer.provideMerge(Layer.provideMerge(KinPersistence.layer, database)), ); +const build = (apns: ReturnType) => buildOn(apns, Sqlite.layerMemory); +// Real T3 auth with Kin's proof key hooks, so revocations write what #54 writes. +const buildRelay = (apns: ReturnType) => + buildOn(apns, layerKinAuthTest("kin-push-")); const seed = Effect.gen(function* () { yield* TestClock.setTime(NOW); @@ -551,6 +558,112 @@ describe("KinPushDevices", () => { }).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) => + SessionStore.SessionStore.pipe( + Effect.flatMap((sessions) => sessions.issue({ proofKeyThumbprint, ttl })), + Effect.map((issued) => caller(issued.sessionId, personId, { proofKeyThumbprint })), + ); + const registerToken = (from: KinPushCaller, deviceToken: KinPushToken) => + KinPushDevices.pipe( + Effect.flatMap((devices) => + devices.register(from, { + orgId, + token: deviceToken, + platform: "ios", + apsEnvironment: "development", + }), + ), + ); + const holder = (sql: SqlClient.SqlClient, deviceToken: KinPushToken) => + sql<{ person_id: string }>`SELECT person_id FROM kin_push_devices WHERE token = ${deviceToken}`; + const relayToken = token("e"); + + it.effect( + "drops a relay phone revoked by its renewed session, until the owner repairs it", + () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql, devices } = yield* seed; + const sessions = yield* SessionStore.SessionStore; + // The phone's socket keeps the session it registered under while the session renews. + yield* registerToken(yield* relay(owner, "relay-a", Duration.minutes(1)), relayToken); + yield* TestClock.adjust(Duration.minutes(2)); + const renewed = yield* relay(owner, "relay-a", Duration.hours(1)); + yield* sessions.revoke(renewed.session.sessionId); + yield* devices.reconcileSessions(); + assert.deepStrictEqual(yield* holder(sql, relayToken), []); + + const repaired = yield* repairProofKey("relay-a"); + yield* registerToken( + caller(repaired.sessionId, owner, { proofKeyThumbprint: "relay-a" }), + relayToken, + ); + yield* devices.reconcileSessions(); + assert.deepStrictEqual(yield* holder(sql, relayToken), [{ person_id: owner }]); + }).pipe(Effect.provide(buildRelay(apns))); + }, + ); + + it.effect("signing out other devices from a phone keeps its own device", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql, devices } = yield* seed; + const sessions = yield* SessionStore.SessionStore; + const otherToken = token("f"); + yield* registerToken(yield* relay(owner, "relay-a", Duration.hours(1)), relayToken); + yield* registerToken(yield* relay(member, "relay-b", Duration.hours(1)), otherToken); + yield* TestClock.adjust(Duration.minutes(30)); + // Both renew early; the phone's first session is still live when it signs the others out. + const current = yield* relay(owner, "relay-a", Duration.hours(1)); + yield* relay(member, "relay-b", Duration.hours(1)); + yield* sessions.revokeAllExcept(current.session.sessionId); + yield* devices.reconcileSessions(); + assert.deepStrictEqual(yield* holder(sql, relayToken), [{ person_id: owner }]); + assert.deepStrictEqual(yield* holder(sql, otherToken), []); + }).pipe(Effect.provide(buildRelay(apns))); + }); + + it.effect("revoking a session after it expired keeps its device", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql, devices } = yield* seed; + const sessions = yield* SessionStore.SessionStore; + const phone = yield* relay(owner, "relay-a", Duration.minutes(1)); + yield* registerToken(phone, relayToken); + yield* TestClock.adjust(Duration.minutes(2)); + yield* sessions.revoke(phone.session.sessionId); + yield* devices.reconcileSessions(); + assert.deepStrictEqual(yield* holder(sql, relayToken), [{ person_id: owner }]); + }).pipe(Effect.provide(buildRelay(apns))); + }); + + it.effect( + "hands a relay phone's token to another person only once reconcile would drop it", + () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { sql } = yield* seed; + const sessions = yield* SessionStore.SessionStore; + const first = yield* relay(owner, "relay-a", Duration.minutes(1)); + yield* registerToken(first, relayToken); + yield* TestClock.adjust(Duration.minutes(2)); + const takeover = registerToken(caller("sess-member", member), relayToken); + yield* sessions.revoke(first.session.sessionId); + const refused = yield* Effect.exit(takeover); + assert.isTrue( + Exit.isFailure(refused) && + (refused.cause.reasons[0] as { error?: KinPushError }).error?.reason === "not_member", + ); + yield* sessions.revoke( + (yield* relay(owner, "relay-a", Duration.hours(1))).session.sessionId, + ); + yield* takeover; + assert.deepStrictEqual(yield* holder(sql, relayToken), [{ person_id: member }]); + }).pipe(Effect.provide(buildRelay(apns))); + }, + ); + it.effect("keeps the ten most recently registered devices per person", () => { const apns = makeApns(); return Effect.gen(function* () { diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index ccff9c65814c5..7b971f45f65d9 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -260,11 +260,11 @@ Hiding the buttons is a convenience, not the protection (DESIGN 9.3). The server **Sending (backend, this spec).** T3's relay can't carry Kin's pushes (see Design corrections). `apps/server/src/kin/push/KinPushSender.ts` sends APNs pushes directly from the Kin server, over HTTP/2 with token auth. The `.p8` key is a file on the Kin host outside the repo, named by `KIN_APNS_KEY_FILE`, with `KIN_APNS_KEY_ID`, `KIN_APNS_TEAM_ID` and `KIN_APNS_TOPIC` (the Kin bundle id), in the same environment as `KIN_ENABLED`. If any is missing or the key won't load, push is off: Kin still starts, nothing is sent, the server logs why, and `registerDevice` answers `sending: "unconfigured"`. -- Device tokens are registered through `kin.push.registerDevice` and removed through `kin.push.unregisterDevice` (contracts in `packages/contracts/src/kinPush.ts`, `orchestration:read`). A row is per org and token, owned by the person, session and DPoP key (`proof_key_thumbprint`) that last registered it. The phone registers on every connect, which moves the row to its current session. A person keeps at most 10 tokens per org; registering an 11th drops the one registered longest ago. Rows go away on unregister, when APNs says the token is dead, and when the registering T3 session is revoked (read from `auth_sessions`, as approver keys do). An expired session doesn't remove its rows, because a live socket outlives the session it connected with. -- **Relay revocation waits on #54.** A relay phone's DPoP session renews hourly under a new id while its socket keeps the first one, so revoking the phone in Settings revokes a session no row names, and its pushes continue. Lane A's #54 adds `kin_auth_session_keys(session_id, proof_key_thumbprint, created_at)`, filled when a session is issued. Then reconciliation removes a row when its `proof_key_thumbprint` matches a `kin_auth_session_keys` row whose `auth_sessions` row has `revoked_at IS NOT NULL`. "Sign out other devices" revokes every session except the caller's, so the same join must skip rows carrying the caller's own thumbprint, or the caller's earlier sessions take its own phone with them. +- Device tokens are registered through `kin.push.registerDevice` and removed through `kin.push.unregisterDevice` (contracts in `packages/contracts/src/kinPush.ts`, `orchestration:read`). A row is per org and token, owned by the person, session and DPoP key (`proof_key_thumbprint`) that last registered it. The phone registers on every connect, which moves the row to its current session. A person keeps at most 10 tokens per org; registering an 11th drops the one registered longest ago. Rows go away on unregister, when APNs says the token is dead, and when a T3 session revocation reaches them by the approver keys' rule (approvals spec section 4, `revokedBySession`): the registering session was revoked before it expired, or a session of the row's `proof_key_thumbprint` was individually revoked before it expired. An expired session doesn't remove its rows, because a live socket outlives the session it connected with. +- 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 the session that registered it is revoked or 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, or the session that registered it is gone; otherwise `registerDevice` refuses with `not_member`. - 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. 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. From db2d49aab73b10b904de212017ba6e419d20f106 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:45:28 +0530 Subject: [PATCH 05/10] fix(kin): follow the repair-aware revocation helper in push devices The helper now always honours repairs, with an optional cutoff only approver keys use, so push devices drop the option and keep their rule. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/push/KinPushDevices.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts index ada2e6630fa92..a8ecbc6369233 100644 --- a/apps/server/src/kin/push/KinPushDevices.ts +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -95,14 +95,10 @@ const make = Effect.gen(function* () { // as ApproverKeys does. Runs before every send. Expired sessions stay: a live socket outlives // the session it registered under. A repaired proof key keeps its pushes; the phone // re-registers on connect anyway (mobile spec). - const revoked = revokedBySession( - sql, - { - sessionId: sql`kin_push_devices.session_id`, - proofKey: sql`kin_push_devices.proof_key_thumbprint`, - }, - { honorRepairs: true }, - ); + const revoked = revokedBySession(sql, { + sessionId: sql`kin_push_devices.session_id`, + proofKey: sql`kin_push_devices.proof_key_thumbprint`, + }); const reconcileSessions = Effect.fn("KinPushDevices.reconcileSessions")( function* () { const removed = yield* sql`DELETE FROM kin_push_devices WHERE ${revoked} RETURNING token`; From 6230571de27ae94fcc72a9e01675696454b2852e Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 20:03:36 +0530 Subject: [PATCH 06/10] fix(kin): push a confirmed deferral card that carries no phase Lane A's deferral card (#64) has no phase field until TRIG-8, so the confirmed-deferral push never fired. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/push/KinPushSender.test.ts | 13 +++++++++++++ apps/server/src/kin/push/KinPushSender.ts | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index d2e813b08e5c1..158d18f77458a 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -275,6 +275,19 @@ describe("KinPushSender", () => { const { notify, sql } = yield* seed; const cases = [ ["deferral", { phase: "confirmed" }, [member], ["kin.deferral.confirmed"]], + // Lane A's card (#64) carries no phase until TRIG-8; a fresh one is a confirmed deferral. + [ + "deferral", + { + itemId: "item-1", + title: "Ship it", + dueAt: "2026-11-13T09:00:00.000Z", + onDue: "start", + text: "Deferred", + }, + [member], + ["kin.deferral.confirmed"], + ], [ "deferral", { phase: "heads_up" }, diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index f85d194d1040f..f6e8786c82b89 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -191,7 +191,7 @@ const make = Effect.gen(function* () { const kind = row.type !== "deferral" ? ({ category: "kin.message", title: "Waiting on you", body: "A card needs you" } as const) - : row.phase === "confirmed" + : row.phase === "confirmed" || row.phase === null ? ({ category: "kin.deferral.confirmed", title: "Deferred", From a018b7745e743e9d2f9972501feef1c8d06a4340 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 20:27:02 +0530 Subject: [PATCH 07/10] fix(kin): name the host environment in push deep links Every Kin host uses org id kin-default, so mobile routes chats and approvals as kin/:environmentId/:orgId/... The sender now reads its id from ServerEnvironment and puts it in every deepLink. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/lead/layer.testkit.ts | 7 +++++++ apps/server/src/kin/push/KinPushSender.test.ts | 15 +++++++++++++-- apps/server/src/kin/push/KinPushSender.ts | 11 ++++++++--- docs/kin/specs/mobile.md | 14 +++++++------- 4 files changed, 35 insertions(+), 12 deletions(-) diff --git a/apps/server/src/kin/lead/layer.testkit.ts b/apps/server/src/kin/lead/layer.testkit.ts index f93d64ade578e..a78b0bd2addca 100644 --- a/apps/server/src/kin/lead/layer.testkit.ts +++ b/apps/server/src/kin/lead/layer.testkit.ts @@ -1,6 +1,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ServerConfig from "../../config.ts"; +import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as ThreadLaunch from "../../orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../../project/ProjectService.ts"; @@ -13,4 +16,8 @@ export const dormantLeadDependencies = Layer.mergeAll( Layer.mock(ProjectService.ProjectService)({}), Layer.mock(VcsProcess.VcsProcess)({}), ServerConfig.layerTest(process.cwd(), { prefix: "kin-dormant-lead-" }), + // Not a lead dependency: push deep links name the host environment. + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("env_kin")), + }), ).pipe(Layer.provideMerge(NodeServices.layer)); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index 158d18f77458a..81285a39481ea 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { AuthSessionId, + EnvironmentId, KinChatId, KinEventId, KinMessageId, @@ -22,6 +23,7 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as SessionStore from "../../auth/SessionStore.ts"; +import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; import * as ApproverKeys from "../approvals/ApproverKeys.ts"; import { KinAttestationTrust } from "../approvals/attestation/AttestationTrust.ts"; @@ -86,6 +88,11 @@ const buildOn = (apns: ReturnType, database: Layer.Lay Layer.provideMerge(ApproverKeys.layer), Layer.provideMerge(PendingActions.layer), Layer.provide(Layer.succeed(KinAttestationTrust, { load: () => Effect.die("unused") })), + Layer.provide( + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("env_kin")), + }), + ), Layer.provideMerge(Layer.provideMerge(KinPersistence.layer, database)), ); const build = (apns: ReturnType) => buildOn(apns, Sqlite.layerMemory); @@ -254,7 +261,7 @@ describe("KinPushSender", () => { kin: 1, orgId, pendingActionId: action.id, - deepLink: `/kin/org_01/actions/${encodeURIComponent(action.id)}`, + deepLink: `/kin/env_kin/org_01/actions/${encodeURIComponent(action.id)}`, }, }); const wire = JSON.stringify(apns.sent.map((push) => push.payload)); @@ -325,7 +332,7 @@ describe("KinPushSender", () => { chatId: "chat_team", widgetId, revision: 3, - deepLink: "/kin/org_01/chats/chat_team", + deepLink: "/kin/env_kin/org_01/chats/chat_team", }, }); assert.isUndefined(apns.sent[0]?.collapseId); @@ -339,6 +346,10 @@ describe("KinPushSender", () => { [memberPhone], ); assert.deepStrictEqual(categories(apns.sent), ["kin.message"]); + assert.include( + JSON.stringify(apns.sent[0]?.payload), + '"deepLink":"/kin/env_kin/org_01/chats/', + ); assert.notInclude(JSON.stringify(apns.sent), "hunter2"); // Messages collapse per chat; cards don't, since each one waits on something different. assert.match(apns.sent[0]?.collapseId ?? "", /^kin:[0-9a-f]{12}$/); diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index f6e8786c82b89..73e24f9ff6fec 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -19,6 +19,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import { ApproverKeys } from "../approvals/ApproverKeys.ts"; import { KinPendingActions } from "../approvals/PendingActions.ts"; import { KinApnsTransport } from "./Apns.ts"; @@ -106,6 +107,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 chatLink = (orgId: KinOrgId, chatId: KinChatId) => + `/kin/${host}/${segment(orgId)}/chats/${segment(chatId)}`; /** People in the chat now. Muting silences messages, not things waiting on you. */ const chatPeople = Effect.fn("KinPushSender.chatPeople")(function* ( @@ -132,7 +137,7 @@ const make = Effect.gen(function* () { ) { const action = yield* actions.get({ orgId, actionId }); if (Option.isNone(action) || action.value.state !== "awaiting_approval") return undefined; - const deepLink = `/kin/${segment(orgId)}/actions/${segment(actionId)}`; + const deepLink = `/kin/${host}/${segment(orgId)}/actions/${segment(actionId)}`; return { category: "kin.approval", title: "Approval needed", @@ -163,7 +168,7 @@ const make = Effect.gen(function* () { kin: 1, orgId, chatId: row.chat_id, - deepLink: `/kin/${segment(orgId)}/chats/${segment(row.chat_id)}`, + deepLink: chatLink(orgId, row.chat_id), }, recipients: people.filter((person) => person !== row.author_person_id), } satisfies Push; @@ -216,7 +221,7 @@ const make = Effect.gen(function* () { chatId: row.chat_id, widgetId, revision: row.revision, - deepLink: `/kin/${segment(orgId)}/chats/${segment(row.chat_id)}`, + deepLink: chatLink(orgId, row.chat_id), }, recipients: people.filter((person) => awaiting.has(person)), } satisfies Push; diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 7b971f45f65d9..e7ab2def5b6ba 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -67,12 +67,12 @@ All Kin code lives in `apps/mobile/src/features/chats/`. It reaches upstream thr 1. **Routes.** `Stack.tsx` spreads `...KIN_SCREENS` into the root `screens` map, next to `...SETTINGS_SCREENS`. That is one import and one line. Kin's routes: -| Route | Linking path | Preset | Screen | -| ------------- | ------------------------------------- | ------------------------------------------ | ------------------------------------------------- | -| `KinChats` | `kin` | `pageRoute({ title: "Kin" })` | Chat list | -| `KinWaiting` | `kin/waiting` | `pageRoute({ title: "Waiting on you" })` | Waiting on you | -| `KinChat` | `kin/:orgId/chats/:chatId` | `pageRoute({ duoMinimize: "onScrollUp" })` | Direct chat | -| `KinApproval` | `kin/:orgId/actions/:pendingActionId` | `sheetRoute({ detent: 0.75 })` | Approval detail (also opened from a notification) | +| Route | Linking path | Preset | Screen | +| ------------- | ---------------------------------------------------- | ------------------------------------------ | ------------------------------------------------- | +| `KinChats` | `kin` | `pageRoute({ title: "Kin" })` | Chat list | +| `KinWaiting` | `kin/waiting` | `pageRoute({ title: "Waiting on you" })` | Waiting on you | +| `KinChat` | `kin/:environmentId/:orgId/chats/:chatId` | `pageRoute({ duoMinimize: "onScrollUp" })` | Direct chat | +| `KinApproval` | `kin/:environmentId/:orgId/actions/:pendingActionId` | `sheetRoute({ detent: 0.75 })` | Approval detail (also opened from a notification) | 2. **Entry row.** `features/home/HomeScreen.tsx` renders `` as the first child of `v2ListHeader`. That is one import and one line. The row reads "Kin" with the latest preview, or "Waiting on you · 2" in the highlighted style when anything waits. A tap pushes `KinChats`. It renders nothing when no connected environment hosts a Kin organization, so upstream T3 users see no change. 3. **Notifications.** `App.tsx` adds `installKinNotifications(linkToAppPath),` to `appServiceDisposers`, plus its import. @@ -265,7 +265,7 @@ Hiding the buttons is a convenience, not the protection (DESIGN 9.3). The server - 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`. -- 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. Its text is fixed per kind and contains no PR body or agent free text, for example "Merge #212 is waiting on you". +- 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. From e5e8334b5659f633ddc6eda72d19d79354160101 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 21:44:39 +0530 Subject: [PATCH 08/10] fix(server): report kin push RPCs as disabled when Kin is off Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/layer.test.ts | 10 ++++++++++ apps/server/src/kin/push/KinPushSender.test.ts | 8 ++++++++ apps/server/src/kin/push/rpcHandlers.ts | 6 +++--- packages/contracts/src/kinPush.ts | 2 +- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/apps/server/src/kin/layer.test.ts b/apps/server/src/kin/layer.test.ts index 50f0b0329b455..b03bd38be3deb 100644 --- a/apps/server/src/kin/layer.test.ts +++ b/apps/server/src/kin/layer.test.ts @@ -13,6 +13,8 @@ import { ScheduledTaskId, AuthStandardClientScopes, KinChatRpcs, + KinOrgId, + type KinPushToken, RpcScopeAuthorization, WsRpcGroup, WS_METHODS, @@ -30,6 +32,7 @@ import * as Kin from "./layer.ts"; import { runKinMigrations } from "./persistence/KinMigrations.ts"; import * as Logger from "effect/Logger"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; +import { makeKinPushHandlers } from "./push/rpcHandlers.ts"; const session = { sessionId: AuthSessionId.make("owner"), @@ -105,6 +108,13 @@ it.effect.each(["identity", "defect", "unconfigured"] as const)( reason: "disabled", message: "Kin is not running on this host.", }); + const push = yield* makeKinPushHandlers(session).pipe( + Effect.provideService(Kin.KinServer, kin), + ); + const device = { orgId: KinOrgId.make("org"), token: "a".repeat(64) as KinPushToken }; + assert.include(yield* push["kin.push.unregisterDevice"](device).pipe(Effect.flip), { + reason: "disabled", + }); }).pipe(Effect.provide(Sqlite.layerMemory)), ); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index 81285a39481ea..85b214bb8a61b 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -515,6 +515,14 @@ describe("KinPushDevices", () => { assert.deepStrictEqual(yield* tokens(sql), [ { token: ownerPhone, person_id: owner, session_id: "sess-owner-phone" }, ]); + yield* sql`ALTER TABLE kin_push_devices RENAME TO kin_push_devices_gone`; + const broken = yield* Effect.exit( + devices.unregister(caller("sess-owner-phone", owner), { orgId, token: ownerPhone }), + ); + assert.isTrue( + Exit.isFailure(broken) && + (broken.cause.reasons[0] as { error?: KinPushError }).error?.reason === "unavailable", + ); }).pipe(Effect.provide(build(apns))); }); diff --git a/apps/server/src/kin/push/rpcHandlers.ts b/apps/server/src/kin/push/rpcHandlers.ts index a7660f3558387..8e052b047c076 100644 --- a/apps/server/src/kin/push/rpcHandlers.ts +++ b/apps/server/src/kin/push/rpcHandlers.ts @@ -13,8 +13,8 @@ import { KinPushPresence } from "./KinPushPresence.ts"; import { KinPushSender } from "./KinPushSender.ts"; const group = RpcGroup.make(...KinPushRpcs); -const unavailable = Effect.fail( - new KinPushError({ reason: "unavailable", message: "Kin notifications are unavailable." }), +const disabled = Effect.fail( + new KinPushError({ reason: "disabled", message: "Kin is not running on this host." }), ); export const makeKinPushHandlers = Effect.fn("makeKinPushHandlers")(function* ( @@ -22,7 +22,7 @@ export const makeKinPushHandlers = Effect.fn("makeKinPushHandlers")(function* ( ) { const kin = yield* Effect.serviceOption(KinServer); const caller = Effect.gen(function* () { - if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; + if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* disabled; const services = kin.value.services.value; const people = yield* Context.get(services, KinIdentity).resolve(session); return { diff --git a/packages/contracts/src/kinPush.ts b/packages/contracts/src/kinPush.ts index 944f15d973e8a..94e0f20bfd3a5 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"]), + reason: Schema.Literals(["not_member", "unavailable", "disabled"]), message: Schema.String, }) {} From 786563a5141bd390731c31a5e166fff176e7b89a Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:05:34 +0530 Subject: [PATCH 09/10] fix(kin): push review fixes Restore the upstream read-grant test and test Kin push methods in their own case. Test that a revoked phone gets no message push. Reuse a provider token a concurrent send already renewed. Register's upsert and trim share one transaction; chatPeople orders its rows; SQL causes are logged through toPersistenceSqlError. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/push/Apns.ts | 3 + apps/server/src/kin/push/KinPushDevices.ts | 64 +++++++++++-------- .../server/src/kin/push/KinPushSender.test.ts | 3 + apps/server/src/kin/push/KinPushSender.ts | 3 +- .../src/state/commandPermissions.test.ts | 54 +++++++++++----- 5 files changed, 86 insertions(+), 41 deletions(-) diff --git a/apps/server/src/kin/push/Apns.ts b/apps/server/src/kin/push/Apns.ts index 40614c2c76cf3..73476a1982338 100644 --- a/apps/server/src/kin/push/Apns.ts +++ b/apps/server/src/kin/push/Apns.ts @@ -258,6 +258,9 @@ export const makeApnsTransport = Effect.fn("KinApns.makeTransport")(function* ( const result = yield* attempt(push, body.value, token.value); if (RETRY_STATUSES.has(result.status)) return yield* attempt(push, body.value, token.value); if (result.reason === "ExpiredProviderToken") { + // A concurrent send already renewed it; reuse that instead of signing another. + if (jwt !== undefined && jwt.at > token.at) + return yield* attempt(push, body.value, jwt.value); const now = yield* Clock.currentTimeMillis; // APNs throttles provider tokens renewed more often than every 20 minutes. if (now - token.at < JWT_MIN_RENEW_MS) { diff --git a/apps/server/src/kin/push/KinPushDevices.ts b/apps/server/src/kin/push/KinPushDevices.ts index a8ecbc6369233..a4c09c209f160 100644 --- a/apps/server/src/kin/push/KinPushDevices.ts +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -18,6 +18,8 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; + import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { revokedBySession } from "../auth/ProofKeySessions.ts"; import type { PersonIdentity } from "../chat/KinIdentity.ts"; @@ -79,10 +81,17 @@ export class KinPushDevices extends Context.Service< const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + // Callers see a plain refusal; the cause is logged through the persistence error shape. const internal = (operation: string) => (cause: unknown) => isKinPushError(cause) - ? cause - : new KinPushError({ reason: "unavailable", message: `${operation} failed.` }); + ? Effect.fail(cause) + : Effect.logWarning(`${operation} failed`, toPersistenceSqlError(operation)(cause)).pipe( + Effect.andThen( + Effect.fail( + new KinPushError({ reason: "unavailable", message: `${operation} failed.` }), + ), + ), + ); const personIn = (caller: KinPushCaller, orgId: KinOrgId) => { const person = caller.people.find((candidate) => candidate.orgId === orgId); @@ -101,30 +110,33 @@ const make = Effect.gen(function* () { }); const reconcileSessions = Effect.fn("KinPushDevices.reconcileSessions")( function* () { + // No org filter: sessions are environment-local, so a revoked one is revoked in every org. const removed = yield* sql`DELETE FROM kin_push_devices WHERE ${revoked} RETURNING token`; return removed.length; }, - Effect.mapError(internal("KinPushDevices.reconcileSessions")), + Effect.catch(internal("KinPushDevices.reconcileSessions")), ); const register = Effect.fn("KinPushDevices.register")( function* (caller: KinPushCaller, input: KinPushRegisterDeviceInput) { const person = yield* personIn(caller, input.orgId); const now = yield* Clock.currentTimeMillis; - // 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. - const saved = yield* sql`INSERT INTO kin_push_devices ${sql.insert({ - org_id: input.orgId, - token: input.token, - person_id: person.personId, - platform: input.platform, - aps_environment: input.apsEnvironment, - device_label: input.deviceLabel ?? null, - session_id: caller.session.sessionId, - proof_key_thumbprint: caller.session.proofKeyThumbprint ?? null, - created_at: now, - updated_at: now, - })} + 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. + const saved = yield* sql`INSERT INTO kin_push_devices ${sql.insert({ + org_id: input.orgId, + token: input.token, + person_id: person.personId, + platform: input.platform, + aps_environment: input.apsEnvironment, + device_label: input.deviceLabel ?? null, + session_id: caller.session.sessionId, + proof_key_thumbprint: caller.session.proofKeyThumbprint ?? null, + created_at: now, + updated_at: now, + })} ON CONFLICT (org_id, token) DO UPDATE SET person_id = excluded.person_id, platform = excluded.platform, @@ -136,18 +148,20 @@ const make = Effect.gen(function* () { 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) RETURNING token`; - if (saved.length === 0) - return yield* fail("not_member", "This device is registered to someone else."); - yield* sql`DELETE FROM kin_push_devices + if (saved.length === 0) + return yield* fail("not_member", "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 ( SELECT token FROM kin_push_devices WHERE org_id = ${input.orgId} AND person_id = ${person.personId} AND token != ${input.token} ORDER BY updated_at DESC, token LIMIT ${KIN_PUSH_DEVICES_PER_PERSON - 1})`; - return { deviceId: kinPushDeviceId(input.token) }; + return { deviceId: kinPushDeviceId(input.token) }; + }), + ); }, - Effect.mapError(internal("KinPushDevices.register")), + Effect.catch(internal("KinPushDevices.register")), ); const unregister = Effect.fn("KinPushDevices.unregister")( @@ -158,7 +172,7 @@ const make = Effect.gen(function* () { RETURNING token`; return { removed: removed.length > 0 }; }, - Effect.mapError(internal("KinPushDevices.unregister")), + Effect.catch(internal("KinPushDevices.unregister")), ); const forPeople = Effect.fn("KinPushDevices.forPeople")( @@ -181,7 +195,7 @@ const make = Effect.gen(function* () { sessionId: row.session_id, })); }, - Effect.mapError(internal("KinPushDevices.forPeople")), + Effect.catch(internal("KinPushDevices.forPeople")), ); const forget = Effect.fn("KinPushDevices.forget")( @@ -189,7 +203,7 @@ const make = Effect.gen(function* () { yield* sql`DELETE FROM kin_push_devices WHERE org_id = ${orgId} AND token = ${token} ${invalidSince === undefined ? sql`` : sql`AND updated_at < ${invalidSince}`}`; }, - Effect.mapError(internal("KinPushDevices.forget")), + Effect.catch(internal("KinPushDevices.forget")), ); return KinPushDevices.of({ register, unregister, forPeople, forget, reconcileSessions }); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index 85b214bb8a61b..9a02f234de2ad 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -423,6 +423,9 @@ describe("KinPushSender", () => { assert.deepStrictEqual(yield* recipients("2026-11-08T03:00:00+05:00", null), [memberPhone]); assert.deepStrictEqual(yield* recipients("2026-11-08T01:00:00Z", null), []); assert.deepStrictEqual(yield* recipients(null, T), []); + // A phone whose session was revoked hears nothing, even before anything reconciles. + yield* sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-member'`; + assert.deepStrictEqual(yield* recipients(null, null), []); }).pipe(Effect.provide(build(apns))); }); diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index 73e24f9ff6fec..dc9f979949f18 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -122,7 +122,8 @@ const make = Effect.gen(function* () { const rows = yield* sql<{ person_id: KinPersonId; muted_until: string | null }>` SELECT person_id, muted_until FROM kin_chat_members WHERE org_id = ${orgId} AND chat_id = ${chatId} AND principal_kind = 'person' - AND left_at IS NULL`; + AND left_at IS NULL + ORDER BY person_id`; return rows .filter( (row) => diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index d4cece0a5bfcb..fa9033b286bbf 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -97,18 +97,15 @@ describe("command permissions", () => { }), ), ); - it.effect.each([WS_METHODS.serverRefreshProviders, ...Object.values(KIN_PUSH_WS_METHODS)])( + it.effect.each(Object.values(KIN_PUSH_WS_METHODS))( "requires the destination read grant for %s", (method) => Effect.scoped( Effect.gen(function* () { const registry = yield* setup; - const refresh = createCommandPermissions(runtime, method); + const push = createCommandPermissions(runtime, method); registry.set(sessions(env), AsyncResult.success(grant(true))); - expect(registry.get(refresh.permissionAtom(env))).toBe(false); - expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( - "EnvironmentAuthorizationError", - ); + expect(registry.get(push.permissionAtom(env))).toBe(false); registry.set( sessions(env), AsyncResult.success({ @@ -117,21 +114,48 @@ describe("command permissions", () => { permissions: [AuthOrchestrationReadScope], }), ); - expect(registry.get(refresh.permissionAtom(env))).toBe(true); - yield* refresh.authorize(registry, env); + expect(registry.get(push.permissionAtom(env))).toBe(true); + yield* push.authorize(registry, env); registry.set(sessions(other), AsyncResult.success(grant(false))); - expect(registry.get(refresh.permissionAtom(other))).toBe(false); - expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe( - "EnvironmentAuthorizationError", - ); - registry.set(sessions(env), AsyncResult.success(grant(false))); - expect(registry.get(refresh.permissionAtom(env))).toBe(false); - expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + expect((yield* push.authorize(registry, other).pipe(Effect.flip))._tag).toBe( "EnvironmentAuthorizationError", ); }), ), ); + it.effect("requires the destination read grant to refresh providers", () => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + const refresh = createCommandPermissions(runtime, WS_METHODS.serverRefreshProviders); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(refresh.permissionAtom(env))).toBe(false); + expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthOrchestrationReadScope], + permissions: [AuthOrchestrationReadScope], + }), + ); + expect(registry.get(refresh.permissionAtom(env))).toBe(true); + yield* refresh.authorize(registry, env); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect(registry.get(refresh.permissionAtom(other))).toBe(false); + expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + registry.set(sessions(env), AsyncResult.success(grant(false))); + expect(registry.get(refresh.permissionAtom(env))).toBe(false); + expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + }), + ), + ); it.effect("requires the destination preview grant to close a browser tab", () => Effect.scoped( From 002f07fd35f01decf1bc24b9f0fa28c0f1c6b7e9 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:29:38 +0530 Subject: [PATCH 10/10] test(kin): two sends hitting an expired APNs token renew it once Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/push/Apns.test.ts | 41 ++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/apps/server/src/kin/push/Apns.test.ts b/apps/server/src/kin/push/Apns.test.ts index c75afa72fd74f..a047d4bc3baea 100644 --- a/apps/server/src/kin/push/Apns.test.ts +++ b/apps/server/src/kin/push/Apns.test.ts @@ -110,8 +110,14 @@ it.effect("loads the .p8 only when fully configured, and signs a token APNs can type Answer = { readonly status: number; readonly body?: object } | "hang"; -/** A local APNs over cleartext HTTP/2. Answers requests in order; "hang" never answers. */ -const fakeApns = (answers: ReadonlyArray) => +/** + * A local APNs over cleartext HTTP/2. Answers requests in order; "hang" never answers. + * With `hold`, requests from index `from` are answered only once `until` have arrived. + */ +const fakeApns = ( + answers: ReadonlyArray, + hold: { readonly from: number; readonly until: number } = { from: 0, until: 0 }, +) => Effect.acquireRelease( Effect.callback<{ readonly origin: string; @@ -122,6 +128,7 @@ const fakeApns = (answers: ReadonlyArray) => const server = NodeHttp2.createServer(); const seen: Array<{ session: number; authorization: string }> = []; const sessions: Array = []; + const held: Array<() => void> = []; let markHung = () => {}; const hung = new Promise((resolve) => (markHung = resolve)); server.on("session", (session) => sessions.push(session)); @@ -132,8 +139,13 @@ const fakeApns = (answers: ReadonlyArray) => }); const answer = answers[seen.length - 1] ?? { status: 200 }; if (answer === "hang") return markHung(); - stream.respond({ ":status": answer.status }); - stream.end(answer.body === undefined ? undefined : JSON.stringify(answer.body)); + const reply = () => { + stream.respond({ ":status": answer.status }); + stream.end(answer.body === undefined ? undefined : JSON.stringify(answer.body)); + }; + if (seen.length - 1 < hold.from) return reply(); + held.push(reply); + if (seen.length >= hold.until) held.splice(0).forEach((send) => send()); }); server.listen(0, "127.0.0.1", () => { const address = server.address(); @@ -233,3 +245,24 @@ it.effect("renews an expired provider token at most every 20 minutes and keeps a assert.strictEqual(kept, renewed); }).pipe(Effect.scoped), ); + +it.effect("two sends that hit an expired token together renew it once", () => + Effect.gen(function* () { + const expired = { status: 403, body: { reason: "ExpiredProviderToken" } } as const; + const apns = yield* fakeApns([{ status: 200 }, expired, expired], { from: 1, until: 3 }); + const transport = yield* makeApnsTransport(credentials, () => apns.origin); + yield* transport.send(push); + yield* TestClock.adjust("20 minutes"); + // Both hold the old token when APNs calls it expired; only one may sign a new one. + const both = yield* Effect.all([transport.send(push), transport.send(push)], { + concurrency: 2, + }); + assert.deepStrictEqual(both, [ + { status: 200, reason: undefined }, + { status: 200, reason: undefined }, + ]); + const tokens = new Set(apns.seen.slice(1).map((request) => request.authorization)); + assert.strictEqual(apns.seen.length, 5); + assert.strictEqual(tokens.size, 2); + }).pipe(Effect.scoped), +);