@prunellejs/auth 0.1.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/links.ts ADDED
@@ -0,0 +1,178 @@
1
+ // One-time emailed link issuance & verification (magic links and email verification) with signup mail-delay equalization.
2
+
3
+ import type { AuthMailPayload, AuthOptions } from './index'
4
+ import type { SessionManager } from './session'
5
+ import type { AuthStore, AuthUser } from './store'
6
+ import { safeEqual, safeRedirect } from 'prunelle/server'
7
+ import { randomToken, sha256Hex } from './crypto'
8
+ import { normalizeEmail } from './store'
9
+
10
+ const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
11
+ const LINK_MAILS = {
12
+ 'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
13
+ 'verify-email': { subject: 'Verify your email address', text: 'Confirm your email address using this one-time link', html: 'Click to verify your email address', label: 'Verify email' },
14
+ } as const
15
+
16
+ // Binds a verify-email token to the user's current passwordHash so any password update invalidates prior verification links.
17
+ function verifyBinding(user: { id: string, passwordHash?: string | undefined }): string {
18
+ return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
19
+ }
20
+
21
+ export function buildMailDeliverer(
22
+ sendMail: AuthOptions['sendMail'],
23
+ mailer: AuthOptions['mailer'],
24
+ ): ((mail: AuthMailPayload) => void | Promise<void>) | undefined {
25
+ if (sendMail)
26
+ return sendMail
27
+ if (!mailer)
28
+ return undefined
29
+ return async (mail) => {
30
+ await mailer.send({ to: mail.to, subject: mail.subject, text: mail.text, html: mail.html })
31
+ }
32
+ }
33
+
34
+ type MailDeliverer = (mail: AuthMailPayload) => void | Promise<void>
35
+
36
+ /** A mail sent after the response, so a taken and a new address take the same time to answer; `onFailure` undoes what the sign-up did when it cannot be sent. */
37
+ export interface MailInBackground {
38
+ onFailure: () => void | Promise<void>
39
+ }
40
+
41
+ export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
42
+ store: AuthStore<TUser>
43
+ sessions: SessionManager<TUser>
44
+ basePath: string
45
+ defaultRedirect: string
46
+ tokenTtlMs: number
47
+ deliverMail: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
48
+ }
49
+
50
+ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkServiceDeps<TUser>) {
51
+ const { store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail } = deps
52
+ const pendingDeliveries = new Set<Promise<void>>()
53
+
54
+ async function issueLink(
55
+ kind: 'magic-link' | 'verify-email',
56
+ userId: string | undefined,
57
+ email: string,
58
+ origin: string | undefined,
59
+ redirectTo: string | undefined,
60
+ background?: MailInBackground,
61
+ ): Promise<string> {
62
+ const normalized = normalizeEmail(email)
63
+ const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
64
+ const rawToken = boundUser ? `${randomToken(32)}.${verifyBinding(boundUser)}` : randomToken(32)
65
+ const tokenHash = sha256Hex(rawToken)
66
+ await sessions.observeAsync(store.createToken({
67
+ tokenHash,
68
+ ...(userId !== undefined ? { userId } : {}),
69
+ email: normalized,
70
+ kind,
71
+ expiresAt: Date.now() + tokenTtlMs,
72
+ }))
73
+
74
+ const next = safeRedirect(redirectTo, defaultRedirect)
75
+ const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
76
+ const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
77
+
78
+ if (deliverMail && origin !== undefined) {
79
+ const delivery = deliverLink(deliverMail, kind, normalized, url, tokenHash)
80
+ if (background === undefined) {
81
+ await delivery
82
+ }
83
+ else {
84
+ const tracked = delivery.catch(err => failBackgroundMail(err, background)).finally(() => { pendingDeliveries.delete(tracked) })
85
+ pendingDeliveries.add(tracked)
86
+ }
87
+ }
88
+ return url
89
+ }
90
+
91
+ // Mails the link; a mail that cannot be sent takes its token back, so a link that never arrived cannot be used.
92
+ async function deliverLink(send: MailDeliverer, kind: 'magic-link' | 'verify-email', to: string, url: string, tokenHash: string): Promise<void> {
93
+ const mail = LINK_MAILS[kind]
94
+ try {
95
+ await send({
96
+ to,
97
+ subject: mail.subject,
98
+ text: `${mail.text}: ${url}`,
99
+ html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
100
+ url,
101
+ kind,
102
+ })
103
+ }
104
+ catch (err) {
105
+ try {
106
+ await sessions.observeAsync(store.consumeToken(tokenHash, kind))
107
+ }
108
+ catch (cleanupErr) {
109
+ console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
110
+ }
111
+ throw err
112
+ }
113
+ }
114
+
115
+ async function failBackgroundMail(err: unknown, background: MailInBackground): Promise<void> {
116
+ console.error('[prunelle/auth] could not send a verification mail:', err)
117
+ try {
118
+ await background.onFailure()
119
+ }
120
+ catch (rollbackErr) {
121
+ console.error('[prunelle/auth] failed to roll back after a mail error:', rollbackErr)
122
+ }
123
+ }
124
+
125
+ async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
126
+ const normalized = normalizeEmail(email)
127
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
128
+ return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
129
+ }
130
+
131
+ async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
132
+ const normalized = normalizeEmail(email)
133
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
134
+ return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
135
+ }
136
+
137
+ async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
138
+ const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
139
+ if (!consumed)
140
+ return undefined
141
+ const user = consumed.userId
142
+ ? await sessions.observeAsync(store.getUserById(consumed.userId))
143
+ : await sessions.observeAsync(store.getUserByEmail(consumed.email))
144
+ if (kind === 'verify-email') {
145
+ const dot = rawToken.lastIndexOf('.')
146
+ if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), verifyBinding(user)))
147
+ return undefined
148
+ }
149
+ return { email: consumed.email, user }
150
+ }
151
+
152
+ async function drain(timeoutMs = 5_000): Promise<void> {
153
+ if (pendingDeliveries.size === 0)
154
+ return
155
+ let timer: ReturnType<typeof setTimeout> | undefined
156
+ try {
157
+ await Promise.race([
158
+ Promise.allSettled([...pendingDeliveries]),
159
+ new Promise<void>((resolve) => {
160
+ timer = setTimeout(resolve, timeoutMs)
161
+ timer.unref?.()
162
+ }),
163
+ ])
164
+ }
165
+ finally {
166
+ if (timer !== undefined)
167
+ clearTimeout(timer)
168
+ }
169
+ }
170
+
171
+ return {
172
+ issueLink,
173
+ sendVerificationEmail,
174
+ sendMagicLink,
175
+ consumeLink,
176
+ drain,
177
+ }
178
+ }
@@ -4,10 +4,12 @@ import type { RequestContext } from 'prunelle/server'
4
4
  import { safeEqual, safeRedirect } from 'prunelle/server'
