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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions packages/auth/src/lib/cached-jwks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { GenericEndpointContext } from "better-auth";
import type { Jwk } from "better-auth/plugins/jwt";

/**
* The jwt plugin reads the whole `jwks` table every time it mints a token, and
* it mints one on every `/get-session` to set the `set-auth-jwt` header. That
* is a database round trip on every authenticated request in the product for a
* key set that only changes when a key is created.
*
* Disabling the header instead would be cheaper still, but the desktop and
* mobile clients read it opportunistically to refresh their token
* (apps/desktop/src/renderer/lib/auth-client.ts, apps/mobile/lib/auth/client.ts),
* so the header stays and the read gets cached.
*
* The TTL is short because the cost of being stale is real but bounded: a key
* created by another instance is absent from `/jwks` until the cache expires,
* so tokens signed with it fail verification until then. Creations go through
* `createJwk` below, which clears this instance's copy immediately.
*/
const JWKS_CACHE_TTL_MS = 60 * 1000;

let cache: { keys: Jwk[]; fetchedAt: number } | null = null;

export function jwksAdapter() {
return {
getJwks: async (ctx: GenericEndpointContext): Promise<Jwk[]> => {
if (cache && Date.now() - cache.fetchedAt < JWKS_CACHE_TTL_MS) {
return cache.keys;
}

const keys = await ctx.context.adapter.findMany<Jwk>({
model: "jwks",
});
cache = { keys, fetchedAt: Date.now() };
return keys;
},

createJwk: async (
data: Omit<Jwk, "id">,
ctx: GenericEndpointContext,
): Promise<Jwk> => {
const created = await ctx.context.adapter.create<Omit<Jwk, "id">, Jwk>({
model: "jwks",
data: { ...data, createdAt: new Date() },
});
cache = null;
return created;
},
};
}
132 changes: 132 additions & 0 deletions packages/auth/src/lib/load-custom-session-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { db } from "@superset/db/client";
import type { SelectMember } from "@superset/db/schema/auth";
import { ACTIVE_SUBSCRIPTION_STATUSES } from "@superset/shared/billing";
import { sql } from "drizzle-orm";

/**
* Everything `customSession` needs, in one round trip.
*
* These were three sequential drizzle calls — memberships, then the active
* organization's subscription, then the user's own row. Neon speaks HTTP, so
* each call is its own request, and with the database in a different region to
* the functions that was ~220ms on every authenticated request in the product.
* Only the active-organization fallback made the order matter, and that is
* expressible in SQL, so the three collapse into one statement.
*
* Raw SQL rather than drizzle's query builder because the point is the single
* statement; expressing the fallback across three builder calls is what we are
* replacing.
*/
export interface CustomSessionData {
memberships: SelectMember[];
/**
* The organization the plan below belongs to. A concurrent request can move
* the session's active organization between this query and the caller
* settling on one, so the caller compares before trusting `plan`.
*/
planOrganizationId: string | null;
plan: string | null;
onboardedAt: Date | null;
deletionRequestedAt: Date | null;
}

interface CustomSessionRow extends Record<string, unknown> {
memberships: Array<{
id: string;
organizationId: string;
userId: string;
role: string;
createdAt: string;
}> | null;
active_organization_id: string | null;
plan: string | null;
onboarded_at: string | Date | null;
deletion_requested_at: string | Date | null;
}

/**
* These are `timestamp` columns, so Postgres hands back a naive string with no
* zone. `new Date()` reads that as local time, which silently shifts every
* value by the server's offset; drizzle's own mapping treats it as UTC, so
* match that or the onboarding gate moves by hours depending on where the
* function ran.
*/
function toDate(value: string | Date | null): Date | null {
if (value === null) return null;
if (value instanceof Date) return value;
const normalized = value.replace(" ", "T");
const hasZone = /(?:Z|[+-]\d{2}(?::?\d{2})?)$/.test(normalized);
return new Date(hasZone ? normalized : `${normalized}Z`);
}

