| 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 { |
| 9 | EmailAlreadyTakenError, |
| 10 | EmailAlreadyVerifiedError, |
| 11 | EmailNotFoundError, |
| 12 | EmailNotVerifiedError, |
| 13 | InvalidVerificationTokenError, |
| 14 | MailNotConfiguredError, |
| 15 | ResendTooSoonError, |
| 16 | } from '../../lib/emails/emails.errors.js'; |
| 17 | import { mailConfigured } |
| 18 | import { MailService } |
| 19 | import { UsersService } |
| 20 | import type { ListEmailsResponseDTO, |
| 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 | /** Addresses beyond `user.email`, which Better Auth keys identity on; they resolve to it before its endpoints run, and nothing here touches its internals. */ |
| 28 | @Injectable() |
| 29 | export class EmailsService |
| 30 | private readonly apiUrl |
| 31 | private readonly webAppUrl |
| 32 | private readonly canSendMail |
| 33 | |
| 34 | constructor( |
| 35 | @Inject(DATABASE) |
| 36 | private readonly users |
| 37 | private readonly mail |
| 38 | config: ConfigService |
| 39 | ) { |
| 40 | this.apiUrl = |
| 41 | .getOrThrow<string>( |
| 42 | .replace(/\/+ |
| 43 | this.webAppUrl = |
| 44 | config.get<string |
| 45 | ).replace(/\/ |
| 46 | this.canSendMail = |
| 47 | } |
| 48 | |
| 49 | /** The account address first, then the extras, oldest first. */ |
| 50 | async list(userId |
| 51 | const [user, |
| 52 | this.users.getUserById |
| 53 | this.db |
| 54 | .select({ |
| 55 | id: schema.userEmail |
| 56 | email: schema.userEmail |
| 57 | verified: schema.userEmail |
| 58 | primary: sql<boolean |
| 59 | }) |
| 60 | .from(schema.userEmail |
| 61 | .where(eq(schema |
| 62 | .orderBy(schema.userEmail |
| 63 | ]); |
| 64 | |
| 65 | const emails: |
| 66 | { |
| 67 | id: 'primary', |
| 68 | email: user.email |
| 69 | verified: user.emailVerified |
| 70 | primary: true, |
| 71 | }, |
| 72 | ...rows, |
| 73 | ]; |
| 74 | |
| 75 | return { emails |
| 76 | } |
| 77 | |
| 78 | /** 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. */ |
| 79 | async add(userId |
| 80 | if (!this.canSendMail |
| 81 | |
| 82 | const email = |
| 83 | await this.assertAvailable |
| 84 | |
| 85 | const [row] |
| 86 | .insert(schema.userEmail |
| 87 | .values({ id: |
| 88 | .returning(); |
| 89 | |
| 90 | await this.mailLink |
| 91 | |
| 92 | return { |
| 93 | id: row!.id |
| 94 | email: row!.email |
| 95 | verified: row!.verified |
| 96 | primary: false, |
| 97 | }; |
| 98 | } |
| 99 | |
| 100 | /** 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. */ |
| 101 | async resend(userId |
| 102 | if (!this.canSendMail |
| 103 | |
| 104 | const row = |
| 105 | if (row.verified |
| 106 | |
| 107 | // 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. |
| 108 | const issuedAt = |
| 109 | ? row.tokenExpiresAt. |
| 110 | : 0; |
| 111 | if (Date.now |
| 112 | throw new ResendTooSoonError() |
| 113 | } |
| 114 | |
| 115 | await this.mailLink |
| 116 | } |
| 117 | |
| 118 | /** Issues a single-use token for a row and mails the link that carries it. */ |
| 119 | private async mailLink |
| 120 | const token = |
| 121 | await this.db |
| 122 | .update(schema.userEmail |
| 123 | .set({ token |
| 124 | .where(eq(schema |
| 125 | |
| 126 | const user = |
| 127 | await this.mail |
| 128 | name: user.name |
| 129 | verifyUrl: `${this. |
| 130 | }); |
| 131 | } |
| 132 | |
| 133 | /** Confirms an address from its link. Single use: the token is cleared, so a forwarded mail cannot be replayed. */ |
| 134 | async verify(token |
| 135 | const [row] |
| 136 | .update(schema.userEmail |
| 137 | .set({ verified: |
| 138 | .where( |
| 139 | and( |
| 140 | eq(schema.userEmail |
| 141 | eq(schema.userEmail |
| 142 | gt(schema.userEmail |
| 143 | ), |
| 144 | ) |
| 145 | .returning(); |
| 146 | |
| 147 | if (!row) |
| 148 | |
| 149 | // Commits indexed before the address was known are now attributable. |
| 150 | await this.db |
| 151 | UPDATE "repository_contribution" |
| 152 | SET "author_id" = ${row.userId} |
| 153 | WHERE "author_id" IS NULL |
| 154 | AND "author_email" = ${row.email} |
| 155 | `); |
| 156 | |
| 157 | return { email: |
| 158 | } |
| 159 | |
| 160 | /** 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. */ |
| 161 | async makePrimary( |
| 162 | userId: string, |
| 163 | id: string, |
| 164 | ): Promise<ListEmailsResponseDTO |
| 165 | const row = |
| 166 | if (!row.verified |
| 167 | |
| 168 | const user = |
| 169 | |
| 170 | await this.db |
| 171 | await tx.delete |
| 172 | await tx.insert |
| 173 | id: `uem_${nanoid |
| 174 | userId, |
| 175 | email: user.email |
| 176 | verified: user.emailVerified |
| 177 | }); |
| 178 | await tx |
| 179 | .update(schema.user |
| 180 | .set({ email: |
| 181 | .where(eq(schema |
| 182 | }); |
| 183 | |
| 184 | return this.list |
| 185 | } |
| 186 | |
| 187 | async remove(userId |
| 188 | const row = |
| 189 | await this.db |
| 190 | .delete(schema.userEmail |
| 191 | .where(eq(schema |
| 192 | } |
| 193 | |
| 194 | /** Where a verification link lands: the settings page, saying whether the link worked. A bad or used link is not an error to show, only an outcome. */ |
| 195 | async verifyLink(token |
| 196 | const status = |
| 197 | () => 'verified' |
| 198 | () => 'invalid' |
| 199 | ); |
| 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 | } |