2026-08-25 14:35:33 +08:00
import { AsyncLocalStorage } from 'node:async_hooks'
2026-05-19 16:05:09 +08:00
import { betterAuth } from 'better-auth'
2026-10-29 15:39:37 +08:00
import { jwt } from 'better-auth/plugins'
import { mcp } from '@better-auth/mcp'
2026-05-19 16:05:09 +08:00
import { prismaAdapter } from 'better-auth/adapters/prisma'
2026-06-01 23:08:58 +08:00
import { prisma } from '@shumai/db'
2026-06-01 23:16:22 +08:00
import { teamService } from '@shumai/core/src/team/team'
import { inviteService } from '@shumai/core/src/invite/invite'
2026-05-19 16:05:09 +08:00
import { createAuthMiddleware } from 'better-auth/api'
2026-07-01 17:46:17 +08:00
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
2026-11-05 22:21:11 +08:00
import { logger } from '@shumai/core/src/logger'
2026-05-19 16:05:09 +08:00
2026-08-25 14:35:33 +08:00
interface GeneratedResetLink {
url : string
token : string
}
const resetLinkStorage = new AsyncLocalStorage < GeneratedResetLink >()
2026-10-29 17:24:31 +08:00
export const authBaseUrl = (
2026-10-29 15:39:37 +08:00
process . env . BETTER_AUTH_URL || `http://localhost: ${ process . env . SHUMAI_SERVER_PORT || '3000' } `
2026-10-29 17:24:31 +08:00
). replace ( /\/+$/ , '' )
2026-10-29 15:39:37 +08:00
export const mcpResource = ` ${ authBaseUrl } /mcp`
export { hashPassword } from 'better-auth/crypto'
2026-11-05 22:21:11 +08:00
/**
* Checks whether a host is a loopback address (localhost, 127.0.0.0/8, or [::1]).
*/
export function isLoopbackHost ( hostname : string ) : boolean {
const ipv4Octets = hostname . split ( '.' )
const isIpv4Loopback =
ipv4Octets . length === 4 &&
ipv4Octets [ 0 ] === '127' &&
ipv4Octets . every (( octet ) => /^\d+$/ . test ( octet ) && Number ( octet ) <= 255 )
return hostname === 'localhost' || hostname === '[::1]' || isIpv4Loopback
}
/**
* Validates whether an MCP resource URL meets RFC 9728 and MCP security requirements
* (HTTPS required unless using a localhost or loopback IP address).
*/
export function isMcpResourceValid ( resource : string ) : { valid : boolean ; error? : string } {
if ( typeof resource !== 'string' || ! resource ) {
return { valid : false , error : 'MCP resource must be a non-empty string URL' }
}
let url : URL
try {
url = new URL ( resource )
} catch {
return { valid : false , error : 'MCP resource must be an absolute URL' }
}
if ( url . username || url . password ) {
return { valid : false , error : 'MCP resource URL must not contain credentials' }
}
if ( resource . includes ( '#' )) {
return { valid : false , error : 'MCP resource URL must not contain a fragment' }
}
if ( resource . includes ( '?' )) {
return { valid : false , error : 'MCP resource URL must not contain a query' }
}
if ( url . protocol !== 'https:' && ! ( url . protocol === 'http:' && isLoopbackHost ( url . hostname ))) {
return {
valid : false ,
error :
'MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs' ,
}
}
return { valid : true }
}
const mcpValidation = isMcpResourceValid ( mcpResource )
export const isMcpOauthEnabled = mcpValidation . valid
if ( ! isMcpOauthEnabled ) {
logger . error (
{ mcpResource , error : mcpValidation.error },
'MCP OAuth 2.1 is disabled: resource URL must use HTTPS for remote hosts. The main server and Web UI will continue running normally, but MCP OAuth clients cannot connect until HTTPS is configured.' ,
)
}
2026-05-19 16:05:09 +08:00
export const auth = betterAuth ({
database : prismaAdapter ( prisma , {
provider : 'postgresql' ,
}),
2026-10-29 15:39:37 +08:00
plugins : [
jwt (),
2026-11-05 22:21:11 +08:00
...( isMcpOauthEnabled
? [
mcp ({
loginPage : '/login' ,
consentPage : '/consent' ,
resource : mcpResource ,
resources : [{ identifier : mcpResource , allowedScopes : [ 'mcp' ] }],
scopes : [ 'openid' , 'profile' , 'email' , 'offline_access' , 'mcp' ],
allowDynamicClientRegistration : true ,
allowUnauthenticatedClientRegistration : true ,
clientRegistrationDefaultApplicationType : 'infer' ,
}),
]
: []),
2026-10-29 15:39:37 +08:00
],
2026-05-19 16:05:09 +08:00
emailAndPassword : {
enabled : true ,
minPasswordLength : 3 ,
2026-08-25 14:35:33 +08:00
revokeSessionsOnPasswordReset : true ,
resetPasswordTokenExpiresIn : 3600 ,
sendResetPassword : async ({ url , token }) => {
const store = resetLinkStorage . getStore ()
if ( store ) {
store . url = url
store . token = token
}
},
2026-05-19 16:05:09 +08:00
},
secret : process.env.BETTER_AUTH_SECRET ,
// eslint-disable-next-line @typescript-eslint/naming-convention
2026-10-29 15:39:37 +08:00
baseURL : authBaseUrl ,
2026-05-19 16:05:09 +08:00
basePath : '/api/auth' ,
2026-06-18 10:08:31 +08:00
trustedOrigins : [
`http://localhost: ${ process . env . SHUMAI_SERVER_PORT || '3000' } ` ,
`http://127.0.0.1: ${ process . env . SHUMAI_SERVER_PORT || '3000' } ` ,
],
2026-05-19 16:05:09 +08:00
advanced : {
disableCSRFCheck : true ,
},
hooks : {
before : createAuthMiddleware ( async ( ctx ) => {
if ( ctx . path === '/sign-up/email' ) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = ctx . body as any
const inviteCode = body ? . inviteCode
const info = await teamService . getSignupInfo ()
2026-06-19 00:36:23 +08:00
if ( info . initialized ) {
2026-06-03 10:18:15 +08:00
if ( ! inviteCode ) {
2026-05-19 16:05:09 +08:00
console . log ( '[Better Auth Hook] Public signup is disabled' )
return ctx . json (
{
error : 'Public signup is disabled' ,
},
{
status : 403 ,
},
)
}
2026-06-03 10:33:14 +08:00
const isValid = await inviteService . validateInvite ( inviteCode )
if ( ! isValid ) {
return ctx . json (
{
error : 'Invalid or expired invite code' ,
},
{
status : 400 ,
},
)
}
2026-05-19 16:05:09 +08:00
}
}
}),
after : createAuthMiddleware ( async ( ctx ) => {
if ( ctx . path === '/sign-up/email' ) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = ctx . context . returned as any
// Only proceed if the signup was successful and we have a user
if ( result && result . user && result . user . id ) {
const user = result . user
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = ctx . body as any
const inviteCode = body ? . inviteCode
try {
const info = await teamService . getSignupInfo ()
const defaultTeam = await teamService . ensureDefaultTeam ()
// If this is the very first user, make them owner
if ( info . userCount === 1 ) {
await prisma . teamMember . create ({
data : {
teamId : defaultTeam.id ,
userId : user.id ,
role : 'owner' ,
scope : 'team' ,
},
})
} else if ( ! inviteCode ) {
// If public signup is enabled and no invite code, add as editor
await prisma . teamMember . create ({
data : {
teamId : defaultTeam.id ,
userId : user.id ,
role : 'editor' ,
scope : 'team' ,
},
})
}
if ( inviteCode ) {
await inviteService . consumeInvite ( inviteCode , user . id )
}
2026-07-01 17:46:17 +08:00
const locale = body ? . locale
2026-11-16 19:48:01 +09:00
if ( locale === 'en' || locale === 'zh' || locale === 'ko' ) {
2026-07-01 17:46:17 +08:00
const joinedTeams = await prisma . teamMember . findMany ({
where : { userId : user.id },
select : { teamId : true },
})
for ( const member of joinedTeams ) {
await userMetadataService . upsertMetadata ( user . id , member . teamId , 'locale' , locale )
}
}
2026-05-19 16:05:09 +08:00
} catch ( err ) {
console . error ( `[Better Auth Hook] Error in after hook: ${ err } ` )
}
}
}
}),
},
})
2026-08-25 14:35:33 +08:00
export class AuthService {
constructor ( private readonly prismaClient : typeof prisma = prisma ) {}
async generatePasswordResetLink ( email : string ) : Promise < string > {
const user = await this . prismaClient . user . findUnique ({
where : { email },
})
if ( ! user ) {
throw new Error ( `User with email " ${ email } " not found` )
}
const context : GeneratedResetLink = { url : '' , token : '' }
await resetLinkStorage . run ( context , async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res = await ( auth . api . requestPasswordReset as any )({
headers : new Headers (),
body : {
email ,
redirectTo : '/reset-password' ,
},
})
if ( res ? . error ) {
throw new Error ( res . error . message || 'Failed to generate reset link' )
}
})
if ( context . token ) {
// Invalidate any other pending reset tokens for this user
await this . prismaClient . verification . deleteMany ({
where : {
value : user.id ,
identifier : {
startsWith : 'reset-password:' ,
not : `reset-password: ${ context . token } ` ,
},
},
})
const rawBaseUrl =
process . env . BETTER_AUTH_URL ||
`http://localhost: ${ process . env . SHUMAI_SERVER_PORT || '3000' } `
2026-10-29 17:24:31 +08:00
const baseUrl = rawBaseUrl . replace ( /\/+$/ , '' )
2026-08-25 14:35:33 +08:00
return ` ${ baseUrl } /reset-password?token= ${ context . token } `
}
throw new Error ( 'Failed to generate reset link' )
}
async resetPassword ( token : string , newPassword : string ) : Promise < { success : boolean } > {
if ( ! token || ! token . trim ()) {
throw new Error ( 'Token is required' )
}
if ( ! newPassword || newPassword . length < 3 ) {
throw new Error ( 'Password must be at least 3 characters' )
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res = await ( auth . api . resetPassword as any )({
headers : new Headers (),
body : {
token ,
newPassword ,
password : newPassword ,
},
})
if ( res ? . error ) {
throw new Error ( res . error . message || 'Failed to reset password' )
}
return { success : true }
}
}
export const authService = new AuthService ()