5
5
  import type { OAuthProfile, OAuthProvider } from './oauth'
6
6
  import type { AuthStore, AuthUser, PublicUser } from './store'
7
+ import type { TotpManager } from './totp'
7
8
  import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
8
- import { fail, withNoStore } from './http'
9
+ import { authCookie, fail, withNoStore } from './http'
9
10
  import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
10
- import { toPublicUser } from './store'
11
+ import { normalizeEmail, toPublicUser } from './store'
12
+ import { respondTwoFactorChallenge } from './totp'
11
13
 
12
14
  interface OAuthStateCookie {
13
15
  provider: string
@@ -21,22 +23,120 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
21
23
  route: (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>) => void
22
24
  store: AuthStore<TUser>
23
25
  providers: ReadonlyMap<string, OAuthProvider>
24
- secret: string
26
+ /** The app's signing secret, resolved at first use. */
27
+ secret: () => string
25
28
  site: string | undefined
26
29
  basePath: string
27
30
  stateCookieName: string
28
31
  defaultRedirect: string
32
+ requireEmailVerification: boolean
33
+ hasMailTransport: boolean
34
+ mailedLinkOrigin: (url: URL) => string | undefined
35
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
29
36
  limitIp: (ctx: RequestContext, scope: string) => Response | undefined
30
37
  isSecureCookie: (ctx: RequestContext) => boolean
31
38
  claimUnverified: (user: TUser) => Promise<TUser>
32
39
  insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
33
- createSessionForUser: (userId: string, ctx: RequestContext) => Promise<unknown>
34
- setResolvedUser: (ctx: RequestContext, user: PublicUser<TUser>) => void
40
+ /** Keep the provider's name and avatar URL on a new account. */
41
+ storeProfile: boolean
42
+ totp: Pick<TotpManager, 'getTwoFactorMethods' | 'issuePendingCookie'>
43
+ twoFactorRedirect: string
44
+ createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
35
45
  observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
36
46
  }
