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 fba20b359ec5c..b0b51a9513e97 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -11,6 +11,9 @@ import { ApproverKeys } from "./approvals/ApproverKeys.ts"; import { GrantVerifier } from "./approvals/GrantVerifier.ts"; import { KinStop } from "./lead/KinStop.ts"; import type { KinGithubWebhookLock } from "./triggers/githubWebhooks.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 @@ -21,7 +24,10 @@ export type Services = | KinStop | KinGithubWebhookLock | ApproverKeys - | GrantVerifier; + | GrantVerifier + | 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 a38a27a7cff07..7ffbdd1bb6aef 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -18,6 +18,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"; @@ -179,6 +180,10 @@ export class ApproverKeys extends Context.Service< readonly reconcileSessions: ( orgId: KinOrgId | undefined, ) => 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") {} @@ -530,6 +535,16 @@ const make = Effect.gen(function* () { Effect.catch(internal("ApproverKeys.activateByGrant")), ); + const activeApprovers = Effect.fn("ApproverKeys.activeApprovers")( + function* (orgId: KinOrgId) { + yield* reconcileSessions(orgId); + 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.catch(internal("ApproverKeys.activeApprovers")), + ); + yield* reconcileSessions(undefined).pipe( Effect.catch((error) => Effect.logError("Kin approver key reconciliation failed.", error)), ); @@ -544,6 +559,7 @@ const make = Effect.gen(function* () { requireActive, activateByGrant, reconcileSessions, + activeApprovers, }); }); diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index 01f9209915ac6..4c9f3f4fbb889 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest"; import { AuthSessionId, AuthStandardClientScopes, + EnvironmentId, KinActionId, KinEventId, KinKeyThumbprint, @@ -25,6 +26,7 @@ import * as TestClock from "effect/testing/TestClock"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; +import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as Kin from "../layer.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { KinAudit, kinAuditHash, layer as auditLayer } from "./Audit.ts"; @@ -528,6 +530,12 @@ describe("kin.audit RPCs", () => { Effect.provide( Kin.layer.pipe( Layer.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ KIN_ENABLED: true }))), + // Push deep links name the host environment. + Layer.provide( + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("env_kin")), + }), + ), ), ), ); diff --git a/apps/server/src/kin/approvals/layer.ts b/apps/server/src/kin/approvals/layer.ts index 4418b6466bb7d..d72c45e6cc1c6 100644 --- a/apps/server/src/kin/approvals/layer.ts +++ b/apps/server/src/kin/approvals/layer.ts @@ -9,11 +9,12 @@ import * as GrantPorts from "./GrantPorts.ts"; import * as GrantVerifier from "./GrantVerifier.ts"; import * as PendingActions from "./PendingActions.ts"; +// Push routing reads pending actions, so they stay in the layer's output. export const layer = GrantVerifier.layer.pipe( Layer.provideMerge(ApproverKeys.layer), + Layer.provideMerge(PendingActions.layer), Layer.provide( Layer.mergeAll( - PendingActions.layer, AttestationTrust.layer.pipe(Layer.provide(FetchHttpClient.layer)), GrantPorts.orgRolesLayer, GrantPorts.liveTargetsUnconfiguredLayer, diff --git a/apps/server/src/kin/approvals/mcp.test.ts b/apps/server/src/kin/approvals/mcp.test.ts index 98aa822818c1b..6073f7d1845a6 100644 --- a/apps/server/src/kin/approvals/mcp.test.ts +++ b/apps/server/src/kin/approvals/mcp.test.ts @@ -39,6 +39,7 @@ import { PullRequestService } from "../../pullRequest/PullRequestService.ts"; import { liveThreadShell } from "../../mcp/McpToolAccess.testkit.ts"; import * as McpHttpServer from "../../mcp/McpHttpServer.ts"; import { McpInvocationContext, type McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; +import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as Kin from "../layer.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { KinChatService } from "../chat/KinChatService.ts"; @@ -153,6 +154,12 @@ const layerWith = (pullRequestFacts: Layer.Layer { { migration_id: 18, name: "Dreams" }, { migration_id: 19, name: "WebhookSecretHash" }, { migration_id: 20, name: "Approvals" }, + { migration_id: 21, name: "PushDevices" }, ]); assert.deepStrictEqual( upstreamBefore.map((row) => [row.migration_id, row.name] as const), @@ -140,6 +142,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}) @@ -191,6 +194,7 @@ describe("Kin migrations", () => { { migration_id: 18, name: "Dreams" }, { migration_id: 19, name: "WebhookSecretHash" }, { migration_id: 20, name: "Approvals" }, + { migration_id: 21, name: "PushDevices" }, ]); assert.deepStrictEqual(yield* upstreamHistory, upstreamBefore); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_orgs`, [ @@ -228,6 +232,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" }, @@ -287,6 +292,7 @@ describe("Kin migrations", () => { [18, "Dreams"], [19, "WebhookSecretHash"], [20, "Approvals"], + [21, "PushDevices"], ]); const before = yield* kinSchema; assert.deepStrictEqual( @@ -341,6 +347,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", @@ -370,6 +377,7 @@ describe("Kin migrations", () => { [18, "Dreams"], [19, "WebhookSecretHash"], [20, "Approvals"], + [21, "PushDevices"], ]); assert.deepStrictEqual( yield* sql`SELECT member_id FROM kin_chat_members WHERE org_id = 'org' ORDER BY member_id`, @@ -415,6 +423,7 @@ describe("Kin migrations", () => { { migration_id: 18, name: "Dreams" }, { migration_id: 19, name: "WebhookSecretHash" }, { migration_id: 20, name: "Approvals" }, + { migration_id: 21, name: "PushDevices" }, ]); assert.deepStrictEqual(yield* runKinMigrations(), []); assert.deepStrictEqual(yield* runMigrations(), []); @@ -426,13 +435,13 @@ describe("Kin migrations", () => { Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* runKinMigrations(); - // What a database looks like when K019 merged before a lower-numbered migration. + // What a database looks like when K021 merged before a lower-numbered migration. yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id = 5`; const history = yield* kinHistory; 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 20"); + assert.include(String(exit), "below the latest applied migration 21"); assert.deepStrictEqual(yield* kinHistory, history); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); @@ -441,11 +450,11 @@ describe("Kin migrations", () => { Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* runKinMigrations(); - // What a database looks like after running another branch's K020. - yield* sql`UPDATE kin_sql_migrations SET name = 'Budget' WHERE migration_id = 20`; + // What a database looks like after running another branch's K021. + yield* sql`UPDATE kin_sql_migrations SET name = 'Budget' WHERE migration_id = 21`; const exit = yield* Effect.exit(runKinMigrations()); assert.isTrue(Exit.isFailure(exit)); - assert.include(String(exit), "20_Approvals"); + assert.include(String(exit), "21_PushDevices"); assert.include(String(exit), "share a number"); }).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 494d238c6cb2b..42d3b3175b6b6 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -22,6 +22,7 @@ import Workers from "./migrations/K017_Workers.ts"; import Dreams from "./migrations/K018_Dreams.ts"; import WebhookSecretHash from "./migrations/K019_WebhookSecretHash.ts"; import Approvals from "./migrations/K020_Approvals.ts"; +import PushDevices from "./migrations/K021_PushDevices.ts"; const table = "kin_sql_migrations"; const run = Migrator.make({}); @@ -46,6 +47,7 @@ const loader = Migrator.fromRecord({ "18_Dreams": Dreams, "19_WebhookSecretHash": WebhookSecretHash, "20_Approvals": Approvals, + "21_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/K021_PushDevices.ts b/apps/server/src/kin/persistence/migrations/K021_PushDevices.ts new file mode 100644 index 0000000000000..b6f275ed6f5fe --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K021_PushDevices.ts @@ -0,0 +1,23 @@ +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, + proof_key_thumbprint TEXT, + 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..a047d4bc3baea --- /dev/null +++ b/apps/server/src/kin/push/Apns.test.ts @@ -0,0 +1,268 @@ +// @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"; + +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, + makeApnsTransport, +} 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", + }, + ); + 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. + * 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; + 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 = []; + const held: Array<() => void> = []; + 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(); + 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(); + 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; + +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: 200 }, + { status: 500 }, + { status: 200 }, + { status: 503 }, + { status: 503 }, + { status: 429, body: { reason: "TooManyRequests" } }, + { status: 200 }, + ]); + const transport = yield* makeApnsTransport(credentials, () => apns.origin); + + // 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: 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), +); + +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, expired, renewed, refused, kept] = apns.seen.map( + (request) => request.authorization, + ); + assert.strictEqual(expired, first); + assert.notStrictEqual(renewed, expired); + assert.strictEqual(refused, renewed); + 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), +); diff --git a/apps/server/src/kin/push/Apns.ts b/apps/server/src/kin/push/Apns.ts new file mode 100644 index 0000000000000..73476a1982338 --- /dev/null +++ b/apps/server/src/kin/push/Apns.ts @@ -0,0 +1,290 @@ +// @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 JWT_MIN_RENEW_MS = 20 * 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; + /** `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. + * `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, + { + 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", + ...(push.collapseId === undefined ? {} : { "apns-collapse-id": push.collapseId }), +}); + +/** + * 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 parsed: unknown; + try { + parsed = text.length > 0 ? JSON.parse(text) : undefined; + } catch { + parsed = undefined; + } + 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); + 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 unreachable: KinApnsResult = { status: 0, reason: "transport" }; +// 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], +) { + 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 open of sessions.values()) open.session.close(); + sessions.clear(); + }), + ); + + const sessionFor = Effect.fnUntraced(function* (environment: KinApsEnvironment) { + const now = yield* Clock.currentTimeMillis; + const open = sessions.get(environment); + 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 === session) sessions.delete(environment); + }; + session.on("error", drop); + session.on("close", drop); + session.on("goaway", drop); + session.unref(); + 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 === 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) + jwt = { value: apnsProviderToken(credentials, now), at: now }; + 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 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") { + // 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) { + 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; + }), + }); +}); + +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 new file mode 100644 index 0000000000000..a4c09c209f160 --- /dev/null +++ b/apps/server/src/kin/push/KinPushDevices.ts @@ -0,0 +1,212 @@ +// @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 { 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"; + +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); + +/** 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 })); + +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. 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; + } +>()("t3/kin/push/KinPushDevices") {} + +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) + ? 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); + 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. 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`, + }); + 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.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; + 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, + 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 + 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 + 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.catch(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.catch(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.catch(internal("KinPushDevices.forPeople")), + ); + + const forget = Effect.fn("KinPushDevices.forget")( + 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.catch(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.test.ts b/apps/server/src/kin/push/KinPushPresence.test.ts new file mode 100644 index 0000000000000..181294b8a5aa6 --- /dev/null +++ b/apps/server/src/kin/push/KinPushPresence.test.ts @@ -0,0 +1,86 @@ +import { assert, it } from "@effect/vitest"; +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"; +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 * as Chat from "../chat/layer.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 acking beats", () => + Effect.gen(function* () { + const presence = yield* Presence.KinPushPresence; + // 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 takes the first beat and never acks it. + const stalled = KinChatId.make("chat_stalled"); + const received = yield* Deferred.make(); + yield* presence.watch(sessionId, stalled).pipe( + Stream.runForEach(() => + Deferred.succeed(received, undefined).pipe(Effect.andThen(Effect.never)), + ), + Effect.forkChild({ startImmediately: true }), + ); + assert.isTrue(yield* presence.isWatching(sessionId, stalled)); + yield* TestClock.adjust("15 seconds"); + yield* Deferred.await(received); + // 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, 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)), +); + +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 watching session through the real handler", () => + Effect.gen(function* () { + const services = Option.getOrThrow((yield* Kin.KinServer).services); + const presence = Context.get(services, Presence.KinPushPresence); + 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* 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(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 new file mode 100644 index 0000000000000..f242490839fb2 --- /dev/null +++ b/apps/server/src/kin/push/KinPushPresence.ts @@ -0,0 +1,83 @@ +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"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +/** 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). + */ +export class KinPushPresence extends Context.Service< + KinPushPresence, + { + /** + * 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 watch: ( + sessionId: AuthSessionId, + chatId: KinChatId, + ) => Stream.Stream; + readonly isWatching: (sessionId: AuthSessionId, chatId: KinChatId) => Effect.Effect; + } +>()("t3/kin/push/KinPushPresence") {} + +const make = Effect.sync(() => { + type Watcher = { refreshedAt: number }; + const open = new Map>(); + const slot = (sessionId: AuthSessionId, chatId: KinChatId) => `${sessionId}\u0000${chatId}`; + const ttl = Duration.toMillis(KIN_PUSH_PRESENCE_TTL); + + const mark = Effect.fn("KinPushPresence.mark")(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 watchers = open.get(key); + watchers?.delete(watcher); + if (watchers?.size === 0) open.delete(key); + }), + ); + return watcher; + }); + + return KinPushPresence.of({ + 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; + }), + 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; + const now = yield* Clock.currentTimeMillis; + for (const watcher of watchers) if (now - watcher.refreshedAt < ttl) return true; + return false; + }), + }); +}); + +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..3d035220a3b42 --- /dev/null +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -0,0 +1,771 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + EnvironmentId, + KinChatId, + KinEventId, + KinMessageId, + KinOrgId, + KinPersonId, + KinWidgetId, + type KinPushError, + 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"; +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 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 * as Audit from "../approvals/Audit.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"; +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, + 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: 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", + 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)).pipe( + Effect.andThen(respond(push)), + Effect.as(answers.get(push.token) ?? { status: 200, reason: undefined }), + ), + }); + return { sent, answers, layer }; +}; + +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.provideMerge(Audit.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); +// 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); + 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", + }); + 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 = ( + 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, notify, 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: [], + ceilingBelowOwner: true, + }, + source: KinEventId.make("evt-212"), + } as unknown as PendingActions.KinPendingActionCreateInput); + + // 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]), + [ + [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/env_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* 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 { 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" }, + [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* 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* 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/env_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" }); + 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), + [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}$/); + // A suggestion only the owner can see isn't announced to anyone. + const suggested = yield* postMessage(sql, "system", "suggested"); + assert.strictEqual((yield* notify({ _tag: "message", orgId, messageId: suggested })).sent, 0); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("skips a device while its session watches the chat and acks", () => { + const apns = makeApns(); + return Effect.gen(function* () { + 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 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 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 { 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"); + 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* 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), []); + // 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))); + }); + + 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 { notify, 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* 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* () { + const { notify, sql } = yield* seed; + const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); + assert.deepStrictEqual(yield* 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 and session revoke", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { 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'`; + // 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" }, + ]); + 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))); + }); + + 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("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))); + }); + + /** 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* () { + 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 { notify, sql } = yield* seed; + const notifyOwner = Effect.gen(function* () { + const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + return yield* 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 new file mode 100644 index 0000000000000..dc9f979949f18 --- /dev/null +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -0,0 +1,329 @@ +import type { + KinActionId, + KinChatId, + KinMessageId, + KinOrgId, + KinPendingAction, + KinPersonId, + KinPushCategory, + KinPushData, + KinPushSendingStatus, + KinWidgetId, +} from "@t3tools/contracts"; +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"; +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"; +import { KinPushDevices, kinPushDeviceId, type KinPushDevice } 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; + /** Message pushes collapse per chat, so a busy chat shows one banner. */ + readonly collapseId?: string; + readonly data: KinPushData; + readonly recipients: ReadonlyArray; +}; + +// 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)), +); + +/** 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; + /** 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; + 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* ( + orgId: KinOrgId, + chatId: KinChatId, + options: { readonly respectMute: boolean }, + ) { + 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 + ORDER BY person_id`; + return rows + .filter( + (row) => + !options.respectMute || row.muted_until === null || !(Date.parse(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/${host}/${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, + collapseId: kinPushCollapseId(orgId, row.chat_id), + data: { + kin: 1, + orgId, + chatId: row.chat_id, + deepLink: chatLink(orgId, 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" || row.phase === null + ? ({ + 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: chatLink(orgId, row.chat_id), + }, + recipients: people.filter((person) => awaiting.has(person)), + } satisfies Push; + }); + + 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) { + 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, + reason: result.reason, + }); + } else { + yield* Effect.logWarning("APNs refused a Kin push.", { + deviceId, + status: result.status, + reason: result.reason, + }); + } + 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 }; + + const run = Effect.fn("KinPushSender.run")( + 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 }), + ), + ), + ); + + const notify = Effect.fn("KinPushSender.notify")(function* (notification: KinPushNotification) { + return yield* Effect.forkIn(run(notification), scope); + }); + + 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..8e052b047c076 --- /dev/null +++ b/apps/server/src/kin/push/rpcHandlers.ts @@ -0,0 +1,52 @@ +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 * 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); +const disabled = Effect.fail( + new KinPushError({ reason: "disabled", message: "Kin is not running on this host." }), +); + +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* disabled; + 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, + presence: Context.get(services, KinPushPresence), + 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))), + // 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/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index a5d340b15ef77..ef8b85462ab8c 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -6,6 +6,7 @@ import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; import { KinServer } from "./KinServer.ts"; +import { makeKinPushHandlers } from "./push/rpcHandlers.ts"; import { makeKinWebhookHandlers } from "./triggers/webhookRpcHandlers.ts"; const group = RpcGroup.make(...KinRpcs); @@ -20,6 +21,7 @@ export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( session, Option.flatMap(kin, (kin) => kin.services), )), + ...(yield* makeKinPushHandlers(session)), ...(yield* makeKinWebhookHandlers(session)), }); }); diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 7500c8214bd48..7ce2c734e2991 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. @@ -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,19 @@ 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, 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 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. `deepLink` names the sending host, `/kin///chats/` or `/kin///actions/`, because every host shares org id `kin-default`. Its text is fixed per kind and contains no PR body or agent free text, for example "Merge #212 is waiting on you". +- The sender skips a device whose session has a live `kin.push.watch({ chatId })` stream. Upstream owns the foreground handler, so this check has to happen on the server. MOB-11 opens it while a chat is on screen with `watchKinChatForPush` (`@t3tools/client-runtime/kin-push`) and ends it when the chat leaves the screen or the app the foreground. The stream sends a beat every 15 seconds, and each pull refreshes the mark. The RPC server pulls only after the client acks the last beat, so a half-open socket stops suppressing within 45 seconds, whatever the chat's traffic. Until a client opens it, nothing is suppressed: the failure mode is an extra push, not a lost one. +- Approval pushes go only to the devices of people with an `active` approver key (DESIGN 9.3), read after session revocations. Approval cards in chat never push on their own. +- Callers pass ids only, `notify({ _tag: "approval", actionId } | { _tag: "message", messageId } | { _tag: "widget", widgetId })`, after their transaction commits, because `notify` reads what the commit wrote. It sends in a fiber owned by the sender's layer, so a request handler can `yield*` it and return; the request ending doesn't cancel the push. The sender reads recipients from the database: approvers, the chat's people other than the author for messages (muted members skipped), and the widget's `awaiting` people who are still in the chat. Message pushes set `apns-collapse-id` per chat, so a busy chat shows one banner. Not wired yet: APPR-3's `request_action` and `registerKey` call `approval` after creating an action, and lane A calls `message` after a post and `widget` when a deferral changes phase or a card starts waiting on someone. + +**Test push (dev only).** Nishchay creates an APNs auth key (Keys, Apple Push Notifications service) in the team that signs the Kin build, then, on the Kin host with a development build installed, runs `cd apps/server && KIN_APNS_KEY_FILE=… KIN_APNS_KEY_ID=… KIN_APNS_TEAM_ID=… KIN_APNS_TOPIC= node scripts/kin-push-test.ts development`. The token comes from `Notifications.getDevicePushTokenAsync()` on the phone. APNs answering 200 and the banner showing is MOB-10's last "done when". **Receiving (`features/chats/notifications/installKinNotifications.ts`, new).** @@ -328,7 +335,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`, and Kin adds its own real-tap gate on actions (Design correction 9). - 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 7e05711fc1076..6593a18420401 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -52,6 +52,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/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/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index ede94e9d9afe6..c456eef69bfe5 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,6 +97,32 @@ describe("command permissions", () => { }), ), ); + 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 push = createCommandPermissions(runtime, method); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(push.permissionAtom(env))).toBe(false); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthOrchestrationReadScope], + permissions: [AuthOrchestrationReadScope], + }), + ); + expect(registry.get(push.permissionAtom(env))).toBe(true); + yield* push.authorize(registry, env); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect((yield* push.authorize(registry, other).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + }), + ), + ); it.effect("guards the Kin stop switch with the destination operate grant", () => Effect.scoped( Effect.gen(function* () { 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/kinChat.test.ts b/packages/contracts/src/kinChat.test.ts index 4b5ec7745a6e2..5f1346d26bb11 100644 --- a/packages/contracts/src/kinChat.test.ts +++ b/packages/contracts/src/kinChat.test.ts @@ -3,6 +3,7 @@ import * as Schema from "effect/Schema"; import * as Kin from "./kinChat.ts"; import { KinCheckRun } from "./kinApprovals.ts"; +import { KinPushRegisterDeviceInput } from "./kinPush.ts"; const at = "2026-11-07T00:00:00.000Z"; const person = { @@ -268,6 +269,16 @@ describe("Kin chat contracts", () => { value: { ...task, [field]: "a\u0000b" }, })), { schema: KinCheckRun, value: { name: "a\u0000b", required: true, status: "passed" } }, + { + schema: KinPushRegisterDeviceInput, + value: { + orgId: "org", + token: "a".repeat(64), + platform: "ios", + apsEnvironment: "production", + deviceLabel: "a\u0000b", + }, + }, ])("rejects NUL text %#", ({ schema, value }) => { const codec: Schema.Codec = schema; expect(() => Schema.decodeSync(codec)(value)).toThrow(); diff --git a/packages/contracts/src/kinPush.ts b/packages/contracts/src/kinPush.ts new file mode 100644 index 0000000000000..94e0f20bfd3a5 --- /dev/null +++ b/packages/contracts/src/kinPush.ts @@ -0,0 +1,133 @@ +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, KinTrimmedText, 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(KinTrimmedText.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 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", "disabled"]), + message: Schema.String, +}) {} + +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]); + +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, + }), + // 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 f6286b0beddbb..bab9b2b6cbd25 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -11,6 +11,7 @@ import { } 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 { KinGithubWebhookOrgInput, KinGithubWebhookSecretInput, @@ -66,10 +67,12 @@ export const KinRpcs = [ ...KinChatAndBudgetRpcs, ...KinApprovalRpcs, ...KinGithubWebhookRpcs, + ...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, "kin.org.get": AuthOrchestrationReadScope, @@ -108,6 +111,9 @@ 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", + "kin.push.watch": "kin-push", "kin.webhooks.github.setup": "kin-webhooks", "kin.webhooks.github.setSecret": "kin-webhooks", "kin.webhooks.github.rotate": "kin-webhooks",