@prunellejs/auth 0.1.1 → 0.6.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,150 @@
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 MAIL_DELAY_MIN_MS = 5
11
+ const MAIL_DELAY_MAX_MS = 2000
12
+ const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
13
+ const LINK_MAILS = {
14
+ 'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
15
+ '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' },
16
+ } as const
17
+
18
+ // Binds a verify-email token to the user's current passwordHash so any password update invalidates prior verification links.
19
+ function verifyBinding(user: { id: string, passwordHash?: string | undefined }): string {
20
+ return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
21
+ }
22
+
23
+ export function buildMailDeliverer(
24
+ sendMail: AuthOptions['sendMail'],
25
+ mailer: AuthOptions['mailer'],
26
+ ): ((mail: AuthMailPayload) => void | Promise<void>) | undefined {
27
+ if (sendMail)
28
+ return sendMail
29
+ if (!mailer)
30
+ return undefined
31
+ return async (mail) => {
32
+ await mailer.send({ to: mail.to, subject: mail.subject, text: mail.text, html: mail.html })
33
+ }
34
+ }
35
+
36
+ function createMailDelayTracker(): { observe: (ms: number) => void, pad: () => Promise<void> } {
37
+ let ewmaMs: number | undefined
38
+ return {
39
+ observe(ms: number) {
40
+ const clamped = Math.min(MAIL_DELAY_MAX_MS, Math.max(0, ms))
41
+ ewmaMs = ewmaMs === undefined ? clamped : ewmaMs * 0.7 + clamped * 0.3
42
+ },
43
+ async pad() {
44
+ if (ewmaMs === undefined || ewmaMs < MAIL_DELAY_MIN_MS)
45
+ return
46
+ const jittered = Math.min(MAIL_DELAY_MAX_MS, Math.round(ewmaMs * (0.85 + Math.random() * 0.3)))
47
+ if (jittered >= MAIL_DELAY_MIN_MS)
48
+ await Bun.sleep(jittered)
49
+ },
50
+ }
51
+ }
52
+
53
+ export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
54
+ store: AuthStore<TUser>
55
+ sessions: SessionManager<TUser>
56
+ basePath: string
57
+ defaultRedirect: string
58
+ tokenTtlMs: number
59
+ deliverMail: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
60
+ }
61
+
62
+ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkServiceDeps<TUser>) {
63
+ const { store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail } = deps
64
+ const mailDelay = createMailDelayTracker()
65
+
66
+ async function issueLink(
67
+ kind: 'magic-link' | 'verify-email',
68
+ userId: string | undefined,
69
+ email: string,
70
+ origin: string | undefined,
71
+ redirectTo: string | undefined,
72
+ ): Promise<string> {
73
+ const normalized = normalizeEmail(email)
74
+ const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
75
+ const rawToken = boundUser ? `${randomToken(32)}.${verifyBinding(boundUser)}` : randomToken(32)
76
+ const tokenHash = sha256Hex(rawToken)
77
+ await sessions.observeAsync(store.createToken({
78
+ tokenHash,
79
+ ...(userId !== undefined ? { userId } : {}),
80
+ email: normalized,
81
+ kind,
82
+ expiresAt: Date.now() + tokenTtlMs,
83
+ }))
84
+
85
+ const next = safeRedirect(redirectTo, defaultRedirect)
86
+ const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
87
+ const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
88
+
89
+ if (deliverMail && origin !== undefined) {
90
+ const mail = LINK_MAILS[kind]
91
+ const startedAt = performance.now()
92
+ try {
93
+ await deliverMail({
94
+ to: normalized,
95
+ subject: mail.subject,
96
+ text: `${mail.text}: ${url}`,
97
+ html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
98
+ url,
99
+ kind,
100
+ })
101
+ mailDelay.observe(performance.now() - startedAt)
102
+ }
103
+ catch (err) {
104
+ try {
105
+ await sessions.observeAsync(store.consumeToken(tokenHash, kind))
106
+ }
107
+ catch (cleanupErr) {
108
+ console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
109
+ }
110
+ throw err
111
+ }
112
+ }
113
+ return url
114
+ }
115
+
116
+ async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
117
+ const normalized = normalizeEmail(email)
118
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
119
+ return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
120
+ }
121
+
122
+ async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
123
+ const normalized = normalizeEmail(email)
124
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
125
+ return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
126
+ }
127
+
128
+ async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
129
+ const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
130
+ if (!consumed)
131
+ return undefined
132
+ const user = consumed.userId
133
+ ? await sessions.observeAsync(store.getUserById(consumed.userId))
134
+ : await sessions.observeAsync(store.getUserByEmail(consumed.email))
135
+ if (kind === 'verify-email') {
136
+ const dot = rawToken.lastIndexOf('.')
137
+ if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), verifyBinding(user)))
138
+ return undefined
139
+ }
140
+ return { email: consumed.email, user }
141
+ }
142
+
143
+ return {
144
+ issueLink,
145
+ sendVerificationEmail,
146
+ sendMagicLink,
147
+ consumeLink,
148
+ equalizeSignupMailDelay: () => deliverMail ? mailDelay.pad() : Promise.resolve(),
149
+ }
150
+ }
@@ -7,7 +7,7 @@ import type { AuthStore, AuthUser, PublicUser } from './store'
7
7
  import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
