From 9eea625481cc5b94715f97ab256a2c35c429c6f8 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 03:16:05 +0530 Subject: [PATCH 1/2] fix(kin): reject NUL in chat bodies before persistence --- .../src/kin/chat/KinChatRepository.test.ts | 8 ++++++++ apps/server/src/kin/chat/KinChatRepository.ts | 2 ++ apps/server/src/kin/lead/LeadPrompt.test.ts | 17 +++-------------- packages/contracts/src/kinChat.test.ts | 2 +- packages/contracts/src/kinChat.ts | 11 +++++++++-- 5 files changed, 23 insertions(+), 17 deletions(-) diff --git a/apps/server/src/kin/chat/KinChatRepository.test.ts b/apps/server/src/kin/chat/KinChatRepository.test.ts index 2dbc36e374017..e652b7a8fb515 100644 --- a/apps/server/src/kin/chat/KinChatRepository.test.ts +++ b/apps/server/src/kin/chat/KinChatRepository.test.ts @@ -300,6 +300,14 @@ describe("KinChatRepository", () => { assert.strictEqual(Option.getOrThrow(yield* repo.getMember(scope)).leftAt, later); const rejoined = yield* repo.addMember({ ...owner, joinedAt: later }); assert.deepStrictEqual(rejoined, { ...owner, joinedAt: later }); + for (const body of ["a\u0000b", "\u0000ab", "ab\u0000"]) { + const failure = yield* Effect.flip(repo.insertMessage(message("nul", { body }))); + assert.strictEqual(failure._tag, "PersistenceDecodeError"); + assert.strictEqual( + Option.isNone(yield* repo.getMessage({ orgId, messageId: decodeMessageId("nul") })), + true, + ); + } const first = yield* repo.insertMessage(message("first")); assert.deepStrictEqual(first, decodeMessage({ ...message("first"), seq: 1 })); const repeated = yield* Effect.all( diff --git a/apps/server/src/kin/chat/KinChatRepository.ts b/apps/server/src/kin/chat/KinChatRepository.ts index eace986b93f0f..00482ec72c2c4 100644 --- a/apps/server/src/kin/chat/KinChatRepository.ts +++ b/apps/server/src/kin/chat/KinChatRepository.ts @@ -70,6 +70,7 @@ const isSqlError = Schema.is(PersistenceSqlError); const encodeMentions = Schema.encodeEffect(Schema.fromJsonString(KinMessage.fields.mentions)); const encodeWidgetState = Schema.encodeEffect(Schema.fromJsonString(KinWidget.fields.state)); const encodeAwaiting = Schema.encodeEffect(Schema.fromJsonString(KinWidget.fields.awaiting)); +const decodeBody = Schema.decodeEffect(KinMessage.fields.body); const decodeHistory = Schema.decodeEffect(KinChatHistoryInput); const decodeSeq = Schema.decodeEffect(NonNegativeInt); const decodeResume = Schema.decodeEffect( @@ -820,6 +821,7 @@ const make = Effect.gen(function* () { ), insertMessage: Effect.fn("KinChatRepository.insertMessage")( function* (input) { + yield* decodeBody(input.body); return yield* sql.withTransaction( Effect.gen(function* () { const author = input.author; diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index c3511d8c0c78d..99d4e435035e4 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -140,18 +140,7 @@ it.effect.each([ { role: "member", tag: "human", label: "member human message (untrusted)" }, { role: "guest", tag: "human", label: "guest human message (untrusted)" }, { role: "owner", tag: "human", label: "owner message" }, - ...[ - "\u0000", - "\u001b", - "\u007f", - "\u0085", - "\u200b", - "\ufeff", - "\u202e", - "\u2066", - "\u2028", - "\u2029", - ].map( + ...["\u001b", "\u007f", "\u0085", "\u200b", "\ufeff", "\u202e", "\u2066", "\u2028", "\u2029"].map( (character) => ({ role: "member", @@ -228,8 +217,8 @@ it.effect.each([ editedAt: null, clientMessageId: null, }); - // Non-human owner roles and NUL text are defensive repository-boundary cases. - const defensiveRecord = (tag !== "human" && role === "owner") || body.includes("\u0000"); + // Non-human owner roles are defensive repository-boundary cases. + const defensiveRecord = tag !== "human" && role === "owner"; const source = defensiveRecord ? Chat.KinChatRepository.of({ ...repo, diff --git a/packages/contracts/src/kinChat.test.ts b/packages/contracts/src/kinChat.test.ts index 0d7de8e5d3c94..f0fada16b7dd7 100644 --- a/packages/contracts/src/kinChat.test.ts +++ b/packages/contracts/src/kinChat.test.ts @@ -223,7 +223,7 @@ describe("Kin chat contracts", () => { expect(decodeSend(payload)).toEqual(send); }); - it.each(["", " \n ", "x".repeat(16_001)])("rejects send body %j", (body) => { + it.each(["", " \n ", "x".repeat(16_001), "a\u0000b"])("rejects send body %j", (body) => { expect(() => decodeSend({ ...send, body })).toThrow(); }); diff --git a/packages/contracts/src/kinChat.ts b/packages/contracts/src/kinChat.ts index dde749e818de3..5abb518509cd4 100644 --- a/packages/contracts/src/kinChat.ts +++ b/packages/contracts/src/kinChat.ts @@ -40,6 +40,13 @@ const isNonBlankBody = Schema.makeFilter((value: string) => value.trim().length expected: "a non-blank message body", }); +// node:sqlite truncates TEXT results at NUL, even when the full value was stored. +const MessageBody = Schema.String.check( + Schema.makeFilter((value) => !value.includes("\u0000"), { + expected: "a message body without NUL characters", + }), +); + export const KinChatKind = Schema.Literals(["direct", "team_group", "project_group", "router"]); export type KinChatKind = typeof KinChatKind.Type; export const KinRole = Schema.Literals(["owner", "member", "guest"]); @@ -142,7 +149,7 @@ export const KinMessage = Schema.Struct({ author: KinAuthor, authorRole: KinRole, kind: KinMessageKind, - body: Schema.String, + body: MessageBody, intent: Schema.NullOr(KinAgentIntent), mentions: Schema.Array(KinMemberId), replyTo: Schema.NullOr(KinMessageId), @@ -293,7 +300,7 @@ export type KinChatHistoryResult = typeof KinChatHistoryResult.Type; export const KinMessagesSendInput = Schema.Struct({ chatId: KinChatId, clientMessageId: TrimmedNonEmptyString, - body: Schema.String.check(isNonBlankBody, Schema.isMaxLength(16_000)), + body: MessageBody.check(isNonBlankBody, Schema.isMaxLength(16_000)), mentions: Schema.optional(Schema.Array(KinMemberId)), replyTo: Schema.optional(KinMessageId), }); From 10b529488e39d42ef9e23e3054ee3780843ba996 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 03:17:24 +0530 Subject: [PATCH 2/2] fix(kin): share contract-validated owner timezone reader --- apps/server/src/kin/lead/LeadPrompt.test.ts | 6 ++- apps/server/src/kin/lead/LeadPrompt.ts | 26 ++++-------- apps/server/src/kin/memory/Memory.test.ts | 35 +++++++++++----- apps/server/src/kin/memory/Memory.ts | 9 +---- apps/server/src/kin/memory/MemoryCache.ts | 44 ++++++++++++++------- docs/kin/specs/lead.md | 2 +- 6 files changed, 70 insertions(+), 52 deletions(-) diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index 99d4e435035e4..8bf2bbcf15878 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -394,6 +394,9 @@ it.effect("bounds the encoded events section and drops oldest events visibly", ( it.effect.each([ { zone: "Asia/Kolkata", expected: "1970-01-01T05:30:00.000+05:30" }, { zone: "America/New_York", expected: "1969-12-31T19:00:00.000-05:00[America/New_York]" }, + { zone: "+05:30", expected: "UTC (invalid owner timezone; using UTC)" }, + { zone: " Asia/Kolkata", expected: "1970-01-01T05:30:00.000+05:30" }, + { zone: "db-failure", expected: "UTC (owner timezone unavailable; using UTC)" }, { zone: "invalid-zone", expected: "UTC (invalid owner timezone; using UTC)" }, { zone: null, expected: "UTC (owner timezone unavailable; using UTC)" }, ])("shows owner timezone $zone only below the divider", ({ zone, expected }) => @@ -402,7 +405,8 @@ it.effect.each([ const sql = yield* SqlClient.SqlClient; const prompt = yield* KinLeadPrompt; const before = yield* prompt.build(input); - if (zone !== null) + if (zone === "db-failure") yield* sql`DROP TABLE kin_trigger_settings`; + else if (zone !== null) yield* sql` INSERT INTO kin_trigger_settings (org_id, time_zone, morning_brief, evening_summary, dream, full_rebuild_weekday, owner_check_weekday, owner_check, quiet_hours_json) diff --git a/apps/server/src/kin/lead/LeadPrompt.ts b/apps/server/src/kin/lead/LeadPrompt.ts index a6be1a82ce54d..22c4c77bf72d0 100644 --- a/apps/server/src/kin/lead/LeadPrompt.ts +++ b/apps/server/src/kin/lead/LeadPrompt.ts @@ -6,10 +6,9 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import * as SqlClient from "effect/sql/SqlClient"; -import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import * as Memory from "../memory/Memory.ts"; +import * as MemoryCache from "../memory/MemoryCache.ts"; import * as Chat from "../chat/KinChatRepository.ts"; import { instructions } from "./instructions.ts"; @@ -44,7 +43,7 @@ export class KinLeadPrompt extends Context.Service< Effect.gen(function* () { const memory = yield* Memory.Memory; const chat = yield* Chat.KinChatRepository; - const sql = yield* SqlClient.SqlClient; + const cache = yield* MemoryCache.MemoryCache; const build = Effect.fn("KinLeadPrompt.build")(function* (input: KinLeadPromptInput) { const { orgId, agentId, memoryHead } = input; if (input.events.some((event) => event.orgId !== orgId || event.agentId !== agentId)) @@ -112,20 +111,11 @@ export class KinLeadPrompt extends Context.Service< ); } const now = yield* Clock.currentTimeMillis; - const settings = yield* sql<{ time_zone: string }>` - SELECT time_zone FROM kin_trigger_settings WHERE org_id = ${orgId} - `.pipe( - Effect.mapError(toPersistenceSqlError("KinLeadPrompt.ownerTimeZone")), - Effect.mapError( - (cause) => - new KinLeadPromptError({ orgId, reason: "Could not read owner timezone", cause }), - ), - ); - const zone = settings[0]?.time_zone; - const local = zone ? DateTime.makeZoned(now, { timeZone: zone }) : Option.none(); - const ownerTime = Option.isSome(local) - ? `${encoded(zone)}; local time: ${DateTime.formatIsoZoned(local.value)}` - : `UTC (${zone ? "invalid owner timezone" : "owner timezone unavailable"}; using UTC); local time: ${DateTime.formatIso(DateTime.makeUnsafe(now))}`; + const zone = yield* cache.readOwnerTimeZone(orgId); + const ownerTime = + zone._tag === "zone" + ? `${encoded(zone.zone)}; local time: ${DateTime.formatIsoZoned(DateTime.makeZonedUnsafe(now, { timeZone: zone.zone }))}` + : `UTC (${zone._tag === "invalid" ? "invalid owner timezone" : "owner timezone unavailable"}; using UTC); local time: ${DateTime.formatIso(DateTime.makeUnsafe(now))}`; return [ instructions, @@ -147,7 +137,7 @@ export class KinLeadPrompt extends Context.Service< }); return KinLeadPrompt.of({ build }); }), - ); + ).pipe(Layer.provide(MemoryCache.layer)); } const messageBodyLimit = 8_000; diff --git a/apps/server/src/kin/memory/Memory.test.ts b/apps/server/src/kin/memory/Memory.test.ts index a913563205cae..de52fda44e423 100644 --- a/apps/server/src/kin/memory/Memory.test.ts +++ b/apps/server/src/kin/memory/Memory.test.ts @@ -16,6 +16,7 @@ import * as Sqlite from "../../persistence/Sqlite.ts"; import * as Memory from "./Memory.ts"; import * as Chat from "../chat/KinChatRepository.ts"; import { KinLeadPrompt } from "../lead/LeadPrompt.ts"; +import * as MemoryCache from "./MemoryCache.ts"; import * as MemoryConfig from "./MemoryConfig.ts"; import * as ServerConfig from "../../config.ts"; import { fixtureItem } from "./__fixtures__/items.ts"; @@ -507,15 +508,31 @@ it.effect( repository.commit(); yield* memory.prepareWakeup(orgA); const utcIndex = yield* memory.readIndex(orgA); - yield* sql`UPDATE kin_trigger_settings SET time_zone = 'Invented/Invalid' WHERE org_id = ${orgA}`; - repository.commit(); - yield* memory.prepareWakeup(orgA); - expect(yield* memory.readIndex(orgA)).toContain("As of "); - expect(yield* memory.readIndex(orgA)).toBe(utcIndex); - expect(messages.some((message) => message.includes("Invalid memory owner time zone"))).toBe( - true, - ); - yield* sql`DROP TABLE kin_trigger_settings`; + yield* Effect.gen(function* () { + const cache = yield* MemoryCache.MemoryCache; + for (const row of [ + { zone: "+05:30", expected: { _tag: "invalid" } }, + { zone: " Asia/Kolkata", expected: { _tag: "zone", zone: "Asia/Kolkata" } }, + { zone: "Asia/Kolkata", expected: { _tag: "zone", zone: "Asia/Kolkata" } }, + { zone: "Invented/Invalid", expected: { _tag: "invalid" } }, + { zone: null, expected: { _tag: "missing" } }, + ]) { + if (row.zone === null) + yield* sql`DELETE FROM kin_trigger_settings WHERE org_id = ${orgA}`; + else + yield* sql`UPDATE kin_trigger_settings SET time_zone = ${row.zone} WHERE org_id = ${orgA}`; + expect(yield* cache.readOwnerTimeZone(orgA)).toEqual(row.expected); + expect(yield* cache.readOwnerTimeZone(orgB)).toEqual({ _tag: "missing" }); + repository.commit(); + yield* memory.prepareWakeup(orgA); + if (row.expected._tag !== "zone") expect(yield* memory.readIndex(orgA)).toBe(utcIndex); + } + expect( + messages.some((message) => message.includes("Invalid memory owner time zone")), + ).toBe(true); + yield* sql`DROP TABLE kin_trigger_settings`; + expect(yield* cache.readOwnerTimeZone(orgA)).toEqual({ _tag: "unavailable" }); + }).pipe(Effect.provide(MemoryCache.layer)); yield* sql`DROP TABLE kin_memory_reads`; repository.commit(); yield* memory.prepareWakeup(orgA); diff --git a/apps/server/src/kin/memory/Memory.ts b/apps/server/src/kin/memory/Memory.ts index 3a3bb6d205f32..284fee200fb22 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -671,14 +671,7 @@ const make = Effect.gen(function* () { ), }), ); - const ownerTimeZone = yield* cache.ownerTimeZone(orgId).pipe( - Effect.catchTags({ - MemoryHistoryError: () => - Effect.logWarning("Could not load memory owner time zone; using UTC", { orgId }).pipe( - Effect.as("UTC"), - ), - }), - ); + const ownerTimeZone = yield* cache.ownerTimeZone(orgId); snapshot.index = buildIndex( snapshot.items.map(({ head }) => head), reads, diff --git a/apps/server/src/kin/memory/MemoryCache.ts b/apps/server/src/kin/memory/MemoryCache.ts index 0d062391cdcfd..e5d9a2861698d 100644 --- a/apps/server/src/kin/memory/MemoryCache.ts +++ b/apps/server/src/kin/memory/MemoryCache.ts @@ -23,6 +23,12 @@ export class MemoryHistoryError extends Schema.TaggedError() { orgId: Schema.String, cause: Schema.Defect() }, ) {} +export type OwnerTimeZone = + | { readonly _tag: "zone"; readonly zone: string } + | { readonly _tag: "missing" } + | { readonly _tag: "invalid" } + | { readonly _tag: "unavailable" }; + export class MemoryCache extends Context.Service< MemoryCache, { @@ -30,7 +36,8 @@ export class MemoryCache extends Context.Service< orgId: KinOrgId, id: KinMemoryItemId, ) => Effect.Effect; - readonly ownerTimeZone: (orgId: KinOrgId) => Effect.Effect; + readonly readOwnerTimeZone: (orgId: KinOrgId) => Effect.Effect; + readonly ownerTimeZone: (orgId: KinOrgId) => Effect.Effect; readonly lastReads: ( orgId: KinOrgId, ) => Effect.Effect>, MemoryHistoryError>; @@ -41,7 +48,21 @@ const decodeTimeZone = Schema.decodeUnknownEffect(KinTrigger.fields.timeZone); const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const readOwnerTimeZone = Effect.fn("MemoryCache.readOwnerTimeZone")(function* ( + orgId: KinOrgId, + ): Effect.fn.Return { + const result = yield* sql<{ time_zone: unknown }>` + SELECT time_zone FROM kin_trigger_settings WHERE org_id = ${orgId} ORDER BY org_id + `.pipe(Effect.mapError(toPersistenceSqlError("MemoryCache.readOwnerTimeZone")), Effect.result); + if (result._tag === "Failure") return { _tag: "unavailable" }; + if (result.success.length === 0) return { _tag: "missing" }; + const decoded = yield* decodeTimeZone(result.success[0]?.time_zone).pipe(Effect.result); + return decoded._tag === "Success" + ? { _tag: "zone", zone: decoded.success } + : { _tag: "invalid" }; + }); return MemoryCache.of({ + readOwnerTimeZone, read: Effect.fn("MemoryCache.read")(function* (orgId, id) { const now = yield* Clock.currentTimeMillis; // Memory.readItem validates the item against this organization's committed snapshot. @@ -55,20 +76,13 @@ const make = Effect.gen(function* () { ); }), ownerTimeZone: Effect.fn("MemoryCache.ownerTimeZone")(function* (orgId) { - const rows = yield* sql<{ time_zone: unknown }>` - SELECT time_zone FROM kin_trigger_settings WHERE org_id = ${orgId} ORDER BY org_id - `.pipe( - Effect.mapError(toPersistenceSqlError("MemoryCache.ownerTimeZone")), - Effect.mapError((cause) => new MemoryHistoryError({ orgId, cause })), - ); - if (rows.length === 0) return "UTC"; - return yield* decodeTimeZone(rows[0]?.time_zone).pipe( - Effect.catch(() => - Effect.logWarning("Invalid memory owner time zone; using UTC", { orgId }).pipe( - Effect.as("UTC"), - ), - ), - ); + const result = yield* readOwnerTimeZone(orgId); + if (result._tag === "zone") return result.zone; + if (result._tag === "invalid") + yield* Effect.logWarning("Invalid memory owner time zone; using UTC", { orgId }); + if (result._tag === "unavailable") + yield* Effect.logWarning("Could not load memory owner time zone; using UTC", { orgId }); + return "UTC"; }), lastReads: Effect.fn("MemoryCache.lastReads")(function* (orgId) { const rows = yield* sql<{ item_id: string; last_read_at: number }>` diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index bdcede1b0ca2f..93abf960e157c 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -216,7 +216,7 @@ The CLIs own their system prompt and tool list, and Kin cannot set cache breakpo 1. The lead instructions (`instructions.ts`, below), with its version line. 2. `rules.md` through `Memory`, verbatim and pinned to the wake-up head. 3. `INDEX.md` through the same atomic, head-checked `Memory.readPromptSnapshot` read. Its content is JSON-encoded inside a labelled data quote because titles can originate in member or external text. Use the rebuilt snapshot index when present, otherwise the committed bytes, under the same lock and head check. If neither exists, quote an empty index and add a one-line "index unavailable" note. Missing committed rules fails the build. Repeated builds at the same head reuse the snapshot index; an explicit index rebuild may change the prefix without a new commit. -4. A divider, then the variable part: time and timezone, wake-up id, level per chat, budget state ("62% of today left"), running workers, and the events. Each event is a short line. Message bodies are loaded by organization and message id from the chat repository. Owner labels require both stored `author._tag: human` and `authorRole: owner`, never event provenance or body text. Only posted messages reach the prompt; suggested guest messages remain hidden until the owner sends them. Quoted message JSON includes kind, status and widgetId. Human non-owner text uses role-labelled quotes; agent and system labels never start with a role word ("agent message (untrusted)" and "system message"), with stored roles inside the JSON. GitHub summaries and other event data are quoted. JSON encoding escapes angle brackets, ampersands and every Unicode Cc, Cf, Zl and Zp character as `\uXXXX` (surrogate pairs where needed), so source text cannot close a block or forge a label. Each quoted event/message text field is capped at 2,000 UTF-16 characters, except message bodies at 8,000; a visible `…[truncated N chars]` marker inside the JSON string reports removed characters. The complete encoded events section is capped at 60,000 characters, including framing and an `N earlier events omitted` line; drop oldest events and their message quotes together. Raw webhook bodies remain references for tool reads. LEAD-6 supplies UTC time, the owner timezone and local time read from organization trigger settings (UTC with a note for a missing or invalid zone), and event context; LEAD-5/LEAD-10 supply level and budget context when available, without changing the stable prefix. +4. A divider, then the variable part: time and timezone, wake-up id, level per chat, budget state ("62% of today left"), running workers, and the events. Each event is a short line. Message bodies are loaded by organization and message id from the chat repository. Owner labels require both stored `author._tag: human` and `authorRole: owner`, never event provenance or body text. Only posted messages reach the prompt; suggested guest messages remain hidden until the owner sends them. Quoted message JSON includes kind, status and widgetId. Human non-owner text uses role-labelled quotes; agent and system labels never start with a role word ("agent message (untrusted)" and "system message"), with stored roles inside the JSON. GitHub summaries and other event data are quoted. JSON encoding escapes angle brackets, ampersands and every Unicode Cc, Cf, Zl and Zp character as `\uXXXX` (surrogate pairs where needed), so source text cannot close a block or forge a label. Each quoted event/message text field is capped at 2,000 UTF-16 characters, except message bodies at 8,000; a visible `…[truncated N chars]` marker inside the JSON string reports removed characters. The complete encoded events section is capped at 60,000 characters, including framing and an `N earlier events omitted` line; drop oldest events and their message quotes together. Raw webhook bodies remain references for tool reads. LEAD-6 supplies UTC time, the owner timezone and local time read from organization trigger settings (validated with the trigger TimeZone contract; UTC with a note for missing, invalid or unavailable settings), and event context; LEAD-5/LEAD-10 supply level and budget context when available, without changing the stable prefix. No wake-up timestamps or ids go above the divider (dates and item ids already in memory remain there). A test asserts that two prompts built for the same organization and memory commit share everything above it while the snapshot index is unchanged. Cache hits are measured with `cachedInputTokens` on the turn's `tokenUsage` and shown in the evening summary.