37
47
 
48
+ // The provider's name and avatar belong to the account only when the app asked to keep them.
49
+ function profileFields(deps: Pick<OAuthRouteDeps, 'storeProfile'>, profile: OAuthProfile): { name?: string, avatarUrl?: string } {
50
+ if (!deps.storeProfile)
51
+ return {}
52
+ return {
53
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
54
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
55
+ }
56
+ }
57
+
58
+ async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
59
+ deps: OAuthRouteDeps<TUser>,
60
+ ctx: RequestContext,
61
+ profile: OAuthProfile,
62
+ redirectTarget: string,
63
+ ): Promise<Response> {
64
+ const linkOrigin = deps.mailedLinkOrigin(ctx.url)
65
+ if (deps.hasMailTransport && linkOrigin === undefined) {
66
+ console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
67
+ return fail(ctx, 500, 'Verification links are not configured')
68
+ }
69
+ const created = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: false } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
70
+ try {
71
+ await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
72
+ }
73
+ catch {
74
+ try {
75
+ await deps.observeAsync(deps.store.deleteUser(created.id))
76
+ }
77
+ catch (rollbackErr) {
78
+ console.error('[prunelle/auth] failed to roll back unverified OAuth user:', rollbackErr)
79
+ }
80
+ return fail(ctx, 500, 'Unable to send verification email')
81
+ }
82
+ return ctx.redirect(redirectTarget, 302)
83
+ }
84
+
85
+ async function resolveOAuthUser<TUser extends AuthUser>(
86
+ deps: OAuthRouteDeps<TUser>,
87
+ ctx: RequestContext,
88
+ provider: OAuthProvider,
89
+ profile: OAuthProfile,
90
+ redirectTarget: string,
91
+ ): Promise<TUser | Response> {
92
+ const { store, observeAsync, requireEmailVerification } = deps
93
+ const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
94
+
95
+ if (existingLink) {
96
+ let userRecord = await observeAsync(store.getUserById(existingLink.userId))
97
+ if (!userRecord)
98
+ return fail(ctx, 500, 'Unable to resolve user account')
99
+ if (requireEmailVerification && !userRecord.emailVerified) {
100
+ if (profile.emailVerified && normalizeEmail(profile.email) === userRecord.email) {
101
+ userRecord = await deps.claimUnverified(userRecord)
102
+ await observeAsync(store.linkOAuthAccount({
103
+ provider: provider.id,
104
+ providerAccountId: profile.id,
105
+ userId: userRecord.id,
106
+ createdAt: Date.now(),
107
+ }))
108
+ return userRecord
109
+ }
110
+ return fail(ctx, 403, 'Email not verified')
111
+ }
112
+ return userRecord
113
+ }
114
+
115
+ const byEmail = await observeAsync(store.getUserByEmail(profile.email))
116
+ let userRecord: TUser | undefined
117
+ if (byEmail && profile.emailVerified) {
118
+ userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
119
+ }
120
+ else if (!byEmail) {
121
+ if (requireEmailVerification && !profile.emailVerified)
122
+ return handleUnverifiedOAuthSignup(deps, ctx, profile, redirectTarget)
123
+ userRecord = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: profile.emailVerified } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
124
+ }
125
+ else {
126
+ return fail(ctx, 409, 'An account with this email already exists; verify email to link')
127
+ }
128
+
129
+ await observeAsync(store.linkOAuthAccount({
130
+ provider: provider.id,
131
+ providerAccountId: profile.id,
132
+ userId: userRecord.id,
133
+ createdAt: Date.now(),
134
+ }))
135
+ return userRecord
136
+ }
137
+
38
138
  export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAuthRouteDeps<TUser>): void {
39
- const { route, store, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp, observeAsync } = deps
139
+ const { route, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp } = deps
40
140
  const callbackUrlFor = (ctx: RequestContext, provider: OAuthProvider): string =>
41
141
  `${site ?? ctx.url.origin}${basePath}/oauth/${encodeURIComponent(provider.id)}/callback`
42
142
 
@@ -57,7 +157,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
57
157
  const verifier = provider.pkce !== false ? randomToken(32) : undefined
58
158
  const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
59
159
 
60
- const cookieVal = signPayload(secret, {
160
+ const cookieVal = signPayload(secret(), {
61
161
  provider: provider.id,
62
162
  state,
63
163
  verifier,
@@ -65,13 +165,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
65
165
  exp: Date.now() + 10 * 60 * 1000,
66
166
  } satisfies OAuthStateCookie)
67
167
 
68
- ctx.cookies.set(stateCookieName, cookieVal, {
69
- path: '/',
70
- httpOnly: true,
71
- sameSite: 'lax',
72
- secure: deps.isSecureCookie(ctx),
73
- maxAge: 600,
74
- })
168
+ ctx.cookies.set(stateCookieName, cookieVal, authCookie(deps.isSecureCookie(ctx), 600))
75
169
 
76
170
  const callbackUrl = callbackUrlFor(ctx, provider)
77
171
  const authUrl = new URL(provider.authorizeUrl)
@@ -84,7 +178,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
84
178
  authUrl.searchParams.set('code_challenge', pkceChallenge(verifier))
85
179
  authUrl.searchParams.set('code_challenge_method', 'S256')
86
180
  }
87
- return ctx.redirect(authUrl.toString(), 302)
181
+ return ctx.redirect(authUrl.toString(), 302, { external: true })
88
182
  })