8
8
  import { 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
@@ -26,17 +26,110 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
26
26
  basePath: string
27
27
  stateCookieName: string
28
28
  defaultRedirect: string
29
+ requireEmailVerification: boolean
30
+ hasMailTransport: boolean
31
+ mailedLinkOrigin: (url: URL) => string | undefined
32
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
29
33
  limitIp: (ctx: RequestContext, scope: string) => Response | undefined
30
34
  isSecureCookie: (ctx: RequestContext) => boolean
31
35
  claimUnverified: (user: TUser) => Promise<TUser>
32
36
  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
37
+ createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
35
38
  observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
36
39
  }
37
40
 
41
+ async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
42
+ deps: OAuthRouteDeps<TUser>,
43
+ ctx: RequestContext,
44
+ profile: OAuthProfile,
45
+ redirectTarget: string,
46
+ ): Promise<Response> {
47
+ const linkOrigin = deps.mailedLinkOrigin(ctx.url)
48
+ if (deps.hasMailTransport && linkOrigin === undefined) {
49
+ console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
50
+ return fail(ctx, 500, 'Verification links are not configured')
51
+ }
52
+ const created = await deps.insertUser({
53
+ email: profile.email,
54
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
55
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
56
+ emailVerified: false,
57
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
58
+ try {
59
+ await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
60
+ }
61
+ catch {
62
+ try {
63
+ await deps.observeAsync(deps.store.deleteUser(created.id))
64
+ }
65
+ catch (rollbackErr) {
66
+ console.error('[prunelle/auth] failed to roll back unverified OAuth user:', rollbackErr)
67
+ }
68
+ return fail(ctx, 500, 'Unable to send verification email')
69
+ }
70
+ return ctx.redirect(redirectTarget, 302)
71
+ }
72
+
73
+ async function resolveOAuthUser<TUser extends AuthUser>(
74
+ deps: OAuthRouteDeps<TUser>,
75
+ ctx: RequestContext,
76
+ provider: OAuthProvider,
77
+ profile: OAuthProfile,
78
+ redirectTarget: string,
79
+ ): Promise<TUser | Response> {
80
+ const { store, observeAsync, requireEmailVerification } = deps
81
+ const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
82
+
83
+ if (existingLink) {
84
+ let userRecord = await observeAsync(store.getUserById(existingLink.userId))
85
+ if (!userRecord)
86
+ return fail(ctx, 500, 'Unable to resolve user account')
87
+ if (requireEmailVerification && !userRecord.emailVerified) {
88
+ if (profile.emailVerified && normalizeEmail(profile.email) === userRecord.email) {
89
+ userRecord = await deps.claimUnverified(userRecord)
90
+ await observeAsync(store.linkOAuthAccount({
91
+ provider: provider.id,
92
+ providerAccountId: profile.id,
93
+ userId: userRecord.id,
94
+ createdAt: Date.now(),
95
+ }))
96
+ return userRecord
97
+ }
98
+ return fail(ctx, 403, 'Email not verified')
99
+ }
100
+ return userRecord
101
+ }
102
+
103
+ const byEmail = await observeAsync(store.getUserByEmail(profile.email))
104
+ let userRecord: TUser | undefined
105
+ if (byEmail && profile.emailVerified) {
106
+ userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
107
+ }
108
+ else if (!byEmail) {
109
+ if (requireEmailVerification && !profile.emailVerified)
110
+ return handleUnverifiedOAuthSignup(deps, ctx, profile, redirectTarget)
111
+ userRecord = await deps.insertUser({
112
+ email: profile.email,
113
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
114
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
115
+ emailVerified: profile.emailVerified,
116
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
117
+ }
118
+ else {
119
+ return fail(ctx, 409, 'An account with this email already exists; verify email to link')
120
+ }
121
+
122
+ await observeAsync(store.linkOAuthAccount({
123
+ provider: provider.id,
124
+ providerAccountId: profile.id,
125
+ userId: userRecord.id,
126
+ createdAt: Date.now(),
127
+ }))
128
+ return userRecord
129
+ }
130
+
38
131
  export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAuthRouteDeps<TUser>): void {
39
- const { route, store, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp, observeAsync } = deps
132
+ const { route, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp } = deps
40
133
  const callbackUrlFor = (ctx: RequestContext, provider: OAuthProvider): string =>
41
134
  `${site ?? ctx.url.origin}${basePath}/oauth/${encodeURIComponent(provider.id)}/callback`
42
135
 
@@ -151,43 +244,12 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
151
244
  if (!profile?.id || !profile.email)
152
245
  return fail(ctx, 502, 'OAuth profile fetch failed')
153
246
 
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')
247
+ const redirectTarget = safeRedirect(saved.redirect, defaultRedirect)
248
+ const resolved = await resolveOAuthUser(deps, ctx, provider, profile, redirectTarget)
249
+ if (resolved instanceof Response)
250
+ return resolved
188
251
 
189
- await deps.createSessionForUser(userRecord.id, ctx)
190
- deps.setResolvedUser(ctx, toPublicUser(userRecord))
191
- return ctx.redirect(safeRedirect(saved.redirect, defaultRedirect), 302)
252
+ await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
253
+ return ctx.redirect(redirectTarget, 302)
192
254
  })
193
255
  }
@@ -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', emailLimit: '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
+ }