fix(M2-005,M2-006): enforce user ownership at repo level for conversations and agents (#293)
Some checks failed
ci/woodpecker/push/ci Pipeline failed
Some checks failed
ci/woodpecker/push/ci Pipeline failed
Co-authored-by: Jason Woltje <jason@diversecanvas.com> Co-committed-by: Jason Woltje <jason@diversecanvas.com>
This commit was merged in pull request #293.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { eq, or, type Db, agents } from '@mosaic/db';
|
||||
import { eq, and, or, type Db, agents } from '@mosaic/db';
|
||||
|
||||
export type Agent = typeof agents.$inferSelect;
|
||||
export type NewAgent = typeof agents.$inferInsert;
|
||||
@@ -27,6 +27,10 @@ export function createAgentsRepo(db: Db) {
|
||||
return db.select().from(agents).where(eq(agents.isSystem, true));
|
||||
},
|
||||
|
||||
/**
|
||||
* Return only agents the user may access: their own agents plus all system agents.
|
||||
* Never returns other users' private agents.
|
||||
*/
|
||||
async findAccessible(ownerId: string): Promise<Agent[]> {
|
||||
return db
|
||||
.select()
|
||||
@@ -39,17 +43,44 @@ export function createAgentsRepo(db: Db) {
|
||||
return rows[0]!;
|
||||
},
|
||||
|
||||
async update(id: string, data: Partial<NewAgent>): Promise<Agent | undefined> {
|
||||
/**
|
||||
* Update an agent.
|
||||
*
|
||||
* For user-owned agents pass `ownerId` — the WHERE clause will enforce ownership so that
|
||||
* one user cannot overwrite another user's agent. For system agents the caller must
|
||||
* omit `ownerId` (admin-only path) and the WHERE clause only matches on `id`.
|
||||
*
|
||||
* Returns undefined when no row was matched (not found or ownership mismatch).
|
||||
*/
|
||||
async update(
|
||||
id: string,
|
||||
data: Partial<NewAgent>,
|
||||
ownerId?: string,
|
||||
): Promise<Agent | undefined> {
|
||||
const condition =
|
||||
ownerId !== undefined
|
||||
? and(eq(agents.id, id), eq(agents.ownerId, ownerId))
|
||||
: eq(agents.id, id);
|
||||
|
||||
const rows = await db
|
||||
.update(agents)
|
||||
.set({ ...data, updatedAt: new Date() })
|
||||
.where(eq(agents.id, id))
|
||||
.where(condition)
|
||||
.returning();
|
||||
return rows[0];
|
||||
},
|
||||
|
||||
async remove(id: string): Promise<boolean> {
|
||||
const rows = await db.delete(agents).where(eq(agents.id, id)).returning();
|
||||
/**
|
||||
* Delete a user-owned agent, scoped to the given owner.
|
||||
* Will not match system agents even if the id is correct, because system agents have
|
||||
* `ownerId = null` which cannot equal a real user id.
|
||||
* Returns false when no row was matched (not found, wrong owner, or system agent).
|
||||
*/
|
||||
async remove(id: string, ownerId: string): Promise<boolean> {
|
||||
const rows = await db
|
||||
.delete(agents)
|
||||
.where(and(eq(agents.id, id), eq(agents.ownerId, ownerId)))
|
||||
.returning();
|
||||
return rows.length > 0;
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user