@prunellejs/auth 0.1.1 → 0.7.0

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