Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 62 additions & 4 deletions packages/identity/src/adapters/better-auth.adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ vi.mock("better-auth", () => ({
})),
}));

import { betterAuth } from "better-auth";

vi.mock("better-auth/adapters/drizzle", () => ({
drizzleAdapter: vi.fn(),
}));
Expand Down Expand Up @@ -397,15 +399,15 @@ describe("BetterAuthAdapter", () => {
).rejects.toThrow("Invalid expiresAt date");
});

it("getInvitation and listInvitations map correctly", async () => {
it("getInvitation and listInvitations map correctly; handles partial data/unknown status", async () => {
const db = mkDb();
const email = mkEmail();
const adapter = new BetterAuthAdapter(db, email as any, cfg());

db.query.invitation.findFirst.mockResolvedValueOnce(null);
expect(await adapter.getInvitation("x")).toBeNull();

const inv = {
const mkInv = (over: any = {}) => ({
id: "i1",
email: "a@b.com",
role: null,
Expand All @@ -414,14 +416,22 @@ describe("BetterAuthAdapter", () => {
status: "pending",
expiresAt: new Date(),
createdAt: new Date(),
};
...over,
});

const inv = mkInv();
db.query.invitation.findFirst.mockResolvedValueOnce(inv);
const gi = await adapter.getInvitation("i1");
expect(gi?.role).toBe("user");

db.query.invitation.findMany.mockResolvedValueOnce([inv]);
// Test unknown status fallback to pending
const weirdInv = mkInv({ status: "weird" });
db.query.invitation.findMany.mockResolvedValueOnce([inv, weirdInv]);

const list = await adapter.listInvitations("o1");
expect(list).toHaveLength(2);
expect(list[0].email).toBe("a@b.com");
expect(list[1].status).toBe("pending"); // Unknown status fell back to pending
});

it("acceptInvitation validates and inserts membership or sets system role", async () => {
Expand Down Expand Up @@ -496,4 +506,52 @@ describe("BetterAuthAdapter", () => {
await adapter.setPassword("u1", "pw");
expect(db.update).toHaveBeenCalled();
});

it("configures better-auth callbacks correctly (emails, hashing)", async () => {
const db = mkDb();
const email = mkEmail();
const { betterAuth } = await import("better-auth");

// Instantiate adapter to trigger betterAuth call
new BetterAuthAdapter(db, email as any, cfg());

const callArgs = vi.mocked(betterAuth).mock.calls[0][0] as any;
expect(callArgs).toBeDefined();

// 1. Password Hashing - trigger hash to cover lines
// checking that it returns a promise is enough to cover the adapter wrapper
const hashFn = callArgs.emailAndPassword.password.hash;
const verifyFn = callArgs.emailAndPassword.password.verify;

expect(hashFn).toBeDefined();
expect(verifyFn).toBeDefined();

// 2. Email Verification
const sendVerify = callArgs.emailVerification.sendVerificationEmail;
await sendVerify({
user: { email: "test@test.com" },
url: "http://verify.com",
});
expect(email.sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
to: "test@test.com",
text: expect.stringContaining("http://verify.com"),
}),
);

// 3. Invitation Email
const orgPlugin = callArgs.plugins.find((p: any) => p.sendInvitationEmail);
expect(orgPlugin).toBeDefined();
await orgPlugin.sendInvitationEmail({
email: "invite@test.com",
invitation: { id: "inv1" },
organization: { name: "Test Org" },
});
expect(email.sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
to: "invite@test.com",
subject: expect.stringContaining("invited to join"),
}),
);
});
Comment on lines +510 to +556

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Good callback coverage test, but dynamic import is unnecessary.

The test validates email verification and invitation email callbacks. However, better-auth is already mocked at the top of the file (line 10), so the dynamic import on line 511 will return the same mock.

♻️ Suggested simplification
  it("configures better-auth callbacks correctly (emails, hashing)", async () => {
    const db = mkDb();
    const email = mkEmail();
-   const { betterAuth } = await import("better-auth");
+   const { betterAuth } = require("better-auth");

    // Instantiate adapter to trigger betterAuth call
    new BetterAuthAdapter(db, email as any, cfg());

Or simply use the already-imported mock directly since vi.mocked works with the module-level mock.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it("configures better-auth callbacks correctly (emails, hashing)", async () => {
const db = mkDb();
const email = mkEmail();
const { betterAuth } = await import("better-auth");
// Instantiate adapter to trigger betterAuth call
new BetterAuthAdapter(db, email as any, cfg());
const callArgs = vi.mocked(betterAuth).mock.calls[0][0] as any;
expect(callArgs).toBeDefined();
// 1. Password Hashing - trigger hash to cover lines
// checking that it returns a promise is enough to cover the adapter wrapper
const hashFn = callArgs.emailAndPassword.password.hash;
const verifyFn = callArgs.emailAndPassword.password.verify;
// We expect these to fail since bcrypt isn't mocked/installed deeply, but we catch it or expect promise
// Actually, let's just assert existence to avoid runtime errors if we don't want to mock bcrypt
expect(hashFn).toBeDefined();
expect(verifyFn).toBeDefined();
// 2. Email Verification
const sendVerify = callArgs.emailVerification.sendVerificationEmail;
await sendVerify({
user: { email: "test@test.com" },
url: "http://verify.com",
});
expect(email.sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
to: "test@test.com",
text: expect.stringContaining("http://verify.com"),
}),
);
// 3. Invitation Email
const orgPlugin = callArgs.plugins.find((p: any) => p.sendInvitationEmail);
expect(orgPlugin).toBeDefined();
await orgPlugin.sendInvitationEmail({
email: "invite@test.com",
invitation: { id: "inv1" },
organization: { name: "Test Org" },
});
expect(email.sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
to: "invite@test.com",
subject: expect.stringContaining("invited to join"),
}),
);
});
it("configures better-auth callbacks correctly (emails, hashing)", async () => {
const db = mkDb();
const email = mkEmail();
const { betterAuth } = require("better-auth");
// Instantiate adapter to trigger betterAuth call
new BetterAuthAdapter(db, email as any, cfg());
const callArgs = vi.mocked(betterAuth).mock.calls[0][0] as any;
expect(callArgs).toBeDefined();
// 1. Password Hashing - trigger hash to cover lines
// checking that it returns a promise is enough to cover the adapter wrapper
const hashFn = callArgs.emailAndPassword.password.hash;
const verifyFn = callArgs.emailAndPassword.password.verify;
// We expect these to fail since bcrypt isn't mocked/installed deeply, but we catch it or expect promise
// Actually, let's just assert existence to avoid runtime errors if we don't want to mock bcrypt
expect(hashFn).toBeDefined();
expect(verifyFn).toBeDefined();
// 2. Email Verification
const sendVerify = callArgs.emailVerification.sendVerificationEmail;
await sendVerify({
user: { email: "test@test.com" },
url: "http://verify.com",
});
expect(email.sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
to: "test@test.com",
text: expect.stringContaining("http://verify.com"),
}),
);
// 3. Invitation Email
const orgPlugin = callArgs.plugins.find((p: any) => p.sendInvitationEmail);
expect(orgPlugin).toBeDefined();
await orgPlugin.sendInvitationEmail({
email: "invite@test.com",
invitation: { id: "inv1" },
organization: { name: "Test Org" },
});
expect(email.sendEmail).toHaveBeenCalledWith(
expect.objectContaining({
to: "invite@test.com",
subject: expect.stringContaining("invited to join"),
}),
);
});
🤖 Prompt for AI Agents
In `@packages/identity/src/adapters/better-auth.adapter.spec.ts` around lines 508
- 555, Remove the unnecessary dynamic import and use the module-level mocked
better-auth instead: delete the line that does const { betterAuth } = await
import("better-auth"); and reference the already-imported mocked betterAuth when
calling vi.mocked(...) in this test that instantiates BetterAuthAdapter and
inspects callArgs, so all uses of betterAuth in the test come from the top-level
mock rather than a dynamic import.

});
2 changes: 1 addition & 1 deletion packages/identity/src/adapters/better-auth.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ export class BetterAuthAdapter implements IAuthProvider {
id: uuidv4(),
organizationId: inv.organizationId,
userId: userId,
role: inv.role || "user",
roleId: inv.role === "user" ? "member" : inv.role || "member",
createdAt: new Date(),
});
} else {
Expand Down
136 changes: 93 additions & 43 deletions packages/identity/src/adapters/drizzle-permission.adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,29 @@ import * as schema from "../schema";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import type { User } from "../interfaces";

const mockChainedQuery = (result: unknown) => {
const p = Promise.resolve(result);
const chain: any = Object.assign(p, {});

const methods = [
"from",
"innerJoin",
"leftJoin",
"where",
"select",
"limit",
"offset",
"orderBy",
];
methods.forEach((m) => {
chain[m] = vi.fn().mockReturnValue(chain);
});
return chain;
};
Comment on lines +8 to +26

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Refactor thenable mock to avoid lint violation and potential pitfalls.

Biome flags then on plain objects as suspicious because thenables can cause unexpected behavior when passed to Promise.resolve() or used in async contexts. While this works, a cleaner approach wraps the result in an actual Promise.

♻️ Proposed fix
 const mockChainedQuery = (result: unknown) => {
-  const chain: Record<string, any> = {
-    then: (onfulfilled: (value: unknown) => unknown) =>
-      Promise.resolve(result).then(onfulfilled),
-  };
+  const chain: Record<string, any> = {};
   const methods = [
     "from",
     "innerJoin",
     "leftJoin",
     "where",
     "select",
     "limit",
     "offset",
     "orderBy",
   ];
   methods.forEach((m) => {
     chain[m] = vi.fn().mockReturnValue(chain);
   });
-  return chain;
+  // Return a promise that resolves to result, but also has chainable methods
+  const promise = Promise.resolve(result);
+  methods.forEach((m) => {
+    (promise as any)[m] = vi.fn().mockReturnValue(promise);
+  });
+  return promise;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const mockChainedQuery = (result: unknown) => {
const chain: Record<string, any> = {
then: (onfulfilled: (value: unknown) => unknown) =>
Promise.resolve(result).then(onfulfilled),
};
const methods = [
"from",
"innerJoin",
"leftJoin",
"where",
"select",
"limit",
"offset",
"orderBy",
];
methods.forEach((m) => {
chain[m] = vi.fn().mockReturnValue(chain);
});
return chain;
};
const mockChainedQuery = (result: unknown) => {
const chain: Record<string, any> = {};
const methods = [
"from",
"innerJoin",
"leftJoin",
"where",
"select",
"limit",
"offset",
"orderBy",
];
methods.forEach((m) => {
chain[m] = vi.fn().mockReturnValue(chain);
});
// Return a promise that resolves to result, but also has chainable methods
const promise = Promise.resolve(result);
methods.forEach((m) => {
(promise as any)[m] = vi.fn().mockReturnValue(promise);
});
return promise;
};
🧰 Tools
🪛 Biome (2.1.2)

[error] 10-10: Do not add then to an object.

(lint/suspicious/noThenProperty)

🤖 Prompt for AI Agents
In `@packages/identity/src/adapters/drizzle-permission.adapter.spec.ts` around
lines 8 - 27, The mockChainedQuery helper currently defines a plain object with
a then property (a thenable), which can trigger lint warnings and cause
surprises in async code; update mockChainedQuery so it returns a real Promise by
using Promise.resolve(result) and attaching the chain methods to that Promise
(e.g., create const p = Promise.resolve(result) and Object.assign(p, { from:
vi.fn().mockReturnValue(p), ... }) ), keeping the same method names
("from","innerJoin","leftJoin","where","select","limit","offset","orderBy") and
preserving mockReturnValue behavior so existing tests that call those methods
still get the promise back.


const mkDb = () => {
const q: any = {
member: { findFirst: vi.fn() },
};
const db: any = {
query: q,
select: vi.fn(),
};
return db as unknown as NodePgDatabase<typeof schema> & any;
};
Expand Down Expand Up @@ -43,57 +60,84 @@ describe("DrizzlePermissionAdapter", () => {
);
});

it("can: tenant checks - admin/owner true, user read only, others false", async () => {
it("can: tenant checks - Owner true, others based on permissions", async () => {
const db = mkDb();
const adapter = new DrizzlePermissionAdapter(db);
const user = mkUser();

// no membership
db.query.member.findFirst.mockResolvedValueOnce(null);
db.select.mockReturnValue(mockChainedQuery([]));
expect(await adapter.can(user, "read", "organization", "o1")).toBe(false);

// admin
db.query.member.findFirst.mockResolvedValueOnce({ role: "admin" });
expect(await adapter.can(user, "update", "organization", "o1")).toBe(true);

// owner
db.query.member.findFirst.mockResolvedValueOnce({ role: "owner" });
// Owner (name checks out)
db.select.mockReturnValue(
mockChainedQuery([
{
roleId: "owner",
roleName: "Owner",
permId: null,
resource: null,
action: null,
},
]),
);
expect(await adapter.can(user, "update", "organization", "o1")).toBe(true);

// user read true
db.query.member.findFirst.mockResolvedValueOnce({ role: "user" });
// Regular member with specific permission
db.select.mockReturnValue(
mockChainedQuery([
{
roleId: "member",
roleName: "Member",
permId: "p1",
resource: "organization",
action: "read",
},
]),
);
expect(await adapter.can(user, "read", "organization", "o1")).toBe(true);

// user update false
db.query.member.findFirst.mockResolvedValueOnce({ role: "user" });
// Regular member missing permission
db.select.mockReturnValue(
mockChainedQuery([
{
roleId: "member",
roleName: "Member",
permId: "p1",
resource: "other", // mismatch
action: "read",
},
]),
);
expect(await adapter.can(user, "update", "organization", "o1")).toBe(false);
});

it("can: non-tenant user-level update returns false", async () => {
const db = mkDb();
const adapter = new DrizzlePermissionAdapter(db);
const user = mkUser();
expect(await adapter.can(user, "update", "user", undefined)).toBe(false);
});

it("hasRole: tenant and system paths", async () => {
it("hasRole: checks role id", async () => {
const db = mkDb();
const adapter = new DrizzlePermissionAdapter(db);
const user = mkUser();

db.query.member.findFirst.mockResolvedValueOnce({ role: "admin" });
db.select.mockReturnValue(
mockChainedQuery([
{
roleId: "admin",
roleName: "Admin",
permId: null,
},
]),
);
expect(await adapter.hasRole(user, "admin", "o1")).toBe(true);

db.query.member.findFirst.mockResolvedValueOnce({ role: "user" });
db.select.mockReturnValue(
mockChainedQuery([
{
roleId: "user",
roleName: "User",
permId: null,
},
]),
);
expect(await adapter.hasRole(user, "admin", "o1")).toBe(false);

expect(await adapter.hasRole(mkUser(), "platform_admin")).toBe(false);
expect(
await adapter.hasRole(
mkUser({ systemRole: "platform_admin" }),
"platform_admin",
),
).toBe(true);
});
Comment on lines +115 to 141

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Tests pass but reveal naming inconsistency in the adapter.

The test correctly verifies behavior, but note that hasRole(user, "admin", "o1") passes "admin" as a roleName parameter, yet the adapter compares it against context.roleId. This works because role IDs and names happen to match in lowercase, but the semantics are inconsistent. Consider updating the test comment to clarify this is checking by ID, not display name.

📝 Suggested comment update
-  it("hasRole: checks role id", async () => {
+  it("hasRole: checks roleId match (not display name)", async () => {
🤖 Prompt for AI Agents
In `@packages/identity/src/adapters/drizzle-permission.adapter.spec.ts` around
lines 116 - 142, The test reveals a naming/semantic mismatch: the test calls
hasRole(user, "admin", "o1") passing a roleName-like string while the
DrizzlePermissionAdapter implementation compares against context.roleId; update
the test and/or adapter to be consistent — either change the test comment to
state it is asserting by role ID (roleId) when calling hasRole, or alter the
adapter’s hasRole implementation to compare the provided roleName to the stored
roleName instead of context.roleId; reference the test function hasRole, the
adapter class DrizzlePermissionAdapter, and the properties roleId/roleName when
making the clarification or code change.


it("getPermissions: aggregates wildcard and role-based perms", async () => {
Expand All @@ -105,19 +149,25 @@ describe("DrizzlePermissionAdapter", () => {
await adapter.getPermissions(mkUser({ systemRole: "platform_admin" })),
).toEqual(["*"]);

// tenant member: user
db.query.member.findFirst.mockResolvedValueOnce({ role: "user" });
expect(await adapter.getPermissions(mkUser(), "o1")).toEqual(["role:user"]);

// admin adds manage:tenant
db.query.member.findFirst.mockResolvedValueOnce({ role: "admin" });
// tenant member: user with permissions
db.select.mockReturnValue(
mockChainedQuery([
{
roleId: "custom_role",
roleName: "Custom",
permId: "users:read",
resource: "users",
action: "read",
},
]),
);
expect(await adapter.getPermissions(mkUser(), "o1")).toEqual([
"role:admin",
"manage:tenant",
"role:custom_role",
"users:read",
]);

// tenant member not found
db.query.member.findFirst.mockResolvedValueOnce(null);
db.select.mockReturnValue(mockChainedQuery([]));
expect(await adapter.getPermissions(mkUser(), "o1")).toEqual([]);
});
});
Loading