-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
332 lines (304 loc) · 9.79 KB
/
Copy pathauth.ts
File metadata and controls
332 lines (304 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { nextCookies } from "better-auth/next-js";
import { APIError } from "better-auth";
import { magicLink } from "better-auth/plugins";
import { sso } from "@better-auth/sso";
import { and, eq } from "drizzle-orm";
import { db } from "@/db";
import * as authSchema from "@/db/auth-schema";
import { platformUsers, portalUsers, tenants } from "@/db/schema";
import { MagicLinkEmail } from "@/emails/magic-link";
import { emailFrom, resend } from "./email";
import { captureServerEvent } from "@/lib/posthog-server";
import { formatAuthUserDisplayName } from "@/lib/user-display-name";
import { claimApprovedTenantJoinRequestForSession } from "@/modules/core/workspace-settings/services/tenant-join-requests-core";
import {
getActiveTenantSsoSettings,
jitProvisionSsoMembership,
} from "@/modules/shared/services/sso-jit";
import { bootstrapAuthUserIdentityOnCreate } from "@/modules/shared/services/signup-profile";
/** True when the in-flight request is an enterprise SSO callback (OIDC or SAML). */
function isSsoCallbackRequest(url: string | null | undefined): boolean {
if (!url) return false;
let pathname: string;
try {
pathname = new URL(url).pathname;
} catch {
return false;
}
return (
pathname.includes("/sso/callback") || pathname.includes("/sso/saml2")
);
}
import {
getRequestTenantHostContextFromHeaders,
getRootDomain,
} from "./tenant-host";
if (!process.env.BETTER_AUTH_SECRET) {
throw new Error("BETTER_AUTH_SECRET is not set");
}
if (!process.env.BETTER_AUTH_URL) {
throw new Error("BETTER_AUTH_URL is not set");
}
const googleAuthEnabled = Boolean(
process.env.GOOGLE_CLIENT_ID?.trim() &&
process.env.GOOGLE_CLIENT_SECRET?.trim(),
);
const rootDomain = getRootDomain();
const crossSubdomainCookiesEnabled =
rootDomain !== "localhost" && rootDomain !== "127.0.0.1";
const betterAuthUrl = new URL(process.env.BETTER_AUTH_URL);
const betterAuthPort = betterAuthUrl.port || null;
function buildTrustedOrigins() {
const origins = [
`https://*.${rootDomain}`,
`http://*.${rootDomain}`,
"https://*.localtest.me",
"http://*.localtest.me",
];
if (betterAuthPort) {
origins.push(
`https://*.${rootDomain}:${betterAuthPort}`,
`http://*.${rootDomain}:${betterAuthPort}`,
`https://*.localtest.me:${betterAuthPort}`,
`http://*.localtest.me:${betterAuthPort}`,
);
}
return origins;
}
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg",
schema: authSchema,
}),
secret: process.env.BETTER_AUTH_SECRET,
baseURL: process.env.BETTER_AUTH_URL,
/**
* Allow any subdomain of ROOT_DOMAIN to make auth requests.
* Better Auth's matchesOriginPattern supports glob wildcards, so
* "https://*.domain.com" covers all tenant subdomains without
* needing to enumerate them. localtest.me is always included for
* local development convenience.
*
* Additional origins can also be added at deploy time via the
* BETTER_AUTH_TRUSTED_ORIGINS env var (comma-separated).
*/
trustedOrigins: buildTrustedOrigins(),
advanced: {
crossSubDomainCookies: crossSubdomainCookiesEnabled
? {
enabled: true,
domain: rootDomain,
}
: undefined,
},
user: {
additionalFields: {
firstName: {
type: "string",
required: false,
input: false,
defaultValue: "",
},
lastName: {
type: "string",
required: false,
input: false,
defaultValue: "",
},
fullName: {
type: "string",
required: false,
input: false,
defaultValue: "",
},
},
},
session: {
additionalFields: {
tenantId: {
type: "string",
required: false,
input: false,
},
},
},
socialProviders: googleAuthEnabled
? {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
}
: {},
emailAndPassword: {
enabled: false,
},
emailVerification: {
sendOnSignUp: false,
sendOnSignIn: false,
autoSignInAfterVerification: false,
},
plugins: [
magicLink({
expiresIn: 60 * 15,
disableSignUp: false,
sendMagicLink: async ({ email, url }) => {
await resend.emails.send({
from: emailFrom,
to: email,
subject: "Sign in to Fluxora",
react: MagicLinkEmail({
url,
name: null,
}),
});
},
}),
// Enterprise SSO (SAML 2.0 + OIDC). JIT provisioning is handled in the
// session.create.before hook (which runs before this plugin's provisionUser
// callback would), so it isn't configured here.
sso(),
nextCookies(),
],
databaseHooks: {
user: {
create: {
after: async (createdUser): Promise<void> => {
await bootstrapAuthUserIdentityOnCreate({
userId: createdUser.id,
emailLower: createdUser.email,
initialName: createdUser.name ?? "",
});
// No tenantId yet at this point — the user signs up before a
// portal_users row exists. The next group() call from the
// client (after they land on a tenant) attaches the tenant.
await captureServerEvent({
userId: createdUser.id,
event: "user.signed_up",
});
},
},
},
session: {
create: {
before: async (session, ctx) => {
if (!ctx) return;
const requestHeaders = ctx.request?.headers ?? ctx.headers;
const hostContext = requestHeaders
? getRequestTenantHostContextFromHeaders(requestHeaders)
: null;
const tenantSlug = hostContext?.tenantSlug ?? null;
if (hostContext?.isPlatformAdminHost) {
const platformUser = await db.query.platformUsers.findFirst({
where: and(
eq(platformUsers.authUserId, session.userId),
eq(platformUsers.isActive, true),
),
});
if (!platformUser) {
throw APIError.from("FORBIDDEN", {
code: "PLATFORM_USER_REQUIRED",
message: "Your account does not have platform admin access.",
});
}
return {
data: {
...session,
tenantId: null,
},
};
}
if (!tenantSlug) {
return {
data: {
...session,
tenantId: null,
},
};
}
const tenant = await db.query.tenants.findFirst({
where: and(eq(tenants.slug, tenantSlug), eq(tenants.isActive, true)),
});
if (!tenant) {
throw APIError.from("FORBIDDEN", {
code: "TENANT_NOT_FOUND",
message: "This tenant was not found or is inactive.",
});
}
const membership = await db.query.portalUsers.findFirst({
where: and(
eq(portalUsers.authUserId, session.userId),
eq(portalUsers.tenantId, tenant.id),
eq(portalUsers.isActive, true),
),
});
if (!membership) {
const [authUserRecord] = await db
.select({
email: authSchema.user.email,
name: authSchema.user.name,
fullName: authSchema.user.fullName,
firstName: authSchema.user.firstName,
lastName: authSchema.user.lastName,
})
.from(authSchema.user)
.where(eq(authSchema.user.id, session.userId))
.limit(1);
const claimedMembership = authUserRecord
? await claimApprovedTenantJoinRequestForSession({
tenantId: tenant.id,
authUserId: session.userId,
email: authUserRecord.email,
fallbackFullName: formatAuthUserDisplayName(authUserRecord),
})
: null;
if (claimedMembership) {
return {
data: {
...session,
tenantId: tenant.id,
},
};
}
// Enterprise SSO JIT: if this session is being created by an SSO
// callback AND the tenant has an active SSO connection, provision
// the IdP-authenticated user as a member with the configured default
// role. Gated to the SSO callback path so ordinary magic-link/Google
// sign-ins can never auto-join a tenant.
const isSsoCallback = isSsoCallbackRequest(ctx.request?.url);
if (isSsoCallback && authUserRecord) {
const ssoSettings = await getActiveTenantSsoSettings(tenant.id);
if (ssoSettings) {
await jitProvisionSsoMembership({
tenantId: tenant.id,
authUserId: session.userId,
email: authUserRecord.email,
fullName: formatAuthUserDisplayName(authUserRecord),
role: ssoSettings.defaultRole,
});
return {
data: {
...session,
tenantId: tenant.id,
},
};
}
}
throw APIError.from("FORBIDDEN", {
code: "TENANT_MEMBERSHIP_REQUIRED",
message: "Your account does not belong to this tenant.",
});
}
return {
data: {
...session,
tenantId: tenant.id,
},
};
},
},
},
},
});