@skaile/forge-layer-core 1.1.0 → 1.3.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/CHANGELOG.md +27 -0
- package/README.md +76 -2
- package/app/components/AssistantAccountSettings.vue +55 -21
- package/app/middleware/auth.global.ts +1 -1
- package/app/pages/login.vue +273 -2
- package/app/pages/settings/agents.vue +36 -9
- package/nuxt.config.ts +1 -1
- package/package.json +5 -2
- package/server/db/migrations/0004_email_sign_in.sql +16 -0
- package/server/db/migrations/meta/0004_snapshot.json +884 -0
- package/server/db/migrations/meta/_journal.json +7 -0
- package/server/db/model.ts +1 -0
- package/server/db/schema/chat.ts +5 -2
- package/server/db/schema/index.ts +1 -0
- package/server/db/schema/login-codes.ts +31 -0
- package/server/db/schema/users.ts +6 -2
- package/server/plugins/00.auth-mode.ts +18 -0
- package/server/plugins/actions.ts +9 -4
- package/server/routes/login/verify.get.ts +30 -0
- package/server/utils/actions/assistant.ts +27 -9
- package/server/utils/actions/auth.ts +81 -0
- package/server/utils/actions/core.ts +3 -0
- package/server/utils/ai/roles.ts +15 -6
- package/server/utils/assistant/account.ts +56 -12
- package/server/utils/assistant/engines.ts +48 -16
- package/server/utils/assistant/policy.ts +69 -0
- package/server/utils/auth-mode.ts +44 -4
- package/server/utils/auth.ts +10 -1
- package/server/utils/login-codes.ts +368 -0
- package/server/utils/mail.ts +118 -0
- package/shared/messages/de.ts +43 -4
- package/shared/messages/en.ts +44 -4
- package/shared/sign-in.ts +28 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import * as z from 'zod'
|
|
2
|
+
import { coreMessages } from '../../../shared/messages'
|
|
3
|
+
import { defineSettingsScope, getSettings } from '../settings'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The owner's rules for the app's one assistant (`settings.get`/`settings.update`
|
|
7
|
+
* with `scope: "assistant-policy"`, Settings › Agents in the assistant's card).
|
|
8
|
+
* `ownModels` decides whether people may run the assistant on their own
|
|
9
|
+
* provider, model and key (Settings › Profile, mode `byok`). Off: nobody can
|
|
10
|
+
* choose it, stored keys stay stored but are ignored, and everyone's
|
|
11
|
+
* assistant runs on the app's model. `engine` names what a new conversation
|
|
12
|
+
* runs on when both can: the plain chat in the app server (`app`) or the SKAILE
|
|
13
|
+
* agent (`skaile`). `chatAccess` is what the plain chat (`app` and `byok`)
|
|
14
|
+
* reaches: every action a model may call (`actions`), or only the record the
|
|
15
|
+
* page shows, with changes as proposals the person applies (`document`).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** What a new conversation prefers when both engines can run. */
|
|
19
|
+
export const ASSISTANT_ENGINES = ['app', 'skaile'] as const
|
|
20
|
+
export type AssistantEnginePreference = (typeof ASSISTANT_ENGINES)[number]
|
|
21
|
+
|
|
22
|
+
/** What the plain chat (`app`, `byok`) reaches. */
|
|
23
|
+
export const CHAT_ACCESS = ['actions', 'document'] as const
|
|
24
|
+
export type ChatAccess = (typeof CHAT_ACCESS)[number]
|
|
25
|
+
|
|
26
|
+
export const assistantPolicy = defineSettingsScope(
|
|
27
|
+
'assistant-policy',
|
|
28
|
+
z
|
|
29
|
+
.object({
|
|
30
|
+
ownModels: z
|
|
31
|
+
.boolean()
|
|
32
|
+
.describe(
|
|
33
|
+
"People may run the assistant on their own provider, model and key (Settings › Profile). Off: everyone uses the app's model",
|
|
34
|
+
),
|
|
35
|
+
engine: z
|
|
36
|
+
.enum(ASSISTANT_ENGINES)
|
|
37
|
+
.describe(
|
|
38
|
+
'What a new conversation runs on when both can: app = the chat in the app server, skaile = the SKAILE agent. The other one steps in when the chosen one cannot run',
|
|
39
|
+
),
|
|
40
|
+
chatAccess: z
|
|
41
|
+
.enum(CHAT_ACCESS)
|
|
42
|
+
.describe(
|
|
43
|
+
'What the chat in the app server reaches: actions = every action a model may call, with the rights of the person; document = only the record the page shows, and changes are proposals the person applies',
|
|
44
|
+
),
|
|
45
|
+
})
|
|
46
|
+
.strict(),
|
|
47
|
+
// Own models on: what apps did before the switch existed. The chat in the app server with every action is the default.
|
|
48
|
+
{ ownModels: true, engine: 'app', chatAccess: 'actions' },
|
|
49
|
+
{
|
|
50
|
+
label: 'Assistant: models and engine',
|
|
51
|
+
description: 'Which models people may run the assistant on, what a conversation runs on and what it reaches',
|
|
52
|
+
i18n: { catalogs: coreMessages, prefix: 'core.settings.assistantPolicy' },
|
|
53
|
+
},
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
/** Whether people may run the assistant on their own model (`assistant-policy.ownModels`). */
|
|
57
|
+
export async function ownModelsAllowed(): Promise<boolean> {
|
|
58
|
+
return (await getSettings(assistantPolicy)).ownModels
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** What a new conversation prefers when both engines can run (`assistant-policy.engine`). */
|
|
62
|
+
export async function preferredAssistantEngine(): Promise<AssistantEnginePreference> {
|
|
63
|
+
return (await getSettings(assistantPolicy)).engine
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What the plain chat reaches (`assistant-policy.chatAccess`). */
|
|
67
|
+
export async function chatAccess(): Promise<ChatAccess> {
|
|
68
|
+
return (await getSettings(assistantPolicy)).chatAccess
|
|
69
|
+
}
|
|
@@ -3,15 +3,55 @@
|
|
|
3
3
|
* default without `DATABASE_URL`). `password`: email + password sign-in against
|
|
4
4
|
* the `users` table (the default with `DATABASE_URL`). `passkey`: sign-in with
|
|
5
5
|
* a passkey (WebAuthn) from the `passkeys` table; the first passkey claims the
|
|
6
|
-
* owner.
|
|
6
|
+
* owner. `email`: sign-in by a six-digit code or a one-click link mailed
|
|
7
|
+
* through `SMTP_URL` (`server/utils/login-codes.ts`). Read at runtime, so one
|
|
8
|
+
* build serves all four.
|
|
7
9
|
*/
|
|
8
|
-
export type AuthMode = 'local' | 'password' | 'passkey'
|
|
10
|
+
export type AuthMode = 'local' | 'password' | 'passkey' | 'email'
|
|
9
11
|
|
|
10
|
-
const AUTH_MODES: readonly AuthMode[] = ['local', 'password', 'passkey']
|
|
12
|
+
const AUTH_MODES: readonly AuthMode[] = ['local', 'password', 'passkey', 'email']
|
|
11
13
|
|
|
12
14
|
export function appAuthMode(env: NodeJS.ProcessEnv = process.env): AuthMode {
|
|
13
15
|
const mode = env.APP_AUTH_MODE
|
|
14
16
|
if (AUTH_MODES.includes(mode as AuthMode)) return mode as AuthMode
|
|
15
|
-
if (mode) throw new Error(`APP_AUTH_MODE must be "local", "password" or "
|
|
17
|
+
if (mode) throw new Error(`APP_AUTH_MODE must be "local", "password", "passkey" or "email", got "${mode}"`)
|
|
16
18
|
return env.DATABASE_URL ? 'password' : 'local'
|
|
17
19
|
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* What the configuration still lacks to run, or `null`: email mode cannot send
|
|
23
|
+
* a code without `SMTP_URL`; any mail with a link (sign-in codes, and a layer's
|
|
24
|
+
* invitations in every mode) cannot link back without `APP_URL`, so `APP_URL`
|
|
25
|
+
* is required whenever mail can go out (email mode or `SMTP_URL` set). Checked
|
|
26
|
+
* once at startup (`server/plugins/00.auth-mode.ts`), which refuses to start
|
|
27
|
+
* with this message.
|
|
28
|
+
*/
|
|
29
|
+
export function authModeConfigError(env: NodeJS.ProcessEnv = process.env): string | null {
|
|
30
|
+
const email = appAuthMode(env) === 'email'
|
|
31
|
+
const smtp = Boolean(env.SMTP_URL?.trim())
|
|
32
|
+
if (email && !smtp) {
|
|
33
|
+
return 'APP_AUTH_MODE=email needs SMTP_URL (e.g. smtps://user:password@smtp.example.com:465) to mail sign-in codes. Set SMTP_URL, or choose another APP_AUTH_MODE.'
|
|
34
|
+
}
|
|
35
|
+
if (email && !env.APP_URL?.trim()) {
|
|
36
|
+
return 'APP_AUTH_MODE=email needs APP_URL (e.g. https://app.example.com), the address the links in sign-in mails open. Set APP_URL, or choose another APP_AUTH_MODE.'
|
|
37
|
+
}
|
|
38
|
+
if (smtp && !env.APP_URL?.trim()) {
|
|
39
|
+
return 'SMTP_URL is set, so mails can go out: their links need APP_URL (e.g. https://app.example.com), the address they open. Set APP_URL, or unset SMTP_URL.'
|
|
40
|
+
}
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `https://host[/base]` of the app, without a trailing slash: the root of every
|
|
46
|
+
* link in a mail. Always `APP_URL`, never the request's Host or X-Forwarded-*
|
|
47
|
+
* headers, which a caller can forge to point a genuine mail at their own host.
|
|
48
|
+
* Startup refuses to run without it whenever mail can go out
|
|
49
|
+
* ({@link authModeConfigError}); elsewhere a missing `APP_URL` throws here
|
|
50
|
+
* rather than producing a link to the wrong place.
|
|
51
|
+
*/
|
|
52
|
+
export function appBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
|
|
53
|
+
const url = env.APP_URL?.trim()
|
|
54
|
+
if (!url)
|
|
55
|
+
throw new Error('APP_URL is not set: it is the address the links in mails open (e.g. https://app.example.com)')
|
|
56
|
+
return url.replace(/\/+$/, '')
|
|
57
|
+
}
|
package/server/utils/auth.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { createError, getHeader, getRequestHost, getRequestProtocol } from 'h3'
|
|
|
4
4
|
import { users } from '../db/schema'
|
|
5
5
|
import { useDb } from './db'
|
|
6
6
|
import type { Principal } from './principal'
|
|
7
|
-
import { tokenPrincipal, userPrincipal } from './principal'
|
|
7
|
+
import { SYSTEM_PRINCIPAL_ID, tokenPrincipal, userPrincipal } from './principal'
|
|
8
8
|
import { resolveApiToken } from './tokens'
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -21,6 +21,15 @@ export async function startUserSession(event: H3Event, user: typeof users.$infer
|
|
|
21
21
|
})
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Who calls the sign-in actions (`SIGN_IN_ACTION_IDS`) before there is a
|
|
26
|
+
* session: no roles, no scopes. Only `server/plugins/actions.ts` hands it out,
|
|
27
|
+
* and only to those actions.
|
|
28
|
+
*/
|
|
29
|
+
export function signInPrincipal(): Principal {
|
|
30
|
+
return { kind: 'system', id: SYSTEM_PRINCIPAL_ID, name: 'sign-in', roles: [], scopes: [] }
|
|
31
|
+
}
|
|
32
|
+
|
|
24
33
|
/** `Authorization: Bearer <token>` without the prefix, or `null`. */
|
|
25
34
|
export function bearerOf(event: H3Event): string | null {
|
|
26
35
|
const header = getHeader(event, 'authorization')
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { and, desc, eq, gte, isNull, lt, lte, ne, sql } from 'drizzle-orm'
|
|
3
|
+
import type { H3Event } from 'h3'
|
|
4
|
+
import { createError } from 'h3'
|
|
5
|
+
import { withQuery } from 'ufo'
|
|
6
|
+
import {
|
|
7
|
+
LOGIN_CODE_LENGTH,
|
|
8
|
+
LOGIN_CODE_TTL_MINUTES,
|
|
9
|
+
MAX_CODE_ATTEMPTS,
|
|
10
|
+
MAX_CODES_PER_HOUR,
|
|
11
|
+
safeNextPath,
|
|
12
|
+
} from '../../shared/sign-in'
|
|
13
|
+
import { loginCodes, users } from '../db/schema'
|
|
14
|
+
import { appAuthMode, appBaseUrl } from './auth-mode'
|
|
15
|
+
import { useDb } from './db'
|
|
16
|
+
import { useCoreServerI18n } from './i18n'
|
|
17
|
+
import type { MailMessage } from './mail'
|
|
18
|
+
import { MailSendError, sendMail } from './mail'
|
|
19
|
+
import { appSettings, getSettings } from './settings'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Sign-in by mail (`APP_AUTH_MODE=email`): code generation and hashing, the
|
|
23
|
+
* limits, the mail, and the checks of a code and of a link token. The actions
|
|
24
|
+
* `auth.code.*` (`server/utils/actions/auth.ts`) and the link route
|
|
25
|
+
* `GET /login/verify` (`server/routes/login/verify.get.ts`) are thin wrappers
|
|
26
|
+
* around it. {@link createSignInLink} gives an app the same kind of link
|
|
27
|
+
* without a code, valid as long as it says, to build invitations on.
|
|
28
|
+
*
|
|
29
|
+
* Every function takes the request's `event` where there is one, so its
|
|
30
|
+
* answers come in the app's language (`useCoreServerI18n`).
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
type UserRow = typeof users.$inferSelect
|
|
34
|
+
|
|
35
|
+
const HOUR_MS = 60 * 60_000
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The `code_hash` of a row made by {@link createSignInLink}: it carries only a
|
|
39
|
+
* link token, so no entered code can match it, and the code limits and checks
|
|
40
|
+
* skip it.
|
|
41
|
+
*/
|
|
42
|
+
const LINK_ONLY = ''
|
|
43
|
+
const isCodeRow = ne(loginCodes.codeHash, LINK_ONLY)
|
|
44
|
+
const isLinkOnlyRow = eq(loginCodes.codeHash, LINK_ONLY)
|
|
45
|
+
|
|
46
|
+
function sha256(value: string): string {
|
|
47
|
+
return createHash('sha256').update(value).digest('hex')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The code is hashed with its user, so equal codes of two people never share a hash. */
|
|
51
|
+
function codeHash(userId: string, code: string): string {
|
|
52
|
+
return sha256(`${userId}:${code}`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function sameHash(a: string, b: string): boolean {
|
|
56
|
+
const left = Buffer.from(a, 'hex')
|
|
57
|
+
const right = Buffer.from(b, 'hex')
|
|
58
|
+
return left.length === right.length && timingSafeEqual(left, right)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Requests for addresses without a User, per address, within the last hour:
|
|
63
|
+
* they get the same 429 as known ones, so the limit does not tell which
|
|
64
|
+
* addresses exist. Process-local; known addresses count their `login_codes` rows.
|
|
65
|
+
*/
|
|
66
|
+
declare global {
|
|
67
|
+
var __forgeUnknownLoginRequests: Map<string, number[]> | undefined
|
|
68
|
+
}
|
|
69
|
+
const unknownRequests = (globalThis.__forgeUnknownLoginRequests ??= new Map<string, number[]>())
|
|
70
|
+
|
|
71
|
+
function countUnknownRequest(email: string, now: number): boolean {
|
|
72
|
+
for (const [address, times] of unknownRequests) {
|
|
73
|
+
const recent = times.filter(time => now - time < HOUR_MS)
|
|
74
|
+
if (recent.length) unknownRequests.set(address, recent)
|
|
75
|
+
else unknownRequests.delete(address)
|
|
76
|
+
}
|
|
77
|
+
const times = unknownRequests.get(email) ?? []
|
|
78
|
+
if (times.length >= MAX_CODES_PER_HOUR) return false
|
|
79
|
+
unknownRequests.set(email, [...times, now])
|
|
80
|
+
return true
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The one-click sign-in link of a mail: `<baseUrl>/login/verify?token=…&next=…` (`next` only when it is not `/`). */
|
|
84
|
+
export function loginLink(baseUrl: string, token: string, next: string): string {
|
|
85
|
+
return withQuery(`${baseUrl}/login/verify`, { token, ...(next === '/' ? {} : { next }) })
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const escapeHtml = (value: string) =>
|
|
89
|
+
value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
90
|
+
|
|
91
|
+
/** The sign-in mail in the app's language; it names the app by the `app` settings' `appName`. */
|
|
92
|
+
async function loginMail(to: string, code: string, link: string, event?: H3Event): Promise<MailMessage> {
|
|
93
|
+
const { t } = useCoreServerI18n(event)
|
|
94
|
+
const { appName } = await getSettings(appSettings)
|
|
95
|
+
const params = { app: appName, code, minutes: LOGIN_CODE_TTL_MINUTES }
|
|
96
|
+
const text = [
|
|
97
|
+
t('core.login.mailCode', params),
|
|
98
|
+
'',
|
|
99
|
+
t('core.login.mailValidity', params),
|
|
100
|
+
link,
|
|
101
|
+
'',
|
|
102
|
+
t('core.login.mailIgnore'),
|
|
103
|
+
].join('\n')
|
|
104
|
+
const html = `<p>${escapeHtml(t('core.login.mailCodeIntro', params))}</p>
|
|
105
|
+
<p style="font-size:24px;font-weight:600;letter-spacing:4px">${code}</p>
|
|
106
|
+
<p>${escapeHtml(t('core.login.mailValidityOneClick', params))}</p>
|
|
107
|
+
<p><a href="${escapeHtml(link)}">${escapeHtml(t('core.login.mailLinkLabel', params))}</a></p>
|
|
108
|
+
<p style="color:#666">${escapeHtml(t('core.login.mailIgnore'))}</p>`
|
|
109
|
+
return { to, subject: t('core.login.mailSubject', params), text, html }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface LoginCodeRequest {
|
|
113
|
+
email: string
|
|
114
|
+
/** Root of the mailed link, `appBaseUrl()`. */
|
|
115
|
+
baseUrl: string
|
|
116
|
+
/** App path the link opens after sign-in; anything but an app-relative path becomes `/`. */
|
|
117
|
+
next?: string
|
|
118
|
+
event?: H3Event
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Mails a known address a new code and link (valid {@link LOGIN_CODE_TTL_MINUTES}
|
|
123
|
+
* minutes) and ends every earlier unused code of that person (a link made by
|
|
124
|
+
* {@link createSignInLink} stays). Answers the same for every address. 429
|
|
125
|
+
* after {@link MAX_CODES_PER_HOUR} requests within an hour; 503 when the mail
|
|
126
|
+
* cannot be sent (retried once), and then the code is discarded so it does not
|
|
127
|
+
* count against the limit.
|
|
128
|
+
*/
|
|
129
|
+
export async function requestLoginCode(input: LoginCodeRequest): Promise<{ ok: true; message: string }> {
|
|
130
|
+
const started = Date.now()
|
|
131
|
+
try {
|
|
132
|
+
return await requestLoginCodeNow(input)
|
|
133
|
+
} finally {
|
|
134
|
+
const rest = loginRequestFloor.ms - (Date.now() - started)
|
|
135
|
+
if (rest > 0) await new Promise(resolve => setTimeout(resolve, rest))
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Every answer of {@link requestLoginCode} (sent, 429, 503, unknown address)
|
|
141
|
+
* takes at least this long from the start, so the time does not tell whether
|
|
142
|
+
* the address has a User (a known one waits for SMTP). The one remaining
|
|
143
|
+
* difference is the 503 when the mail cannot be sent, which only a known
|
|
144
|
+
* address can get. Tests set `ms` to 0.
|
|
145
|
+
*/
|
|
146
|
+
export const loginRequestFloor = { ms: 1500 }
|
|
147
|
+
|
|
148
|
+
async function requestLoginCodeNow(input: LoginCodeRequest): Promise<{ ok: true; message: string }> {
|
|
149
|
+
const db = useDb()
|
|
150
|
+
const { t } = useCoreServerI18n(input.event)
|
|
151
|
+
const email = input.email.trim().toLowerCase()
|
|
152
|
+
const now = new Date()
|
|
153
|
+
const tooMany = () => createError({ statusCode: 429, statusMessage: t('core.login.tooManyCodes') })
|
|
154
|
+
const sent = { ok: true as const, message: t('core.login.codeSent') }
|
|
155
|
+
const [user] = await db.select().from(users).where(eq(users.email, email)).limit(1)
|
|
156
|
+
if (!user) {
|
|
157
|
+
if (!countUnknownRequest(email, now.getTime())) throw tooMany()
|
|
158
|
+
return sent
|
|
159
|
+
}
|
|
160
|
+
const [recent] = await db
|
|
161
|
+
.select({ count: sql<number>`count(*)::int` })
|
|
162
|
+
.from(loginCodes)
|
|
163
|
+
.where(and(eq(loginCodes.userId, user.id), isCodeRow, gte(loginCodes.createdAt, new Date(now.getTime() - HOUR_MS))))
|
|
164
|
+
if ((recent?.count ?? 0) >= MAX_CODES_PER_HOUR) throw tooMany()
|
|
165
|
+
|
|
166
|
+
const code = String(randomInt(0, 10 ** LOGIN_CODE_LENGTH)).padStart(LOGIN_CODE_LENGTH, '0')
|
|
167
|
+
const token = randomBytes(32).toString('base64url')
|
|
168
|
+
const [row] = await db
|
|
169
|
+
.insert(loginCodes)
|
|
170
|
+
.values({
|
|
171
|
+
userId: user.id,
|
|
172
|
+
codeHash: codeHash(user.id, code),
|
|
173
|
+
linkTokenHash: sha256(token),
|
|
174
|
+
expiresAt: new Date(now.getTime() + LOGIN_CODE_TTL_MINUTES * 60_000),
|
|
175
|
+
})
|
|
176
|
+
.returning({ id: loginCodes.id })
|
|
177
|
+
try {
|
|
178
|
+
const link = loginLink(input.baseUrl, token, safeNextPath(input.next))
|
|
179
|
+
await sendMail(await loginMail(user.email, code, link, input.event))
|
|
180
|
+
} catch (error) {
|
|
181
|
+
await db.delete(loginCodes).where(eq(loginCodes.id, row!.id))
|
|
182
|
+
if (error instanceof MailSendError)
|
|
183
|
+
throw createError({ statusCode: 503, statusMessage: t('core.login.mailFailed') })
|
|
184
|
+
throw error
|
|
185
|
+
}
|
|
186
|
+
await db
|
|
187
|
+
.update(loginCodes)
|
|
188
|
+
.set({ usedAt: now, updatedAt: now })
|
|
189
|
+
.where(and(eq(loginCodes.userId, user.id), isCodeRow, ne(loginCodes.id, row!.id), isNull(loginCodes.usedAt)))
|
|
190
|
+
return sent
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Sets `usedAt` once (a concurrent second use finds it set) and `users.lastSignInAt`; `null` when it was used up. */
|
|
194
|
+
async function consume(codeId: string, user: UserRow): Promise<UserRow | null> {
|
|
195
|
+
const db = useDb()
|
|
196
|
+
const now = new Date()
|
|
197
|
+
const used = await db
|
|
198
|
+
.update(loginCodes)
|
|
199
|
+
.set({ usedAt: now, updatedAt: now })
|
|
200
|
+
.where(and(eq(loginCodes.id, codeId), isNull(loginCodes.usedAt), lte(loginCodes.attempts, MAX_CODE_ATTEMPTS)))
|
|
201
|
+
.returning({ id: loginCodes.id })
|
|
202
|
+
if (!used.length) return null
|
|
203
|
+
const [signedIn] = await db.update(users).set({ lastSignInAt: now }).where(eq(users.id, user.id)).returning()
|
|
204
|
+
return signedIn ?? user
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Checks `code` against the newest code mailed to `email`. 401 wrong (also for
|
|
209
|
+
* an unknown address or a used code), 410 expired, 429 dead after
|
|
210
|
+
* {@link MAX_CODE_ATTEMPTS} wrong entries (the fifth wrong one ends it).
|
|
211
|
+
* Success uses the code up, sets `users.last_sign_in_at` and returns the user;
|
|
212
|
+
* the caller opens the session (`startUserSession`).
|
|
213
|
+
*/
|
|
214
|
+
export async function verifyLoginCode(input: { email: string; code: string; event?: H3Event }): Promise<UserRow> {
|
|
215
|
+
const db = useDb()
|
|
216
|
+
const { t } = useCoreServerI18n(input.event)
|
|
217
|
+
const wrongCode = () => createError({ statusCode: 401, statusMessage: t('core.login.wrongCode') })
|
|
218
|
+
const tooManyAttempts = () => createError({ statusCode: 429, statusMessage: t('core.login.tooManyAttempts') })
|
|
219
|
+
const email = input.email.trim().toLowerCase()
|
|
220
|
+
const [user] = await db.select().from(users).where(eq(users.email, email)).limit(1)
|
|
221
|
+
if (!user) throw wrongCode()
|
|
222
|
+
const [row] = await db
|
|
223
|
+
.select()
|
|
224
|
+
.from(loginCodes)
|
|
225
|
+
.where(and(eq(loginCodes.userId, user.id), isCodeRow))
|
|
226
|
+
.orderBy(desc(loginCodes.createdAt))
|
|
227
|
+
.limit(1)
|
|
228
|
+
if (!row) throw wrongCode()
|
|
229
|
+
if (row.attempts >= MAX_CODE_ATTEMPTS) throw tooManyAttempts()
|
|
230
|
+
if (row.usedAt) throw wrongCode()
|
|
231
|
+
if (row.expiresAt.getTime() <= Date.now())
|
|
232
|
+
throw createError({ statusCode: 410, statusMessage: t('core.login.expiredCode') })
|
|
233
|
+
// Claim one attempt atomically before comparing, so concurrent guesses cannot
|
|
234
|
+
// exceed the limit: no row back means the code is dead or used up.
|
|
235
|
+
const now = new Date()
|
|
236
|
+
const [claimed] = await db
|
|
237
|
+
.update(loginCodes)
|
|
238
|
+
.set({ attempts: sql`${loginCodes.attempts} + 1`, updatedAt: now })
|
|
239
|
+
.where(and(eq(loginCodes.id, row.id), lt(loginCodes.attempts, MAX_CODE_ATTEMPTS), isNull(loginCodes.usedAt)))
|
|
240
|
+
.returning({ attempts: loginCodes.attempts })
|
|
241
|
+
if (!claimed) {
|
|
242
|
+
const [current] = await db
|
|
243
|
+
.select({ attempts: loginCodes.attempts })
|
|
244
|
+
.from(loginCodes)
|
|
245
|
+
.where(eq(loginCodes.id, row.id))
|
|
246
|
+
.limit(1)
|
|
247
|
+
if ((current?.attempts ?? MAX_CODE_ATTEMPTS) >= MAX_CODE_ATTEMPTS) throw tooManyAttempts()
|
|
248
|
+
throw wrongCode()
|
|
249
|
+
}
|
|
250
|
+
if (!sameHash(row.codeHash, codeHash(user.id, input.code.trim()))) {
|
|
251
|
+
if (claimed.attempts >= MAX_CODE_ATTEMPTS) {
|
|
252
|
+
await db
|
|
253
|
+
.update(loginCodes)
|
|
254
|
+
.set({ usedAt: now })
|
|
255
|
+
.where(and(eq(loginCodes.id, row.id), isNull(loginCodes.usedAt)))
|
|
256
|
+
throw tooManyAttempts()
|
|
257
|
+
}
|
|
258
|
+
throw wrongCode()
|
|
259
|
+
}
|
|
260
|
+
const signedIn = await consume(row.id, user)
|
|
261
|
+
if (!signedIn) throw wrongCode()
|
|
262
|
+
return signedIn
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The one-click link: the same checks as the code, by the link token. 401 for
|
|
267
|
+
* an unknown, used or dead token, 410 expired. Success uses the link up, sets
|
|
268
|
+
* `users.last_sign_in_at` and returns the user.
|
|
269
|
+
*/
|
|
270
|
+
export async function verifyLinkToken(token: string, event?: H3Event): Promise<UserRow> {
|
|
271
|
+
const db = useDb()
|
|
272
|
+
const { t } = useCoreServerI18n(event)
|
|
273
|
+
const invalidLink = () => createError({ statusCode: 401, statusMessage: t('core.login.invalidLink') })
|
|
274
|
+
const [row] = token
|
|
275
|
+
? await db
|
|
276
|
+
.select()
|
|
277
|
+
.from(loginCodes)
|
|
278
|
+
.where(eq(loginCodes.linkTokenHash, sha256(token)))
|
|
279
|
+
.limit(1)
|
|
280
|
+
: []
|
|
281
|
+
if (!row || row.usedAt || row.attempts >= MAX_CODE_ATTEMPTS) throw invalidLink()
|
|
282
|
+
if (row.expiresAt.getTime() <= Date.now())
|
|
283
|
+
throw createError({ statusCode: 410, statusMessage: t('core.login.expiredLink') })
|
|
284
|
+
const [user] = await db.select().from(users).where(eq(users.id, row.userId)).limit(1)
|
|
285
|
+
if (!user) throw invalidLink()
|
|
286
|
+
const signedIn = await consume(row.id, user)
|
|
287
|
+
if (!signedIn) throw invalidLink()
|
|
288
|
+
return signedIn
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 429 when the person got {@link MAX_CODES_PER_HOUR} links from
|
|
293
|
+
* {@link createSignInLink} within the last hour (links discarded after a
|
|
294
|
+
* failed send do not count).
|
|
295
|
+
*/
|
|
296
|
+
export async function assertSignInLinkAllowed(userId: string, event?: H3Event): Promise<void> {
|
|
297
|
+
const [recent] = await useDb()
|
|
298
|
+
.select({ count: sql<number>`count(*)::int` })
|
|
299
|
+
.from(loginCodes)
|
|
300
|
+
.where(and(eq(loginCodes.userId, userId), isLinkOnlyRow, gte(loginCodes.createdAt, new Date(Date.now() - HOUR_MS))))
|
|
301
|
+
if ((recent?.count ?? 0) >= MAX_CODES_PER_HOUR) {
|
|
302
|
+
throw createError({ statusCode: 429, statusMessage: useCoreServerI18n(event).t('core.login.tooManyLinks') })
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export interface SignInLink {
|
|
307
|
+
/** `<APP_URL>/login/verify?token=…&next=…`: following it signs the person in, once. */
|
|
308
|
+
link: string
|
|
309
|
+
/** The `login_codes` row behind the link. */
|
|
310
|
+
id: string
|
|
311
|
+
expiresAt: Date
|
|
312
|
+
/** Revokes the link, e.g. when the mail carrying it could not be sent; it then no longer counts against the limit. */
|
|
313
|
+
discard: () => Promise<void>
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* A one-click sign-in link for `userId` without a code, valid `ttlMs` and
|
|
318
|
+
* once: what an app builds an invitation on (it writes and sends the mail
|
|
319
|
+
* itself, with `sendMail`). Following the link signs the person in like the
|
|
320
|
+
* link of a code mail and opens `next` (app paths only). Earlier links and
|
|
321
|
+
* codes of the person stay valid. The link starts with `APP_URL`
|
|
322
|
+
* (`appBaseUrl()`).
|
|
323
|
+
*
|
|
324
|
+
* 400 outside email mode, where `/login/verify` signs nobody in; 404 for an
|
|
325
|
+
* unknown user; 429 per {@link assertSignInLinkAllowed}.
|
|
326
|
+
*/
|
|
327
|
+
export async function createSignInLink(input: {
|
|
328
|
+
userId: string
|
|
329
|
+
ttlMs: number
|
|
330
|
+
next?: string
|
|
331
|
+
event?: H3Event
|
|
332
|
+
}): Promise<SignInLink> {
|
|
333
|
+
if (appAuthMode() !== 'email') {
|
|
334
|
+
throw createError({
|
|
335
|
+
statusCode: 400,
|
|
336
|
+
statusMessage: 'Sign-in links are only used in email mode (APP_AUTH_MODE=email)',
|
|
337
|
+
})
|
|
338
|
+
}
|
|
339
|
+
if (!Number.isFinite(input.ttlMs) || input.ttlMs <= 0) throw new Error('createSignInLink: ttlMs must be positive')
|
|
340
|
+
const db = useDb()
|
|
341
|
+
const baseUrl = appBaseUrl()
|
|
342
|
+
const [user] = await db.select({ id: users.id }).from(users).where(eq(users.id, input.userId)).limit(1)
|
|
343
|
+
if (!user) throw createError({ statusCode: 404, statusMessage: `User ${input.userId} not found` })
|
|
344
|
+
await assertSignInLinkAllowed(user.id, input.event)
|
|
345
|
+
const now = new Date()
|
|
346
|
+
const token = randomBytes(32).toString('base64url')
|
|
347
|
+
const expiresAt = new Date(now.getTime() + input.ttlMs)
|
|
348
|
+
const [row] = await db
|
|
349
|
+
.insert(loginCodes)
|
|
350
|
+
.values({
|
|
351
|
+
userId: user.id,
|
|
352
|
+
codeHash: LINK_ONLY,
|
|
353
|
+
linkTokenHash: sha256(token),
|
|
354
|
+
expiresAt,
|
|
355
|
+
createdAt: now,
|
|
356
|
+
updatedAt: now,
|
|
357
|
+
})
|
|
358
|
+
.returning({ id: loginCodes.id })
|
|
359
|
+
const id = row!.id
|
|
360
|
+
return {
|
|
361
|
+
link: loginLink(baseUrl, token, safeNextPath(input.next)),
|
|
362
|
+
id,
|
|
363
|
+
expiresAt,
|
|
364
|
+
discard: async () => {
|
|
365
|
+
await db.delete(loginCodes).where(eq(loginCodes.id, id))
|
|
366
|
+
},
|
|
367
|
+
}
|
|
368
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import nodemailer from 'nodemailer'
|
|
2
|
+
|
|
3
|
+
/** One outgoing mail. `text` is always sent; `html` is the optional rich part. */
|
|
4
|
+
export interface MailMessage {
|
|
5
|
+
to: string
|
|
6
|
+
subject: string
|
|
7
|
+
text: string
|
|
8
|
+
html?: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** The transport behind every mail the app sends (sign-in codes, and whatever a layer mails). */
|
|
12
|
+
export interface MailSender {
|
|
13
|
+
send(message: MailMessage): Promise<void>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A send that failed twice (the first try and one retry). `cause` holds the transport's error. */
|
|
17
|
+
export class MailSendError extends Error {
|
|
18
|
+
readonly to: string
|
|
19
|
+
|
|
20
|
+
constructor(to: string, cause: unknown) {
|
|
21
|
+
super(`Mail to ${to} could not be sent: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
|
|
22
|
+
this.name = 'MailSendError'
|
|
23
|
+
this.to = to
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* SMTP through nodemailer. `url` is `SMTP_URL` (`smtp://` or `smtps://`, with
|
|
29
|
+
* user and password in the URL), `from` is `MAIL_FROM`.
|
|
30
|
+
*/
|
|
31
|
+
export function createSmtpMailSender(options: { url: string; from: string }): MailSender {
|
|
32
|
+
const transport = nodemailer.createTransport(options.url)
|
|
33
|
+
return {
|
|
34
|
+
async send(message) {
|
|
35
|
+
await transport.sendMail({
|
|
36
|
+
from: options.from,
|
|
37
|
+
to: message.to,
|
|
38
|
+
subject: message.subject,
|
|
39
|
+
text: message.text,
|
|
40
|
+
html: message.html,
|
|
41
|
+
})
|
|
42
|
+
},
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `MAIL_FROM`, else `noreply@<host of SMTP_URL>`. */
|
|
47
|
+
export function mailFromEnv(env: NodeJS.ProcessEnv = process.env): string {
|
|
48
|
+
const from = env.MAIL_FROM?.trim()
|
|
49
|
+
if (from) return from
|
|
50
|
+
let host = 'localhost'
|
|
51
|
+
try {
|
|
52
|
+
host = new URL(env.SMTP_URL ?? '').hostname || host
|
|
53
|
+
} catch {
|
|
54
|
+
// An unparsable SMTP_URL fails at send time with nodemailer's own message.
|
|
55
|
+
}
|
|
56
|
+
return `noreply@${host}`
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Keeps every mail in `sent` instead of sending it; `fail` makes the next sends throw. For tests. */
|
|
60
|
+
export interface MemoryMailSender extends MailSender {
|
|
61
|
+
sent: MailMessage[]
|
|
62
|
+
/** How many of the following sends throw (each retry counts as one send). */
|
|
63
|
+
fail: number
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createMemoryMailSender(): MemoryMailSender {
|
|
67
|
+
const sender: MemoryMailSender = {
|
|
68
|
+
sent: [],
|
|
69
|
+
fail: 0,
|
|
70
|
+
async send(message) {
|
|
71
|
+
if (sender.fail > 0) {
|
|
72
|
+
sender.fail -= 1
|
|
73
|
+
throw new Error('memory sender: simulated failure')
|
|
74
|
+
}
|
|
75
|
+
sender.sent.push(message)
|
|
76
|
+
},
|
|
77
|
+
}
|
|
78
|
+
return sender
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
declare global {
|
|
82
|
+
var __forgeMailSender: MailSender | undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Replaces the process-wide sender (tests install a memory sender); `undefined` returns to SMTP from the
|
|
87
|
+
* environment. Process-global, like the settings registry: layers may each bundle a copy of this module.
|
|
88
|
+
*/
|
|
89
|
+
export function setMailSender(sender: MailSender | undefined): void {
|
|
90
|
+
globalThis.__forgeMailSender = sender
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The process-wide sender: the one set by {@link setMailSender}, else SMTP from `SMTP_URL` / `MAIL_FROM`. */
|
|
94
|
+
export function useMailSender(): MailSender {
|
|
95
|
+
if (globalThis.__forgeMailSender) return globalThis.__forgeMailSender
|
|
96
|
+
const url = process.env.SMTP_URL?.trim()
|
|
97
|
+
if (!url) throw new MailSendError('(no recipient)', new Error('SMTP_URL is not set'))
|
|
98
|
+
globalThis.__forgeMailSender = createSmtpMailSender({ url, from: mailFromEnv() })
|
|
99
|
+
return globalThis.__forgeMailSender
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Sends through {@link useMailSender}; a failed send is retried once, then {@link MailSendError} is thrown. */
|
|
103
|
+
export async function sendMail(message: MailMessage): Promise<void> {
|
|
104
|
+
const sender = useMailSender()
|
|
105
|
+
try {
|
|
106
|
+
await sender.send(message)
|
|
107
|
+
} catch (first) {
|
|
108
|
+
console.warn(
|
|
109
|
+
`[mail] send to ${message.to} failed, retrying once: ${first instanceof Error ? first.message : String(first)}`,
|
|
110
|
+
)
|
|
111
|
+
try {
|
|
112
|
+
await sender.send(message)
|
|
113
|
+
} catch (second) {
|
|
114
|
+
console.error(`[mail] send to ${message.to} failed: ${second instanceof Error ? second.message : String(second)}`)
|
|
115
|
+
throw new MailSendError(message.to, second)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|