Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

7.3 KB
Raw Blame
import { describe, it, expect, vi } from "vitest";

vi.mock("../../src/logger", () => ({
  createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));

import * as channelQueries from "../../src/db/queries/community/channel";
import { canSeePrivateChannel } from "../../src/utils/community-roles";

function channelRow(over: Record<string, unknown> = {}) {
  return {
    id: "c1",
    serverId: "s1",
    categoryId: null,
    name: "chan",
    type: "text",
    topic: "",
    position: 0,
    parentChannelId: null,
    creatorId: "creator",
    messageCount: 0,
    archived: 0,
    parentMessageId: null,
    lastMessageAt: null,
    createdAt: "2026-01-01T00:00:00.000Z",
    ...over,
  };
}

/**
 * Sequenced select mock: `queue` holds the resolved rows for each select() in
 * call order. getChannelForMember now issues: (1) a leading `type='dm'` probe
 * (empty for a non-DM channel, which lets the original flow run) → (2)
 * channel+member join → (3) anchor + category-private join → (4, optional)
 * isChannelMember lookup.
 */
function makeSeqDb(queue: any[][]) {
  let i = 0;
  const db: any = {
    select: vi.fn(() => {
      const rows = queue[i++] ?? [];
      const chain: any = {};
      chain.from = vi.fn(() => chain);
      chain.innerJoin = vi.fn(() => chain);
      chain.leftJoin = vi.fn(() => chain);
      chain.where = vi.fn(() => Object.assign(Promise.resolve(rows), chain));
      chain.limit = vi.fn(() => Promise.resolve(rows));
      chain.orderBy = vi.fn(() => Promise.resolve(rows));
      return chain;
    }),
  };
  return db;
}

describe("canSeePrivateChannel — shared rule", () => {
  it("admin/owner does NOT see it without membership (no content privilege)", () => {
    expect(canSeePrivateChannel({ role: "admin", isCreator: false, isChannelMember: false })).toBe(false)
    expect(canSeePrivateChannel({ role: "owner", isCreator: false, isChannelMember: false })).toBe(false)
  })
  it("admin who is also a member/creator sees it (via those, not role)", () => {
    expect(canSeePrivateChannel({ role: "admin", isCreator: false, isChannelMember: true })).toBe(true)
    expect(canSeePrivateChannel({ role: "admin", isCreator: true, isChannelMember: false })).toBe(true)
  })
  it("creator sees it", () => {
    expect(canSeePrivateChannel({ role: "member", isCreator: true, isChannelMember: false })).toBe(true)
  })
  it("added member sees it", () => {
    expect(canSeePrivateChannel({ role: "member", isCreator: false, isChannelMember: true })).toBe(true)
  })
  it("unrelated member cannot", () => {
    expect(canSeePrivateChannel({ role: "member", isCreator: false, isChannelMember: false })).toBe(false)
  })
})

describe("deleteChannelMemberAndChildParticipants", () => {
  it("batches access removal with child notify cleanup", async () => {
    const handoffStatement: any = {};
    handoffStatement.set = vi.fn(() => handoffStatement);
    handoffStatement.where = vi.fn(() => handoffStatement);
    handoffStatement.returning = vi.fn(() => handoffStatement);
    const accessStatement: any = {};
    accessStatement.where = vi.fn(() => accessStatement);
    accessStatement.returning = vi.fn(() => accessStatement);
    const notifyStatement: any = {};
    notifyStatement.where = vi.fn(() => notifyStatement);
    const selectStatement: any = {};
    selectStatement.from = vi.fn(() => selectStatement);
    selectStatement.where = vi.fn(() => selectStatement);
    const db: any = {
      update: vi.fn(() => handoffStatement),
      delete: vi
        .fn()
        .mockReturnValueOnce(accessStatement)
        .mockReturnValueOnce(notifyStatement),
      select: vi.fn(() => selectStatement),
      batch: vi.fn().mockResolvedValue([[], [{ id: "cm1" }], { rowsAffected: 3 }]),
    };

    await expect(channelQueries.deleteChannelMemberAndChildParticipants(
      db,
      "c1",
      "u2",
    )).resolves.toEqual({ id: "cm1" });

    expect(db.batch).toHaveBeenCalledWith([
      handoffStatement,
      accessStatement,
      notifyStatement,
    ]);
  });
});

describe("getChannelForMember — private visibility", () => {
  // Every queue leads with `[]` — the new `type='dm'` probe returns no row for
  // a non-DM channel, then the original server-member → private-category flow
  // runs exactly as before.
  it("non-server-member → null (empty join)", async () => {
    const db = makeSeqDb([[], []]);
    expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();
  });

  it("public channel → returns the channel for any member", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow({ categoryId: null }), memberRole: "member" }],
      [{ creatorId: "creator", categoryPrivate: 0 }],
    ]);
    const res = await channelQueries.getChannelForMember(db, "c1", "u1");
    expect(res?.id).toBe("c1");
  });

  it("private channel + non-member, non-creator, non-admin → null", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow({ categoryId: "cat1" }), memberRole: "member" }],
      [{ creatorId: "creator", categoryPrivate: 1 }],
      [], // isChannelMember → no row
    ]);
    expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();
  });

  it("private channel + admin, NOT a member/creator → null (no content privilege)", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],
      [{ creatorId: "creator", categoryPrivate: 1 }],
      [], // isChannelMember → no row; admin role no longer short-circuits
    ]);
    expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();
  });

  it("private channel + admin who IS an added member → returns the channel", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],
      [{ creatorId: "creator", categoryPrivate: 1 }],
      [{ id: "cm1" }], // isChannelMember → row present
    ]);
    const res = await channelQueries.getChannelForMember(db, "c1", "u1");
    expect(res?.id).toBe("c1");
  });

  it("private channel + creator → returns the channel", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow({ categoryId: "cat1", creatorId: "u1" }), memberRole: "member" }],
      [{ creatorId: "u1", categoryPrivate: 1 }],
    ]);
    const res = await channelQueries.getChannelForMember(db, "c1", "u1");
    expect(res?.id).toBe("c1");
  });

  it("private channel + added member → returns the channel", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow({ categoryId: "cat1" }), memberRole: "member" }],
      [{ creatorId: "creator", categoryPrivate: 1 }],
      [{ id: "cm1" }], // isChannelMember → row present
    ]);
    const res = await channelQueries.getChannelForMember(db, "c1", "u1");
    expect(res?.id).toBe("c1");
  });

  it("strips the joined memberRole from the returned row", async () => {
    const db = makeSeqDb([
      [], // dm probe → not a DM
      [{ ...channelRow(), memberRole: "member" }],
      [{ creatorId: "creator", categoryPrivate: 0 }],
    ]);
    const res = await channelQueries.getChannelForMember(db, "c1", "u1");
    expect(res).not.toHaveProperty("memberRole");
  });
});