89
183
 
90
184
  noStoreRoute('GET', `${basePath}/oauth/:provider/callback`, async (ctx) => {
@@ -104,7 +198,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
104
198
  if (!code || !returnedState || !rawCookie)
105
199
  return fail(ctx, 400, 'Invalid OAuth callback parameters')
106
200
 
107
- const saved = verifyPayload<OAuthStateCookie>(secret, rawCookie)
201
+ const saved = verifyPayload<OAuthStateCookie>(secret(), rawCookie)
108
202
  if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
109
203
  return fail(ctx, 400, 'Invalid or expired OAuth state')
110
204
 
@@ -151,43 +245,16 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
151
245
  if (!profile?.id || !profile.email)
152
246
  return fail(ctx, 502, 'OAuth profile fetch failed')
153
247
 
154
- const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
155
- let userRecord: TUser | undefined
248
+ const redirectTarget = safeRedirect(saved.redirect, defaultRedirect)
249
+ const resolved = await resolveOAuthUser(deps, ctx, provider, profile, redirectTarget)
250
+ if (resolved instanceof Response)
251
+ return resolved
156
252
 
157
- if (existingLink) {
158
- userRecord = await observeAsync(store.getUserById(existingLink.userId))
159
- }
160
- else {
161
- const byEmail = await observeAsync(store.getUserByEmail(profile.email))
162
- if (byEmail && profile.emailVerified) {
163
- userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
164
- }
165
- else if (!byEmail) {
166
- userRecord = await deps.insertUser({
167
- email: profile.email,
168
- ...(profile.name !== undefined ? { name: profile.name } : {}),
169
- ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
170
- emailVerified: profile.emailVerified,
171
- } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
172
- }
173
- else {
174
- return fail(ctx, 409, 'An account with this email already exists; verify email to link')
175
- }
176
- if (userRecord) {
177
- await observeAsync(store.linkOAuthAccount({
178
- provider: provider.id,
179
- providerAccountId: profile.id,
180
- userId: userRecord.id,
181
- createdAt: Date.now(),
182
- }))
183
- }
184
- }
185
-
186
- if (!userRecord)
187
- return fail(ctx, 500, 'Unable to resolve user account')
253
+ const twoFactorMethods = await deps.totp.getTwoFactorMethods(resolved.id)
254
+ if (twoFactorMethods.length > 0)
255
+ return respondTwoFactorChallenge(deps.totp, ctx, resolved.id, redirectTarget, deps.twoFactorRedirect, twoFactorMethods, 302)
188
256
 
189
- await deps.createSessionForUser(userRecord.id, ctx)
190
- deps.setResolvedUser(ctx, toPublicUser(userRecord))
191
- return ctx.redirect(safeRedirect(saved.redirect, defaultRedirect), 302)
257
+ await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
258
+ return ctx.redirect(redirectTarget, 302)
192
259
  })
193
260
  }
