From 2b674b00a8408696e4eea0d3c01f5751d4abf5e3 Mon Sep 17 00:00:00 2001 From: Tushar Tripathi Date: Mon, 23 Nov 2026 17:21:41 +0530 Subject: [PATCH 1/3] fix(teams): a read-only key's use names the key as its actor A key belongs to its team and keeps working after the admin who minted it is demoted or leaves, so team_read_key_used no longer names that admin. authority_events takes an actor_key_id in place of actor_user_id for it; mint and revoke keep their admin. cast audit prints the key as the actor. Codecast-Session: https://codecast.sh/conversation/jx79zb6wppynmd2h8ryahc3vrh8jswyy --- packages/cli/src/index.ts | 3 ++- packages/convex/convex/lib/authorityEvents.ts | 17 ++++++++++++----- packages/convex/convex/schema.ts | 4 +++- packages/convex/convex/teamReadKeys.test.ts | 3 ++- packages/convex/convex/teamReadKeys.ts | 6 +++--- 5 files changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 5afb800c19..1fc9255322 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -10502,7 +10502,8 @@ program .filter(Boolean).join(" "); for (const r of rows) { const change = r.detail?.after ? ` ${c.dim}${JSON.stringify(r.detail.after)}${c.reset}` : ""; - console.log(`${c.dim}${formatRelativeTime(r.created_at)}${c.reset} ${c.cyan}${r.kind}${c.reset} by ${String(r.actor_user_id).slice(0, 8)} ${subject(r)}${change}`); + const actor = r.actor_key_id ? `key ${String(r.actor_key_id).slice(0, 8)}` : String(r.actor_user_id).slice(0, 8); + console.log(`${c.dim}${formatRelativeTime(r.created_at)}${c.reset} ${c.cyan}${r.kind}${c.reset} by ${actor} ${subject(r)}${change}`); } }); diff --git a/packages/convex/convex/lib/authorityEvents.ts b/packages/convex/convex/lib/authorityEvents.ts index e58c2d8d8f..648e41ddb0 100644 --- a/packages/convex/convex/lib/authorityEvents.ts +++ b/packages/convex/convex/lib/authorityEvents.ts @@ -9,7 +9,7 @@ // A leaf like accessKeys.ts: conversationVisibility.ts (patchConversationVisibility) imports // it at load, so nothing here may reach a module that defines functions. import { Id } from "../_generated/dataModel"; -import { computeWorkspaceKey } from "./accessKeys"; +import { computeWorkspaceKey, workspaceKey } from "./accessKeys"; import { sha256Hex } from "./hash"; export const AUTHORITY_EVENT_KINDS = [ @@ -35,9 +35,14 @@ export const AUTHORITY_EVENT_KINDS = [ ] as const; export type AuthorityEventKind = (typeof AUTHORITY_EVENT_KINDS)[number]; -export type AuthorityEventInput = { +/** Who acted: a person, or a team read key using itself. A key belongs to its + * team, not to the admin who minted it, so its events are the team's. */ +type AuthorityActor = + | { actor_user_id: Id<"users">; actor_key_id?: never } + | { actor_key_id: Id<"team_read_keys">; actor_user_id?: never; team_id: Id<"teams"> }; + +export type AuthorityEventInput = AuthorityActor & { kind: AuthorityEventKind; - actor_user_id: Id<"users">; actor_conversation_id?: Id<"conversations">; /** The conversation the event is about; its POST-change row decides the * access key (a team-visible session's events are the team's, a private @@ -63,7 +68,7 @@ export async function recordAuthorityEvent(ctx: { db: any }, ev: AuthorityEventI const team_id = ev.team_id ?? conv?.team_id; return ctx.db.insert("authority_events", { kind: ev.kind, - actor_user_id: ev.actor_user_id, + ...(ev.actor_user_id === undefined ? { actor_key_id: ev.actor_key_id } : { actor_user_id: ev.actor_user_id }), ...(ev.actor_conversation_id ? { actor_conversation_id: ev.actor_conversation_id } : {}), ...(conv ? { conversation_id: conv._id } : {}), ...(team_id ? { team_id } : {}), @@ -72,7 +77,9 @@ export async function recordAuthorityEvent(ctx: { db: any }, ev: AuthorityEventI ...(ev.share_table ? { share_table: ev.share_table } : {}), ...(ev.share_token ? { share_token_hash: await sha256Hex(ev.share_token) } : {}), detail: ev.detail ?? {}, - workspace: computeWorkspaceKey({ user_id: ev.actor_user_id, team_id }, conv), + workspace: ev.actor_user_id === undefined + ? workspaceKey({ type: "team", teamId: ev.team_id }) + : computeWorkspaceKey({ user_id: ev.actor_user_id, team_id }, conv), created_at: Date.now(), }); } diff --git a/packages/convex/convex/schema.ts b/packages/convex/convex/schema.ts index ef2a21a23a..9038da8fdf 100644 --- a/packages/convex/convex/schema.ts +++ b/packages/convex/convex/schema.ts @@ -5739,7 +5739,9 @@ export default defineSchema({ v.literal("team_read_key_revoked"), v.literal("team_read_key_used"), ), - actor_user_id: v.id("users"), + // One of the two: the person who acted, or the team read key that was used. + actor_user_id: v.optional(v.id("users")), + actor_key_id: v.optional(v.id("team_read_keys")), actor_conversation_id: v.optional(v.id("conversations")), conversation_id: v.optional(v.id("conversations")), team_id: v.optional(v.id("teams")), diff --git a/packages/convex/convex/teamReadKeys.test.ts b/packages/convex/convex/teamReadKeys.test.ts index d7e33c6fa0..8ac6f2f1fd 100644 --- a/packages/convex/convex/teamReadKeys.test.ts +++ b/packages/convex/convex/teamReadKeys.test.ts @@ -275,8 +275,9 @@ describe("team read keys", () => { "team_read_key_used", "team_read_key_revoked", ]); + // A person mints and revokes; the key itself is the actor of its use. + expect(events.map((e: any) => e.actor_key_id ?? e.actor_user_id)).toEqual([ada, key_id, key_id, ada]); for (const e of events) { - expect(e.actor_user_id).toBe(ada); expect(e.detail.after).toMatchObject({ key_id, name: "eng site" }); expect(JSON.stringify(e)).not.toContain(key); } diff --git a/packages/convex/convex/teamReadKeys.ts b/packages/convex/convex/teamReadKeys.ts index 5d0b94b041..700712a633 100644 --- a/packages/convex/convex/teamReadKeys.ts +++ b/packages/convex/convex/teamReadKeys.ts @@ -166,8 +166,8 @@ export const keyForHash = internalQuery({ /** * A key's use, recorded before the read it opens: last_used_at moves and a - * team_read_key_used event names the key, with the admin who minted it as the - * actor. Requests inside the same window record nothing. + * team_read_key_used event names the key as its actor. Requests inside the + * same window record nothing. */ export const recordUse = internalMutation({ args: { key_id: v.id("team_read_keys") }, @@ -178,7 +178,7 @@ export const recordUse = internalMutation({ await ctx.db.patch(key._id, { last_used_at: now }); await recordAuthorityEvent(ctx, { kind: "team_read_key_used", - actor_user_id: key.created_by, + actor_key_id: key._id, team_id: key.team_id, detail: { after: { key_id: key._id, name: key.name, prefix: key.prefix } }, }); From facbd48f2adfa5945703a2dbb4c3cc8c72507c5e Mon Sep 17 00:00:00 2001 From: Tushar Tripathi Date: Mon, 23 Nov 2026 17:21:45 +0530 Subject: [PATCH 2/3] feat(teams): flag read-only keys whose minter is no longer an admin The key list says, for each key, whether the admin who minted it is still an admin of the team. Team settings shows a live key whose minter was demoted or left as "by , no longer an admin", beside Revoke. Codecast-Session: https://codecast.sh/conversation/jx79zb6wppynmd2h8ryahc3vrh8jswyy --- packages/convex/convex/teamReadKeys.test.ts | 17 +++++++++++++ packages/convex/convex/teamReadKeys.ts | 24 ++++++++++++------- .../web/components/settings/TeamReadKeys.tsx | 7 ++++-- 3 files changed, 37 insertions(+), 11 deletions(-) diff --git a/packages/convex/convex/teamReadKeys.test.ts b/packages/convex/convex/teamReadKeys.test.ts index 8ac6f2f1fd..7c66249996 100644 --- a/packages/convex/convex/teamReadKeys.test.ts +++ b/packages/convex/convex/teamReadKeys.test.ts @@ -250,6 +250,23 @@ describe("team read keys", () => { await expect(as(mo).mutation(api.teamReadKeys.revoke, { team_id: team, key_id: minted.key_id })).rejects.toThrow(); }); + test("the list flags a key whose minter was demoted or left the team", async () => { + const { ada, mo, vi, team, as } = await setup(); + const setRole = (by: Id<"users">, member: Id<"users">, role: "admin" | "member") => + as(by).mutation(api.teams.setMemberRole, { team_id: team, member_user_id: member, role }); + await setRole(ada, vi, "admin"); + await setRole(ada, mo, "admin"); + await mint(as(ada), team, "by ada"); + await mint(as(vi), team, "by vi"); + const flags = async () => + Object.fromEntries((await as(mo).query(api.teamReadKeys.list, { team_id: team }))!.map((k) => [k.name, k.created_by_still_admin])); + expect(await flags()).toEqual({ "by ada": true, "by vi": true }); + await setRole(vi, ada, "member"); + expect(await flags()).toEqual({ "by ada": false, "by vi": true }); + await as(vi).mutation(api.teams.removeFromTeam, { team_id: team, user_id: vi }); + expect(await flags()).toEqual({ "by ada": false, "by vi": false }); + }); + test(`a team holds at most ${MAX_LIVE_TEAM_READ_KEYS} live keys; a revoked one frees a place`, async () => { const { ada, team, as } = await setup(); const first = await mint(as(ada), team, "key 0"); diff --git a/packages/convex/convex/teamReadKeys.ts b/packages/convex/convex/teamReadKeys.ts index 700712a633..1697f6224b 100644 --- a/packages/convex/convex/teamReadKeys.ts +++ b/packages/convex/convex/teamReadKeys.ts @@ -54,6 +54,14 @@ async function requireAdmin(ctx: any, teamId: Id<"teams">): Promise> return userId; } +async function isAdmin(ctx: any, userId: Id<"users">, teamId: Id<"teams">): Promise { + const membership = await ctx.db + .query("team_memberships") + .withIndex("by_user_team", (q: any) => q.eq("user_id", userId).eq("team_id", teamId)) + .first(); + return membership?.role === "admin"; +} + function keysOf(ctx: any, teamId: Id<"teams">): Promise[]> { return ctx.db.query("team_read_keys").withIndex("by_team", (q: any) => q.eq("team_id", teamId)).collect(); } @@ -64,15 +72,12 @@ export const list = query({ handler: async (ctx, args) => { const userId = await getAuthUserId(ctx); if (!userId) return null; - const membership = await ctx.db - .query("team_memberships") - .withIndex("by_user_team", (q) => q.eq("user_id", userId).eq("team_id", args.team_id)) - .first(); - if (membership?.role !== "admin") return null; + if (!(await isAdmin(ctx, userId, args.team_id))) return null; const keys = await keysOf(ctx, args.team_id); - const creators = new Map(); - for (const id of new Set(keys.map((k) => String(k.created_by)))) { - creators.set(id, (await ctx.db.get(id as Id<"users">))?.name ?? null); + // A key outlives its minter's admin role, so the list says which minters are no longer admins. + const creators = new Map(); + for (const id of new Set(keys.map((k) => k.created_by))) { + creators.set(String(id), { name: (await ctx.db.get(id))?.name ?? null, admin: await isAdmin(ctx, id, args.team_id) }); } return keys .sort((a, b) => b.created_at - a.created_at) @@ -81,7 +86,8 @@ export const list = query({ name: k.name, prefix: k.prefix, created_at: k.created_at, - created_by_name: creators.get(String(k.created_by)) ?? null, + created_by_name: creators.get(String(k.created_by))?.name ?? null, + created_by_still_admin: creators.get(String(k.created_by))?.admin ?? false, expires_at: k.expires_at, revoked_at: k.revoked_at ?? null, last_used_at: k.last_used_at ?? null, diff --git a/packages/web/components/settings/TeamReadKeys.tsx b/packages/web/components/settings/TeamReadKeys.tsx index dabfc7f68f..df0f3b1dd1 100644 --- a/packages/web/components/settings/TeamReadKeys.tsx +++ b/packages/web/components/settings/TeamReadKeys.tsx @@ -220,9 +220,12 @@ function MintedKey({ minted, onDone }: { minted: Minted; onDone: (fromKeyboard: function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now: number }) { const ended = row.revoked_at ? "Revoked" : row.expires_at <= now ? "Expired" : null; const daysLeft = Math.ceil((row.expires_at - now) / DAY_MS); + // A live key whose minter left the team or lost the admin role: the remaining admins decide whether to revoke it. + const orphaned = !ended && !row.created_by_still_admin; + const creator = orphaned ? `by ${row.created_by_name ?? "someone"}, no longer an admin` : row.created_by_name && `by ${row.created_by_name}`; const details = [ `${row.prefix}…`, - row.created_by_name && `by ${row.created_by_name}`, + creator, row.last_used_at ? `Used ${relativeTime(row.last_used_at)}` : ended ? "Never used" : "Not used yet", ended ? null : daysLeft === 1 ? "1 day left" : `${daysLeft} days left`, ].filter((d): d is string => !!d); @@ -236,7 +239,7 @@ function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now:
{details.map((d, i) => ( - {d} + {d} ))}
From cd78659706c3d55762e40bf51dbae1e38012d500 Mon Sep 17 00:00:00 2001 From: Tushar Tripathi Date: Mon, 23 Nov 2026 17:31:13 +0530 Subject: [PATCH 3/3] fix(teams): tighten the minter flag after review The flag reads "no longer a team admin" as its own item, so it wraps instead of being cut off at phone width, and only an explicit false from the server sets it, so a row cached before the field existed is not flagged. The list looks up the minters of live keys only, which the live-key cap bounds. The audit test checks actor_user_id and actor_key_id separately. Codecast-Session: https://codecast.sh/conversation/jx79zb6wppynmd2h8ryahc3vrh8jswyy --- packages/convex/convex/teamReadKeys.test.ts | 8 ++++++-- packages/convex/convex/teamReadKeys.ts | 19 +++++++++++++------ .../web/components/settings/TeamReadKeys.tsx | 14 +++++++++----- 3 files changed, 28 insertions(+), 13 deletions(-) diff --git a/packages/convex/convex/teamReadKeys.test.ts b/packages/convex/convex/teamReadKeys.test.ts index 7c66249996..fe57fe76b1 100644 --- a/packages/convex/convex/teamReadKeys.test.ts +++ b/packages/convex/convex/teamReadKeys.test.ts @@ -257,7 +257,7 @@ describe("team read keys", () => { await setRole(ada, vi, "admin"); await setRole(ada, mo, "admin"); await mint(as(ada), team, "by ada"); - await mint(as(vi), team, "by vi"); + const byVi = await mint(as(vi), team, "by vi"); const flags = async () => Object.fromEntries((await as(mo).query(api.teamReadKeys.list, { team_id: team }))!.map((k) => [k.name, k.created_by_still_admin])); expect(await flags()).toEqual({ "by ada": true, "by vi": true }); @@ -265,6 +265,9 @@ describe("team read keys", () => { expect(await flags()).toEqual({ "by ada": false, "by vi": true }); await as(vi).mutation(api.teams.removeFromTeam, { team_id: team, user_id: vi }); expect(await flags()).toEqual({ "by ada": false, "by vi": false }); + // An ended key's minter is not looked up. + await as(mo).mutation(api.teamReadKeys.revoke, { team_id: team, key_id: byVi.key_id }); + expect(await flags()).toEqual({ "by ada": false, "by vi": null }); }); test(`a team holds at most ${MAX_LIVE_TEAM_READ_KEYS} live keys; a revoked one frees a place`, async () => { @@ -293,7 +296,8 @@ describe("team read keys", () => { "team_read_key_revoked", ]); // A person mints and revokes; the key itself is the actor of its use. - expect(events.map((e: any) => e.actor_key_id ?? e.actor_user_id)).toEqual([ada, key_id, key_id, ada]); + expect(events.map((e: any) => e.actor_user_id)).toEqual([ada, undefined, undefined, ada]); + expect(events.map((e: any) => e.actor_key_id)).toEqual([undefined, key_id, key_id, undefined]); for (const e of events) { expect(e.detail.after).toMatchObject({ key_id, name: "eng site" }); expect(JSON.stringify(e)).not.toContain(key); diff --git a/packages/convex/convex/teamReadKeys.ts b/packages/convex/convex/teamReadKeys.ts index 1697f6224b..3981fe3b12 100644 --- a/packages/convex/convex/teamReadKeys.ts +++ b/packages/convex/convex/teamReadKeys.ts @@ -74,10 +74,16 @@ export const list = query({ if (!userId) return null; if (!(await isAdmin(ctx, userId, args.team_id))) return null; const keys = await keysOf(ctx, args.team_id); - // A key outlives its minter's admin role, so the list says which minters are no longer admins. - const creators = new Map(); - for (const id of new Set(keys.map((k) => k.created_by))) { - creators.set(String(id), { name: (await ctx.db.get(id))?.name ?? null, admin: await isAdmin(ctx, id, args.team_id) }); + const creators = new Map(); + for (const id of new Set(keys.map((k) => String(k.created_by)))) { + creators.set(id, (await ctx.db.get(id as Id<"users">))?.name ?? null); + } + // A key outlives its minter's admin role, so the list says which live keys' + // minters are no longer team admins. The live-key cap bounds these reads. + const now = Date.now(); + const stillAdmin = new Map(); + for (const id of new Set(keys.filter((k) => isLive(k, now)).map((k) => k.created_by))) { + stillAdmin.set(String(id), await isAdmin(ctx, id, args.team_id)); } return keys .sort((a, b) => b.created_at - a.created_at) @@ -86,8 +92,9 @@ export const list = query({ name: k.name, prefix: k.prefix, created_at: k.created_at, - created_by_name: creators.get(String(k.created_by))?.name ?? null, - created_by_still_admin: creators.get(String(k.created_by))?.admin ?? false, + created_by_name: creators.get(String(k.created_by)) ?? null, + /** Null for an ended key, whose minter is not looked up. */ + created_by_still_admin: stillAdmin.get(String(k.created_by)) ?? null, expires_at: k.expires_at, revoked_at: k.revoked_at ?? null, last_used_at: k.last_used_at ?? null, diff --git a/packages/web/components/settings/TeamReadKeys.tsx b/packages/web/components/settings/TeamReadKeys.tsx index df0f3b1dd1..3396174835 100644 --- a/packages/web/components/settings/TeamReadKeys.tsx +++ b/packages/web/components/settings/TeamReadKeys.tsx @@ -217,15 +217,19 @@ function MintedKey({ minted, onDone }: { minted: Minted; onDone: (fromKeyboard: ); } +const ORPHANED = "no longer a team admin"; + function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now: number }) { const ended = row.revoked_at ? "Revoked" : row.expires_at <= now ? "Expired" : null; const daysLeft = Math.ceil((row.expires_at - now) / DAY_MS); - // A live key whose minter left the team or lost the admin role: the remaining admins decide whether to revoke it. - const orphaned = !ended && !row.created_by_still_admin; - const creator = orphaned ? `by ${row.created_by_name ?? "someone"}, no longer an admin` : row.created_by_name && `by ${row.created_by_name}`; + // A live key whose minter left the team or lost the admin role: the remaining + // admins decide whether to revoke it. A row cached before the server sent the + // field has no value, which is not a flag. + const orphaned = !ended && row.created_by_still_admin === false; const details = [ `${row.prefix}…`, - creator, + orphaned ? `by ${row.created_by_name ?? "someone"}` : row.created_by_name && `by ${row.created_by_name}`, + orphaned && ORPHANED, row.last_used_at ? `Used ${relativeTime(row.last_used_at)}` : ended ? "Never used" : "Not used yet", ended ? null : daysLeft === 1 ? "1 day left" : `${daysLeft} days left`, ].filter((d): d is string => !!d); @@ -239,7 +243,7 @@ function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now:
{details.map((d, i) => ( - {d} + {d} ))}