Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: invite members as viewers and resolve sessions through better-auth (#604)

Carl-Gerhard Lindesvärddda72e20d204
diff --git a/.env.example b/.env.example
index dd3d48ddd..f50a8486c 100644
--- a/.env.example
+++ b/.env.example
@@ -16,6 +16,10 @@ ENCRYPTION_KEY=""
# `bun run --filter @openpanel/db migrate:deploy`.
# AUTOMATIC_MIGRATIONS="true"
+# Signs the session cookie; changing it signs everyone out. Falls back to
+# COOKIE_SECRET when unset. Generate with: openssl rand -base64 32
+# AUTH_SECRET=""
+
# OBJECT-STORE EXPORT (S3/GCS) tuning — optional, sensible defaults shown.
# The flushExports cron job windows ClickHouse by inserted_at and uploads
# batched files. LAG keeps a safety gap behind now() for in-flight inserts;
diff --git a/apps/api/e2e/legacy-job-proof.ts b/apps/api/e2e/legacy-job-proof.ts
index 315a57d14..47c7d056d 100644
--- a/apps/api/e2e/legacy-job-proof.ts
+++ b/apps/api/e2e/legacy-job-proof.ts
@@ -284,6 +284,7 @@ async function main() {
});
const deps: AppDeps = {
+ auth: null,
db: undefined as unknown as AppDeps['db'],
prisma: undefined as unknown as AppDeps['prisma'],
ch: undefined as unknown as AppDeps['ch'],
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index 2d9f23505..751b81041 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -418,6 +418,8 @@ const rawSchema = z.object({
blankToUndefined,
z.string().optional().default('')
),
+ /** Signs better-auth's session cookie. Falls back to COOKIE_SECRET. */
+ AUTH_SECRET: optionalString,
/** Set on the demo deployment only. `validateSessionToken` short-circuits on
* it, and `enforceAccess` bans mutations for it. */
DEMO_USER_ID: optionalString,
@@ -848,6 +850,7 @@ function deriveCoreConfig(raw: RawEnv): CoreConfig {
raw.LOG_EXPORTER !== undefined,
},
auth: {
+ secret: raw.AUTH_SECRET ?? (raw.COOKIE_SECRET || undefined),
allowRegistration:
raw.ALLOW_REGISTRATION === undefined
? undefined
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index a9ba1f797..da1b9a4b2 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -17,6 +17,7 @@ import {
checkNotificationRulesForEvent,
cookieOptions,
corsDelegator,
+ createAuth,
createBuffers,
createClients,
createIncomingEventHandler,
@@ -186,6 +187,7 @@ function buildDeps(): AppDeps {
producers,
logger,
config: config.core,
+ auth: createAuth({ db, config: config.core, logger }),
};
}
diff --git a/apps/start/e2e/auth-session.spec.ts b/apps/start/e2e/auth-session.spec.ts
index 8d7197506..a6027aee3 100644
--- a/apps/start/e2e/auth-session.spec.ts
+++ b/apps/start/e2e/auth-session.spec.ts
@@ -16,6 +16,7 @@ test.use({ storageState: FRESH_CONTEXT });
test.describe.configure({ timeout: 90_000 });
const STALE_SESSION_TOKEN = 'stalestalestalestalestalestale12';
+const BETTER_AUTH_COOKIE = 'openpanel.session_token';
test('an invalid session cookie is treated as signed out, not as an error', async ({
page,
@@ -98,3 +99,41 @@ test('a password with a trailing space signs in after signing up with it', async
expect(cleanup.status()).toBe(200);
}
});
+
+// Sign-in still issues the legacy `session` cookie; the first request after it
+// hands out better-auth's, which must keep the user signed in on its own.
+test("a signed-in browser gets better-auth's cookie and stays signed in on it alone", async ({
+ page,
+ context,
+ seed,
+}) => {
+ await gotoHydrated(page, '/login');
+ const response = await submitSignIn(page, seed.user);
+ expect(response.status()).toBe(200);
+ await expect(page).toHaveURL(new RegExp(`/${seed.organizationId}$`), {
+ timeout: 15_000,
+ });
+
+ await expect
+ .poll(async () =>
+ (await context.cookies()).some(
+ (cookie) => cookie.name === BETTER_AUTH_COOKIE
+ )
+ )
+ .toBe(true);
+ const upgraded = (await context.cookies()).find(
+ (cookie) => cookie.name === BETTER_AUTH_COOKIE
+ );
+ expect(upgraded?.httpOnly).toBe(true);
+
+ await context.clearCookies({ name: 'session' });
+ await gotoHydrated(page, `/${seed.organizationId}`);
+ await expect(page).toHaveURL(new RegExp(`/${seed.organizationId}$`));
+ await expect(page.getByText('Acme Web').first()).toBeVisible();
+ await page.screenshot({ path: `${SHOTS_DIR}/session-better-auth-only.png` });
+
+ const session = await page.request.get(`${apiUrl()}/trpc/auth.session`);
+ const body = await session.json();
+ expect(body.result.data.json.user.email).toBe(seed.user.email);
+ expect(body.result.data.json.session.token).toBeUndefined();
+});
diff --git a/apps/start/e2e/org-members.spec.ts b/apps/start/e2e/org-members.spec.ts
index cbd076e5c..423620763 100644
--- a/apps/start/e2e/org-members.spec.ts
+++ b/apps/start/e2e/org-members.spec.ts
@@ -430,6 +430,88 @@ test.describe('an invited member', () => {
}
});
+ test('a viewer reads the selected projects and cannot change them', async ({
+ page,
+ seed,
+ browser,
+ }) => {
+ const email = uniqueEmail();
+ await gotoHydrated(page, `/${seed.organizationId}/members/invitations`);
+ const sheet = await openInviteSheet(page);
+ await sheet.getByLabel('Email').fill(email);
+ await sheet.getByRole('radio', { name: 'Viewer' }).click();
+ await pickProjects(page, sheet, ['Acme Shop']);
+ // A viewer reads every project in scope; there is no level to pick.
+ await expect(sheet.getByRole('combobox')).toHaveCount(0);
+ await expect(sheet.getByText('Read-only', { exact: true })).toBeVisible();
+ await shot(page, 'invite-sheet-viewer');
+ await sendInvite(sheet);
+ await expect(
+ sheet.getByRole('heading', { name: 'User has been invited' })
+ ).toBeVisible();
+ await sheet.getByRole('button', { name: 'Close' }).first().click();
+ await expect(
+ page.getByRole('row', { name: new RegExp(email) })
+ ).toContainText('viewer');
+ const invite = (await listInvites(page, seed.organizationId)).find(
+ (candidate) => candidate.email === email
+ );
+ if (!invite) {
+ throw new Error('Invite was not created');
+ }
+ expect(invite.role).toBe('viewer');
+
+ const { context, guest } = await signUpThroughInvite(
+ browser,
+ invite.id,
+ email
+ );
+ try {
+ const member = (await listMembers(page, seed.organizationId)).find(
+ (candidate) => candidate.email === email
+ );
+ expect(member?.role).toBe('viewer');
+ expect(member?.projectScope).toBe('selected');
+ expect(member?.projects.map((grant) => grant.projectId)).toEqual([
+ 'acme-shop',
+ ]);
+
+ await expect(guest.locator('.card')).toHaveCount(1);
+ await expect(
+ guest.locator('.card', { hasText: 'Acme Shop' })
+ ).toBeVisible();
+ await guest.screenshot({
+ path: 'test-results/org/shots/viewer-projects.png',
+ });
+ expect(
+ await guestStatus(guest, 'project.getProjectWithClients', {
+ projectId: 'acme-shop',
+ })
+ ).toBe(HTTP_OK);
+ const update = await trpcMutation(guest, 'project.update', {
+ id: 'acme-shop',
+ name: 'Acme Shop',
+ });
+ expect(update.status).toBe(HTTP_FORBIDDEN);
+ expect(update.error).toBe('You have read-only access to this project');
+ expect(
+ await guestStatus(guest, 'project.getProjectWithClients', {
+ projectId: 'acme-web',
+ })
+ ).toBe(HTTP_FORBIDDEN);
+
+ await gotoHydrated(page, `/${seed.organizationId}/members`);
+ await expect(
+ page.getByRole('row', { name: new RegExp(email) })
+ ).toContainText('viewer');
+ await shot(page, 'members-with-viewer');
+ } finally {
+ await gotoHydrated(page, `/${seed.organizationId}/members`);
+ await removeMember(page, email);
+ await context.close();
+ }
+ });
+
// Open defect: removeMember and updateMemberAccess do not clear the 5-minute
// access cache, so the removed user keeps reading project data.
test('loses access as soon as an admin removes them', async ({
diff --git a/apps/start/src/components/settings/project-access-grants.tsx b/apps/start/src/components/settings/project-access-grants.tsx
index 3e7ab8bc9..eb4d39f67 100644
--- a/apps/start/src/components/settings/project-access-grants.tsx
+++ b/apps/start/src/components/settings/project-access-grants.tsx
@@ -12,6 +12,8 @@ interface ProjectAccessGrantsProps {
value: IProjectAccessGrant[];
onChange: (value: IProjectAccessGrant[]) => void;
projects: { id: string; name: string }[];
+ /** A viewer reads every project in scope, so the per-project level is moot. */
+ isReadOnly?: boolean;
}
/**
@@ -22,6 +24,7 @@ export function ProjectAccessGrants({
value,
onChange,
projects,
+ isReadOnly = false,
}: ProjectAccessGrantsProps) {
const selectedIds = value.map((grant) => grant.projectId);
@@ -69,20 +72,29 @@ export function ProjectAccessGrants({
{projects.find((project) => project.id === grant.projectId)
?.name ?? grant.projectId}
</span>
- <Select
- onValueChange={(level) =>
- handleLevelChange(grant.projectId, level as 'read' | 'write')
- }
- value={grant.level}
- >
- <SelectTrigger className="w-36 shrink-0">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="write">Can edit</SelectItem>
- <SelectItem value="read">Read-only</SelectItem>
- </SelectContent>
- </Select>
+ {isReadOnly ? (
+ <span className="shrink-0 text-muted-foreground text-sm">
+ Read-only
+ </span>
+ ) : (
+ <Select
+ onValueChange={(level) =>
+ handleLevelChange(
+ grant.projectId,
+ level as 'read' | 'write'
+ )
+ }
+ value={grant.level}
+ >
+ <SelectTrigger className="w-36 shrink-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="write">Can edit</SelectItem>
+ <SelectItem value="read">Read-only</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
</div>
))}
</div>
diff --git a/apps/start/src/components/settings/project-scope-picker.tsx b/apps/start/src/components/settings/project-scope-picker.tsx
index 30c75a5d8..a42f4e51d 100644
--- a/apps/start/src/components/settings/project-scope-picker.tsx
+++ b/apps/start/src/components/settings/project-scope-picker.tsx
@@ -14,6 +14,7 @@ interface ProjectScopePickerProps {
onScopeChange: (projectScope: ProjectScope) => void;
onAccessChange: (access: IProjectAccessGrant[]) => void;
projects: { id: string; name: string }[];
+ isReadOnly?: boolean;
}
/**
@@ -26,6 +27,7 @@ export function ProjectScopePicker({
onScopeChange,
onAccessChange,
projects,
+ isReadOnly,
}: ProjectScopePickerProps) {
const allId = useId();
const selectedId = useId();
@@ -53,6 +55,7 @@ export function ProjectScopePicker({
{projectScope === 'selected' && (
<>
<ProjectAccessGrants
+ isReadOnly={isReadOnly}
onChange={onAccessChange}
projects={projects}
value={access}
diff --git a/apps/start/src/modals/create-invite.tsx b/apps/start/src/modals/create-invite.tsx
index 9eaa25353..602427c5c 100644
--- a/apps/start/src/modals/create-invite.tsx
+++ b/apps/start/src/modals/create-invite.tsx
@@ -46,6 +46,7 @@ export default function CreateInvite() {
},
});
const projectScope = watch('projectScope');
+ const isViewer = watch('role') === 'viewer';
const mutation = useMutation(
trpc.organization.inviteUser.mutationOptions({
@@ -138,6 +139,12 @@ export default function CreateInvite() {
Member
</Label>
</div>
+ <div className="flex items-center gap-2">
+ <RadioGroupItem id="viewer" value="viewer" />
+ <Label className="mb-0" htmlFor="viewer">
+ Viewer
+ </Label>
+ </div>
<div className="flex items-center gap-2">
<RadioGroupItem id="admin" value="admin" />
<Label className="mb-0" htmlFor="admin">
@@ -149,7 +156,7 @@ export default function CreateInvite() {
/>
<p className="mt-1 text-muted-foreground text-sm">
Admins manage members and projects. Members can edit the
- projects they have access to.
+ projects they have access to, viewers can only look at them.
</p>
</div>
<Controller
@@ -164,6 +171,7 @@ export default function CreateInvite() {
render={({ field: scopeField }) => (
<ProjectScopePicker
access={field.value}
+ isReadOnly={isViewer}
onAccessChange={field.onChange}
onScopeChange={scopeField.onChange}
projectScope={projectScope}
diff --git a/apps/start/src/modals/edit-member.tsx b/apps/start/src/modals/edit-member.tsx
index c703ed834..ebd364431 100644
--- a/apps/start/src/modals/edit-member.tsx
+++ b/apps/start/src/modals/edit-member.tsx
@@ -68,6 +68,7 @@ export default function EditMember(member: EditMemberProps) {
<div className="col gap-4">
<ProjectScopePicker
access={access}
+ isReadOnly={member.role === 'viewer'}
onAccessChange={setAccess}
onScopeChange={setProjectScope}
projectScope={projectScope}
diff --git a/bun.lock b/bun.lock
index 2deb77391..1b3f06d79 100644
--- a/bun.lock
+++ b/bun.lock
@@ -332,6 +332,7 @@
"@trpc/server": "11.6.0",
"ai": "7.0.144",
"arctic": "2.3.0",
+ "better-auth": "1.7.10",
"bullmq": "6.3.3",
"cheerio": "1.1.2",
"csv-parse": "6.1.0",
@@ -1092,6 +1093,24 @@
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@floating-ui/utils": "^0.2.12", "reselect": "^5.3.0", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A=="],
+ "@better-auth/core": ["@better-auth/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.41.1", "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.2", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.2", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-c5vxtnk7UxWe/iF/X5sKSgmPcN5n6biuwJBs2dMkceMwvMWBHLosue6h/vmvKns9SYKbkBNWsurFe7yIbv13dQ=="],
+
+ "@better-auth/drizzle-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.10", "@better-auth/utils": "^0.4.2 || ^0.5.0", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-Uc/Eh9cnvorIWA6J97Hv8zjR8sCVUP6G7M3xHJGTD9qJXC69zoY4ULmNGA73AmGJB1q+VEYs2cRMtJ6fR6HP6g=="],
+
+ "@better-auth/kysely-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.10", "@better-auth/utils": "^0.4.2 || ^0.5.0", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-ZWWc6h5lgcwQMTcqMLNWw+jTEMFfrqJHD+VamiCUdaAxZzVAkjLZzVA2r0vZ5w7xnTY9vWS7wuNVqAKNLRTlYQ=="],
+
+ "@better-auth/memory-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.10", "@better-auth/utils": "^0.4.2 || ^0.5.0" } }, "sha512-3Di7y8BK5I2pCdpRaJ2ggkVliO/Swr6a/J+y9RFdwkbxhEMU1o9WD9IwoG3LFH8dvFF3kVo+GilsZsVNlYD+sw=="],
+
+ "@better-auth/mongo-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.10", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-7z48PlXtlSKGvdOXfVmbjZE1vRmYyOQqHiPbeLpw+NvAPSTI9N4r7OO47u2MebA3q25e3GoGEwk5BAEE07u+PQ=="],
+
+ "@better-auth/prisma-adapter": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.10", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-hNlhn0Kcq/O76SehvqznFsjqfEMdM2m2ctazU/BLv+jT8+hGvvxCInXZi6x86/xpAyDTgU7t7KsK50r6mdNR1g=="],
+
+ "@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.10", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.2" } }, "sha512-1OamUtbGRaYHB0tRjKK3Jv6hzI6mZMv3pujkg8k7tr3idQuToMoVXsWAD9oFbUTmOLeix58n+grzsl7r0fR0Sw=="],
+
+ "@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="],
+
+ "@better-fetch/fetch": ["@better-fetch/[email protected]", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],
+
"@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.3.15", "@biomejs/cli-darwin-x64": "2.3.15", "@biomejs/cli-linux-arm64": "2.3.15", "@biomejs/cli-linux-arm64-musl": "2.3.15", "@biomejs/cli-linux-x64": "2.3.15", "@biomejs/cli-linux-x64-musl": "2.3.15", "@biomejs/cli-win32-arm64": "2.3.15", "@biomejs/cli-win32-x64": "2.3.15" }, "bin": { "biome": "bin/biome" } }, "sha512-u+jlPBAU2B45LDkjjNNYpc1PvqrM/co4loNommS9/sl9oSxsAQKsNZejYuUztvToB5oXi1tN/e62iNd6ESiY3g=="],
"@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-SDCdrJ4COim1r8SNHg19oqT50JfkI/xGZHSyC6mGzMfKrpNe/217Eq6y98XhNTc0vGWDjznSDNXdUc6Kg24jbw=="],
@@ -1198,8 +1217,6 @@
"@dxup/unimport": ["@dxup/[email protected]", "", {}, "sha512-/B8YJGPzaYq1NbsQmwgP8EZqg40NpTw4ZB3suuI0TplbxKHeK94jeaawLmVhCv+YwUnOpiWEz9U6SeThku/8JQ=="],
- "@ecies/ciphers": ["@ecies/[email protected]", "", { "peerDependencies": { "@noble/ciphers": "^1.0.0" } }, "sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g=="],
-
"@elysiajs/cors": ["@elysiajs/[email protected]", "", { "peerDependencies": { "elysia": ">= 1.4.0" } }, "sha512-FTCcbH35brTLigF1W7BYySRZomgI/dBEMK9BgK9RP9Nez7zmpGh4koL/Yr1BFv8nYz7CfhRvcM8d/c+XnwMaVQ=="],
"@elysiajs/openapi": ["@elysiajs/[email protected]", "", { "peerDependencies": { "elysia": ">= 1.4.0" } }, "sha512-HDtGIrWfFJk6UJS7qbgRmjifbSqnnRGDM3CsU/GVJkxLbEVEkNuQDf+Quh9fGbytSrJ8g4+tX9eVjshYhCH29w=="],
@@ -1532,11 +1549,11 @@
"@nivo/tooltip": ["@nivo/[email protected]", "", { "dependencies": { "@nivo/core": "0.99.0", "@nivo/theming": "0.99.0", "@react-spring/web": "9.4.5 || ^9.7.2 || ^10.0" }, "peerDependencies": { "react": "^16.14 || ^17.0 || ^18.0 || ^19.0" } }, "sha512-weoEGR3xAetV4k2P6k96cdamGzKQ5F2Pq+uyDaHr1P3HYArM879Pl+x+TkU0aWjP6wgUZPx/GOBiV1Hb1JxIqg=="],
- "@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="],
+ "@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw=="],
"@noble/curves": ["@noble/[email protected]", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw=="],
- "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
+ "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="],
"@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw=="],
@@ -3174,6 +3191,10 @@
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ=="],
+ "better-auth": ["[email protected]", "", { "dependencies": { "@better-auth/core": "1.7.10", "@better-auth/drizzle-adapter": "1.7.10", "@better-auth/kysely-adapter": "1.7.10", "@better-auth/memory-adapter": "1.7.10", "@better-auth/mongo-adapter": "1.7.10", "@better-auth/prisma-adapter": "1.7.10", "@better-auth/telemetry": "1.7.10", "@better-auth/utils": "0.5.0", "@better-fetch/fetch": "1.3.2", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.2", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0 || ^3.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-Paf0X8cHKQc8jCgM3vl4AoxRicWdNf0zw8Aggn1q6aNSWCDDxSZCb6rkXa/O9cPc8idjVPK0rV/eHPHAbs07ZA=="],
+
+ "better-call": ["[email protected]", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-lOmFCTG1KcE60YWxoff2Wx0Fv7v7drP/fQTDYnhJUCdkA7V6QWXdLPUiMpOQCq7Fd0Ts3AkrRwD23xoiootlGA=="],
+
"big-integer": ["[email protected]", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="],
"bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
@@ -4352,6 +4373,8 @@
"knitwork": ["[email protected]", "", {}, "sha512-4LqMNoONzR43B1W0ek0fhXMsDNW/zxa1NdFAVMY+k28pgZLovR4G3PB5MrpTxCy1QaZCqNoiaKPr5w5qZHfSNw=="],
+ "kysely": ["[email protected]", "", {}, "sha512-fmIq+7kv4WbFm2tcfznRzikqB4cuNpgZ40PSU2fAJ2/OO5XhojqnTPrmgrCjYSRJVwBln03XcRXJGnw9H099IQ=="],
+
"lan-network": ["[email protected]", "", { "bin": { "lan-network": "dist/lan-network-cli.js" } }, "sha512-ONPnazC96VKDntab9j9JKwIWhZ4ZUceB4A9Epu4Ssg0hYFmtHZSeQ+n15nIwTFmcBUKtExOer8WTJ4GF9MO64A=="],
"launch-editor": ["[email protected]", "", { "dependencies": { "picocolors": "^1.1.1", "shell-quote": "^1.8.4" } }, "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA=="],
@@ -4714,6 +4737,8 @@
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-c7+7RQ+dMB5dPwwCp4ee1/iV/q2P6aK1mTZcfr1BTuVlyW9hJYiMPybJCcnBlQtuSmTIWNeazm/zqNoZSSElBg=="],
+ "nanostores": ["[email protected]", "", {}, "sha512-FixtE239Gl6Gz0ZGCK0WzvNwObNCIwVT+L7zQcf1QgcA6AzBxblzqe9OT88qiucNkhsjSOqiogSaF5jVbJiqSA=="],
+
"nanotar": ["[email protected]", "", {}, "sha512-MUrzzDUcIOPbv7ubhDV/L4CIfVTATd9XhDE2ixFeCrM5yp9AlzUpn91JrnN0HD6hksdxvz9IW9aKANz0Bta0GA=="],
"negotiator": ["[email protected]", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="],
@@ -5280,7 +5305,7 @@
"rollup-plugin-visualizer": ["[email protected]", "", { "dependencies": { "open": "^8.0.0", "picomatch": "^4.0.2", "source-map": "^0.7.4", "yargs": "^17.5.1" }, "peerDependencies": { "rolldown": "1.x || ^1.0.0-beta", "rollup": "2.x || 3.x || 4.x" }, "optionalPeers": ["rolldown", "rollup"], "bin": { "rollup-plugin-visualizer": "dist/bin/cli.js" } }, "sha512-TBwVHVY7buHjIKVLqr9scTVFwqZqMXINcCphPwIWKPDCOBIa+jCQfafvbjRJDZgXdq/A996Dy6yGJ/+/NtAXDQ=="],
- "rou3": ["[email protected]", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="],
+ "rou3": ["[email protected]", "", {}, "sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ=="],
"rrdom": ["[email protected]", "", { "dependencies": { "rrweb-snapshot": "^2.1.1" } }, "sha512-VBkTF3bGNqcZjqnbo/gKi9GVQPIxiG0dofw7CQdAZQFQ2juJdt2YKIf3oS9QudL8HTpGh9bz5TUN+3amBn1Geg=="],
@@ -5354,7 +5379,7 @@
"set-blocking": ["[email protected]", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
- "set-cookie-parser": ["[email protected]", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],
+ "set-cookie-parser": ["[email protected]", "", {}, "sha512-Npd1Pt+4zb3BrSZDPd2qFwRpS6b1EUEasRrO8xS0zMJi0fApXXK5YuzP0minyJnxwnFHoVoJwA55q0A0cu63gQ=="],
"set-function-length": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="],
@@ -5996,6 +6021,10 @@
"@babel/traverse/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA=="],
+ "@better-auth/core/@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
+
+ "@better-auth/core/zod": ["[email protected]", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="],
+
"@cloudflare/vite-plugin/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="],
"@codemirror/language/@codemirror/state": ["@codemirror/[email protected]", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-QhQIVRY+xHZDxwOSFrJ1eUMapJBUID3IdeAjf7dHO7zBUzSkyooHiodnalz5MG3iHzwixKMlAAyn7244y537EA=="],
@@ -6168,6 +6197,8 @@
"@nivo/sankey/@types/d3-sankey": ["@types/[email protected]", "", { "dependencies": { "@types/d3-shape": "^1" } }, "sha512-U6SrTWUERSlOhnpSrgvMX64WblX1AxX6nEjI2t3mLK2USpQrnbwYYK+AS9SwiE7wgYmOsSSKoSdr8aoKBH0HgQ=="],
+ "@noble/curves/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
+
"@node-minify/core/glob": ["[email protected]", "", { "dependencies": { "fs.realpath": "^1.0.0", "minimatch": "^8.0.2", "minipass": "^4.2.4", "path-scurry": "^1.6.1" } }, "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q=="],
"@node-minify/core/mkdirp": ["[email protected]", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="],
@@ -6748,6 +6779,8 @@
"babel-plugin-syntax-hermes-parser/hermes-parser": ["[email protected]", "", { "dependencies": { "hermes-estree": "0.36.1" } }, "sha512-GApNk4zLHi2UWoWZZkx7LNCOSzLSc5lB55pZ/PhK7ycFeg7u5LcF88p/WbpIi1XUDtE0MpHE3uRR3u3KB7TjSQ=="],
+ "better-auth/zod": ["[email protected]", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="],
+
"bl/readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"body-parser/debug": ["[email protected]", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],
@@ -6824,6 +6857,12 @@
"duplexify/readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
+ "eciesjs/@ecies/ciphers": ["@ecies/[email protected]", "", { "peerDependencies": { "@noble/ciphers": "^1.0.0" } }, "sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g=="],
+
+ "eciesjs/@noble/ciphers": ["@noble/[email protected]", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="],
+
+ "eciesjs/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
+
"editorconfig/commander": ["[email protected]", "", {}, "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug=="],
"editorconfig/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
@@ -6920,6 +6959,8 @@
"h3-v2/cookie-es": ["[email protected]", "", {}, "sha512-aVf4A4hI2w70LnF7GG+7xDQUkliwiXWXFvTjkip4+b64ygDQ2sJPRSKFDHbxn8o0xu9QzPkMuuiWIXyFSE2slA=="],
+ "h3-v2/rou3": ["[email protected]", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="],
+
"h3-v2/srvx": ["[email protected]", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-hmcGW4CgroeSmzgF1Ihwgl+Ths0JqAJ7HwjP2X7e3JzY7u4IydLMcdnlqGQiQGUswz+PO9oh/KtCpOISIvs9QQ=="],
"hast-util-from-dom/hastscript": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w=="],
@@ -7250,6 +7291,8 @@
"react-redux/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
+ "react-router/set-cookie-parser": ["[email protected]", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],
+
"react-smooth/fast-equals": ["[email protected]", "", {}, "sha512-Ywe6jodPTWOTL9/k0bV7gdfP8twKL5Y8I8CZ933fAY5gBekICZSUQTbyH6ut2NZCNyB05mSUwAuEqdEIaOOlDQ=="],
"react-svg-worldmap/d3-geo": ["[email protected]", "", { "dependencies": { "d3-array": "^2.5.0" } }, "sha512-8pM1WGMLGFuhq9S+FpPURxic+gKzjluCD/CHTuUF3mXMeiCo0i6R0tO1s4+GArRFde96SLcW/kOFRjoAosPsFA=="],
diff --git a/packages/core/package.json b/packages/core/package.json
index 88ff3a01d..f86d10809 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -45,6 +45,7 @@
"@trpc/server": "11.6.0",
"ai": "7.0.144",
"arctic": "2.3.0",
+ "better-auth": "1.7.10",
"bullmq": "6.3.3",
"cheerio": "1.1.2",
"csv-parse": "6.1.0",
diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts
index 1967a91ba..2336e6368 100644
--- a/packages/core/src/config.ts
+++ b/packages/core/src/config.ts
@@ -25,6 +25,11 @@ export interface OAuthClientConfig {
}
export interface AuthConfig {
+ /**
+ * AUTH_SECRET, else COOKIE_SECRET. Signs better-auth's session cookie;
+ * changing it signs everyone out. Unset leaves only legacy sessions.
+ */
+ secret: string | undefined;
/**
* `undefined` means the variable is unset, which is what cloud runs and what
* makes registration unconditionally open — distinct from an explicit
diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.ts
index cb40b4622..fefbe2799 100644
--- a/packages/core/src/context.test.ts
+++ b/packages/core/src/context.test.ts
@@ -65,6 +65,7 @@ function stubDeps(): {
scopes,
scoped,
deps: {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index e7ed9b94b..d3f401e85 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -3,6 +3,7 @@ import { bindReadsToSignal } from './ch-abortable';
import type { CoreConfig } from './config';
import type { QueueProducerHandle, QueueProducers } from './jobs.registry';
import type { Logger } from './logger';
+import type { Auth } from './modules/auth/src/better-auth';
import type { SessionValidationResult } from './modules/auth/src/login-session';
import { createServices, type Services } from './services';
import type { CookieJar, CookieOptions } from './shared/cookie';
@@ -62,6 +63,8 @@ export interface AppDeps {
producers: QueueProducerHandle;
logger: Logger;
config: CoreConfig;
+ /** Null when no secret is configured; see `createAuth`. */
+ auth: Auth | null;
}
/** Work scope. One per HTTP request, RPC call, job run or Kafka batch. */
@@ -75,6 +78,7 @@ export interface Ctx {
logger: Logger;
queues: QueueProducers;
config: CoreConfig;
+ auth: Auth | null;
services: Services;
requestId: string;
}
@@ -119,6 +123,7 @@ export function createCtx(deps: AppDeps, scope: ScopeMeta): Ctx {
logger: scope.logger,
queues: deps.producers.scope({ requestId: scope.requestId }),
config: deps.config,
+ auth: deps.auth,
requestId: scope.requestId,
services: undefined as unknown as Services,
};
@@ -155,6 +160,7 @@ function installLazyServices(ctx: Ctx): void {
logger: ctx.logger,
queues: ctx.queues,
config: ctx.config,
+ auth: ctx.auth,
});
return built;
},
diff --git a/packages/core/src/http/context.ts b/packages/core/src/http/context.ts
index 9c50687b8..b6bc66cc3 100644
--- a/packages/core/src/http/context.ts
+++ b/packages/core/src/http/context.ts
@@ -59,7 +59,11 @@ export function requestContext(deps: AppDeps) {
ip: clientIp,
cookies,
session: () =>
- (session ??= resolveSession(ctx, cookies, request.headers)),
+ (session ??= resolveSession(ctx, {
+ cookies,
+ headers: request.headers,
+ setCookie: ctx.setCookie,
+ })),
setCookie: (name: string, value: string, options?: CookieOptions) =>
writeCookie(cookie, name, value, options),
cancellation,
diff --git a/packages/core/src/http/session.test.ts b/packages/core/src/http/session.test.ts
index 82c33ed64..86c12adc7 100644
--- a/packages/core/src/http/session.test.ts
+++ b/packages/core/src/http/session.test.ts
@@ -1,6 +1,11 @@
import { expect, test } from 'bun:test';
+import { testCoreConfig } from '../../test/config-fixture';
import { stubAppDeps } from '../../test/http-fixtures';
import { type AppDeps, createCtx } from '../context';
+import {
+ AUTH_SESSION_COOKIE,
+ type Auth,
+} from '../modules/auth/src/better-auth';
import { hashSessionToken } from '../modules/auth/src/token';
import { resolveSession } from './session';
@@ -16,11 +21,18 @@ function cookieJar(token: string | undefined) {
return { get: (name: string) => (name === 'session' ? token : undefined) };
}
+function request(cookies: ReturnType<typeof cookieJar>, headers: Headers) {
+ return { cookies, headers, setCookie: () => undefined };
+}
+
test('a cookie that matches no session resolves to nobody signed in', async () => {
const ctx = ctxWithSessionLookup(() => Promise.resolve(null));
expect(
- await resolveSession(ctx, cookieJar('not-a-real-token'), NO_HEADERS)
+ await resolveSession(
+ ctx,
+ request(cookieJar('not-a-real-token'), NO_HEADERS)
+ )
).toBeNull();
});
@@ -30,7 +42,7 @@ test('no cookie resolves to nobody signed in without touching the database', asy
);
expect(
- await resolveSession(ctx, cookieJar(undefined), NO_HEADERS)
+ await resolveSession(ctx, request(cookieJar(undefined), NO_HEADERS))
).toBeNull();
});
@@ -40,7 +52,7 @@ test('a failing session lookup propagates instead of signing the user out', asyn
);
await expect(
- resolveSession(ctx, cookieJar('some-token'), NO_HEADERS)
+ resolveSession(ctx, request(cookieJar('some-token'), NO_HEADERS))
).rejects.toThrow("Can't reach database server");
});
@@ -59,8 +71,199 @@ test('with several session cookies the first that is signed in wins', async () =
cookie: `session=${encodeURIComponent('stale-token')}; other=1; session=${encodeURIComponent('live-token')}`,
});
- const resolved = await resolveSession(ctx, cookieJar('stale-token'), headers);
+ const resolved = await resolveSession(
+ ctx,
+ request(cookieJar('stale-token'), headers)
+ );
expect(resolved?.userId).toBe('user_1');
expect(lookedUp).toEqual([hashSessionToken('stale-token'), liveId]);
});
+
+const AUTH_SECRET = 'test-auth-secret-at-least-32-characters';
+const FUTURE = () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
+const USER = { id: 'user_1', email: '[email protected]' };
+
+interface CapturedCookie {
+ name: string;
+ value: string;
+}
+
+function ctxWithAuth({
+ auth,
+ db,
+ demoUserId,
+}: {
+ auth: unknown;
+ db: unknown;
+ demoUserId?: string;
+}) {
+ const { deps, logger } = stubAppDeps();
+ const config = testCoreConfig({ demoUserId });
+ config.auth.secret = AUTH_SECRET;
+ return createCtx(
+ {
+ ...deps,
+ config,
+ auth: auth as Auth,
+ db: db as AppDeps['db'],
+ },
+ { requestId: 'req-1', logger }
+ );
+}
+
+function capturingRequest(cookieHeader: string, legacyToken?: string) {
+ const written: CapturedCookie[] = [];
+ return {
+ written,
+ request: {
+ cookies: cookieJar(legacyToken),
+ headers: new Headers({ cookie: cookieHeader }),
+ setCookie: (name: string, value: string) => {
+ written.push({ name, value });
+ },
+ },
+ };
+}
+
+test("better-auth's cookie resolves the session without the legacy lookup", async () => {
+ const session = { id: 'sess_ba', token: 'ba-token', userId: USER.id };
+ const auth = {
+ api: {
+ getSession: () =>
+ Promise.resolve({
+ headers: new Headers(),
+ response: {
+ session,
+ user: { ...USER, name: '', emailVerified: false },
+ },
+ }),
+ },
+ };
+ const db = {
+ session: {
+ findUnique: () => Promise.reject(new Error('legacy lookup not expected')),
+ },
+ };
+ const ctx = ctxWithAuth({ auth, db });
+ const { request } = capturingRequest(
+ `${AUTH_SESSION_COOKIE}=ba-token.sig; session=legacy`,
+ 'legacy'
+ );
+
+ const resolved = await resolveSession(ctx, request);
+
+ expect(resolved?.userId).toBe(USER.id);
+ expect(resolved?.session?.id).toBe('sess_ba');
+});
+
+interface TokenWrite {
+ where: { id: string; token: null };
+ data: { token: string };
+}
+
+function legacyRow(id: string, token: string | null) {
+ return { id, token, userId: USER.id, expiresAt: FUTURE(), user: USER };
+}
+
+test("a legacy session gets better-auth's cookie under its own token, never the legacy one", async () => {
+ const legacyToken = 'legacy-token';
+ const id = hashSessionToken(legacyToken);
+ const tokenWrites: TokenWrite[] = [];
+ const auth = {
+ api: {
+ getSession: () => Promise.reject(new Error('no better-auth cookie sent')),
+ },
+ };
+ const db = {
+ session: {
+ findUnique: () => Promise.resolve(legacyRow(id, null)),
+ updateMany: (args: TokenWrite) => {
+ tokenWrites.push(args);
+ return Promise.resolve({ count: 1 });
+ },
+ },
+ };
+ const ctx = ctxWithAuth({ auth, db });
+ const { request, written } = capturingRequest(
+ `session=${encodeURIComponent(legacyToken)}`,
+ legacyToken
+ );
+
+ const resolved = await resolveSession(ctx, request);
+
+ expect(resolved?.userId).toBe(USER.id);
+ expect(tokenWrites).toHaveLength(1);
+ const stored = tokenWrites[0]?.data.token;
+ expect(tokenWrites[0]?.where).toEqual({ id, token: null });
+ expect(stored).toBeString();
+ expect(stored).not.toBe(legacyToken);
+ const upgraded = written.find(
+ (cookie) => cookie.name === AUTH_SESSION_COOKIE
+ );
+ expect(upgraded?.value.startsWith(`${stored}.`)).toBe(true);
+ expect(upgraded?.value).not.toContain(legacyToken);
+});
+
+test('a session another request upgraded first reuses that token', async () => {
+ const legacyToken = 'legacy-token';
+ const id = hashSessionToken(legacyToken);
+ const auth = { api: { getSession: () => Promise.resolve(null) } };
+ const db = {
+ session: {
+ findUnique: () => Promise.resolve(legacyRow(id, null)),
+ updateMany: () => Promise.resolve({ count: 0 }),
+ findUniqueOrThrow: () => Promise.resolve({ token: 'won-the-race' }),
+ },
+ };
+ const ctx = ctxWithAuth({ auth, db });
+ const { request, written } = capturingRequest(
+ `session=${encodeURIComponent(legacyToken)}`,
+ legacyToken
+ );
+
+ await resolveSession(ctx, request);
+
+ const upgraded = written.find(
+ (cookie) => cookie.name === AUTH_SESSION_COOKIE
+ );
+ expect(upgraded?.value.startsWith('won-the-race.')).toBe(true);
+});
+
+test('an already upgraded legacy row is not written again', async () => {
+ const legacyToken = 'legacy-token';
+ const auth = { api: { getSession: () => Promise.resolve(null) } };
+ const db = {
+ session: {
+ findUnique: () =>
+ Promise.resolve(legacyRow(hashSessionToken(legacyToken), 'stored')),
+ updateMany: () => Promise.reject(new Error('should not be called')),
+ },
+ };
+ const ctx = ctxWithAuth({ auth, db });
+ const { request, written } = capturingRequest(
+ `session=${encodeURIComponent(legacyToken)}`,
+ legacyToken
+ );
+
+ expect((await resolveSession(ctx, request))?.userId).toBe(USER.id);
+ const upgraded = written.find(
+ (cookie) => cookie.name === AUTH_SESSION_COOKIE
+ );
+ expect(upgraded?.value.startsWith('stored.')).toBe(true);
+});
+
+test('the demo user wins over any cookie', async () => {
+ const auth = {
+ api: {
+ getSession: () => Promise.reject(new Error('should not be called')),
+ },
+ };
+ const db = {
+ user: { findUniqueOrThrow: () => Promise.resolve({ ...USER, id: 'demo' }) },
+ };
+ const ctx = ctxWithAuth({ auth, db, demoUserId: 'demo' });
+ const { request } = capturingRequest(`${AUTH_SESSION_COOKIE}=x.y`);
+
+ expect((await resolveSession(ctx, request))?.userId).toBe('demo');
+});
diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.ts
index 3448f026f..7862109ea 100644
--- a/packages/core/src/http/session.ts
+++ b/packages/core/src/http/session.ts
@@ -1,6 +1,6 @@
-// `HttpCtx.session` memoizes this call. The flow is decode, `runWithAlsSession`,
-// validate; the `DEMO_USER_ID` branch lives inside `validateSessionToken`, so the
-// no-cookie path still goes through it.
+// `HttpCtx.session` memoizes this call. Order: the demo user, better-auth's
+// cookie, then the legacy `session` cookie, whose session is handed
+// better-auth's cookie on the way out so the legacy path drains by itself.
//
// `null` means "nobody is signed in", NOT `EMPTY_SESSION`: the `session` macro,
// the bull-board guard and the `/live` handlers treat the resolved value as
@@ -8,7 +8,7 @@
import type { Ctx, Session } from '../context';
import { runWithAlsSession } from '../shared/als-session';
-import type { CookieJar } from '../shared/cookie';
+import type { CookieJar, ISetCookie } from '../shared/cookie';
export const SESSION_COOKIE_NAME = 'session';
@@ -42,29 +42,39 @@ function sessionTokens(cookies: CookieJar, headers: Headers): string[] {
return [...tokens];
}
+export interface SessionRequest {
+ cookies: CookieJar;
+ headers: Headers;
+ setCookie: ISetCookie;
+}
+
export async function resolveSession(
ctx: Ctx,
- cookies: CookieJar,
- headers: Headers
+ { cookies, headers, setCookie }: SessionRequest
): Promise<Session | null> {
const auth = ctx.services.auth;
- const tokens = sessionTokens(cookies, headers);
- // No catch: decoding is a hash and cannot fail, so only the database throws.
- // Answering `null` would be a 401 and sign every user out during a blip; a
- // 500 makes the client retry.
- if (tokens.length === 0) {
- const result = await runWithAlsSession(DEMO_ALS_SESSION_ID, () =>
+ // No catch on either lookup: only the database throws, and answering `null`
+ // would be a 401 that signs every user out during a blip; a 500 makes the
+ // client retry.
+ if (ctx.config.demoUserId) {
+ const demo = await runWithAlsSession(DEMO_ALS_SESSION_ID, () =>
auth.validateSessionToken(null)
);
- return result.userId === null ? null : result;
+ return demo.userId === null ? null : demo;
+ }
+
+ const session = await auth.getAuthSession(headers, setCookie);
+ if (session) {
+ return session;
}
- for (const token of tokens) {
+ for (const token of sessionTokens(cookies, headers)) {
const result = await runWithAlsSession(auth.decodeSessionToken(token), () =>
auth.validateSessionToken(token)
);
if (result.userId !== null) {
+ await auth.upgradeLegacySession(result.session, setCookie);
return result;
}
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0c5ca2c42..6c9f4a8ae 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -114,6 +114,7 @@ export {
} from './modules/auth/auth.service';
export type { AccessLookups } from './modules/auth/src/access';
export { createAccessChecks } from './modules/auth/src/access';
+export { createAuth } from './modules/auth/src/better-auth';
export { validateSessionToken } from './modules/auth/src/login-session';
export { getIsRegistrationAllowed } from './modules/auth/src/registration';
export type {
diff --git a/packages/core/src/jobs/workers.test.ts b/packages/core/src/jobs/workers.test.ts
index d6af36337..aee033ff4 100644
--- a/packages/core/src/jobs/workers.test.ts
+++ b/packages/core/src/jobs/workers.test.ts
@@ -25,6 +25,7 @@ function stubLogger(): Logger {
function stubDeps(): AppDeps {
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.ts
index 05165ea62..a976e4303 100644
--- a/packages/core/src/modules/auth/auth.routes.ts
+++ b/packages/core/src/modules/auth/auth.routes.ts
@@ -9,6 +9,7 @@ import {
fetchGoogleOAuthUser,
OAuthCallbackError,
} from './auth.service';
+import { AUTH_BASE_PATH } from './src/better-auth';
// Anyone can call this URL directly, so both values are attacker-controlled.
const callbackQuery = z.object({
@@ -30,8 +31,15 @@ function loginErrorRedirect(
return redirect(url.toString());
}
-export const authRoutes = defineRoutes((app) =>
+export const authRoutes = defineRoutes((app, deps) =>
app
+ .all(
+ `${AUTH_BASE_PATH}/*`,
+ ({ request }) =>
+ deps.auth?.handler(request) ??
+ new Response('Not Found', { status: 404 }),
+ { parse: 'none', detail: { hide: true } }
+ )
.get(
'/oauth/github/callback',
async ({ query, ctx }) => {
diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.ts
index b7e75dc73..e3b45a1c5 100644
--- a/packages/core/src/modules/auth/auth.rpc.test.ts
+++ b/packages/core/src/modules/auth/auth.rpc.test.ts
@@ -2,7 +2,7 @@
import { expect, test } from 'bun:test';
import { testCoreConfig } from '../../../test/config-fixture';
-import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import { stubHttpCtx, TEST_SESSION } from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
import type { CookieOptions } from '../../shared/cookie';
import { authRouter } from './auth.rpc';
@@ -125,3 +125,17 @@ test('session returns the caller session unauthenticated (no login required)', a
const caller = await anonCaller();
await expect(caller.session()).resolves.toEqual(EMPTY_SESSION);
});
+
+test('session never hands the session token to the browser', async () => {
+ const signedIn = {
+ ...TEST_SESSION,
+ session: { ...TEST_SESSION.session, token: 'cookie-value' },
+ };
+ const { ctx } = stubHttpCtx({}, signedIn);
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ const result = await authRouter.createCaller(trpcCtx).session();
+ expect(result.userId).toBe(TEST_SESSION.userId);
+ expect(JSON.stringify(result)).not.toContain('cookie-value');
+});
diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.ts
index ae01858cb..3d760f8df 100644
--- a/packages/core/src/modules/auth/auth.rpc.ts
+++ b/packages/core/src/modules/auth/auth.rpc.ts
@@ -2,6 +2,7 @@
// anything resolved from another id needs its own explicit check in the handler.
import { z } from 'zod';
+import type { Session } from '../../context';
import {
createRateLimitMiddleware,
createTRPCRouter,
@@ -41,6 +42,15 @@ import {
const rateLimit = createRateLimitMiddleware(enforceRateLimit);
+// The token is the cookie's value; the cookie is httpOnly so scripts never see it.
+function withoutSessionToken(result: Session) {
+ if (!result.session) {
+ return result;
+ }
+ const { token: _token, ...session } = result.session;
+ return { ...result, session };
+}
+
export const authRouter = createTRPCRouter({
/**
* Which optional OAuth features this instance has credentials for, so the
@@ -125,7 +135,7 @@ export const authRouter = createTRPCRouter({
.input(zRequestResetPassword)
.mutation(({ input, ctx }) => requestPasswordReset(ctx, input)),
- session: publicProcedure.query(({ ctx }) => ctx.session),
+ session: publicProcedure.query(({ ctx }) => withoutSessionToken(ctx.session)),
extendSession: publicProcedure.mutation(({ ctx }) =>
extendSessionCookie(
diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.ts
index 42a70f136..80492ff7d 100644
--- a/packages/core/src/modules/auth/auth.service.access.test.ts
+++ b/packages/core/src/modules/auth/auth.service.access.test.ts
@@ -12,7 +12,6 @@ let projectAccess: FakeProjectAccess | null = null;
interface FakeOrganizationAccess {
role: string;
userId: string;
- organization: { createdByUserId: string | null };
}
let organizationAccess: FakeOrganizationAccess | null = null;
@@ -20,7 +19,6 @@ let organizationAccess: FakeOrganizationAccess | null = null;
const memberAccess = (role: string): FakeOrganizationAccess => ({
role,
userId: 'user_1',
- organization: { createdByUserId: null },
});
let projectById: { organizationId: string | null } | null = null;
@@ -110,7 +108,7 @@ test('requireProjectAccess allows write and admin levels to write', async () =>
});
test('requireOrganizationAdmin rejects a non-admin with the default message', async () => {
- organizationAccess = memberAccess('org:member');
+ organizationAccess = memberAccess('member');
await expect(
authService().requireOrganizationAdmin({
userId: 'user_1',
@@ -141,14 +139,14 @@ test('requireProjectAdmin fails closed when the project has no organization', as
test('requireProjectAdmin defers to the organization-admin gate once resolved', async () => {
projectById = { organizationId: 'org_1' };
- organizationAccess = memberAccess('org:admin');
+ organizationAccess = memberAccess('admin');
await expect(
authService().requireProjectAdmin({ userId: 'user_1', projectId: 'proj_1' })
- ).resolves.toMatchObject({ role: 'org:admin' });
+ ).resolves.toMatchObject({ role: 'admin' });
});
-test('requireOrganizationAdmin accepts the stored and the new admin spellings, and refuses a viewer', async () => {
- for (const role of ['org:admin', 'admin', 'owner']) {
+test('requireOrganizationAdmin accepts owner and admin, and refuses member and viewer', async () => {
+ for (const role of ['admin', 'owner']) {
organizationAccess = memberAccess(role);
await expect(
authService().requireOrganizationAdmin({
@@ -157,40 +155,47 @@ test('requireOrganizationAdmin accepts the stored and the new admin spellings, a
})
).resolves.toBeDefined();
}
- organizationAccess = memberAccess('viewer');
- await expect(
- authService().requireOrganizationAdmin({
- userId: 'user_1',
- organizationId: 'org_1',
- })
- ).rejects.toThrow('Only organization admins can do this');
+ for (const role of ['member', 'viewer']) {
+ organizationAccess = memberAccess(role);
+ await expect(
+ authService().requireOrganizationAdmin({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).rejects.toThrow('Only organization admins can do this');
+ }
});
-test('getOrganizationAccess reports the creator as owner and maps the stored spellings', async () => {
- organizationAccess = {
- role: 'org:admin',
- userId: 'user_1',
- organization: { createdByUserId: 'user_1' },
- };
- await expect(
- authService().getOrganizationAccess({
- userId: 'user_1',
- organizationId: 'org_1',
- })
- ).resolves.toMatchObject({ role: 'owner' });
+test('getOrganizationAccess reports the stored role, the old spellings by their new names, and an unknown one as member', async () => {
+ for (const role of ['owner', 'admin', 'member', 'viewer']) {
+ organizationAccess = memberAccess(role);
+ await expect(
+ authService().getOrganizationAccess({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).resolves.toMatchObject({ role });
+ }
- organizationAccess = memberAccess('org:member');
- await expect(
- authService().getOrganizationAccess({
- userId: 'user_1',
- organizationId: 'org_1',
- })
- ).resolves.toMatchObject({ role: 'member' });
+ const readAs: [stored: string, role: string][] = [
+ ['org:admin', 'admin'],
+ ['org:member', 'member'],
+ ['superuser', 'member'],
+ ];
+ for (const [stored, role] of readAs) {
+ organizationAccess = memberAccess(stored);
+ await expect(
+ authService().getOrganizationAccess({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).resolves.toMatchObject({ role });
+ }
});
test('getProjectAccess / getOrganizationAccess reach the same fake lookups', async () => {
projectAccess = { level: 'admin' };
- organizationAccess = memberAccess('org:admin');
+ organizationAccess = memberAccess('admin');
await expect(
authService().getProjectAccess({ userId: 'user_1', projectId: 'proj_1' })
).resolves.toEqual({ level: 'admin' });
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index 2a9f606f9..0d355d561 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -1,3 +1,4 @@
+import type { Session } from '@openpanel/db/src/prisma-client';
import { z } from 'zod';
import type { CoreConfig } from '../../config';
import type { ServiceDeps, Services } from '../../services';
@@ -13,10 +14,16 @@ import {
import type { ISetCookie } from '../../shared/cookie';
import {
isOrganizationAdminRole,
+ normalizeOrganizationRole,
type OrganizationRole,
- resolveOrganizationRole,
} from '../organization/organization.constants';
import { type AccessChecks, createAccessChecks } from './src/access';
+import {
+ type AuthSessionResult,
+ deleteAuthSessionCookie,
+ getAuthSession,
+ upgradeLegacySession,
+} from './src/better-auth';
import {
deleteSessionTokenCookie,
setLastAuthProviderCookie,
@@ -94,7 +101,8 @@ export function getAccessChecks(): Promise<ProjectAccessChecks> {
canWriteProject,
getOrganizationAccess: getOrganizationAccessLookup,
isOrganizationAdmin: (access) =>
- !!access && isOrganizationAdminRole(resolveOrganizationRole(access)),
+ !!access &&
+ isOrganizationAdminRole(normalizeOrganizationRole(access.role)),
getProjectById,
})
);
@@ -164,7 +172,7 @@ export function createAuthService(
if (!access) {
return null;
}
- return { ...access, role: resolveOrganizationRole(access) };
+ return { ...access, role: normalizeOrganizationRole(access.role) };
}
function getClientAccess(
@@ -198,6 +206,31 @@ export function createAuthService(
deleteSessionTokenCookie(deps.config, setCookie);
}
+ function getSession(
+ headers: Headers,
+ setCookie: ISetCookie
+ ): Promise<AuthSessionResult | null> {
+ if (!deps.auth) {
+ return Promise.resolve(null);
+ }
+ return getAuthSession(deps.auth, deps.config, headers, setCookie);
+ }
+
+ async function upgradeSession(
+ session: Session,
+ setCookie: ISetCookie
+ ): Promise<void> {
+ if (!(deps.auth && deps.config.auth.secret)) {
+ return;
+ }
+ await upgradeLegacySession(
+ deps,
+ deps.config.auth.secret,
+ session,
+ setCookie
+ );
+ }
+
function cookieDomainForUrl(
url: string
): ReturnType<typeof parseCookieDomain> {
@@ -210,6 +243,8 @@ export function createAuthService(
requireProjectAdmin,
requireLogin,
validateSessionToken: checkSessionToken,
+ getAuthSession: getSession,
+ upgradeLegacySession: upgradeSession,
getProjectAccess,
getOrganizationAccess,
getClientAccess,
@@ -248,7 +283,7 @@ import {
shareAccessCookieName,
} from '../../shared/share-access';
import { connectUserToOrganization } from '../organization/organization.service';
-import { getUserAccount } from '../user/user.service';
+import { getUserAccount, toDisplayName } from '../user/user.service';
import {
createSession,
invalidateSession,
@@ -261,6 +296,8 @@ const TWO_FACTOR_COOKIE = '2fa_challenge';
const TWO_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60;
const INVITE_COOKIE = 'inviteId';
const RESET_PASSWORD_TTL_MS = 1000 * 60 * 10;
+/** better-auth's provider id for email and password accounts. */
+const CREDENTIAL_PROVIDER = 'credential';
export type AuthProvider = 'email' | 'google' | 'github';
@@ -298,6 +335,7 @@ export async function signOutUser(
sessionId: string | null | undefined
): Promise<void> {
deleteSessionTokenCookie(deps.config, setCookie);
+ deleteAuthSessionCookie(deps.config, setCookie);
if (sessionId) {
await invalidateSession(deps, sessionId);
}
@@ -433,21 +471,26 @@ export async function signUpWithEmail(
throw new TRPCForbiddenError('Registrations are not allowed');
}
- const provider = 'email';
- const existing = await getUserAccount(deps, { email: input.email, provider });
+ const existing = await getUserAccount(deps, {
+ email: input.email,
+ provider: CREDENTIAL_PROVIDER,
+ });
if (existing) {
throw new TRPCNotFoundError('User already exists');
}
+ const userId = generateSecureId('user');
const createdUser = await deps.db.user.create({
data: {
- id: generateSecureId('user'),
+ id: userId,
email: input.email,
firstName: input.firstName,
lastName: input.lastName,
+ name: toDisplayName(input.firstName, input.lastName),
accounts: {
create: {
- provider,
+ provider: CREDENTIAL_PROVIDER,
+ accountId: userId,
password: await hashPassword(input.password),
},
},
@@ -483,7 +526,7 @@ export async function signInWithEmail(
): Promise<SignInEmailResult> {
const user = await getUserAccount(deps, {
email: input.email,
- provider: 'email',
+ provider: CREDENTIAL_PROVIDER,
});
if (!user) {
@@ -628,7 +671,7 @@ export async function getTotpStatus(deps: ServiceDeps, userId: string) {
const [totp, emailAccount] = await Promise.all([
deps.db.userTotp.findUnique({ where: { userId } }),
deps.db.account.findFirst({
- where: { userId, provider: 'email' },
+ where: { userId, provider: CREDENTIAL_PROVIDER },
select: { id: true },
}),
]);
@@ -642,7 +685,7 @@ export async function getTotpStatus(deps: ServiceDeps, userId: string) {
export async function setupTotp(deps: ServiceDeps, userId: string) {
const emailAccount = await deps.db.account.findFirst({
- where: { userId, provider: 'email' },
+ where: { userId, provider: CREDENTIAL_PROVIDER },
select: { id: true },
});
if (!emailAccount) {
@@ -797,7 +840,7 @@ export async function requestPasswordReset(
): Promise<true> {
const user = await getUserAccount(deps, {
email: input.email,
- provider: 'email',
+ provider: CREDENTIAL_PROVIDER,
});
// Deliberately not found-vs-found: always `true`, so the endpoint cannot be
// used to enumerate registered emails.
@@ -1119,7 +1162,12 @@ async function completeExistingOAuthUser(
await deps.db.account.update({
where: { id: account.id },
- data: { provider, providerId: oauthUser.id, email: oauthUser.email },
+ data: {
+ provider,
+ providerId: oauthUser.id,
+ accountId: oauthUser.id,
+ email: oauthUser.email,
+ },
});
if (inviteId) {
@@ -1178,8 +1226,14 @@ async function completeNewOAuthUser(
email: oauthUser.email,
firstName: oauthUser.firstName,
lastName: oauthUser.lastName,
+ name: toDisplayName(oauthUser.firstName, oauthUser.lastName),
+ emailVerified: true,
accounts: {
- create: { provider, providerId: oauthUser.id },
+ create: {
+ provider,
+ providerId: oauthUser.id,
+ accountId: oauthUser.id,
+ },
},
},
});
diff --git a/packages/core/src/modules/auth/src/better-auth.ts b/packages/core/src/modules/auth/src/better-auth.ts
new file mode 100644
index 000000000..cbc121e0f
--- /dev/null
+++ b/packages/core/src/modules/auth/src/better-auth.ts
@@ -0,0 +1,238 @@
+// better-auth, installed but inert: only `/get-session` answers over HTTP and
+// no flow creates users or sessions through it yet. What it does do is read
+// its own session cookie, which `resolveSession` hands out to legacy sessions
+// as they are used, so the switch of sign-in to better-auth signs nobody out.
+
+import type { Session, User } from '@openpanel/db/src/prisma-client';
+import { APIError, type BetterAuthPlugin, betterAuth } from 'better-auth';
+import { prismaAdapter } from 'better-auth/adapters/prisma';
+import { parseSetCookieHeader } from 'better-auth/cookies';
+import { makeSignature } from 'better-auth/crypto';
+import type { CoreConfig } from '../../../config';
+import type { Db } from '../../../context';
+import type { Logger } from '../../../logger';
+import type { ISetCookie } from '../../../shared/cookie';
+import { cookieOptions } from './constants';
+import { hashPassword, verifyPasswordHash } from './password';
+import { generateSessionToken } from './token';
+
+export const AUTH_BASE_PATH = '/api/auth';
+const COOKIE_PREFIX = 'openpanel';
+/** `${COOKIE_PREFIX}.session_token`, which is how better-auth names it. */
+export const AUTH_SESSION_COOKIE = `${COOKIE_PREFIX}.session_token`;
+
+// The legacy session's lifetime and renewal rule, so a session keeps its
+// expiry whichever cookie resolved it.
+const SESSION_EXPIRES_IN_SECONDS = 60 * 60 * 24 * 30;
+const SESSION_UPDATE_AGE_SECONDS = 60 * 60 * 24 * 15;
+
+const OPEN_PATHS = new Set(['/get-session', '/ok']);
+
+interface AuthDeps {
+ db: Db;
+ config: CoreConfig;
+ logger: Logger;
+}
+
+/** Answers 404 for everything but the open paths until sign-in moves here. */
+const inertPlugin = {
+ id: 'openpanel-inert',
+ onRequest: async (request: Request) => {
+ const path = new URL(request.url).pathname.slice(AUTH_BASE_PATH.length);
+ if (OPEN_PATHS.has(path)) {
+ return;
+ }
+ return { response: new Response('Not Found', { status: 404 }) };
+ },
+} satisfies BetterAuthPlugin;
+
+function buildAuth({ db, config, logger }: AuthDeps, secret: string) {
+ return betterAuth({
+ secret,
+ basePath: AUTH_BASE_PATH,
+ trustedOrigins: config.dashboardUrl ? [config.dashboardUrl] : [],
+ database: prismaAdapter(db, { provider: 'postgresql' }),
+ telemetry: { enabled: false },
+ logger: {
+ log: (level, message, ...args) => {
+ const log = level === 'error' || level === 'warn' ? level : 'info';
+ logger[log]({ args }, `better-auth: ${message}`);
+ },
+ },
+ user: {
+ additionalFields: {
+ firstName: { type: 'string', required: false, input: false },
+ lastName: { type: 'string', required: false, input: false },
+ deletedAt: { type: 'date', required: false, input: false },
+ },
+ },
+ account: {
+ // Our column for the provider's name. `providerId` is the legacy IdP id.
+ fields: { providerId: 'provider' },
+ },
+ session: {
+ expiresIn: SESSION_EXPIRES_IN_SECONDS,
+ updateAge: SESSION_UPDATE_AGE_SECONDS,
+ },
+ emailAndPassword: {
+ enabled: true,
+ disableSignUp: true,
+ password: {
+ hash: hashPassword,
+ verify: ({ hash, password }) => verifyPasswordHash(hash, password),
+ },
+ },
+ advanced: {
+ cookiePrefix: COOKIE_PREFIX,
+ // The name stays `openpanel.session_token` on https too; `Secure` comes
+ // from the same options as the legacy cookie.
+ useSecureCookies: false,
+ defaultCookieAttributes: cookieOptions(config),
+ },
+ plugins: [inertPlugin],
+ });
+}
+
+export type Auth = ReturnType<typeof buildAuth>;
+
+/** Null without a secret: sessions then resolve through the legacy cookie only. */
+export function createAuth(deps: AuthDeps): Auth | null {
+ const secret = deps.config.auth.secret;
+ if (!secret) {
+ deps.logger.warn(
+ 'AUTH_SECRET and COOKIE_SECRET are unset; better-auth is off and only legacy sessions resolve'
+ );
+ return null;
+ }
+ return buildAuth(deps, secret);
+}
+
+export interface AuthSessionResult {
+ session: Session;
+ user: User;
+ userId: string;
+}
+
+/**
+ * Re-sets the cookies better-auth wrote, so a refreshed session's cookie
+ * reaches the browser through whichever transport is answering.
+ */
+function forwardSetCookies(
+ config: CoreConfig,
+ headers: Headers,
+ setCookie: ISetCookie
+): void {
+ for (const header of headers.getSetCookie()) {
+ for (const [name, cookie] of parseSetCookieHeader(header)) {
+ setCookie(name, cookie.value, {
+ ...cookieOptions(config),
+ maxAge: cookie['max-age'],
+ });
+ }
+ }
+}
+
+/** The better-auth session in the request's cookies, in our row types. */
+export async function getAuthSession(
+ auth: Auth,
+ config: CoreConfig,
+ headers: Headers,
+ setCookie: ISetCookie
+): Promise<AuthSessionResult | null> {
+ if (!headers.get('cookie')?.includes(AUTH_SESSION_COOKIE)) {
+ return null;
+ }
+ const response = await auth.api
+ .getSession({ headers, returnHeaders: true })
+ .catch((error: unknown) => {
+ // A refresh racing a sign-out; anything else is the database.
+ if (error instanceof APIError) {
+ return null;
+ }
+ throw error;
+ });
+ if (!response) {
+ return null;
+ }
+ forwardSetCookies(config, response.headers, setCookie);
+ const result = response.response;
+ if (!result) {
+ return null;
+ }
+ const { session, user } = result;
+ return {
+ userId: user.id,
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ emailVerified: user.emailVerified,
+ image: user.image ?? null,
+ firstName: user.firstName ?? null,
+ lastName: user.lastName ?? null,
+ deletedAt: user.deletedAt ?? null,
+ createdAt: user.createdAt,
+ updatedAt: user.updatedAt,
+ },
+ session: {
+ id: session.id,
+ token: session.token,
+ userId: session.userId,
+ expiresAt: session.expiresAt,
+ ipAddress: session.ipAddress ?? null,
+ userAgent: session.userAgent ?? null,
+ createdAt: session.createdAt,
+ updatedAt: session.updatedAt,
+ },
+ };
+}
+
+/**
+ * The token better-auth knows this session by. It is its own random value, never
+ * the legacy cookie's: that cookie is unsigned, so storing it would let a
+ * database read sign in.
+ */
+async function claimAuthToken(db: Db, session: Session): Promise<string> {
+ if (session.token) {
+ return session.token;
+ }
+ const token = generateSessionToken();
+ const claimed = await db.session.updateMany({
+ where: { id: session.id, token: null },
+ data: { token },
+ });
+ if (claimed.count > 0) {
+ return token;
+ }
+ // A concurrent request upgraded it first.
+ const row = await db.session.findUniqueOrThrow({
+ where: { id: session.id },
+ select: { token: true },
+ });
+ return row.token ?? token;
+}
+
+/**
+ * Gives a legacy session better-auth's cookie on the same row, so the session
+ * keeps its id and expiry and signing out either way ends both.
+ */
+export async function upgradeLegacySession(
+ { db, config }: Pick<AuthDeps, 'db' | 'config'>,
+ secret: string,
+ session: Session,
+ setCookie: ISetCookie
+): Promise<void> {
+ const token = await claimAuthToken(db, session);
+ const signature = await makeSignature(token, secret);
+ setCookie(AUTH_SESSION_COOKIE, `${token}.${signature}`, {
+ ...cookieOptions(config),
+ maxAge: Math.floor((session.expiresAt.getTime() - Date.now()) / 1000),
+ });
+}
+
+export function deleteAuthSessionCookie(
+ config: CoreConfig,
+ setCookie: ISetCookie
+): void {
+ setCookie(AUTH_SESSION_COOKIE, '', { ...cookieOptions(config), maxAge: 0 });
+}
diff --git a/packages/core/src/modules/auth/src/login-session.ts b/packages/core/src/modules/auth/src/login-session.ts
index 8965c10ca..80de96db4 100644
--- a/packages/core/src/modules/auth/src/login-session.ts
+++ b/packages/core/src/modules/auth/src/login-session.ts
@@ -24,8 +24,11 @@ export async function createSession(
): Promise<Session> {
const session: Session = {
id: hashSessionToken(token),
+ token: null,
userId,
expiresAt: new Date(Date.now() + SESSION_TTL_MS),
+ ipAddress: null,
+ userAgent: null,
createdAt: new Date(),
updatedAt: new Date(),
};
@@ -50,8 +53,11 @@ export async function createDemoSession(
userId: user.id,
session: {
id: DEMO_SESSION_ID,
+ token: null,
userId: user.id,
expiresAt: new Date(Date.now() + DEMO_SESSION_TTL_MS),
+ ipAddress: null,
+ userAgent: null,
createdAt: new Date(),
updatedAt: new Date(),
},
diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.ts
index c5e1e4d4c..cca08a8b3 100644
--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts
+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts
@@ -68,6 +68,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.ts
index e732af7d8..0d40ef24b 100644
--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts
+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts
@@ -68,6 +68,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
@@ -147,6 +148,7 @@ test('gscProjectBackfill delegates to runProjectBackfill', async () => {
test('gscSync fans out one gscProjectSync enqueue per connected project', async () => {
const producers = createRecordingProducers(queues);
const ctx: JobCtx = {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.ts
index 71f65d72a..19f36a6e7 100644
--- a/packages/core/src/modules/import/import.jobs.test.ts
+++ b/packages/core/src/modules/import/import.jobs.test.ts
@@ -67,6 +67,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.ts
index f08f2944c..e2da023b7 100644
--- a/packages/core/src/modules/import/import.service.test.ts
+++ b/packages/core/src/modules/import/import.service.test.ts
@@ -143,6 +143,7 @@ test('ImportService.enqueue adds the import job onto the import queue', async ()
const producers = createRecordingProducers(queues);
const service = createImportService(
{
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.ts
index 87e4dfb3d..c97d745d7 100644
--- a/packages/core/src/modules/insight/insight.jobs.test.ts
+++ b/packages/core/src/modules/insight/insight.jobs.test.ts
@@ -72,6 +72,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
@@ -134,6 +135,7 @@ test('insightsProject delegates to runProjectInsights', async () => {
test('insightsDaily fans out one insightsProject enqueue per candidate, jobId deduped by day+project', async () => {
const producers = createRecordingProducers(queues);
const ctx: JobCtx = {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.ts
index 4e8109d61..8cafa199d 100644
--- a/packages/core/src/modules/insight/insight.service.test.ts
+++ b/packages/core/src/modules/insight/insight.service.test.ts
@@ -49,21 +49,21 @@ const member = {
findMany: mock(async () => [
{
userId: 'u_all',
- role: 'org:member',
+ role: 'member',
projectScope: 'all',
projects: [],
user: { email: '[email protected]' },
},
{
userId: 'u_this',
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
projects: [{ projectId: 'p1', level: null }],
user: { email: '[email protected]' },
},
{
userId: 'u_other',
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
projects: [{ projectId: 'p_other', level: null }],
user: { email: '[email protected]' },
@@ -214,6 +214,7 @@ test('createInsightService binds every InsightService method', () => {
};
const service = subject.createInsightService(
{
+ auth: null,
db: undefined as unknown as AppDeps['db'],
prisma: undefined as unknown as AppDeps['prisma'],
ch: undefined as unknown as AppDeps['ch'],
diff --git a/packages/core/src/modules/integration/integration.service.test.ts b/packages/core/src/modules/integration/integration.service.test.ts
index c44598d23..2807b132b 100644
--- a/packages/core/src/modules/integration/integration.service.test.ts
+++ b/packages/core/src/modules/integration/integration.service.test.ts
@@ -27,7 +27,7 @@ mock.module('../../shared/access-lookups', () => ({
getProjectAccess: mock(async () =>
projectAccessLevel ? { level: projectAccessLevel } : null
),
- getOrganizationAccess: mock(async () => ({ role: 'org:member' })),
+ getOrganizationAccess: mock(async () => ({ role: 'member' })),
canWriteProject: (access: { level: string } | null) =>
!!access && (access.level === 'write' || access.level === 'admin'),
getProjectById: mock(async () => ({ organizationId: 'org_1' })),
diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.ts
index 4a59068c9..6a85aece4 100644
--- a/packages/core/src/modules/notification/notification.jobs.test.ts
+++ b/packages/core/src/modules/notification/notification.jobs.test.ts
@@ -68,6 +68,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/notification/notification.service.test.ts b/packages/core/src/modules/notification/notification.service.test.ts
index f1fcebecc..2925724ed 100644
--- a/packages/core/src/modules/notification/notification.service.test.ts
+++ b/packages/core/src/modules/notification/notification.service.test.ts
@@ -124,21 +124,21 @@ const member = {
findMany: mock(async () => [
{
userId: 'u_all',
- role: 'org:member',
+ role: 'member',
projectScope: 'all',
projects: [],
user: { email: '[email protected]' },
},
{
userId: 'u_other',
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
projects: [{ projectId: 'proj_other', level: null }],
user: { email: '[email protected]' },
},
{
userId: 'u_this',
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
projects: [{ projectId: 'proj_1', level: null }],
user: { email: '[email protected]' },
diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
index 7a4739e2b..60db58295 100644
--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
@@ -69,6 +69,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.test.ts b/packages/core/src/modules/onboarding/onboarding.rpc.test.ts
index 4e0746ef2..fc0eca14c 100644
--- a/packages/core/src/modules/onboarding/onboarding.rpc.test.ts
+++ b/packages/core/src/modules/onboarding/onboarding.rpc.test.ts
@@ -57,7 +57,7 @@ test('project refuses an organization member who is not an admin', async () => {
);
const services = {
auth: {
- getOrganizationAccess: () => Promise.resolve({ role: 'org:member' }),
+ getOrganizationAccess: () => Promise.resolve({ role: 'member' }),
requireOrganizationAdmin,
},
} as unknown as Services;
diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.ts
index 9183d52f8..6f94795f9 100644
--- a/packages/core/src/modules/onboarding/onboarding.service.ts
+++ b/packages/core/src/modules/onboarding/onboarding.service.ts
@@ -11,7 +11,6 @@ import {
type SequenceSubject,
step,
} from '../email/src/sequence';
-import { toStoredOrganizationRole } from '../organization/organization.constants';
import {
getOrganizationById,
getOrganizationEventsCount,
@@ -32,18 +31,8 @@ export async function canSkipOnboarding(
return { canSkip: false };
}
- // Sequential, not Promise.all: the early return below skips the projectAccess query
- // for any user with a membership, which a parallel fetch would give up.
- const db = deps.db;
- const members = await db.member.count({ where: { userId } });
- if (members > 0) {
- return { canSkip: true };
- }
-
- // Rows without a membership never granted access, but they did let the user
- // past onboarding; kept until `project_access` is dropped.
- const projectAccess = await db.projectAccess.count({ where: { userId } });
- return { canSkip: projectAccess > 0 };
+ const members = await deps.db.member.count({ where: { userId } });
+ return { canSkip: members > 0 };
}
async function createOrGetOnboardingOrganization(
@@ -86,7 +75,7 @@ async function createOrGetOnboardingOrganization(
data: {
email: (await getUserById(deps, userId)).email,
organizationId,
- role: toStoredOrganizationRole('owner'),
+ role: 'owner',
userId,
},
}),
diff --git a/packages/core/src/modules/organization/organization.constants.test.ts b/packages/core/src/modules/organization/organization.constants.test.ts
index 8d18fe3d0..b16b4cc23 100644
--- a/packages/core/src/modules/organization/organization.constants.test.ts
+++ b/packages/core/src/modules/organization/organization.constants.test.ts
@@ -27,39 +27,24 @@ describe('zTimezone', () => {
});
});
-// The previous image reads no project_access rows as every project.
+// A selection of no projects means no project access, which is a valid choice.
describe('an empty selected scope', () => {
- const invite = {
- email: '[email protected]',
- organizationId: 'org_1',
- role: 'member' as const,
- };
-
- it('is rejected for invites and access updates', () => {
- expect(
- zInviteUser.safeParse({ ...invite, projectScope: 'selected', access: [] })
- .success
- ).toBe(false);
+ it('is accepted for invites and access updates', () => {
expect(
- zUpdateMemberAccess.safeParse({
- userId: 'user_1',
+ zInviteUser.safeParse({
+ email: '[email protected]',
organizationId: 'org_1',
+ role: 'member',
projectScope: 'selected',
access: [],
}).success
- ).toBe(false);
- });
-
- it('allows all projects, or a selection with at least one project', () => {
- expect(
- zInviteUser.safeParse({ ...invite, projectScope: 'all', access: [] })
- .success
).toBe(true);
expect(
- zInviteUser.safeParse({
- ...invite,
+ zUpdateMemberAccess.safeParse({
+ userId: 'user_1',
+ organizationId: 'org_1',
projectScope: 'selected',
- access: [{ projectId: 'proj_1', level: 'read' }],
+ access: [],
}).success
).toBe(true);
});
diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.ts
index eff949275..75c7df98c 100644
--- a/packages/core/src/modules/organization/organization.constants.ts
+++ b/packages/core/src/modules/organization/organization.constants.ts
@@ -26,68 +26,42 @@ export const ORGANIZATION_ROLES = [
export const zOrganizationRole = z.enum(ORGANIZATION_ROLES);
export type OrganizationRole = z.infer<typeof zOrganizationRole>;
-/**
- * Owner is derived from who created the organization, never assigned. Viewer
- * is not offered until the stored roles are renamed: the previous image does
- * not know it and would give a viewer write access after a rollback.
- */
-export const zInvitableRole = z.enum(['admin', 'member']);
+/** Owner is whoever created the organization; it is never handed out by invite. */
+export const zInvitableRole = z.enum(['admin', 'member', 'viewer']);
export type InvitableRole = z.infer<typeof zInvitableRole>;
-const ORGANIZATION_ADMIN_ROLES: ReadonlySet<OrganizationRole> = new Set([
+const ORGANIZATION_ADMIN_ROLES = [
'owner',
'admin',
-]);
-
-// The spellings the previous build wrote and still compares against. They are
-// read and written as-is for one more build so a rolling deploy or rollback
-// never turns an admin into a member; the stored rename is the next build's
-// migration.
-const STORED_ROLE_BY_ROLE: Record<OrganizationRole, string> = {
- owner: 'org:admin',
- admin: 'org:admin',
- member: 'org:member',
- viewer: 'viewer',
-};
-const ROLE_BY_STORED_ROLE: Record<string, OrganizationRole> = {
+] as const satisfies readonly OrganizationRole[];
+
+// The previous build still writes these while a rollout replaces it, after the
+// rename migration has run, so they are read for one more release; the next
+// release's migration renames them again.
+const ROLE_BY_LEGACY_ROLE: Record<string, OrganizationRole> = {
'org:admin': 'admin',
'org:member': 'member',
};
-/** Every stored spelling that counts as an organization admin, for database filters. */
-export const STORED_ADMIN_ROLES = ['org:admin', 'admin', 'owner'] as const;
+/** Every stored role that manages the organization, for database filters. */
+export const STORED_ADMIN_ROLES = [...ORGANIZATION_ADMIN_ROLES, 'org:admin'];
+/** An unknown stored role reads as `member`, never as an admin. */
export function normalizeOrganizationRole(stored: string): OrganizationRole {
- const mapped = ROLE_BY_STORED_ROLE[stored];
- if (mapped) {
- return mapped;
+ const legacy = ROLE_BY_LEGACY_ROLE[stored];
+ if (legacy) {
+ return legacy;
}
const parsed = zOrganizationRole.safeParse(stored);
return parsed.success ? parsed.data : 'member';
}
-export function toStoredOrganizationRole(role: OrganizationRole): string {
- return STORED_ROLE_BY_ROLE[role];
-}
-
-/**
- * The role a membership row resolves to. The organization's creator is its
- * owner; the stored row still says admin until the next build's migration.
- */
-export function resolveOrganizationRole(member: {
- role: string;
- userId: string | null;
- organization: { createdByUserId: string | null };
-}): OrganizationRole {
- const role = normalizeOrganizationRole(member.role);
- const isCreator =
- member.userId !== null &&
- member.userId === member.organization.createdByUserId;
- return role === 'admin' && isCreator ? 'owner' : role;
-}
+const ADMIN_ROLE_SET: ReadonlySet<OrganizationRole> = new Set(
+ ORGANIZATION_ADMIN_ROLES
+);
export function isOrganizationAdminRole(role: OrganizationRole): boolean {
- return ORGANIZATION_ADMIN_ROLES.has(role);
+ return ADMIN_ROLE_SET.has(role);
}
/**
@@ -99,41 +73,20 @@ export type ProjectScope = z.infer<typeof zProjectScope>;
export const SELECT_A_PROJECT_MESSAGE = 'Select at least one project';
-/**
- * The previous image reads "no project_access rows" as every project, so an
- * empty selection would widen access on an old pod or after a rollback.
- * Allowed again once `project_access` is dropped.
- */
-function hasGrantsWhenSelected(value: {
- projectScope: ProjectScope;
- access: unknown[];
-}): boolean {
- return value.projectScope === 'all' || value.access.length > 0;
-}
-
-const SELECTED_NEEDS_GRANTS = {
- message: SELECT_A_PROJECT_MESSAGE,
- path: ['access'],
-};
+export const zInviteUser = z.object({
+ email: z.string().max(MAX_EMAIL).email(),
+ organizationId: z.string().max(MAX_ID),
+ role: zInvitableRole,
+ projectScope: zProjectScope,
+ access: z.array(zProjectAccessGrant),
+});
-export const zInviteUser = z
- .object({
- email: z.string().max(MAX_EMAIL).email(),
- organizationId: z.string().max(MAX_ID),
- role: zInvitableRole,
- projectScope: zProjectScope,
- access: z.array(zProjectAccessGrant),
- })
- .refine(hasGrantsWhenSelected, SELECTED_NEEDS_GRANTS);
-
-export const zUpdateMemberAccess = z
- .object({
- userId: z.string(),
- organizationId: z.string(),
- projectScope: zProjectScope,
- access: z.array(zProjectAccessGrant),
- })
- .refine(hasGrantsWhenSelected, SELECTED_NEEDS_GRANTS);
+export const zUpdateMemberAccess = z.object({
+ userId: z.string(),
+ organizationId: z.string(),
+ projectScope: zProjectScope,
+ access: z.array(zProjectAccessGrant),
+});
export const DEFAULT_TIMEZONE = 'UTC';
diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.ts
index 8783b3bc2..731a0fd75 100644
--- a/packages/core/src/modules/organization/organization.jobs.test.ts
+++ b/packages/core/src/modules/organization/organization.jobs.test.ts
@@ -68,6 +68,7 @@ function stubJobCtx(
mcp: {} as Services['mcp'],
};
return {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.ts
index b0513144f..58a56f9f1 100644
--- a/packages/core/src/modules/organization/organization.service.test.ts
+++ b/packages/core/src/modules/organization/organization.service.test.ts
@@ -84,16 +84,6 @@ const projectStore = new Map<string, FakeProject>();
const memberStore = new Map<string, FakeMember>();
const inviteStore = new Map<string, FakeInvite>();
const userStore = new Map<string, FakeUser>();
-const projectAccessStore = new Map<
- string,
- {
- id: string;
- userId: string;
- organizationId: string;
- projectId: string;
- level: string;
- }
->();
const memberProjectStore: FakeMemberProject[] = [];
function resetStores() {
@@ -102,10 +92,22 @@ function resetStores() {
memberStore.clear();
inviteStore.clear();
userStore.clear();
- projectAccessStore.clear();
memberProjectStore.length = 0;
}
+type OrphanFilter =
+ | { deleteAt: { lte: Date } }
+ | { members: { none: { role: { in: string[] } } } };
+
+function adminRolesIn(filters: OrphanFilter[]): string[] {
+ for (const filter of filters) {
+ if ('members' in filter) {
+ return filter.members.none.role.in;
+ }
+ }
+ return [];
+}
+
const organization = {
findMany: mock(
async ({
@@ -113,7 +115,7 @@ const organization = {
}: {
where?: {
members?: { some: { userId: string } };
- OR?: unknown[];
+ OR?: OrphanFilter[];
deleteAt?: { lte: Date };
};
} = {}) => {
@@ -127,11 +129,12 @@ const organization = {
);
}
if (where?.OR) {
+ const adminRoles = adminRolesIn(where.OR);
rows = rows.filter((org) => {
const scheduledForDeletion =
org.deleteAt && org.deleteAt <= new Date();
const noAdmin = ![...memberStore.values()].some(
- (m) => m.organizationId === org.id && m.role === 'org:admin'
+ (m) => m.organizationId === org.id && adminRoles.includes(m.role)
);
return scheduledForDeletion || noAdmin;
});
@@ -272,10 +275,6 @@ const member = {
...m,
user: userStore.get(m.userId as string),
projects: memberProjectStore.filter((row) => row.memberId === m.id),
- organization: {
- createdByUserId:
- organizationStore.get(m.organizationId)?.createdByUserId ?? null,
- },
}))
),
update: mock(
@@ -388,68 +387,6 @@ const user = {
),
};
-const projectAccess = {
- findMany: mock(async ({ where }: { where: { organizationId: string } }) =>
- [...projectAccessStore.values()].filter(
- (a) => a.organizationId === where.organizationId
- )
- ),
- create: mock(
- async ({
- data,
- }: {
- data: {
- projectId: string;
- userId: string;
- organizationId: string;
- level: string;
- };
- }) => {
- const id = `access_${projectAccessStore.size + 1}`;
- const row = { id, ...data };
- projectAccessStore.set(id, row);
- return row;
- }
- ),
- createMany: mock(
- async ({
- data,
- }: {
- data: {
- projectId: string;
- userId: string;
- organizationId: string;
- level: string;
- }[];
- }) => {
- for (const grant of data) {
- const id = `access_${projectAccessStore.size + 1}`;
- projectAccessStore.set(id, { id, ...grant });
- }
- return { count: data.length };
- }
- ),
- deleteMany: mock(
- async ({
- where,
- }: {
- where: { userId: string; organizationId: string };
- }) => {
- let count = 0;
- for (const [id, row] of projectAccessStore.entries()) {
- if (
- row.userId === where.userId &&
- row.organizationId === where.organizationId
- ) {
- projectAccessStore.delete(id);
- count++;
- }
- }
- return { count };
- }
- ),
-};
-
const memberProject = {
deleteMany: mock(async ({ where }: { where: { memberId: string } }) => {
const remaining = memberProjectStore.filter(
@@ -479,7 +416,6 @@ const deps = {
member,
invite,
user,
- projectAccess,
memberProject,
$transaction,
},
@@ -515,7 +451,7 @@ function seedMemberWithTwoProjects() {
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
});
for (const id of ['proj_1', 'proj_2']) {
@@ -524,7 +460,7 @@ function seedMemberWithTwoProjects() {
}
const EXPECTED_CLEARED_ACCESS_KEYS = [
- 'getOrganizationAccessV2:{"userId":"user_1","organizationId":"org_1"}',
+ 'getOrganizationAccessV3:{"userId":"user_1","organizationId":"org_1"}',
'getProjectAccessV3:{"userId":"user_1","projectId":"proj_1"}',
'getProjectAccessV3:{"userId":"user_1","projectId":"proj_2"}',
];
@@ -647,7 +583,7 @@ test('removeOrganizationMember refuses a user removing themself as the last memb
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:admin',
+ role: 'admin',
});
@@ -662,22 +598,14 @@ test('removeOrganizationMember refuses a user removing themself as the last memb
expect(memberStore.has('member_1')).toBe(true);
});
-test('removeOrganizationMember deletes the member and their project access', async () => {
+test('removeOrganizationMember deletes the member', async () => {
memberStore.set('member_1', {
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
});
- projectAccessStore.set('access_1', {
- id: 'access_1',
- userId: 'user_1',
- organizationId: 'org_1',
- projectId: 'proj_1',
- level: 'write',
- });
-
await subject.removeOrganizationMember(deps, {
organizationId: 'org_1',
memberId: 'member_1',
@@ -686,7 +614,6 @@ test('removeOrganizationMember deletes the member and their project access', asy
});
expect(memberStore.has('member_1')).toBe(false);
- expect(projectAccessStore.has('access_1')).toBe(false);
});
// The lookups cache a granted answer for minutes; without these clears a
@@ -724,7 +651,7 @@ test('connectUserToOrganization drops the cached access for every project of the
id: 'invite_1',
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
createdById: 'user_admin',
projectScope: 'selected',
projectAccess: [{ projectId: 'proj_1', level: 'read' }],
@@ -745,7 +672,7 @@ test('updateOrganizationMemberAccess replaces project access with the given gran
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
});
projectStore.set('proj_new', {
@@ -753,10 +680,8 @@ test('updateOrganizationMemberAccess replaces project access with the given gran
organizationId: 'org_1',
deleteAt: null,
});
- projectAccessStore.set('access_old', {
- id: 'access_old',
- userId: 'user_1',
- organizationId: 'org_1',
+ memberProjectStore.push({
+ memberId: 'member_1',
projectId: 'proj_old',
level: 'read',
});
@@ -768,21 +693,18 @@ test('updateOrganizationMemberAccess replaces project access with the given gran
access: [{ projectId: 'proj_new', level: 'write' }],
});
- const remaining = [...projectAccessStore.values()];
- expect(remaining).toHaveLength(1);
- expect(remaining[0]).toMatchObject({ projectId: 'proj_new', level: 'write' });
expect(memberProjectStore).toEqual([
{ memberId: 'member_1', projectId: 'proj_new', level: null },
]);
expect(memberStore.get('member_1')?.projectScope).toBe('selected');
});
-test('updateOrganizationMemberAccess with scope all clears both tables', async () => {
+test('updateOrganizationMemberAccess with scope all clears the selected projects', async () => {
memberStore.set('member_1', {
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
});
@@ -791,14 +713,6 @@ test('updateOrganizationMemberAccess with scope all clears both tables', async (
projectId: 'proj_old',
level: 'read',
});
- projectAccessStore.set('access_old', {
- id: 'access_old',
- userId: 'user_1',
- organizationId: 'org_1',
- projectId: 'proj_old',
- level: 'read',
- });
-
await subject.updateOrganizationMemberAccess(deps, {
organizationId: 'org_1',
targetUserId: 'user_1',
@@ -807,41 +721,15 @@ test('updateOrganizationMemberAccess with scope all clears both tables', async (
});
expect(memberProjectStore).toHaveLength(0);
- expect(projectAccessStore.size).toBe(0);
expect(memberStore.get('member_1')?.projectScope).toBe('all');
});
-// An old pod accepting a restricted invite mid-deploy leaves the member on the
-// default `all` with only legacy rows; the list must not show "All projects".
-test("getMembers reports legacy grants as the member's selection", async () => {
- memberStore.set('member_1', {
- id: 'member_1',
- organizationId: 'org_1',
- userId: 'user_1',
- role: 'org:member',
- email: '[email protected]',
- projectScope: 'all',
- });
- projectAccessStore.set('access_1', {
- id: 'access_1',
- userId: 'user_1',
- organizationId: 'org_1',
- projectId: 'proj_1',
- level: 'read',
- });
-
- const [member] = await subject.getMembers(deps, 'org_1');
-
- expect(member?.projectScope).toBe('selected');
- expect(member?.projects).toEqual([{ projectId: 'proj_1', level: 'read' }]);
-});
-
test("connectUserToOrganization keeps an existing member's scope and grants", async () => {
memberStore.set('member_1', {
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
projectScope: 'all',
});
@@ -849,7 +737,7 @@ test("connectUserToOrganization keeps an existing member's scope and grants", as
id: 'invite_1',
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
createdById: 'user_admin',
projectScope: 'selected',
projectAccess: [],
@@ -867,38 +755,7 @@ test("connectUserToOrganization keeps an existing member's scope and grants", as
expect(inviteStore.has('invite_1')).toBe(false);
});
-// Invites from before the scope column, or from the previous image during a
-// rolling deploy, default to `all` and carry the restriction only in grants.
-test('connectUserToOrganization treats an invite with grants as selected whatever its stored scope', async () => {
- projectStore.set('proj_1', {
- id: 'proj_1',
- organizationId: 'org_1',
- deleteAt: null,
- });
- inviteStore.set('invite_1', {
- id: 'invite_1',
- email: '[email protected]',
- organizationId: 'org_1',
- role: 'org:member',
- createdById: 'user_admin',
- projectScope: 'all',
- projectAccess: [{ projectId: 'proj_1', level: 'write' }],
- expiresAt: new Date(Date.now() + 60_000),
- createdAt: EPOCH,
- });
-
- const created = await subject.connectUserToOrganization(deps, {
- user: { id: 'user_1', email: '[email protected]' } as never,
- inviteId: 'invite_1',
- });
-
- expect(memberStore.get(created.id)?.projectScope).toBe('selected');
- expect(memberProjectStore).toEqual([
- { memberId: created.id, projectId: 'proj_1', level: null },
- ]);
-});
-
-test('connectUserToOrganization writes the invite grants to both tables, keeping only read as a level', async () => {
+test('connectUserToOrganization writes the invite grants, keeping only read as a level', async () => {
projectStore.set('proj_1', {
id: 'proj_1',
organizationId: 'org_1',
@@ -913,7 +770,7 @@ test('connectUserToOrganization writes the invite grants to both tables, keeping
id: 'invite_1',
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
createdById: 'user_admin',
projectScope: 'selected',
projectAccess: [
@@ -934,12 +791,6 @@ test('connectUserToOrganization writes the invite grants to both tables, keeping
{ memberId: member.id, projectId: 'proj_1', level: 'read' },
{ memberId: member.id, projectId: 'proj_2', level: null },
]);
- expect(
- [...projectAccessStore.values()].map((row) => [row.projectId, row.level])
- ).toEqual([
- ['proj_1', 'read'],
- ['proj_2', 'write'],
- ]);
});
// Guards: access rows must not be written for a user never confirmed as a
@@ -960,7 +811,7 @@ test('updateOrganizationMemberAccess refuses a user who is not a member', async
})
).rejects.toThrow(/not a member/i);
- expect([...projectAccessStore.values()]).toHaveLength(0);
+ expect(memberProjectStore).toHaveLength(0);
});
test('updateOrganizationMemberAccess refuses a project from another organization', async () => {
@@ -968,7 +819,7 @@ test('updateOrganizationMemberAccess refuses a project from another organization
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
});
projectStore.set('proj_elsewhere', {
@@ -986,7 +837,7 @@ test('updateOrganizationMemberAccess refuses a project from another organization
})
).rejects.toThrow(/not in this organization/i);
- expect([...projectAccessStore.values()]).toHaveLength(0);
+ expect(memberProjectStore).toHaveLength(0);
});
test('inviteUserToOrganization refuses when the email is already a member', async () => {
@@ -995,7 +846,7 @@ test('inviteUserToOrganization refuses when the email is already a member', asyn
id: 'member_1',
organizationId: 'org_1',
userId: 'user_1',
- role: 'org:member',
+ role: 'member',
});
@@ -1016,7 +867,7 @@ test('inviteUserToOrganization refuses a duplicate pending invite', async () =>
id: 'invite_1',
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
createdById: 'user_admin',
projectAccess: [],
expiresAt: new Date(Date.now() + 1000),
@@ -1074,7 +925,7 @@ test('revokeInvite deletes the invite row', async () => {
id: 'invite_1',
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
createdById: 'user_admin',
projectAccess: [],
expiresAt: new Date(Date.now() + 1000),
@@ -1102,7 +953,7 @@ test('runDeleteCron sweeps orphaned and scheduled-for-deletion organizations and
id: 'member_paying_admin',
organizationId: 'org_paying',
userId: 'user_1',
- role: 'org:admin',
+ role: 'admin',
});
projectStore.set('proj_orphaned', {
@@ -1132,7 +983,7 @@ test('runDeleteCron is a no-op when nothing is due', async () => {
id: 'member_1',
organizationId: 'org_healthy',
userId: 'user_1',
- role: 'org:admin',
+ role: 'admin',
});
@@ -1141,6 +992,22 @@ test('runDeleteCron is a no-op when nothing is due', async () => {
expect(organizationStore.has('org_healthy')).toBe(true);
});
+// The previous build still writes `org:admin` while a rollout replaces it.
+test('runDeleteCron keeps an organization whose only admin has the old role spelling', async () => {
+ organizationStore.set('org_rollout', makeOrganization({ id: 'org_rollout' }));
+ memberStore.set('member_1', {
+ id: 'member_1',
+ organizationId: 'org_rollout',
+ userId: 'user_1',
+ role: 'org:admin',
+ email: '[email protected]',
+ });
+
+ const result = await subject.runDeleteCron(deps);
+ expect(result).toEqual({ organizations: 0, projects: 0 });
+ expect(organizationStore.has('org_rollout')).toBe(true);
+});
+
test('getSettingsForOrganization falls back to UTC when the stored timezone is unknown', async () => {
organizationStore.set(
'org_1',
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 5ade52a63..2bf3f36c1 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -19,7 +19,6 @@ import { sendEmail } from '../../clients/email';
import { TRPCBadRequestError, TRPCNotFoundError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
import {
- effectiveProjectGrants,
getOrganizationAccess,
getProjectAccess,
} from '../../shared/access-lookups';
@@ -33,9 +32,7 @@ import {
normalizeOrganizationRole,
type OrganizationRole,
type ProjectScope,
- resolveOrganizationRole,
STORED_ADMIN_ROLES,
- toStoredOrganizationRole,
} from './organization.constants';
export type IServiceOrganization = Awaited<
@@ -175,49 +172,27 @@ export async function getMembers(
organizationId: string
): Promise<IServiceMember[]> {
const db = deps.db;
- const [members, legacyGrants] = await Promise.all([
- db.member.findMany({
- where: {
- organizationId,
- userId: {
- not: null,
- },
- },
- include: {
- user: true,
- projects: { select: { projectId: true, level: true } },
- organization: { select: { createdByUserId: true } },
+ const members = await db.member.findMany({
+ where: {
+ organizationId,
+ userId: {
+ not: null,
},
- }),
- db.projectAccess.findMany({
- where: { organizationId },
- select: { userId: true, projectId: true, level: true },
- }),
- ]);
-
- // The same projection the access lookup applies, so the edit modal never
- // starts from "all projects" for a member an old pod restricted.
- return members.map(({ organization, ...member }) => ({
+ },
+ include: {
+ user: true,
+ projects: { select: { projectId: true, level: true } },
+ },
+ });
+ return members.map((member) => ({
...member,
- ...effectiveProjectGrants({
- projectScope: member.projectScope,
- projects: member.projects,
- legacyGrants: legacyGrants.filter(
- (grant) => grant.userId === member.userId
- ),
- }),
- role: resolveOrganizationRole({ ...member, organization }),
+ role: normalizeOrganizationRole(member.role),
}));
}
-/**
- * Write a member's project grants to both tables. `project_access` is the
- * previous build's source of truth and is kept in step for one more build so
- * a rollback changes nobody's access; the next build drops it.
- */
function writeMemberProjects(
deps: ServiceDeps,
- member: { id: string; userId: string; organizationId: string },
+ memberId: string,
projectScope: ProjectScope,
grants: IProjectAccessGrant[]
) {
@@ -225,29 +200,18 @@ function writeMemberProjects(
const selected = projectScope === 'all' ? [] : grants;
return [
db.member.update({
- where: { id: member.id },
+ where: { id: memberId },
data: { projectScope },
}),
- db.memberProject.deleteMany({ where: { memberId: member.id } }),
+ db.memberProject.deleteMany({ where: { memberId } }),
db.memberProject.createMany({
data: selected.map((grant) => ({
- memberId: member.id,
+ memberId,
projectId: grant.projectId,
// Write is what the role gives; only a restriction is worth storing.
level: grant.level === 'read' ? 'read' : null,
})),
}),
- db.projectAccess.deleteMany({
- where: { userId: member.userId, organizationId: member.organizationId },
- }),
- db.projectAccess.createMany({
- data: selected.map((grant) => ({
- userId: member.userId,
- organizationId: member.organizationId,
- projectId: grant.projectId,
- level: grant.level,
- })),
- }),
];
}
@@ -306,10 +270,7 @@ export async function connectUserToOrganization(
throw new Error('Invite expired');
}
- // Invites written before the scope column, or by the previous image during
- // a rolling deploy, carry their restriction only in `projectAccess`.
- const projectScope: ProjectScope =
- invite.projectAccess.length > 0 ? 'selected' : invite.projectScope;
+ const { projectScope } = invite;
const existing = await db.member.findUnique({
where: {
@@ -345,16 +306,7 @@ export async function connectUserToOrganization(
if (!existing) {
await db.$transaction(
- writeMemberProjects(
- deps,
- {
- id: member.id,
- userId: user.id,
- organizationId: invite.organizationId,
- },
- projectScope,
- invite.projectAccess
- )
+ writeMemberProjects(deps, member.id, projectScope, invite.projectAccess)
);
}
@@ -752,7 +704,7 @@ export async function runDeleteCron(
where: {
OR: [
{ deleteAt: { lte: now } },
- { members: { none: { role: { in: [...STORED_ADMIN_ROLES] } } } },
+ { members: { none: { role: { in: STORED_ADMIN_ROLES } } } },
],
},
include: { projects: { select: { id: true } } },
@@ -947,7 +899,7 @@ export async function inviteUserToOrganization(
id: generateSecureId('invite'),
email,
organizationId: input.organizationId,
- role: toStoredOrganizationRole(input.role),
+ role: input.role,
createdById: input.invitedById,
projectScope: input.projectScope,
projectAccess: access,
@@ -1033,21 +985,13 @@ export async function removeOrganizationMember(
throw new Error('You cannot remove yourself from the organization');
}
- await db.$transaction([
- db.member.delete({
- where: {
- id: input.memberId,
- userId: input.targetUserId,
- organizationId: input.organizationId,
- },
- }),
- db.projectAccess.deleteMany({
- where: {
- userId: input.targetUserId,
- organizationId: input.organizationId,
- },
- }),
- ]);
+ await db.member.delete({
+ where: {
+ id: input.memberId,
+ userId: input.targetUserId,
+ organizationId: input.organizationId,
+ },
+ });
await clearMemberAccessCache(deps, {
userId: input.targetUserId,
organizationId: input.organizationId,
@@ -1056,8 +1000,8 @@ export async function removeOrganizationMember(
/**
* A grant may only name a project inside the organization it is granted in.
- * Without this an admin of one organization could write projectAccess rows
- * pointing at another organization's projects.
+ * Without this an admin of one organization could grant access to another
+ * organization's projects.
*/
async function assertProjectsInOrganization(
deps: ServiceDeps,
@@ -1108,16 +1052,7 @@ export async function updateOrganizationMemberAccess(
await assertProjectsInOrganization(deps, input.organizationId, access);
await db.$transaction(
- writeMemberProjects(
- deps,
- {
- id: member.id,
- userId: input.targetUserId,
- organizationId: input.organizationId,
- },
- input.projectScope,
- access
- )
+ writeMemberProjects(deps, member.id, input.projectScope, access)
);
await clearMemberAccessCache(deps, {
userId: input.targetUserId,
diff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.ts
index 35d55f496..81fc6054d 100644
--- a/packages/core/src/modules/realtime/realtime.routes.test.ts
+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts
@@ -294,7 +294,7 @@ test('wsOrganizationEvents: session but no org access -> "No access" then close'
test('wsOrganizationEvents: subscribes scoped to the organization the caller is a member of', async () => {
session = { userId: 'user_1' };
organizationAccess = {
- role: 'org:member',
+ role: 'member',
userId: 'user_1',
organization: { createdByUserId: null },
};
diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.ts
index 0cc98a5c2..4c6083ece 100644
--- a/packages/core/src/modules/session/src/usage.ts
+++ b/packages/core/src/modules/session/src/usage.ts
@@ -149,7 +149,7 @@ async function sendUsageAlerts(
const admins = await db.member.findMany({
where: {
organizationId: organization.id,
- role: { in: [...STORED_ADMIN_ROLES] },
+ role: { in: STORED_ADMIN_ROLES },
user: { deletedAt: null },
},
include: { user: { select: { email: true, firstName: true } } },
diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.ts
index e7e7c9b03..e694f1d8a 100644
--- a/packages/core/src/modules/user/user.service.ts
+++ b/packages/core/src/modules/user/user.service.ts
@@ -84,7 +84,7 @@ export async function listUserDeletionBlockers(
/**
* Hard delete the user. Cascades clean up sessions, accounts, totp,
- * twoFactorChallenges, members, projectAccess, invites and conversations.
+ * twoFactorChallenges, members, invites and conversations.
* Organizations the user created have `createdByUserId`/`subscriptionCreatedByUserId`
* set to null (SetNull); any org left without an admin member is then
* removed by the organization module's `delete` cron.
@@ -106,6 +106,14 @@ export async function deleteUserAccount(
await deps.db.user.delete({ where: { id: userId } });
}
+/** better-auth's `name`, kept in step with the first and last name. */
+export function toDisplayName(
+ firstName: string | null | undefined,
+ lastName: string | null | undefined
+): string {
+ return [firstName?.trim(), lastName?.trim()].filter(Boolean).join(' ');
+}
+
export async function updateUserProfile(
deps: ServiceDeps,
input: {
@@ -121,6 +129,7 @@ export async function updateUserProfile(
data: {
firstName: input.firstName,
lastName: input.lastName,
+ name: toDisplayName(input.firstName, input.lastName),
},
});
}
diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts
index d59f54c09..835805254 100644
--- a/packages/core/src/services.ts
+++ b/packages/core/src/services.ts
@@ -49,6 +49,7 @@ export type ServiceDeps = Pick<
| 'logger'
| 'queues'
| 'config'
+ | 'auth'
>;
// `Services` must stay an INTERFACE: a type alias over
diff --git a/packages/core/src/shared/access-lookups.test.ts b/packages/core/src/shared/access-lookups.test.ts
index 9dd594f33..fea659f54 100644
--- a/packages/core/src/shared/access-lookups.test.ts
+++ b/packages/core/src/shared/access-lookups.test.ts
@@ -5,13 +5,12 @@
import { expect, test } from 'bun:test';
import type { Db } from '../context';
import {
- effectiveProjectGrants,
listProjectMemberEmails,
resolveProjectAccess,
} from './access-lookups';
test('scope all follows the role: write for members and admins, read for viewers', () => {
- for (const role of ['org:admin', 'org:member', 'admin', 'member', 'owner']) {
+ for (const role of ['admin', 'member', 'owner']) {
expect(
resolveProjectAccess({ role, projectScope: 'all', grant: null })
).toEqual({ level: 'write' });
@@ -22,7 +21,7 @@ test('scope all follows the role: write for members and admins, read for viewers
});
test('scope selected without a row is no access, whatever the role', () => {
- for (const role of ['org:admin', 'owner', 'member', 'viewer']) {
+ for (const role of ['admin', 'owner', 'member', 'viewer']) {
expect(
resolveProjectAccess({ role, projectScope: 'selected', grant: null })
).toBeNull();
@@ -32,14 +31,14 @@ test('scope selected without a row is no access, whatever the role', () => {
test('a selected row derives write from the role unless it restricts to read', () => {
expect(
resolveProjectAccess({
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
grant: { level: null },
})
).toEqual({ level: 'write' });
expect(
resolveProjectAccess({
- role: 'org:member',
+ role: 'member',
projectScope: 'selected',
grant: { level: 'read' },
})
@@ -76,7 +75,7 @@ function migrated(
) {
const grant = rows.find((item) => item.projectId === projectId);
return resolveProjectAccess({
- role: 'org:member',
+ role: 'member',
projectScope: rows.length === 0 ? 'all' : 'selected',
grant: grant ? { level: grant.level === 'read' ? 'read' : null } : null,
});
@@ -106,66 +105,11 @@ test('the migrated shape gives the same verdict as the legacy rule for every row
}
});
-test('legacy rows written by the previous image override a stale all scope', () => {
- expect(
- effectiveProjectGrants({
- projectScope: 'all',
- projects: [],
- legacyGrants: [
- { projectId: 'a', level: 'read' },
- { projectId: 'b', level: 'write' },
- ],
- })
- ).toEqual({
- projectScope: 'selected',
- projects: [
- { projectId: 'a', level: 'read' },
- { projectId: 'b', level: null },
- ],
- });
-});
-
-test('without legacy rows the member scope and rows apply as stored', () => {
- const member = {
- projectScope: 'selected' as const,
- projects: [{ projectId: 'a', level: null }],
- legacyGrants: [],
- };
- expect(effectiveProjectGrants(member)).toEqual({
- projectScope: 'selected',
- projects: [{ projectId: 'a', level: null }],
- });
-});
-
-test('duplicate legacy rows for one project keep the read restriction', () => {
- for (const legacyGrants of [
- [
- { projectId: 'a', level: 'write' as const },
- { projectId: 'a', level: 'read' as const },
- ],
- [
- { projectId: 'a', level: 'read' as const },
- { projectId: 'a', level: 'admin' as const },
- ],
- ]) {
- expect(
- effectiveProjectGrants({
- projectScope: 'all',
- projects: [],
- legacyGrants,
- })
- ).toEqual({
- projectScope: 'selected',
- projects: [{ projectId: 'a', level: 'read' }],
- });
- }
-});
-
test('listProjectMemberEmails mails all-scope members and selected members with a row, nobody else', async () => {
const members = [
{
userId: 'u_all',
- role: 'org:member',
+ role: 'member',
projectScope: 'all',
projects: [],
user: { email: '[email protected]' },
@@ -179,30 +123,19 @@ test('listProjectMemberEmails mails all-scope members and selected members with
},
{
userId: 'u_other',
- role: 'org:admin',
+ role: 'admin',
projectScope: 'selected',
projects: [{ projectId: 'p2', level: null }],
user: { email: '[email protected]' },
},
- {
- userId: 'u_legacy',
- role: 'org:member',
- projectScope: 'all',
- projects: [],
- user: { email: '[email protected]' },
- },
{
userId: 'u_dup',
- role: 'org:member',
+ role: 'member',
projectScope: 'all',
projects: [],
user: { email: '[email protected]' },
},
];
- // A project_access row written by the previous image restricts u_legacy to p2.
- const legacyGrants = [
- { userId: 'u_legacy', projectId: 'p2', level: 'write' },
- ];
const memberWhere: unknown[] = [];
const db = {
member: {
@@ -211,7 +144,6 @@ test('listProjectMemberEmails mails all-scope members and selected members with
return members;
},
},
- projectAccess: { findMany: async () => legacyGrants },
} as unknown as Db;
const emails = await listProjectMemberEmails(db, {
diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.ts
index 77268e546..3f81cf19c 100644
--- a/packages/core/src/shared/access-lookups.ts
+++ b/packages/core/src/shared/access-lookups.ts
@@ -74,36 +74,8 @@ interface MemberGrant {
level: AccessLevel | null;
}
-/**
- * The scope and grants to apply for a member while `project_access` is still
- * written. New code keeps that table identical to `member_projects` (empty for
- * `all`), so legacy rows only differ when the previous image wrote them during
- * a rolling deploy; they then win, or an old pod restricting a member would
- * leave them on `all`. Remove with `project_access`.
- */
-export function effectiveProjectGrants(member: {
- projectScope: ProjectScope;
- projects: MemberGrant[];
- legacyGrants: { projectId: string; level: AccessLevel }[];
-}): { projectScope: ProjectScope; projects: MemberGrant[] } {
- if (member.legacyGrants.length === 0) {
- return { projectScope: member.projectScope, projects: member.projects };
- }
- // project_access has no unique key; a read row among duplicates wins.
- const levels = new Map<string, AccessLevel | null>();
- for (const grant of member.legacyGrants) {
- const isRead =
- grant.level === 'read' || levels.get(grant.projectId) === 'read';
- levels.set(grant.projectId, isRead ? 'read' : null);
- }
- return {
- projectScope: 'selected',
- projects: [...levels].map(([projectId, level]) => ({ projectId, level })),
- };
-}
-
-/** Loads what `effectiveProjectGrants` needs for one membership, or null when there is none. */
-export async function getMemberProjectGrants(
+/** One membership's role, scope and selected projects, or null when there is none. */
+export function getMemberProjectGrants(
db: Db,
{ userId, organizationId }: { userId: string; organizationId: string }
): Promise<{
@@ -111,27 +83,14 @@ export async function getMemberProjectGrants(
projectScope: ProjectScope;
projects: MemberGrant[];
} | null> {
- const [member, legacyGrants] = await Promise.all([
- db.member.findFirst({
- where: { organizationId, userId },
- select: {
- role: true,
- projectScope: true,
- projects: { select: { projectId: true, level: true } },
- },
- }),
- db.projectAccess.findMany({
- where: { organizationId, userId },
- select: { projectId: true, level: true },
- }),
- ]);
- if (!member) {
- return null;
- }
- return {
- role: member.role,
- ...effectiveProjectGrants({ ...member, legacyGrants }),
- };
+ return db.member.findFirst({
+ where: { organizationId, userId },
+ select: {
+ role: true,
+ projectScope: true,
+ projects: { select: { projectId: true, level: true } },
+ },
+ });
}
/**
@@ -144,32 +103,15 @@ export async function listProjectMemberEmails(
db: Db,
{ organizationId, projectId }: { organizationId: string; projectId: string }
): Promise<string[]> {
- const [members, legacyGrants] = await Promise.all([
- db.member.findMany({
- where: { organizationId, user: { deletedAt: null } },
- select: {
- userId: true,
- role: true,
- projectScope: true,
- projects: { select: { projectId: true, level: true } },
- user: { select: { email: true } },
- },
- }),
- db.projectAccess.findMany({
- where: { organizationId },
- select: { userId: true, projectId: true, level: true },
- }),
- ]);
-
- const legacyByUser = new Map<
- string,
- { projectId: string; level: AccessLevel }[]
- >();
- for (const grant of legacyGrants) {
- const grants = legacyByUser.get(grant.userId) ?? [];
- grants.push(grant);
- legacyByUser.set(grant.userId, grants);
- }
+ const members = await db.member.findMany({
+ where: { organizationId, user: { deletedAt: null } },
+ select: {
+ role: true,
+ projectScope: true,
+ projects: { select: { projectId: true, level: true } },
+ user: { select: { email: true } },
+ },
+ });
const emails = new Set<string>();
for (const member of members) {
@@ -177,16 +119,10 @@ export async function listProjectMemberEmails(
if (!email) {
continue;
}
- const grants = effectiveProjectGrants({
- ...member,
- legacyGrants: member.userId
- ? (legacyByUser.get(member.userId) ?? [])
- : [],
- });
const access = resolveProjectAccess({
role: member.role,
- projectScope: grants.projectScope,
- grant: grants.projects.find((row) => row.projectId === projectId) ?? null,
+ projectScope: member.projectScope,
+ grant: member.projects.find((row) => row.projectId === projectId) ?? null,
});
if (access) {
emails.add(email);
@@ -244,13 +180,11 @@ export const getProjectAccess = cacheable(
60 * 5
);
-/** The membership row plus what the auth module needs to derive the owner role. */
-export type IOrganizationAccess = Member & {
- organization: { createdByUserId: string | null };
-};
+export type IOrganizationAccess = Member;
+// V3: roles are stored under their new names, and V2 entries carry the old ones.
export const getOrganizationAccess = cacheable(
- 'getOrganizationAccessV2',
+ 'getOrganizationAccessV3',
async ({
userId,
organizationId,
@@ -264,7 +198,6 @@ export const getOrganizationAccess = cacheable(
userId,
organizationId,
},
- include: { organization: { select: { createdByUserId: true } } },
});
},
60 * 5
diff --git a/packages/core/test/config-fixture.ts b/packages/core/test/config-fixture.ts
index 14c7c8586..aacba0dd0 100644
--- a/packages/core/test/config-fixture.ts
+++ b/packages/core/test/config-fixture.ts
@@ -28,6 +28,7 @@ export function testCoreConfig(
interceptProcessOutput: false,
},
auth: {
+ secret: undefined,
allowRegistration: undefined,
allowInvitation: undefined,
github: { clientId: '', clientSecret: '', redirectUri: '' },
diff --git a/packages/core/test/exports-map.test.ts b/packages/core/test/exports-map.test.ts
index 330462407..0fe2afbcd 100644
--- a/packages/core/test/exports-map.test.ts
+++ b/packages/core/test/exports-map.test.ts
@@ -1,4 +1,5 @@
import { expect, test } from 'bun:test';
+import { TEST_CLICKHOUSE_URL } from '../../../test/databases';
// The exports map is the only structural barrier between apps/start and a
// service. Widening it is silent, so it is asserted here.
@@ -13,7 +14,8 @@ test('a non-exported internal path does not resolve', async () => {
});
test('preload pins infrastructure at local addresses', () => {
- expect(process.env.CLICKHOUSE_URL).toBe(
+ expect(process.env.CLICKHOUSE_URL).toBe(TEST_CLICKHOUSE_URL);
+ expect(process.env.CLICKHOUSE_URL).toStartWith(
'http://localhost:23123/openpanel_test'
);
expect(process.env.SELF_HOSTED).toBe('true');
diff --git a/packages/core/test/http-fixtures.ts b/packages/core/test/http-fixtures.ts
index a7773ce3f..1798c48fe 100644
--- a/packages/core/test/http-fixtures.ts
+++ b/packages/core/test/http-fixtures.ts
@@ -38,6 +38,7 @@ export function stubAppDeps(): AppDepsStub {
scopeCalls: () => scopeCalls,
childCalls: () => childCalls,
deps: {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
diff --git a/packages/core/test/preload.ts b/packages/core/test/preload.ts
index b0d2d7056..250cb6640 100644
--- a/packages/core/test/preload.ts
+++ b/packages/core/test/preload.ts
@@ -3,12 +3,16 @@
// idempotent and cheap.
//
// The pins below are a safety property: a test must not reach a real database
-// because someone's .env happened to be loaded. Kept in step with
-// test/databases.ts by hand.
-process.env.DATABASE_URL =
- 'postgresql://postgres:postgres@localhost:23432/openpanel_test?schema=public';
-process.env.CLICKHOUSE_URL = 'http://localhost:23123/openpanel_test';
-process.env.REDIS_URL = 'redis://localhost:23379';
+// because someone's .env happened to be loaded.
+import {
+ TEST_CLICKHOUSE_URL,
+ TEST_DATABASE_URL,
+ TEST_REDIS_URL,
+} from '../../../test/databases';
+
+process.env.DATABASE_URL = TEST_DATABASE_URL;
+process.env.CLICKHOUSE_URL = TEST_CLICKHOUSE_URL;
+process.env.REDIS_URL = TEST_REDIS_URL;
process.env.SELF_HOSTED = 'true';
// Unsubscribe links are HMAC-signed with no default secret, so a test that
// exercises one needs a key.
diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.ts
index a5f36c9a4..406145372 100644
--- a/packages/core/test/request-id-end-to-end.test.ts
+++ b/packages/core/test/request-id-end-to-end.test.ts
@@ -147,6 +147,7 @@ function stubDeps() {
const lines: CapturedLine[] = [];
const deps: AppDeps = {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
@@ -321,6 +322,7 @@ function chartDeps() {
const lines: ChartLine[] = [];
const producers = createRecordingProducers({});
const deps: AppDeps = {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: chartClickHouse(),
@@ -506,6 +508,7 @@ function ingestDeps() {
} as unknown as Buffers;
const deps: AppDeps = {
+ auth: null,
prisma: {} as AppDeps['prisma'],
db: {
project: {
@@ -709,6 +712,7 @@ function chainDeps() {
} as unknown as AppDeps['ch'];
const deps: AppDeps = {
+ auth: null,
db: {
cohort: {
findUnique: () =>
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index 6530813a2..37aa757ed 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -53,14 +53,20 @@ const TEST_EPOCH = new Date('2026-09-03T00:00:00.000Z');
export const TEST_SESSION: Session = {
session: {
id: 'sess_1',
+ token: null,
userId: 'user_1',
createdAt: TEST_EPOCH,
updatedAt: TEST_EPOCH,
expiresAt: TEST_EPOCH,
+ ipAddress: null,
+ userAgent: null,
},
user: {
id: 'user_1',
+ name: null,
+ emailVerified: false,
+ image: null,
firstName: null,
lastName: null,
createdAt: TEST_EPOCH,
@@ -87,6 +93,7 @@ export function stubHttpCtx(
const stub = { sessionCalls: 0 };
const deps: AppDeps = {
+ auth: null,
db: {} as AppDeps['db'],
prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
@@ -143,7 +150,7 @@ export function servicesWithProjectAccess(): Services {
return {
auth: {
requireProjectAccess: () => Promise.resolve({ level: 'write' }),
- getOrganizationAccess: () => Promise.resolve({ role: 'org:admin' }),
+ getOrganizationAccess: () => Promise.resolve({ role: 'admin' }),
},
} as unknown as Services;
}
diff --git a/packages/core/test/service-deps.ts b/packages/core/test/service-deps.ts
index d21dc6061..caab326d5 100644
--- a/packages/core/test/service-deps.ts
+++ b/packages/core/test/service-deps.ts
@@ -57,6 +57,7 @@ export async function testServiceDeps(
redis,
logger: recordingLogger(),
config: testCoreConfig(),
+ auth: null,
get clients(): never {
return unavailable('ServiceDeps.clients');
},
diff --git a/packages/db/prisma/migrations/20261023130000_better_auth_tables_drop_project_access/migration.sql b/packages/db/prisma/migrations/20261023130000_better_auth_tables_drop_project_access/migration.sql
new file mode 100644
index 000000000..8df505fd1
--- /dev/null
+++ b/packages/db/prisma/migrations/20261023130000_better_auth_tables_drop_project_access/migration.sql
@@ -0,0 +1,65 @@
+-- AlterTable
+ALTER TABLE "public"."accounts" ADD COLUMN "accountId" TEXT,
+ADD COLUMN "idToken" TEXT;
+
+-- AlterTable
+ALTER TABLE "public"."sessions" ADD COLUMN "ipAddress" TEXT,
+ADD COLUMN "token" TEXT,
+ADD COLUMN "userAgent" TEXT;
+
+-- AlterTable
+ALTER TABLE "public"."users" ADD COLUMN "emailVerified" BOOLEAN NOT NULL DEFAULT false,
+ADD COLUMN "image" TEXT,
+ADD COLUMN "name" TEXT;
+
+-- CreateTable
+CREATE TABLE "public"."verifications" (
+ "id" TEXT NOT NULL,
+ "identifier" TEXT NOT NULL,
+ "value" TEXT NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "verifications_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "verifications_identifier_idx" ON "public"."verifications"("identifier");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "sessions_token_key" ON "public"."sessions"("token");
+
+-- Fold project_access into member_projects the way the previous build read
+-- them: a member with project_access rows has exactly those projects, read
+-- where any duplicate row says read. The previous build kept both tables in
+-- step, so this only matters for grants written by older pods mid-deploy.
+-- Done here because code migrations run after this file drops the table.
+CREATE TEMPORARY TABLE "legacy_grants" AS
+SELECT m.id AS "memberId", pa."projectId",
+ CASE WHEN bool_or(pa.level = 'read') THEN 'read'::"public"."AccessLevel" END AS "level"
+FROM "public"."project_access" pa
+JOIN "public"."members" m
+ ON m."userId" = pa."userId"
+ AND m."organizationId" = pa."organizationId"
+GROUP BY m.id, pa."projectId";
+
+UPDATE "public"."members"
+SET "projectScope" = 'selected'
+WHERE id IN (SELECT "memberId" FROM "legacy_grants");
+
+DELETE FROM "public"."member_projects" mp
+WHERE mp."memberId" IN (SELECT "memberId" FROM "legacy_grants")
+ AND NOT EXISTS (
+ SELECT 1 FROM "legacy_grants" lg
+ WHERE lg."memberId" = mp."memberId" AND lg."projectId" = mp."projectId"
+ );
+
+INSERT INTO "public"."member_projects" ("memberId", "projectId", "level")
+SELECT "memberId", "projectId", "level" FROM "legacy_grants"
+ON CONFLICT ("memberId", "projectId") DO UPDATE SET "level" = EXCLUDED."level";
+
+-- DropTable
+DROP TABLE "public"."project_access";
+
+DROP TABLE "legacy_grants";
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index b5860f969..9231fa65a 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -77,7 +77,6 @@ model Organization {
members Member[]
createdByUserId String?
createdBy User? @relation(name: "organizationCreatedBy", fields: [createdByUserId], references: [id], onDelete: SetNull)
- ProjectAccess ProjectAccess[]
Client Client[]
Dashboard Dashboard[]
ShareOverview ShareOverview[]
@@ -150,6 +149,10 @@ model User {
email String @unique
firstName String?
lastName String?
+ // better-auth's user fields, backfilled from the ones above and the IdP.
+ name String?
+ emailVerified Boolean @default(false)
+ image String?
createdOrganizations Organization[] @relation("organizationCreatedBy")
subscriptions Organization[] @relation("subscriptionCreatedBy")
membership Member[]
@@ -157,7 +160,6 @@ model User {
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
deletedAt DateTime?
- ProjectAccess ProjectAccess[]
sessions Session[]
accounts Account[]
invites Invite[]
@@ -197,8 +199,12 @@ model Account {
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
email String?
+ // better-auth's `providerId` ('credential', 'google', 'github').
provider String
+ // The IdP's user id, read by the legacy OAuth callback. better-auth reads `accountId`.
providerId String?
+ accountId String?
+ idToken String?
accessToken String?
refreshToken String?
accessTokenExpiresAt DateTime?
@@ -214,8 +220,13 @@ model Account {
model Session {
id String @id
+ // What better-auth looks a session up by. A legacy row is keyed by the hash of
+ // its cookie and gets one when its first request upgrades it.
+ token String? @unique
userId String
expiresAt DateTime
+ ipAddress String?
+ userAgent String?
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
user User @relation(references: [id], fields: [userId], onDelete: Cascade)
@@ -223,6 +234,18 @@ model Session {
@@map("sessions")
}
+model Verification {
+ id String @id
+ identifier String
+ value String
+ expiresAt DateTime
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ @@index([identifier])
+ @@map("verifications")
+}
+
model Member {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
role String
@@ -315,7 +338,6 @@ model Project {
meta EventMeta[]
customEvents CustomEvent[]
references Reference[]
- access ProjectAccess[]
memberProjects MemberProject[]
notificationRules NotificationRule[]
notifications Notification[]
@@ -359,21 +381,6 @@ enum AccessLevel {
admin
}
-model ProjectAccess {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
- projectId String
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
- organizationId String
- userId String
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- level AccessLevel
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
-
- @@map("project_access")
-}
-
model Salt {
salt String @id
createdAt DateTime @default(now())
@@ -597,12 +604,12 @@ model EventMeta {
}
model CustomEvent {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
/// [IPrismaCustomEventItems]
items Json
projectId String
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
diff --git a/packages/db/scripts/access-snapshot.ts b/packages/db/scripts/access-snapshot.ts
index 81899670e..248f74102 100644
--- a/packages/db/scripts/access-snapshot.ts
+++ b/packages/db/scripts/access-snapshot.ts
@@ -6,13 +6,11 @@
// bun run --filter @openpanel/db access-snapshot --evaluator current > after.json
// bun run --filter @openpanel/db access-snapshot --diff before.json after.json [--expect keys.json]
//
-// `legacy` is the rule the previous build applied, spelled out here from its
-// tables (`project_access`, `members.role`), so it keeps answering after the
-// app has moved on. `current` goes through core's public lookups, the same
-// code every procedure calls, with each cache entry cleared first.
-//
-// Both tables are kept in step for one build, so both evaluators can run on
-// the same database and must agree.
+// `legacy` is the rule the previous build applied, spelled out here so it
+// keeps answering after the app has moved on: both role spellings, scope and
+// `member_projects`. Run it before a migration and `current` after. `current`
+// goes through core's public lookups, the same code every procedure calls,
+// with each cache entry cleared first.
import {
canWriteProject,
@@ -21,7 +19,7 @@ import {
} from '@openpanel/core';
import {
isOrganizationAdminRole,
- resolveOrganizationRole,
+ normalizeOrganizationRole,
} from '@openpanel/core/modules/organization/organization.constants';
import { db } from '../src/prisma-client';
@@ -34,8 +32,8 @@ interface AccessLine {
orgAdmin: boolean;
}
-const LEGACY_ADMIN_ROLE = 'org:admin';
-const LEGACY_WRITE_LEVELS = new Set(['write', 'admin']);
+const LEGACY_ADMIN_ROLES = new Set(['org:admin', 'admin', 'owner']);
+const LEGACY_READ_ONLY_ROLE = 'viewer';
function lineKey(line: AccessLine): string {
return `${line.organizationId}|${line.userId}|${line.projectId}`;
@@ -52,6 +50,8 @@ async function loadMembers() {
userId: true,
organizationId: true,
role: true,
+ projectScope: true,
+ projects: { select: { projectId: true, level: true } },
organization: {
select: { projects: { select: { id: true } } },
},
@@ -60,37 +60,20 @@ async function loadMembers() {
}
async function legacySnapshot(): Promise<AccessLine[]> {
- const [members, grants] = await Promise.all([
- loadMembers(),
- db.projectAccess.findMany({
- select: {
- userId: true,
- organizationId: true,
- projectId: true,
- level: true,
- },
- }),
- ]);
- const grantsByMember = new Map<string, typeof grants>();
- for (const grant of grants) {
- const key = `${grant.organizationId}|${grant.userId}`;
- grantsByMember.set(key, [...(grantsByMember.get(key) ?? []), grant]);
- }
-
+ const members = await loadMembers();
const lines: AccessLine[] = [];
for (const member of members) {
- const userId = member.userId as string;
- const rows = grantsByMember.get(`${member.organizationId}|${userId}`) ?? [];
- const orgAdmin = member.role === LEGACY_ADMIN_ROLE;
+ const isReadOnly = member.role === LEGACY_READ_ONLY_ROLE;
+ const orgAdmin = LEGACY_ADMIN_ROLES.has(member.role);
for (const project of member.organization.projects) {
- const row = rows.find((grant) => grant.projectId === project.id);
- const level = rows.length === 0 ? 'write' : row?.level;
+ const grant = member.projects.find((row) => row.projectId === project.id);
+ const read = member.projectScope === 'all' || grant !== undefined;
lines.push({
organizationId: member.organizationId,
- userId,
+ userId: member.userId as string,
projectId: project.id,
- read: level !== undefined,
- write: level !== undefined && LEGACY_WRITE_LEVELS.has(level),
+ read,
+ write: read && !isReadOnly && grant?.level !== 'read',
orgAdmin,
});
}
@@ -111,7 +94,9 @@ async function currentSnapshot(): Promise<AccessLine[]> {
});
const orgAdmin =
!!organizationAccess &&
- isOrganizationAdminRole(resolveOrganizationRole(organizationAccess));
+ isOrganizationAdminRole(
+ normalizeOrganizationRole(organizationAccess.role)
+ );
for (const project of member.organization.projects) {
await getProjectAccess.clear({ userId, projectId: project.id });
const access = await getProjectAccess({ userId, projectId: project.id });
diff --git a/packages/db/src/code-migrations/26-member-project-scope.ts b/packages/db/src/code-migrations/26-member-project-scope.ts
index 10aa6cc05..0a2e7b064 100644
--- a/packages/db/src/code-migrations/26-member-project-scope.ts
+++ b/packages/db/src/code-migrations/26-member-project-scope.ts
@@ -24,6 +24,10 @@ import { getIsDry, printBoxMessage } from './helpers';
* restricted and becomes `selected`. `project_access` rows with no membership
* are reported and left alone: they never granted access, so making them
* memberships would.
+ *
+ * An install that upgrades past the next build gets `project_access` folded in
+ * and dropped by that build's Prisma migration before this runs, so only the
+ * invite and slug steps are left to do.
*/
interface Count {
@@ -103,6 +107,20 @@ async function countGrantsWithoutMembership(): Promise<number> {
return Number(rows[0]?.count ?? 0);
}
+async function hasProjectAccessTable(): Promise<boolean> {
+ const rows = await db.$queryRaw<{ exists: boolean }[]>`
+ SELECT to_regclass('public.project_access') IS NOT NULL AS exists
+ `;
+ return rows[0]?.exists ?? false;
+}
+
+async function countGrants(): Promise<number> {
+ const rows = await db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM project_access
+ `;
+ return Number(rows[0]?.count ?? 0);
+}
+
async function countOrganizationsWithoutSlug(): Promise<number> {
return db.organization.count({ where: { slug: null } });
}
@@ -115,13 +133,14 @@ function backfillSlugs() {
export async function up() {
const isDry = getIsDry();
+ const hasGrants = await hasProjectAccessTable();
const [membersToScope, grantsToCopy, invitesToScope, orphanGrants] =
await Promise.all([
- countMembersToScope(),
- db.projectAccess.count(),
+ hasGrants ? countMembersToScope() : 0,
+ hasGrants ? countGrants() : 0,
countInvitesToScope(),
- countGrantsWithoutMembership(),
+ hasGrants ? countGrantsWithoutMembership() : 0,
]);
const orphanLine = `project_access rows without a membership, left as is: ${orphanGrants}`;
@@ -137,11 +156,10 @@ export async function up() {
return;
}
- const [scoped, copied, invitesScoped] = await db.$transaction([
- scopeMembers(),
- copyGrants(),
- scopeInvites(),
- ]);
+ const [scoped, copied] = hasGrants
+ ? await db.$transaction([scopeMembers(), copyGrants()])
+ : [0, 0];
+ const invitesScoped = await scopeInvites();
const slugs = await backfillSlugs();
printBoxMessage('✅ Member project scope', [
diff --git a/packages/db/src/code-migrations/29-better-auth-backfill.test.ts b/packages/db/src/code-migrations/29-better-auth-backfill.test.ts
new file mode 100644
index 000000000..19ecbcc7e
--- /dev/null
+++ b/packages/db/src/code-migrations/29-better-auth-backfill.test.ts
@@ -0,0 +1,280 @@
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
+import { db } from '../prisma-client';
+import { up } from './29-better-auth-backfill';
+
+const PREFIX = 'm29';
+const ORG_ID = `${PREFIX}-org`;
+const OTHER_ORG_ID = `${PREFIX}-other-org`;
+
+const id = (name: string) => `${PREFIX}-${name}`;
+const OLDER = new Date('2024-01-01T00:00:00Z');
+const NEWER = new Date('2024-06-01T00:00:00Z');
+
+async function cleanUp() {
+ await db.organization.deleteMany({
+ where: { id: { in: [ORG_ID, OTHER_ORG_ID] } },
+ });
+ await db.user.deleteMany({ where: { id: { startsWith: `${PREFIX}-` } } });
+}
+
+async function seed() {
+ await db.user.createMany({
+ data: [
+ {
+ id: id('creator'),
+ email: 'm29-creator@test',
+ firstName: ' Ada ',
+ lastName: 'Lovelace ',
+ },
+ {
+ id: id('admin'),
+ email: 'm29-admin@test',
+ firstName: 'Grace',
+ lastName: null,
+ },
+ {
+ id: id('member'),
+ email: 'm29-member@test',
+ firstName: null,
+ lastName: null,
+ },
+ {
+ id: id('demoted-creator'),
+ email: 'm29-demoted@test',
+ firstName: '',
+ lastName: 'Hopper',
+ },
+ { id: id('github'), email: 'm29-github@test' },
+ { id: id('google-dup'), email: 'm29-google-dup@test' },
+ { id: id('imported'), email: 'm29-imported@test' },
+ { id: id('shared-a'), email: 'm29-shared-a@test' },
+ { id: id('shared-b'), email: 'm29-shared-b@test' },
+ ],
+ });
+ await db.account.createMany({
+ data: [
+ {
+ id: id('acc-email'),
+ userId: id('creator'),
+ provider: 'email',
+ password: 'hash',
+ },
+ {
+ id: id('acc-google'),
+ userId: id('admin'),
+ provider: 'google',
+ providerId: 'g-1',
+ },
+ {
+ id: id('acc-github'),
+ userId: id('github'),
+ provider: 'github',
+ providerId: 'gh-1',
+ createdAt: OLDER,
+ },
+ {
+ id: id('acc-github-dup'),
+ userId: id('github'),
+ provider: 'github',
+ providerId: 'gh-1',
+ createdAt: NEWER,
+ },
+ {
+ id: id('acc-google-no-email'),
+ userId: id('google-dup'),
+ provider: 'google',
+ providerId: 'g-dup',
+ createdAt: OLDER,
+ },
+ {
+ id: id('acc-google-with-email'),
+ userId: id('google-dup'),
+ provider: 'google',
+ providerId: 'g-dup',
+ email: 'm29-google-dup@test',
+ createdAt: NEWER,
+ },
+ { id: id('acc-oauth'), userId: id('imported'), provider: 'oauth' },
+ {
+ id: id('acc-github-no-id'),
+ userId: id('member'),
+ provider: 'github',
+ email: 'm29-member@test',
+ },
+ {
+ id: id('acc-shared-a'),
+ userId: id('shared-a'),
+ provider: 'github',
+ providerId: 'gh-shared',
+ },
+ {
+ id: id('acc-shared-b'),
+ userId: id('shared-b'),
+ provider: 'github',
+ providerId: 'gh-shared',
+ },
+ ],
+ });
+ await db.organization.create({
+ data: { id: ORG_ID, name: 'M29', createdByUserId: id('creator') },
+ });
+ await db.organization.create({
+ data: {
+ id: OTHER_ORG_ID,
+ name: 'M29 other',
+ createdByUserId: id('demoted-creator'),
+ },
+ });
+ await db.member.createMany({
+ data: [
+ {
+ organizationId: ORG_ID,
+ userId: id('creator'),
+ email: 'm29-creator@test',
+ role: 'org:admin',
+ },
+ {
+ organizationId: ORG_ID,
+ userId: id('admin'),
+ email: 'm29-admin@test',
+ role: 'org:admin',
+ },
+ {
+ organizationId: ORG_ID,
+ userId: id('member'),
+ email: 'm29-member@test',
+ role: 'org:member',
+ },
+ {
+ organizationId: OTHER_ORG_ID,
+ userId: id('demoted-creator'),
+ email: 'm29-demoted@test',
+ role: 'org:member',
+ },
+ ],
+ });
+ await db.invite.create({
+ data: {
+ id: id('invite'),
+ email: 'm29-invitee@test',
+ organizationId: ORG_ID,
+ createdById: id('creator'),
+ role: 'org:admin',
+ expiresAt: NEWER,
+ },
+ });
+}
+
+async function snapshot() {
+ const [users, accounts, members, invite] = await Promise.all([
+ db.user.findMany({
+ where: { id: { startsWith: `${PREFIX}-` } },
+ select: { id: true, name: true, emailVerified: true },
+ orderBy: { id: 'asc' },
+ }),
+ db.account.findMany({
+ where: { id: { startsWith: `${PREFIX}-` } },
+ select: { id: true, provider: true, providerId: true, accountId: true },
+ orderBy: { id: 'asc' },
+ }),
+ db.member.findMany({
+ where: { organizationId: { in: [ORG_ID, OTHER_ORG_ID] } },
+ select: { userId: true, role: true },
+ orderBy: { userId: 'asc' },
+ }),
+ db.invite.findUniqueOrThrow({
+ where: { id: id('invite') },
+ select: { role: true },
+ }),
+ ]);
+ return {
+ users: Object.fromEntries(users.map((user) => [user.id, user])),
+ accounts: Object.fromEntries(
+ accounts.map((account) => [account.id, account])
+ ),
+ roles: Object.fromEntries(
+ members.map((member) => [member.userId, member.role])
+ ),
+ inviteRole: invite.role,
+ };
+}
+
+describe('29-better-auth-backfill', () => {
+ let after: Awaited<ReturnType<typeof snapshot>>;
+
+ beforeAll(async () => {
+ await cleanUp();
+ await seed();
+ await up();
+ after = await snapshot();
+ });
+
+ afterAll(cleanUp);
+
+ it('joins and trims names, leaving an empty name when there is none', () => {
+ expect(after.users[id('creator')]?.name).toBe('Ada Lovelace');
+ expect(after.users[id('admin')]?.name).toBe('Grace');
+ expect(after.users[id('demoted-creator')]?.name).toBe('Hopper');
+ expect(after.users[id('member')]?.name).toBe('');
+ });
+
+ it('marks email verified only for users with a Google or GitHub account', () => {
+ expect(after.users[id('admin')]?.emailVerified).toBe(true);
+ expect(after.users[id('github')]?.emailVerified).toBe(true);
+ expect(after.users[id('member')]?.emailVerified).toBe(true);
+ expect(after.users[id('creator')]?.emailVerified).toBe(false);
+ expect(after.users[id('imported')]?.emailVerified).toBe(false);
+ });
+
+ it('turns email accounts into credential accounts keyed by the user id', () => {
+ expect(after.accounts[id('acc-email')]).toMatchObject({
+ provider: 'credential',
+ accountId: id('creator'),
+ });
+ });
+
+ it('copies the IdP id into accountId for Google and GitHub', () => {
+ expect(after.accounts[id('acc-google')]?.accountId).toBe('g-1');
+ expect(after.accounts[id('acc-github')]?.accountId).toBe('gh-1');
+ });
+
+ it('leaves accounts without an IdP id for the next sign-in', () => {
+ expect(after.accounts[id('acc-oauth')]).toMatchObject({
+ provider: 'oauth',
+ accountId: null,
+ });
+ expect(after.accounts[id('acc-github-no-id')]?.accountId).toBeNull();
+ });
+
+ it("keeps the oldest of a user's duplicate accounts", () => {
+ expect(after.accounts[id('acc-github')]).toBeDefined();
+ expect(after.accounts[id('acc-github-dup')]).toBeUndefined();
+ });
+
+ it('prefers the duplicate that has an email over the oldest', () => {
+ expect(after.accounts[id('acc-google-with-email')]?.accountId).toBe(
+ 'g-dup'
+ );
+ expect(after.accounts[id('acc-google-no-email')]).toBeUndefined();
+ });
+
+ it('keeps one IdP id shared by two users on both', () => {
+ expect(after.accounts[id('acc-shared-a')]?.accountId).toBe('gh-shared');
+ expect(after.accounts[id('acc-shared-b')]?.accountId).toBe('gh-shared');
+ });
+
+ it("renames roles and makes the creator's admin membership owner", () => {
+ expect(after.roles).toEqual({
+ [id('admin')]: 'admin',
+ [id('creator')]: 'owner',
+ [id('demoted-creator')]: 'member',
+ [id('member')]: 'member',
+ });
+ expect(after.inviteRole).toBe('admin');
+ });
+
+ it('changes nothing when run again', async () => {
+ await up();
+ expect(await snapshot()).toEqual(after);
+ });
+});
diff --git a/packages/db/src/code-migrations/29-better-auth-backfill.ts b/packages/db/src/code-migrations/29-better-auth-backfill.ts
new file mode 100644
index 000000000..03a7aa553
--- /dev/null
+++ b/packages/db/src/code-migrations/29-better-auth-backfill.ts
@@ -0,0 +1,209 @@
+import { db } from '../prisma-client';
+import { getIsDry, printBoxMessage } from './helpers';
+
+/**
+ * Fill the columns better-auth reads, and store roles under their new names.
+ *
+ * - `users.name` from first and last name, trimmed; empty when both are.
+ * - `users.emailVerified` for users with a Google or GitHub account: the IdP
+ * verified the address. Everyone else stays unverified, which locks nobody
+ * out because email verification is not required.
+ * - Email accounts become better-auth's `credential` accounts, whose
+ * `accountId` is the user id. Google and GitHub accounts get `accountId`
+ * from `providerId`. Rows without a `providerId` (the bulk-imported `oauth`
+ * ones and a few Google/GitHub ones) have nothing to copy and are left for
+ * the next sign-in to resolve.
+ * - Duplicate accounts for the same user, provider and IdP id (a December
+ * 2024 import that ran twice) are collapsed into one: the copy with an
+ * email, else the oldest. The same IdP id on two users is left alone.
+ * - Roles: `org:admin` → `admin`, `org:member` → `member` on members and
+ * pending invites, then the organization creator's admin membership →
+ * `owner`, which is what the previous build derived at read time.
+ *
+ * Idempotent: every statement only touches rows still in the old shape.
+ */
+
+interface Count {
+ count: bigint;
+}
+
+const LEGACY_ROLES = ['org:admin', 'org:member'];
+const VERIFYING_PROVIDERS = ['google', 'github'];
+
+function toNumber(rows: Count[]): number {
+ return Number(rows[0]?.count ?? 0);
+}
+
+async function countPending() {
+ const [names, verified, duplicates, credentials, oauthIds, roles, owners] =
+ await Promise.all([
+ db.user.count({ where: { name: null } }),
+ db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM users u
+ WHERE NOT u."emailVerified" AND EXISTS (
+ SELECT 1 FROM accounts a
+ WHERE a."userId" = u.id AND a.provider = ANY(${VERIFYING_PROVIDERS})
+ )
+ `.then(toNumber),
+ db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM accounts a
+ WHERE a."providerId" IS NOT NULL AND EXISTS (
+ SELECT 1 FROM accounts b
+ WHERE b."userId" = a."userId"
+ AND b.provider = a.provider
+ AND b."providerId" = a."providerId"
+ AND (b.email IS NULL, b."createdAt", b.id) < (a.email IS NULL, a."createdAt", a.id)
+ )
+ `.then(toNumber),
+ db.account.count({ where: { provider: 'email' } }),
+ db.account.count({
+ where: {
+ provider: { in: VERIFYING_PROVIDERS },
+ providerId: { not: null },
+ accountId: null,
+ },
+ }),
+ Promise.all([
+ db.member.count({ where: { role: { in: LEGACY_ROLES } } }),
+ db.invite.count({ where: { role: { in: LEGACY_ROLES } } }),
+ ]).then(([members, invites]) => members + invites),
+ db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM members m
+ JOIN organizations o ON o.id = m."organizationId"
+ WHERE m."userId" = o."createdByUserId"
+ AND m.role IN ('admin', 'org:admin')
+ `.then(toNumber),
+ ]);
+ return {
+ names,
+ verified,
+ duplicates,
+ credentials,
+ oauthIds,
+ roles,
+ owners,
+ };
+}
+
+function backfillNames() {
+ return db.$executeRaw`
+ UPDATE users
+ SET name = btrim(concat_ws(' ', btrim("firstName"), btrim("lastName")))
+ WHERE name IS NULL
+ `;
+}
+
+function markIdpVerifiedEmails() {
+ return db.$executeRaw`
+ UPDATE users u
+ SET "emailVerified" = true
+ WHERE NOT u."emailVerified" AND EXISTS (
+ SELECT 1 FROM accounts a
+ WHERE a."userId" = u.id AND a.provider = ANY(${VERIFYING_PROVIDERS})
+ )
+ `;
+}
+
+function collapseDuplicateAccounts() {
+ return db.$executeRaw`
+ DELETE FROM accounts a
+ USING accounts b
+ WHERE a."providerId" IS NOT NULL
+ AND b."userId" = a."userId"
+ AND b.provider = a.provider
+ AND b."providerId" = a."providerId"
+ AND (b.email IS NULL, b."createdAt", b.id) < (a.email IS NULL, a."createdAt", a.id)
+ `;
+}
+
+function toCredentialAccounts() {
+ return db.$executeRaw`
+ UPDATE accounts
+ SET provider = 'credential', "accountId" = "userId"
+ WHERE provider = 'email'
+ `;
+}
+
+function copyOAuthAccountIds() {
+ return db.$executeRaw`
+ UPDATE accounts
+ SET "accountId" = "providerId"
+ WHERE provider = ANY(${VERIFYING_PROVIDERS})
+ AND "providerId" IS NOT NULL
+ AND "accountId" IS NULL
+ `;
+}
+
+function renameMemberRoles() {
+ return db.$executeRaw`
+ UPDATE members
+ SET role = CASE role WHEN 'org:admin' THEN 'admin' ELSE 'member' END
+ WHERE role = ANY(${LEGACY_ROLES})
+ `;
+}
+
+function renameInviteRoles() {
+ return db.$executeRaw`
+ UPDATE invites
+ SET role = CASE role WHEN 'org:admin' THEN 'admin' ELSE 'member' END
+ WHERE role = ANY(${LEGACY_ROLES})
+ `;
+}
+
+function promoteCreatorsToOwner() {
+ return db.$executeRaw`
+ UPDATE members m
+ SET role = 'owner'
+ FROM organizations o
+ WHERE o.id = m."organizationId"
+ AND m."userId" = o."createdByUserId"
+ AND m.role = 'admin'
+ `;
+}
+
+export async function up() {
+ const pending = await countPending();
+
+ if (getIsDry()) {
+ printBoxMessage('🧪 Dry run: better-auth backfill', [
+ `Users to get a name: ${pending.names}`,
+ `Users to mark email verified: ${pending.verified}`,
+ `Duplicate accounts to remove: ${pending.duplicates}`,
+ `Email accounts to turn into credential accounts: ${pending.credentials}`,
+ `Google/GitHub accounts to get an accountId: ${pending.oauthIds}`,
+ `Members and invites with a legacy role name: ${pending.roles}`,
+ `Creator memberships to make owner: ${pending.owners}`,
+ ]);
+ return;
+ }
+
+ const [
+ names,
+ verified,
+ duplicates,
+ credentials,
+ oauthIds,
+ memberRoles,
+ inviteRoles,
+ owners,
+ ] = await db.$transaction([
+ backfillNames(),
+ markIdpVerifiedEmails(),
+ collapseDuplicateAccounts(),
+ toCredentialAccounts(),
+ copyOAuthAccountIds(),
+ renameMemberRoles(),
+ renameInviteRoles(),
+ promoteCreatorsToOwner(),
+ ]);
+
+ printBoxMessage('✅ better-auth backfill', [
+ `Users given a name: ${names}`,
+ `Users marked email verified: ${verified}`,
+ `Duplicate accounts removed: ${duplicates}`,
+ `Credential accounts: ${credentials}`,
+ `Google/GitHub accounts given an accountId: ${oauthIds}`,
+ `Roles renamed: ${memberRoles} members, ${inviteRoles} invites`,
+ `Creator memberships made owner: ${owners}`,
+ ]);
+}
diff --git a/packages/seed/src/postgres.ts b/packages/seed/src/postgres.ts
index a84c1b388..16f91a3d8 100644
--- a/packages/seed/src/postgres.ts
+++ b/packages/seed/src/postgres.ts
@@ -10,7 +10,7 @@ import type { Archetype } from './archetypes/archetype';
import { deterministicUuid, projectIdFor } from './ids';
import type { Rng } from './rng';
import {
- ORGANIZATION_ADMIN_ROLE,
+ ORGANIZATION_OWNER_ROLE,
SEED_ORGANIZATION,
SEED_USER,
SUBSCRIPTION_EVENTS_LIMIT,
@@ -129,9 +129,9 @@ async function upsertOrganization(
organizationId: organization.id,
userId,
email: SEED_USER.email,
- role: ORGANIZATION_ADMIN_ROLE,
+ role: ORGANIZATION_OWNER_ROLE,
},
- update: { role: ORGANIZATION_ADMIN_ROLE },
+ update: { role: ORGANIZATION_OWNER_ROLE },
});
return organization.id;
}
diff --git a/packages/seed/src/seed.constants.ts b/packages/seed/src/seed.constants.ts
index e4d1c5d18..6394dbcd8 100644
--- a/packages/seed/src/seed.constants.ts
+++ b/packages/seed/src/seed.constants.ts
@@ -11,7 +11,8 @@ export const SEED_USER = {
export const SEED_ORGANIZATION = { id: 'acme', name: 'Acme' } as const;
-export const ORGANIZATION_ADMIN_ROLE = 'org:admin';
+/** The seeded user created the organization, so they own it. */
+export const ORGANIZATION_OWNER_ROLE = 'owner';
/**
* The organization is on an active paid subscription, not a trial: a branch seeded weeks ago
diff --git a/self-hosting/.env.template b/self-hosting/.env.template
index d72cffc44..96e038da7 100644
--- a/self-hosting/.env.template
+++ b/self-hosting/.env.template
@@ -13,6 +13,7 @@ DATABASE_URL_DIRECT="$DATABASE_URL_DIRECT"
DASHBOARD_URL="$DASHBOARD_URL"
API_URL="$API_URL"
COOKIE_SECRET="$COOKIE_SECRET"
+AUTH_SECRET="$AUTH_SECRET"
# HTTP Basic credentials for operator-only surfaces (the queue dashboard at
# /bullboard). Leave empty to guard it with a dashboard session alone.
diff --git a/self-hosting/cli/src/doctor/checks.ts b/self-hosting/cli/src/doctor/checks.ts
index 9be5efa7c..3ec31b109 100644
--- a/self-hosting/cli/src/doctor/checks.ts
+++ b/self-hosting/cli/src/doctor/checks.ts
@@ -488,6 +488,22 @@ export const cookieSecret: Check = (install) => {
};
};
+export const authSecret: Check = (install) => {
+ const cookie = install.env.get('COOKIE_SECRET');
+ if (install.env.get('AUTH_SECRET') || !cookie) {
+ return null;
+ }
+ return {
+ id: 'env/auth-secret',
+ severity: 'warn',
+ title: 'AUTH_SECRET is not set',
+ detail:
+ 'Sign-in sessions are signed with COOKIE_SECRET until it is. Set it so rotating COOKIE_SECRET does not sign everyone out.',
+ // The current value, so nobody signed in under the fallback is signed out.
+ fix: (target) => target.env.set('AUTH_SECRET', cookie),
+ };
+};
+
export const renamedEnvVars: Check = (install) => {
const present = RENAMED_ENV_VARS.filter(([oldName]) =>
install.env.has(oldName)
@@ -734,6 +750,7 @@ export const checks: Check[] = [
kafkaPartitions,
encryptionKey,
cookieSecret,
+ authSecret,
renamedEnvVars,
dashboardUrl,
apiUrl,
diff --git a/self-hosting/cli/src/init/generate.ts b/self-hosting/cli/src/init/generate.ts
index 0be1c917a..8dec1c42f 100644
--- a/self-hosting/cli/src/init/generate.ts
+++ b/self-hosting/cli/src/init/generate.ts
@@ -16,7 +16,12 @@ const OPENPANEL_IMAGE_SERVICES = [
] as const;
const BCRYPT_COST = 10;
-const SECRET_BYTES = { cookie: 16, encryption: 32, admin: 12 } as const;
+const SECRET_BYTES = {
+ cookie: 16,
+ auth: 32,
+ encryption: 32,
+ admin: 12,
+} as const;
export const BUNDLED_URLS = {
clickhouse: 'http://op-ch:8123/openpanel',
@@ -47,6 +52,7 @@ export interface InitAnswers {
export interface Secrets {
cookieSecret: string;
+ authSecret: string;
encryptionKey: string;
adminPassword: string;
}
@@ -56,6 +62,10 @@ export const generateSecrets = (existing: EnvFile | null = null): Secrets => ({
cookieSecret:
existing?.get('COOKIE_SECRET') ??
randomBytes(SECRET_BYTES.cookie).toString('hex'),
+ authSecret:
+ existing?.get('AUTH_SECRET') ??
+ existing?.get('COOKIE_SECRET') ??
+ randomBytes(SECRET_BYTES.auth).toString('hex'),
encryptionKey:
existing?.get('ENCRYPTION_KEY') ??
randomBytes(SECRET_BYTES.encryption).toString('hex'),
@@ -87,6 +97,7 @@ const renderEnv = (answers: InitAnswers, secrets: Secrets): string => {
DASHBOARD_URL: answers.domain,
API_URL: `${answers.domain}/api`,
COOKIE_SECRET: secrets.cookieSecret,
+ AUTH_SECRET: secrets.authSecret,
ADMIN_USERNAME: 'admin',
ADMIN_PASSWORD: secrets.adminPassword,
ENCRYPTION_KEY: secrets.encryptionKey,
diff --git a/self-hosting/cli/test/doctor.test.ts b/self-hosting/cli/test/doctor.test.ts
index c54252eed..9bc9c5fe6 100644
--- a/self-hosting/cli/test/doctor.test.ts
+++ b/self-hosting/cli/test/doctor.test.ts
@@ -36,6 +36,7 @@ describe('doctor on a v1 install', () => {
'compose/api-migrations',
'env/kafka-brokers',
'env/kafka-partitions',
+ 'env/auth-secret',
'env/automatic-migrations',
'env/enabled-queues',
'env/removed-vars',
@@ -110,6 +111,7 @@ describe('doctor on a v1 install', () => {
expect(env.get('ENCRYPTION_KEY')).toBe('0123456789abcdef'.repeat(4));
expect(env.get('COOKIE_SECRET')).toBe('0123456789abcdef'.repeat(2));
+ expect(env.get('AUTH_SECRET')).toBe(env.get('COOKIE_SECRET'));
expect(env.get('KAFKA_BROKERS')).toBe('op-rp:9092');
expect(env.get('ENABLED_QUEUES')).toBe('events,sessions,cron');
expect(env.has('WORKER_PORT')).toBe(false);
diff --git a/test/databases.ts b/test/databases.ts
index a97778521..2780d59e5 100644
--- a/test/databases.ts
+++ b/test/databases.ts
@@ -7,8 +7,34 @@
const POSTGRES_ORIGIN = 'postgresql://postgres:postgres@localhost:23432';
const CLICKHOUSE_ORIGIN = 'http://localhost:23123';
-export const TEST_POSTGRES_DATABASE = 'openpanel_test';
-export const TEST_CLICKHOUSE_DATABASE = 'openpanel_test';
+const SHARED_TEST_DATABASE = 'openpanel_test';
+const WORKTREE_APP_DATABASE = /^openpanel_(\w+)$/;
+
+/**
+ * A worktree's app database is `openpanel_<name>`; its tests get `openpanel_test_<name>`, so one branch's migrations
+ * never reach another branch's test runs. The main checkout and CI share `openpanel_test`. Already-pinned test names
+ * are kept, so evaluating this after a preload has rewritten `DATABASE_URL` gives the same answer.
+ */
+function testDatabaseName(appDatabaseUrl: string | undefined): string {
+ const appDatabase = appDatabaseUrl
+ ? new URL(appDatabaseUrl).pathname.slice(1)
+ : '';
+ const isTestDatabase =
+ appDatabase === SHARED_TEST_DATABASE ||
+ appDatabase.startsWith(`${SHARED_TEST_DATABASE}_`);
+ if (isTestDatabase) {
+ return appDatabase;
+ }
+ const worktree = WORKTREE_APP_DATABASE.exec(appDatabase)?.[1];
+ return worktree
+ ? `${SHARED_TEST_DATABASE}_${worktree}`
+ : SHARED_TEST_DATABASE;
+}
+
+export const TEST_POSTGRES_DATABASE = testDatabaseName(
+ process.env.DATABASE_URL
+);
+export const TEST_CLICKHOUSE_DATABASE = TEST_POSTGRES_DATABASE;
/** `CREATE DATABASE` cannot be issued from inside the database it creates. */
export const POSTGRES_MAINTENANCE_DATABASE = 'postgres';