export async function loadCustomSessionData({
userId,
activeOrganizationId,
}: {
userId: string;
activeOrganizationId: string | null;
}): Promise<CustomSessionData> {
const statuses = sql.join(
ACTIVE_SUBSCRIPTION_STATUSES.map((status) => sql`${status}`),
sql`, `,
);

const result = await db.execute<CustomSessionRow>(sql`
WITH memberships AS (
SELECT id, organization_id, user_id, role, created_at
FROM auth.members
WHERE user_id = ${userId}::uuid
),
active AS (
SELECT COALESCE(
(SELECT organization_id FROM memberships
WHERE organization_id = ${activeOrganizationId}::uuid LIMIT 1),
(SELECT organization_id FROM memberships
ORDER BY created_at DESC LIMIT 1)
) AS organization_id
)
SELECT
(SELECT COALESCE(json_agg(json_build_object(
'id', id,
'organizationId', organization_id,
'userId', user_id,
'role', role,
'createdAt', created_at
) ORDER BY created_at DESC), '[]'::json)
FROM memberships) AS memberships,
(SELECT organization_id FROM active) AS active_organization_id,
(SELECT s.plan FROM subscriptions s, active a
WHERE s.reference_id = a.organization_id
AND s.status IN (${statuses})
LIMIT 1) AS plan,
u.onboarded_at,
u.deletion_requested_at
FROM auth.users u
WHERE u.id = ${userId}::uuid
`);

const row = result.rows[0];
if (!row) {
return {
memberships: [],
planOrganizationId: null,
plan: null,
onboardedAt: null,
deletionRequestedAt: null,
};
}

return {
memberships: (row.memberships ?? []).map((member) => ({
id: member.id,
organizationId: member.organizationId,
userId: member.userId,
role: member.role,
createdAt: toDate(member.createdAt) ?? new Date(0),
})),
planOrganizationId: row.active_organization_id,
plan: row.plan,
onboardedAt: toDate(row.onboarded_at),
deletionRequestedAt: toDate(row.deletion_requested_at),
};
}
3 changes: 2 additions & 1 deletion packages/auth/src/lib/resolve-session-organization-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ export async function resolveSessionOrganizationState(
userId?: string | null;
session?: SessionOrganizationContext | null;
},
deps: ResolveSessionOrganizationDeps = defaultResolveSessionOrganizationDeps,
overrides: Partial<ResolveSessionOrganizationDeps> = {},
) {
const deps = { ...defaultResolveSessionOrganizationDeps, ...overrides };
const previousActiveOrganizationId = session?.activeOrganizationId ?? null;
let activeOrganizationId = previousActiveOrganizationId;
if (!userId) {
Expand Down
50 changes: 31 additions & 19 deletions packages/auth/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ import { and, asc, count, desc, eq, inArray, ne, sql } from "drizzle-orm";
import type Stripe from "stripe";
import { env } from "./env";
import { acceptInvitationEndpoint } from "./lib/accept-invitation-endpoint";
import { jwksAdapter } from "./lib/cached-jwks";
import { generateMagicTokenForInvite } from "./lib/generate-magic-token";
import { loadCustomSessionData } from "./lib/load-custom-session-data";
import { invitationRateLimit } from "./lib/rate-limit";
import { resend } from "./lib/resend";
import {
Expand Down Expand Up @@ -305,6 +307,7 @@ export const auth = betterAuth({
jwks: {
keyPairConfig: { alg: "RS256" },
},
adapter: jwksAdapter(),
jwt: {
issuer: env.NEXT_PUBLIC_API_URL,
audience: env.NEXT_PUBLIC_API_URL,
Expand Down Expand Up @@ -872,22 +875,39 @@ export const auth = betterAuth({
customSession(
async ({ user, session: baseSession }) => {
const session = baseSession as typeof sessions.$inferSelect;
const userId = session.userId ?? user.id;

// Memberships, the active organization's plan and the user's own
// flags in one statement. This runs on every authenticated request
// in the product, so each extra round trip here is a region-crossing
// hop the whole fleet pays for.
const data = await loadCustomSessionData({
userId,
activeOrganizationId: session.activeOrganizationId ?? null,
});

const { activeOrganizationId, allMemberships, membership } =
await resolveSessionOrganizationState({
userId: session.userId ?? user.id,
session,
});
await resolveSessionOrganizationState(
{ userId, session },
{ listMemberships: async () => data.memberships },
);

const organizationIds = [
...new Set(allMemberships.map((m) => m.organizationId)),
];

// Same statuses the rest of the app gates on — this is the value
// the paywall falls back to when the activePlan query can't be
// reached, so an "active"-only read here would strand trialing
// and past_due organizations on a cold start.
let plan: string | null = null;
if (activeOrganizationId) {
// Same statuses the rest of the app gates on — this is the value
// the paywall falls back to when the activePlan query can't be
// reached, so an "active"-only read here would strand trialing
// and past_due orgs on a cold start.
if (activeOrganizationId === data.planOrganizationId) {
plan = data.plan;
} else if (activeOrganizationId) {
// A concurrent request moved the session's active organization
// after the query above ran, so the plan it found belongs to the
// wrong one. Rare enough to be worth a second read rather than
// serialising the common path behind it.
const subscription = await db.query.subscriptions.findFirst({
where: and(
eq(subscriptions.referenceId, activeOrganizationId),
Expand All @@ -897,19 +917,11 @@ export const auth = betterAuth({
plan = subscription?.plan ?? null;
}

// additionalFields declares onboardedAt for client typing, but the
// drizzle adapter doesn't surface it on the passed-in user — read it
// explicitly so the onboarding gate is deterministic.
const userRow = await db.query.users.findFirst({
where: eq(authSchema.users.id, user.id),
columns: { onboardedAt: true, deletionRequestedAt: true },
});

return {
user: {
...user,
onboardedAt: userRow?.onboardedAt ?? null,
deletionRequestedAt: userRow?.deletionRequestedAt ?? null,
onboardedAt: data.onboardedAt,
deletionRequestedAt: data.deletionRequestedAt,
},
session: {
...session,
Expand Down
Loading