@@ -0,0 +1,226 @@
1
+ // HTTP routes for organizations: create, invite, accept invitation, update member role, remove/leave member.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+ import type { AuthLimits, AuthRouteRegistrar } from './http'
5
+ import type { OrgError, OrgManager } from './orgs'
6
+ import type { SessionManager } from './session'
7
+ import type { AuthUser, Organization } from './store'
8
+ import { safeRedirect, wantsJson } from 'prunelle/server'
9
+ import { fail, isValidEmail, linkConfirmPage } from './http'
10
+ import { normalizeEmail } from './store'
11
+
12
+ export interface OrgRoutesDeps<TUser extends AuthUser = AuthUser> {
13
+ authRoute: AuthRouteRegistrar
14
+ limits: AuthLimits
15
+ sessions: SessionManager<TUser>
16
+ orgs: OrgManager
17
+ defaultRedirect: string
18
+ hasMailTransport: boolean
19
+ mailedLinkOrigin: (url: URL) => string | undefined
20
+ }
21
+
22
+ function respondOrgErr(ctx: RequestContext, err: unknown): Response {
23
+ const oe = err as Partial<OrgError>
24
+ const status = typeof oe?.status === 'number' ? oe.status : 400
25
+ const message = err instanceof Error ? err.message : 'Organization request failed'
26
+ return fail(ctx, status, message)
27
+ }
28
+
29
+ function isAdminRole(role: string): boolean {
30
+ return role === 'owner' || role === 'admin'
31
+ }
32
+
33
+ function registerOrgMemberRoutes<TUser extends AuthUser>(
34
+ deps: OrgRoutesDeps<TUser>,
35
+ resolveOrgParam: (body: Record<string, string>) => Promise<Organization | undefined>,
36
+ ): void {
37
+ const { authRoute, sessions, orgs, defaultRedirect } = deps
38
+
39
+ authRoute('POST', '/orgs/member/role', { limit: 'orgs-member', readBody: true }, async (ctx, body) => {
40
+ const resolved = await sessions.resolve(ctx)
41
+ if (!resolved)
42
+ return fail(ctx, 401, 'Authentication required')
43
+
44
+ const org = await resolveOrgParam(body)
45
+ if (!org)
46
+ return fail(ctx, 404, 'Organization not found')
47
+
48
+ const caller = await orgs.getOrgMember(org.id, resolved.user.id)
49
+ if (!caller || !isAdminRole(caller.role))
50
+ return fail(ctx, 403, 'Forbidden')
51
+
52
+ const targetUserId = (body.userId ?? '').trim()
53
+ const newRole = (body.role ?? '').trim()
54
+ if (!targetUserId || !newRole)
55
+ return fail(ctx, 400, 'userId and role are required')
56
+
57
+ const target = await orgs.getOrgMember(org.id, targetUserId)
58
+ if (!target)
59
+ return fail(ctx, 404, 'Member not found')
60
+ if ((target.role === 'owner' || newRole === 'owner') && caller.role !== 'owner')
61
+ return fail(ctx, 403, 'Only organization owners can change owner roles')
62
+
63
+ try {
64
+ const membership = await orgs.updateOrgMemberRole(org.id, targetUserId, newRole)
65
+ if (!membership)
66
+ return fail(ctx, 404, 'Member not found')
67
+ if (wantsJson(ctx.request))
68
+ return ctx.json({ ok: true, membership }, { status: 200 })
69
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
70
+ }
71
+ catch (err) {
72
+ return respondOrgErr(ctx, err)
73
+ }
74
+ })
75
+
76
+ authRoute('POST', '/orgs/member/remove', { limit: 'orgs-member', readBody: true }, async (ctx, body) => {
77
+ const resolved = await sessions.resolve(ctx)
78
+ if (!resolved)
79
+ return fail(ctx, 401, 'Authentication required')
80
+
81
+ const org = await resolveOrgParam(body)
82
+ if (!org)
83
+ return fail(ctx, 404, 'Organization not found')
84
+
85
+ const targetUserId = (body.userId ?? '').trim() || resolved.user.id
86
+ const isSelfLeave = targetUserId === resolved.user.id
87
+ const caller = await orgs.getOrgMember(org.id, resolved.user.id)
88
+ if (!caller)
89
+ return fail(ctx, 403, 'Forbidden')
90
+ if (!isSelfLeave && !isAdminRole(caller.role))
91
+ return fail(ctx, 403, 'Forbidden')
92
+
93
+ const target = await orgs.getOrgMember(org.id, targetUserId)
94
+ if (!target)
95
+ return fail(ctx, 404, 'Member not found')
96
+ if (!isSelfLeave && target.role === 'owner' && caller.role !== 'owner')
97
+ return fail(ctx, 403, 'Only organization owners can remove another owner')
98
+
99
+ try {
100
+ await orgs.removeOrgMember(org.id, targetUserId)
101
+ if (wantsJson(ctx.request))
102
+ return ctx.json({ ok: true }, { status: 200 })
103
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
104
+ }
105
+ catch (err) {
106
+ return respondOrgErr(ctx, err)
107
+ }
108
+ })
109
+ }
110
+
111
+ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRoutesDeps<TUser>): void {
112
+ const { authRoute, limits, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin } = deps
113
+
114
+ async function resolveOrgParam(body: Record<string, string>): Promise<Organization | undefined> {
115
+ const ref = (body.orgId ?? body.org ?? body.slug ?? '').trim()
116
+ return ref ? orgs.getOrg(ref) : undefined
117
+ }
118
+
119
+ authRoute('POST', '/orgs', { limit: 'orgs', readBody: true }, async (ctx, body) => {
120
+ const resolved = await sessions.resolve(ctx)
121
+ if (!resolved)
122
+ return fail(ctx, 401, 'Authentication required')
123
+ try {
124
+ const org = await orgs.createOrg(resolved.user.id, {
125
+ name: body.name ?? '',
126
+ ...(body.slug ? { slug: body.slug } : {}),
127
+ })
128
+ if (wantsJson(ctx.request))
129
+ return ctx.json({ ok: true, org }, { status: 201 })
130
+ return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
131
+ }
132
+ catch (err) {
133
+ return respondOrgErr(ctx, err)
134
+ }
135
+ })
136
+
137
+ authRoute('POST', '/orgs/invite', { limit: 'orgs-invite', readBody: true }, async (ctx, body) => {
138
+ const resolved = await sessions.resolve(ctx)
139
+ if (!resolved)
140
+ return fail(ctx, 401, 'Authentication required')
141
+
142
+ const org = await resolveOrgParam(body)
143
+ if (!org)
144
+ return fail(ctx, 404, 'Organization not found')
145
+
146
+ const caller = await orgs.getOrgMember(org.id, resolved.user.id)
147
+ if (!caller || !isAdminRole(caller.role))
148
+ return fail(ctx, 403, 'Forbidden')
149
+
150
+ const role = (body.role?.trim()) || 'member'
151
+ if (role === 'owner' && caller.role !== 'owner')
152
+ return fail(ctx, 403, 'Only organization owners can invite another owner')
153
+
154
+ const email = normalizeEmail(body.email ?? '')
155
+ if (!isValidEmail(email))
156
+ return fail(ctx, 400, 'prunelle: please enter a valid email address')
157
+
158
+ const linkOrigin = mailedLinkOrigin(ctx.url)
159
+ if (hasMailTransport && linkOrigin === undefined) {
160
+ console.error(`[prunelle/auth] refusing to mail an organization invite for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
161
+ return fail(ctx, 500, 'Invitation links are not configured')
162
+ }
163
+
164
+ const limited = limits.limitMail(ctx, email)
165
+ if (limited)
166
+ return limited
167
+
168
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
169
+ try {
170
+ const { invitation } = await orgs.inviteToOrg(org.id, {
171
+ email,
172
+ role,
173
+ invitedBy: resolved.user.id,
174
+ origin: linkOrigin,
175
+ redirectTo: redirectTarget,
176
+ })
177
+ if (wantsJson(ctx.request)) {
178
+ return ctx.json({
179
+ ok: true,
180
+ invitation: {
181
+ id: invitation.id,
182
+ orgId: invitation.orgId,
183
+ email: invitation.email,
184
+ role: invitation.role,
185
+ expiresAt: invitation.expiresAt,
186
+ createdAt: invitation.createdAt,
187
+ },
188
+ }, { status: 201 })
189
+ }
190
+ return ctx.redirect(redirectTarget, 303)
191
+ }
192
+ catch (err) {
193
+ return respondOrgErr(ctx, err)
194
+ }
195
+ })
196
+
197
+ authRoute('GET', '/orgs/invite/accept', { limit: 'orgs-accept' }, (ctx) => {
198
+ const token = ctx.url.searchParams.get('token') ?? ''
199
+ if (!token)
200
+ return fail(ctx, 400, 'Missing token')
201
+ return linkConfirmPage(
202
+ { title: 'Accept organization invitation', button: 'Accept invitation' },
203
+ { token, redirect: ctx.url.searchParams.get('redirect') ?? '' },
204
+ )
205
+ })
206
+
207
+ authRoute('POST', '/orgs/invite/accept', { limit: 'orgs-accept', readBody: true }, async (ctx, body) => {
208
+ const resolved = await sessions.resolve(ctx)
209
+ if (!resolved)
210
+ return fail(ctx, 401, 'Authentication required')
211
+
212
+ const token = body.token ?? ctx.url.searchParams.get('token') ?? ''
213
+ const redirectTarget = safeRedirect(body.redirect ?? body.next ?? ctx.url.searchParams.get('redirect'), defaultRedirect)
214
+ try {
215
+ const { org, membership } = await orgs.acceptOrgInvite(token, resolved.user.id)
216
+ if (wantsJson(ctx.request))
217
+ return ctx.json({ ok: true, org, membership }, { status: 200 })
218
+ return ctx.redirect(redirectTarget, 303)
219
+ }
220
+ catch (err) {
221
+ return respondOrgErr(ctx, err)
222
+ }
223
+ })
224
+
225
+ registerOrgMemberRoutes(deps, resolveOrgParam)
226
+ }