| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { Inject, Injectable |
| 3 | import { ConfigService } |
| 4 | import { and, eq |
| 5 | import { nanoid } |
| 6 | |
| 7 | import { DATABASE } |
| 8 | import { mailConfigured } |
| 9 | import { MailService } |
| 10 | import { UsersService } |
| 11 | import type { ListEmailsResponseDTO, |
| 12 | import { |
| 13 | EmailAlreadyTakenError, |
| 14 | EmailAlreadyVerifiedError, |
| 15 | EmailNotFoundError, |
| 16 | EmailNotVerifiedError, |
| 17 | InvalidVerificationTokenError, |
| 18 | MailNotConfiguredError, |
| 19 | ResendTooSoonError, |
| 20 | } from './emails.errors.js'; |
| 21 | |
| 22 | /** Long enough that a link cannot be guessed, short enough to stay pasteable. */ |
| 23 | const TOKEN_TTL_MS = 60 |
| 24 | /** A fresh link is useless twice over, so resends wait this long. */ |
| 25 | const RESEND_INTERVAL_MS = 60 |
| 26 | |
| 27 | /** |
| 28 | * Addresses an account owns beyond the one Better Auth signs it in with. |
| 29 | * |
| 30 | * Better Auth keys identity on `user.email` and always will; these rows sit beside it and are resolved to it before its endpoints run. Nothing here touches its internals - the table, the tokens and the mail are ours. |
| 31 | */ |
| 32 | @Injectable() |
| 33 | export class EmailsService |
| 34 | private readonly apiUrl |
| 35 | private readonly webAppUrl |
| 36 | private readonly canSendMail |
| 37 | |
| 38 | constructor( |
| 39 | @Inject(DATABASE) |
| 40 | private readonly users |
| 41 | private readonly mail |
| 42 | config: ConfigService |
| 43 | ) { |
| 44 | this.apiUrl = |
| 45 | .getOrThrow<string>( |
| 46 | .replace(/\/+ |
| 47 | this.webAppUrl = |
| 48 | config.get<string |
| 49 | ).replace(/\/ |
| 50 | this.canSendMail = |
| 51 | } |
| 52 | |
| 53 | /** The account address first, then the extras, oldest first. */ |
| 54 | async list(userId |
| 55 | const [user, |
| 56 | this.users.getUserById |
| 57 | this.db |
| 58 | .select() |
| 59 | .from(schema.userEmail |
| 60 | .where(eq(schema |
| 61 | .orderBy(schema.userEmail |
| 62 | ]); |
| 63 | |
| 64 | const emails: |
| 65 | { |
| 66 | id: 'primary', |
| 67 | email: user.email |
| 68 | verified: user.emailVerified |
| 69 | primary: true, |
| 70 | }, |
| 71 | ...rows.map( |
| 72 | id: row.id |
| 73 | email: row.email |
| 74 | verified: row.verified |
| 75 | primary: false, |
| 76 | })), |
| 77 | ]; |
| 78 | |
| 79 | return { emails |
| 80 | } |
| 81 | |
| 82 | /** Adds an address and mails it a verification link. The row exists straight away but counts for nothing until the link is followed, so adding an address can never claim another person's commits or sign-ins. */ |
| 83 | async add(userId |
| 84 | if (!this.canSendMail |
| 85 | |
| 86 | const email = |
| 87 | await this.assertAvailable |
| 88 | |
| 89 | const [row] |
| 90 | .insert(schema.userEmail |
| 91 | .values({ id: |
| 92 | .returning(); |
| 93 | |
| 94 | await this.mailLink |
| 95 | |
| 96 | return { |
| 97 | id: row!.id |
| 98 | email: row!.email |
| 99 | verified: row!.verified |
| 100 | primary: false, |
| 101 | }; |
| 102 | } |
| 103 | |
| 104 | /** Sends a fresh link to an address that has not been confirmed yet, for the mail that never arrived or expired. The previous link stops working. */ |
| 105 | async resend(userId |
| 106 | if (!this.canSendMail |
| 107 | |
| 108 | const row = |
| 109 | if (row.verified |
| 110 | |
| 111 | // The stored expiry doubles as the "last sent" stamp: a token issued less than a minute ago still has all but a minute of its life left. |
| 112 | const issuedAt = |
| 113 | ? row.tokenExpiresAt. |
| 114 | : 0; |
| 115 | if (Date.now |
| 116 | throw new ResendTooSoonError() |
| 117 | } |
| 118 | |
| 119 | await this.mailLink |
| 120 | } |
| 121 | |
| 122 | /** Issues a single-use token for a row and mails the link that carries it. */ |
| 123 | private async mailLink |
| 124 | const token = |
| 125 | await this.db |
| 126 | .update(schema.userEmail |
| 127 | .set({ token |
| 128 | .where(eq(schema |
| 129 | |
| 130 | const user = |
| 131 | await this.mail |
| 132 | name: user.name |
| 133 | verifyUrl: `${this. |
| 134 | }); |
| 135 | } |
| 136 | |
| 137 | /** Confirms an address from its link. Single use: the token is cleared, so a forwarded mail cannot be replayed. */ |
| 138 | async verify(token |
| 139 | const [row] |
| 140 | .update(schema.userEmail |
| 141 | .set({ verified: |
| 142 | .where( |
| 143 | and( |
| 144 | eq(schema.userEmail |
| 145 | eq(schema.userEmail |
| 146 | gt(schema.userEmail |
| 147 | ), |
| 148 | ) |
| 149 | .returning(); |
| 150 | |
| 151 | if (!row) |
| 152 | |
| 153 | // Commits indexed before the address was known are now attributable. |
| 154 | await this.db |
| 155 | UPDATE "repository_contribution" |
| 156 | SET "author_id" = ${row.userId} |
| 157 | WHERE "author_id" IS NULL |
| 158 | AND "author_email" = ${row.email} |
| 159 | `); |
| 160 | |
| 161 | return { email: |
| 162 | } |
| 163 | |
| 164 | /** Swaps a verified address with the account one. Better Auth keeps seeing exactly one address; the old primary stays on the account as an extra, so sign-in with it keeps working. */ |
| 165 | async makePrimary( |
| 166 | userId: string, |
| 167 | id: string, |
| 168 | ): Promise<ListEmailsResponseDTO |
| 169 | const row = |
| 170 | if (!row.verified |
| 171 | |
| 172 | const user = |
| 173 | |
| 174 | await this.db |
| 175 | await tx.delete |
| 176 | await tx.insert |
| 177 | id: `uem_${nanoid |
| 178 | userId, |
| 179 | email: user.email |
| 180 | verified: user.emailVerified |
| 181 | }); |
| 182 | await tx |
| 183 | .update(schema.user |
| 184 | .set({ email: |
| 185 | .where(eq(schema |
| 186 | }); |
| 187 | |
| 188 | return this.list |
| 189 | } |
| 190 | |
| 191 | async remove(userId |
| 192 | const row = |
| 193 | await this.db |
| 194 | .delete(schema.userEmail |
| 195 | .where(eq(schema |
| 196 | } |
| 197 | |
| 198 | /** Where a verification link sends the browser once it has been followed. */ |
| 199 | settingsUrl(status: |
| 200 | return `${this. |
| 201 | } |
| 202 | |
| 203 | private async own |
| 204 | const [row] |
| 205 | .select() |
| 206 | .from(schema.userEmail |
| 207 | .where( |
| 208 | and(eq(schema |
| 209 | ); |
| 210 | if (!row) |
| 211 | return row; |
| 212 | } |
| 213 | |
| 214 | /** An address belongs to one account only, primary or extra. */ |
| 215 | private async assertAvailable |
| 216 | const [[takenAsPrimary], |
| 217 | this.db |
| 218 | .select({ id: |
| 219 | .from(schema.user |
| 220 | .where(eq(sql |
| 221 | this.db |
| 222 | .select({ id: |
| 223 | .from(schema.userEmail |
| 224 | .where(eq(schema |
| 225 | ]); |
| 226 | |
| 227 | if (takenAsPrimary || |
| 228 | } |
| 229 | } |