Skip to content

AI-native design editor. Open-source Figma alternative.

refactor(cloud): stop matching Better Auth and route paths by hand (#1539)

Danila Poyarkovf13105dbbe42
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.md
index 7579faed2..04001ef17 100644
--- a/packages/cloud/AGENTS.md
+++ b/packages/cloud/AGENTS.md
@@ -16,7 +16,9 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo
- Code inside Better Auth's own callbacks must not query the database, which deadlocks its transaction on one connection (`tests/integration/server/account/routes.test.ts`).
- Name a table for what it holds, without a `cloud_` prefix; only a name Better Auth already uses gets a qualifier, such as `api_rate_limit` (`src/server/db/migrations/025_table_names.ts`).
- Renaming a table that shipped migrations query gives them a type under the name they ran with, so their SQL stays the same (`LegacyAuthSchemaDatabase` in `src/server/db/migrations/helpers.ts`).
-- `user.image` only ever holds an address this server serves; a picture from anywhere else is copied into `user_picture` or dropped, never linked (`src/server/pictures/service.ts`, `tests/integration/server/pictures/routes.test.ts`).
+- `user.image` only ever holds an address this server serves; a picture from anywhere else is copied into `user_picture` or dropped, never linked, and a provider's picture comes from the ID token on its account row, never from the endpoint that wrote it (`src/server/pictures/provider.ts`, `tests/integration/server/pictures/provider.test.ts`).
+- Name a Better Auth endpoint by the object that declares it: a plugin's from the plugin the factory builds, a core one from `auth.api`; only the core paths options need before Better Auth is built are written out, in `CORE_AUTH_PATHS`, where the type check holds them to the library's own. Match hook paths with `isAuthEndpoint`, and put endpoints clients must not reach in `disabledPaths` (`src/server/auth/factory.ts`, `src/server/auth/endpoints.ts`).
+- A route with a rate budget of its own mounts `createRouteRateLimiter`, and general limiters skip what it counts through `routeHasOwnBudget`; never exempt routes by matching their paths (`tests/integration/server/rate-limit/budgets.test.ts`).
- Database rows use `crypto.randomUUID()`; secrets that leave the server use `randomHex` from `@open-pencil/scene-graph/random`, are stored as SHA-256 digests (a single-use OAuth continuation keeps a JWE copy), and travel in URL fragments (`src/server/sharing/capabilities/service.ts`).
- An admin list takes `search`, `filter`, `limit`, and `offset` through `listQuery` and answers with its rows, `total`, and per-filter `counts`; it declares its filters once as `ListFilters`, which count in one query and page with the same condition (`src/admin/list.ts`, `tests/integration/admin/lists.test.ts`).
- Every HTTP body goes through `validatedJSON` with a contract schema, and every response the client reads is parsed with Valibot (`src/server/validation.ts`, `src/client/api.ts`).
diff --git a/packages/cloud/src/server/ai/routes.ts b/packages/cloud/src/server/ai/routes.ts
index 5b8e69994..e927119f2 100644
--- a/packages/cloud/src/server/ai/routes.ts
+++ b/packages/cloud/src/server/ai/routes.ts
@@ -2,7 +2,7 @@ import { parseCreateAIToken } from '#cloud/contract'
import type { CloudActor } from '#cloud/server/auth'
import type { CloudDatabase } from '#cloud/server/db'
import { DocumentNotFoundError } from '#cloud/server/documents'
-import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
import { validatedJSON } from '#cloud/server/validation'
import { Hono } from 'hono'
import type { Kysely } from 'kysely'
@@ -21,7 +21,7 @@ export function createAIRoutes(
if (service && rateLimit) {
router.use(
'/ai/token',
- createActorRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.aiToken)
+ createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.aiToken)
)
}
return router.post('/ai/token', validatedJSON(parseCreateAIToken), async (context) => {
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
index 1cad2d2a6..a68c27e2a 100644
--- a/packages/cloud/src/server/app.ts
+++ b/packages/cloud/src/server/app.ts
@@ -21,6 +21,7 @@ import {
type CloudAPIEnvironment
} from '#cloud/server/api'
import {
+ AUTH_BASE_PATH,
createAuthenticationEmailService,
createCloudIdentityResolver,
createCloudSessionResolver,
@@ -53,7 +54,8 @@ import {
import {
CLOUD_RATE_LIMITS,
createActorRateLimiter,
- createTrustedIPRateLimiter
+ createTrustedIPRateLimiter,
+ routeHasOwnBudget
} from '#cloud/server/rate-limit'
import { createDocumentSharingService } from '#cloud/server/sharing'
import { createWorkspaceMemberService, createWorkspaceService } from '#cloud/server/workspaces'
@@ -93,36 +95,6 @@ function discoveryFromServices(services: CloudServices): CloudDiscovery {
return cloudDiscoveryFromConfig(services.config)
}
-const POLICY_MANAGED_AUTH_PATHS = new Set([
- '/api/auth/passkey/delete-passkey',
- '/api/auth/two-factor/disable'
-])
-
-const ACTIVE_ACCOUNT_AUTH_PATHS = new Set([
- '/api/auth/passkey/delete-passkey',
- '/api/auth/passkey/generate-register-options',
- '/api/auth/passkey/list-user-passkeys',
- '/api/auth/passkey/update-passkey',
- '/api/auth/passkey/verify-registration',
- '/api/auth/two-factor/disable',
- '/api/auth/two-factor/enable',
- '/api/auth/two-factor/generate-backup-codes',
- '/api/auth/two-factor/get-totp-uri',
- '/api/auth/account-info',
- '/api/auth/change-email',
- '/api/auth/change-password',
- '/api/auth/delete-user',
- '/api/auth/get-access-token',
- '/api/auth/link-social',
- '/api/auth/list-accounts',
- '/api/auth/list-sessions',
- '/api/auth/refresh-token',
- '/api/auth/revoke-other-sessions',
- '/api/auth/revoke-session',
- '/api/auth/revoke-sessions',
- '/api/auth/unlink-account'
-])
-
export function shouldPreventIndexing(path: string, policy: 'allow' | 'deny'): boolean {
return (
policy === 'deny' ||
@@ -274,7 +246,7 @@ export function createCloudApp(services: CloudServices) {
{
resource: (context) => context.req.path,
// Guests refresh collaboration tickets on their own budget, `publicCollaborationLimiter`.
- skip: (context) => context.req.path.endsWith('/collaboration-ticket')
+ skip: routeHasOwnBudget
}
)
const publicCollaborationLimiter = createTrustedIPRateLimiter(
@@ -283,19 +255,15 @@ export function createCloudApp(services: CloudServices) {
CLOUD_RATE_LIMITS.collaborationTicket,
{ trustedHeaders: services.config.authTrustedIPHeaders },
(context) => context.json({ error: { code: 'not_found' as const } }, 404),
- { resource: (context) => context.req.path }
+ { resource: (context) => context.req.path, route: true }
)
const authenticatedMutationLimiter = createActorRateLimiter(
services.database,
services.config.authSecret,
CLOUD_RATE_LIMITS.authenticatedMutation,
- (context) =>
- context.req.method === 'GET' ||
- context.req.path.endsWith('/collaboration-ticket') ||
- context.req.path === '/api/ai/token' ||
- context.req.path.endsWith('/invitations') ||
- context.req.path.endsWith('/uploads') ||
- /^\/api\/workspaces(?:\/[^/]+\/documents)?$/.test(context.req.path)
+ // Reads are free, and a route with a budget of its own, such as creating documents, counts
+ // against that instead.
+ (context) => context.req.method === 'GET' || routeHasOwnBudget(context)
)
const accountRoutes = createAccountRoutes({
@@ -389,18 +357,7 @@ export function createCloudApp(services: CloudServices) {
.get(CLOUD_AI_JWKS_PATH, async (context) =>
aiTokens ? context.json(aiTokens.jwks()) : context.notFound()
)
- .on(['GET', 'POST'], '/api/auth/*', async (context) => {
- if (POLICY_MANAGED_AUTH_PATHS.has(context.req.path)) {
- return context.json({ error: { code: 'forbidden' as const } }, 403)
- }
- if (
- ACTIVE_ACCOUNT_AUTH_PATHS.has(context.req.path) &&
- !(await resolveSession(context.req.raw))
- ) {
- return context.json({ error: { code: 'unauthorized' as const } }, 401)
- }
- return services.auth.handler(context.req.raw)
- })
+ .on(['GET', 'POST'], `${AUTH_BASE_PATH}/*`, (context) => services.auth.handler(context.req.raw))
.route('/', accountRoutes)
.route('/', createPictureRoutes(pictures))
.use('/api/shares/:shareId/collaboration-ticket', publicCollaborationLimiter)
diff --git a/packages/cloud/src/server/auth/activity.ts b/packages/cloud/src/server/auth/activity.ts
index c59873665..883cd2c9e 100644
--- a/packages/cloud/src/server/auth/activity.ts
+++ b/packages/cloud/src/server/auth/activity.ts
@@ -6,19 +6,34 @@ import { createAuthMiddleware, isAPIError } from 'better-auth/api'
import type { Kysely } from 'kysely'
import type { AuthenticationEmailService } from './email'
+import { CORE_AUTH_PATHS, isAuthEndpoint } from './endpoints'
import { describeUserAgent } from './user-agent'
/** The newest sign-ins an account's history shows. */
const SIGN_IN_HISTORY_LIMIT = 50
+type Endpoint = { path: string }
+
+/** The plugin endpoints that sign someone in, as the server's plugins declare them. */
+export type SignInPluginEndpoints = {
+ twoStep: { verifyTOTP: Endpoint; verifyBackupCode: Endpoint }
+ passkeys: { verifyPasskeyAuthentication: Endpoint; verifyPasskeyRegistration: Endpoint }
+ devices: { deviceToken: Endpoint }
+}
+
/** The Better Auth endpoints that sign someone in, and the method each one is. */
-const ENDPOINT_METHODS: Record<string, CloudSignInMethod> = {
- '/sign-in/email': 'password',
- '/passkey/verify-authentication': 'passkey',
- '/two-factor/verify-totp': 'two-step',
- '/two-factor/verify-backup-code': 'two-step',
- '/verify-email': 'email-link',
- '/device/token': 'desktop'
+export type SignInEndpoints = readonly (readonly [path: string, method: CloudSignInMethod])[]
+
+/** The sign-in endpoints of the core and of the server's plugins, from their own paths. */
+export function signInEndpoints(plugins: SignInPluginEndpoints): SignInEndpoints {
+ return [
+ [CORE_AUTH_PATHS.signInEmail, 'password'],
+ [plugins.passkeys.verifyPasskeyAuthentication.path, 'passkey'],
+ [plugins.twoStep.verifyTOTP.path, 'two-step'],
+ [plugins.twoStep.verifyBackupCode.path, 'two-step'],
+ [CORE_AUTH_PATHS.verifyEmail, 'email-link'],
+ [plugins.devices.deviceToken.path, 'desktop']
+ ]
}
/**
@@ -26,16 +41,15 @@ const ENDPOINT_METHODS: Record<string, CloudSignInMethod> = {
* a session. A provider's callback names the provider, as Better Auth's own `lastLoginMethod`
* reads it.
*/
-export function signInMethod(endpoint: {
- path?: string
- params?: Record<string, string | undefined>
-}): CloudSignInMethod | null {
- const path = endpoint.path ?? ''
- if (path.startsWith('/callback/')) {
+export function signInMethod(
+ endpoint: { path?: string; params?: Record<string, string | undefined> },
+ methods: SignInEndpoints
+): CloudSignInMethod | null {
+ if (isAuthEndpoint(endpoint.path, CORE_AUTH_PATHS.callbackOAuth)) {
const provider = endpoint.params?.id
return provider === 'google' || provider === 'apple' ? provider : 'other'
}
- return ENDPOINT_METHODS[path] ?? null
+ return methods.find(([path]) => isAuthEndpoint(endpoint.path, path))?.[1] ?? null
}
/**
@@ -169,22 +183,25 @@ export type SignInActivity = ReturnType<typeof createSignInActivity>
*/
export function accountActivity(
activity: SignInActivity,
+ plugins: SignInPluginEndpoints,
onPasskeyAdded: (user: { id: string; email: string; name: string }) => Promise<void>
): BetterAuthPlugin {
+ const methods = signInEndpoints(plugins)
return {
id: 'openpencil-account-activity',
hooks: {
after: [
{
- matcher: (context) => signInMethod(context) !== null,
+ matcher: (context) => signInMethod(context, methods) !== null,
handler: createAuthMiddleware(async (context) => {
const issued = context.context.newSession
- const method = signInMethod(context)
+ const method = signInMethod(context, methods)
if (issued && method) await activity.record(issued, method)
})
},
{
- matcher: (context) => context.path === '/passkey/verify-registration',
+ matcher: (context) =>
+ isAuthEndpoint(context.path, plugins.passkeys.verifyPasskeyRegistration.path),
handler: createAuthMiddleware(async (context) => {
const user = context.context.session?.user
if (user && !isAPIError(context.context.returned)) await onPasskeyAdded(user)
diff --git a/packages/cloud/src/server/auth/endpoints.ts b/packages/cloud/src/server/auth/endpoints.ts
new file mode 100644
index 000000000..f826c3d47
--- /dev/null
+++ b/packages/cloud/src/server/auth/endpoints.ts
@@ -0,0 +1,57 @@
+import type * as BetterAuthEndpoints from 'better-auth/api'
+
+/** Where Better Auth answers under the Cloud server. */
+export const AUTH_BASE_PATH = '/api/auth'
+
+/** The path an endpoint declares, whether the library exports it built or as a factory. */
+type PathOf<Endpoint> = Endpoint extends { path: infer Path extends string }
+ ? Path
+ : Endpoint extends (...args: never) => { path: infer Path extends string }
+ ? Path
+ : never
+type CorePaths<Names extends keyof typeof BetterAuthEndpoints> = {
+ readonly [Name in Names]: PathOf<(typeof BetterAuthEndpoints)[Name]>
+}
+
+/**
+ * The core endpoints whose paths Better Auth's own options need before it is built: rate limits,
+ * captcha, and the hooks that record sign-ins. Plugin endpoints come from the plugin objects and
+ * the rest from `auth.api`; these few are written out, and the type check holds each to the path
+ * the library declares, so a renamed endpoint fails to compile.
+ */
+export const CORE_AUTH_PATHS: CorePaths<
+ | 'callbackOAuth'
+ | 'requestPasswordReset'
+ | 'sendVerificationEmail'
+ | 'signInEmail'
+ | 'signUpEmail'
+ | 'verifyEmail'
+> = {
+ callbackOAuth: '/callback/:id',
+ requestPasswordReset: '/request-password-reset',
+ sendVerificationEmail: '/send-verification-email',
+ signInEmail: '/sign-in/email',
+ signUpEmail: '/sign-up/email',
+ verifyEmail: '/verify-email'
+}
+
+/**
+ * Whether `path`, as a hook context or request has it, is the endpoint at `endpoint`. Hooks see the
+ * declared pattern or the concrete path, so a `:param` segment matches any one segment.
+ */
+export function isAuthEndpoint(path: string | undefined, endpoint: string): boolean {
+ if (!path) return false
+ const actual = path.split('/')
+ const expected = endpoint.split('/')
+ return (
+ actual.length === expected.length &&
+ expected.every((segment, index) =>
+ segment.startsWith(':') ? Boolean(actual[index]) : segment === actual[index]
+ )
+ )
+}
+
+/** The path a request for the endpoint at `endpoint` arrives at on the Cloud server. */
+export function authRequestPath(endpoint: string): string {
+ return `${AUTH_BASE_PATH}${endpoint}`
+}
diff --git a/packages/cloud/src/server/auth/factory.ts b/packages/cloud/src/server/auth/factory.ts
index c516ce023..fd1092cb6 100644
--- a/packages/cloud/src/server/auth/factory.ts
+++ b/packages/cloud/src/server/auth/factory.ts
@@ -3,7 +3,7 @@ import type { CloudServerConfig } from '#cloud/server/config'
import type { CloudDatabase } from '#cloud/server/db'
import { createUserPictures, providerPictures } from '#cloud/server/pictures'
import { passkey } from '@better-auth/passkey'
-import { APIError, betterAuth, type BetterAuthOptions } from 'better-auth'
+import { APIError, betterAuth } from 'better-auth'
import { getMigrations } from 'better-auth/db/migration'
import {
admin,
@@ -13,74 +13,18 @@ import {
haveIBeenPwned,
twoFactor
} from 'better-auth/plugins'
-import { importPKCS8, SignJWT } from 'jose'
import type { Kysely } from 'kysely'
import { accountActivity, createSignInActivity } from './activity'
import type { CloudAuthAdapter } from './adapter'
import type { AuthenticationEmailService } from './email'
+import { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath } from './endpoints'
import { createMFAAssuranceService } from './mfa-assurance'
+import { APPLE_AUDIENCE, socialProviders } from './social-providers'
-const APPLE_AUDIENCE = 'https://appleid.apple.com'
-const APPLE_SECRET_LIFETIME_SECONDS = 180 * 24 * 60 * 60
const BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'
const ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60
-async function generateAppleClientSecret(config: CloudServerConfig): Promise<string> {
- if (
- !config.appleClientId ||
- !config.appleTeamId ||
- !config.appleKeyId ||
- !config.applePrivateKey
- ) {
- throw new Error('Apple authentication is not configured')
- }
- const privateKey = await importPKCS8(config.applePrivateKey.replaceAll('\\n', '\n'), 'ES256')
- const issuedAt = Math.floor(Date.now() / 1000)
- return new SignJWT({})
- .setProtectedHeader({ alg: 'ES256', kid: config.appleKeyId })
- .setIssuer(config.appleTeamId)
- .setSubject(config.appleClientId)
- .setAudience(APPLE_AUDIENCE)
- .setIssuedAt(issuedAt)
- .setExpirationTime(issuedAt + APPLE_SECRET_LIFETIME_SECONDS)
- .sign(privateKey)
-}
-
-function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {
- const providers: BetterAuthOptions['socialProviders'] = {}
- if (config.googleClientId && config.googleClientSecret) {
- providers.google = {
- clientId: config.googleClientId,
- clientSecret: config.googleClientSecret
- }
- }
- if (config.appleClientId) {
- providers.apple = async () => {
- const provider: {
- clientId: string
- clientSecret: string
- appBundleIdentifier?: string
- } = {
- clientId: config.appleClientId ?? '',
- clientSecret: await generateAppleClientSecret(config)
- }
- if (config.appleAppBundleIdentifier) {
- provider.appBundleIdentifier = config.appleAppBundleIdentifier
- }
- return provider
- }
- }
- return providers
-}
-
-function assuranceMethod(path: string): 'totp' | 'recovery-code' | 'passkey' | null {
- if (path === '/api/auth/two-factor/verify-totp') return 'totp'
- if (path === '/api/auth/two-factor/verify-backup-code') return 'recovery-code'
- if (path === '/api/auth/passkey/verify-authentication') return 'passkey'
- return null
-}
-
async function recordResponseAssurance(
response: Response,
method: 'totp' | 'recovery-code' | 'passkey',
@@ -105,11 +49,12 @@ async function verifySecondFactor(
assurance: ReturnType<typeof createMFAAssuranceService>,
headers: Headers,
code: string,
- method: 'totp' | 'recovery-code'
+ method: 'totp' | 'recovery-code',
+ /** The two-step plugin's endpoint that checks this kind of code. */
+ endpoint: { path: string }
): Promise<Response> {
- const path = method === 'totp' ? 'verify-totp' : 'verify-backup-code'
const response = await auth.handler(
- new Request(new URL(`/api/auth/two-factor/${path}`, config.publicURL), {
+ new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {
method: 'POST',
headers: new Headers({
...Object.fromEntries(headers),
@@ -144,10 +89,39 @@ export function createBetterAuthAdapter(
const activity = createSignInActivity(database, authenticationEmail)
// A new address is confirmed through a link sent to it, so changing one needs email delivery.
const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)
+ // The plugins are built first, so the options below name their endpoints by the paths they declare.
+ const twoStep = twoFactor({
+ issuer: 'OpenPencil Cloud',
+ trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,
+ allowPasswordless: true,
+ totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },
+ backupCodeOptions: {
+ disable: !config.totpEnabled || !config.recoveryCodesEnabled,
+ storeBackupCodes: 'encrypted'
+ }
+ })
+ const passkeys = passkey({
+ rpID: new URL(config.publicURL).hostname,
+ rpName: config.passkeyRPName,
+ origin: new URL(config.publicURL).origin
+ })
+ const devices = deviceAuthorization({
+ verificationUri: new URL('/auth/device', config.publicURL).href,
+ validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')
+ })
+ const administration = admin()
const auth = betterAuth({
appName: 'OpenPencil Cloud',
baseURL: config.publicURL,
- basePath: '/api/auth',
+ basePath: AUTH_BASE_PATH,
+ // Clients never reach Better Auth's own administration, which `/api/admin` replaces with MFA,
+ // origin, last-administrator, and audit checks, nor the two endpoints Cloud's policy manages
+ // through its account routes; the server still calls them itself.
+ disabledPaths: [
+ ...Object.values(administration.endpoints).map((endpoint) => endpoint.path),
+ passkeys.endpoints.deletePasskey.path,
+ twoStep.endpoints.disableTwoFactor.path
+ ],
secret: config.authSecret,
database: {
db: database,
@@ -180,14 +154,14 @@ export function createBetterAuthAdapter(
window: 60,
max: 100,
customRules: {
- '/device/code': { window: 60, max: 10 },
- '/device/token': { window: 60, max: 60 },
- '/device/approve': { window: 60, max: 10 },
- '/device/deny': { window: 60, max: 10 },
- '/sign-in/email': { window: 10, max: 3 },
- '/sign-up/email': { window: 10, max: 3 },
- '/request-password-reset': { window: 60, max: 3 },
- '/send-verification-email': { window: 60, max: 3 }
+ [devices.endpoints.deviceCode.path]: { window: 60, max: 10 },
+ [devices.endpoints.deviceToken.path]: { window: 60, max: 60 },
+ [devices.endpoints.deviceApprove.path]: { window: 60, max: 10 },
+ [devices.endpoints.deviceDeny.path]: { window: 60, max: 10 },
+ [CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },
+ [CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },
+ [CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },
+ [CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }
}
},
emailAndPassword: config.emailPasswordEnabled
@@ -277,35 +251,27 @@ export function createBetterAuthAdapter(
provider: config.captchaProvider,
secretKey: config.captchaSecretKey,
allowedHostnames: config.captchaAllowedHostnames,
- endpoints: ['/sign-up/email', '/sign-in/email', '/request-password-reset']
+ endpoints: [
+ CORE_AUTH_PATHS.signUpEmail,
+ CORE_AUTH_PATHS.signInEmail,
+ CORE_AUTH_PATHS.requestPasswordReset
+ ]
})
]
: []),
...(config.compromisedPasswordCheck ? [haveIBeenPwned()] : []),
- twoFactor({
- issuer: 'OpenPencil Cloud',
- trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,
- allowPasswordless: true,
- totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },
- backupCodeOptions: {
- disable: !config.totpEnabled || !config.recoveryCodesEnabled,
- storeBackupCodes: 'encrypted'
- }
- }),
- passkey({
- rpID: new URL(config.publicURL).hostname,
- rpName: config.passkeyRPName,
- origin: new URL(config.publicURL).origin
- }),
- admin(),
+ twoStep,
+ passkeys,
+ administration,
// Device authorization returns opaque database session tokens, not signed cookies.
bearer(),
- deviceAuthorization({
- verificationUri: new URL('/auth/device', config.publicURL).href,
- validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')
- }),
+ devices,
// After two-step sign-in's own hooks, so a sign-in waiting for its second step is skipped.
- accountActivity(activity, (user) => notifyTwoStep(user, 'passkey-added')),
+ accountActivity(
+ activity,
+ { twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },
+ (user) => notifyTwoStep(user, 'passkey-added')
+ ),
providerPictures(createUserPictures(database, { publicURL: config.publicURL }))
],
socialProviders: socialProviders(config),
@@ -365,29 +331,66 @@ export function createBetterAuthAdapter(
})
}
+ /** The signed-in person while their account may use the server, which awaiting approval it may not. */
+ async function resolveSession(headers: Headers) {
+ const identity = await resolveIdentity(headers)
+ if (!identity) return null
+ if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {
+ return null
+ }
+ return identity
+ }
+
+ /**
+ * The endpoints that read or change an account, which only an account that may use the server
+ * reaches; one awaiting approval still signs in and out. Better Auth checks the session inside
+ * most of these endpoints rather than declaring it, so they are listed by their own objects.
+ */
+ const activeAccountPaths = new Set(
+ [
+ auth.api.generatePasskeyRegistrationOptions,
+ auth.api.listPasskeys,
+ auth.api.updatePasskey,
+ auth.api.verifyPasskeyRegistration,
+ auth.api.enableTwoFactor,
+ auth.api.generateBackupCodes,
+ auth.api.getTOTPURI,
+ auth.api.accountInfo,
+ auth.api.changeEmail,
+ auth.api.changePassword,
+ auth.api.deleteUser,
+ auth.api.getAccessToken,
+ auth.api.linkSocialAccount,
+ auth.api.listUserAccounts,
+ auth.api.listSessions,
+ auth.api.refreshToken,
+ auth.api.revokeOtherSessions,
+ auth.api.revokeSession,
+ auth.api.revokeSessions,
+ auth.api.unlinkAccount
+ ].map((endpoint) => authRequestPath(endpoint.path))
+ )
+ /** The second factor a request proves, by the endpoint it is for. */
+ const assuranceMethods = new Map<string, 'totp' | 'recovery-code' | 'passkey'>([
+ [authRequestPath(twoStep.endpoints.verifyTOTP.path), 'totp'],
+ [authRequestPath(twoStep.endpoints.verifyBackupCode.path), 'recovery-code'],
+ [authRequestPath(passkeys.endpoints.verifyPasskeyAuthentication.path), 'passkey']
+ ])
+
return {
handler: async (request) => {
const path = new URL(request.url).pathname
- // Administration goes through `/api/admin`, which adds MFA, origin, last-admin, and audit
- // checks; Better Auth's own admin endpoints would skip all of them.
- if (path === '/api/auth/admin' || path.startsWith('/api/auth/admin/')) {
- return Response.json({ error: { code: 'forbidden' } }, { status: 403 })
+ if (activeAccountPaths.has(path) && !(await resolveSession(request.headers))) {
+ return Response.json({ error: { code: 'unauthorized' } }, { status: 401 })
}
const response = await auth.handler(request)
- const method = assuranceMethod(path)
+ const method = assuranceMethods.get(path)
if (response.ok && method)
await recordResponseAssurance(response, method, database, assurance)
return response
},
resolveIdentity,
- async resolveSession(headers) {
- const identity = await resolveIdentity(headers)
- if (!identity) return null
- if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {
- return null
- }
- return identity
- },
+ resolveSession,
async listAuthenticationMethods(headers) {
const accounts = await auth.api.listUserAccounts({ headers })
return accounts.map((account) => ({
@@ -470,7 +473,8 @@ export function createBetterAuthAdapter(
assurance,
headers,
code,
- 'totp'
+ 'totp',
+ twoStep.endpoints.verifyTOTP
)
// The first code from a new authenticator is what turns it on.
if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {
@@ -479,7 +483,16 @@ export function createBetterAuthAdapter(
return response
},
async verifyRecoveryCode(headers, code) {
- return verifySecondFactor(auth, config, database, assurance, headers, code, 'recovery-code')
+ return verifySecondFactor(
+ auth,
+ config,
+ database,
+ assurance,
+ headers,
+ code,
+ 'recovery-code',
+ twoStep.endpoints.verifyBackupCode
+ )
},
async generateRecoveryCodes(headers, password) {
return (await auth.api.generateBackupCodes({ headers, body: { password } })).backupCodes
diff --git a/packages/cloud/src/server/auth/index.ts b/packages/cloud/src/server/auth/index.ts
index 574910907..77fb23d00 100644
--- a/packages/cloud/src/server/auth/index.ts
+++ b/packages/cloud/src/server/auth/index.ts
@@ -2,6 +2,7 @@ export { createAccountAuthenticationService, type AccountAuthenticationService }
export { createSignInActivity, type SignInActivity } from './activity'
export type { CloudAuthAdapter } from './adapter'
export { createAuthenticationEmailService, type AuthenticationEmailService } from './email'
+export { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath, isAuthEndpoint } from './endpoints'
export { createMFAAssuranceService, type MFAAssuranceService } from './mfa-assurance'
export { createCloudAuthenticationRuntime } from './runtime'
export { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
diff --git a/packages/cloud/src/server/auth/social-providers.ts b/packages/cloud/src/server/auth/social-providers.ts
new file mode 100644
index 000000000..5b47c5897
--- /dev/null
+++ b/packages/cloud/src/server/auth/social-providers.ts
@@ -0,0 +1,55 @@
+import type { CloudServerConfig } from '#cloud/server/config'
+import type { BetterAuthOptions } from 'better-auth'
+import { importPKCS8, SignJWT } from 'jose'
+
+/** The audience Apple's sign-in tokens carry, which the server also trusts as an origin. */
+export const APPLE_AUDIENCE = 'https://appleid.apple.com'
+const APPLE_SECRET_LIFETIME_SECONDS = 180 * 24 * 60 * 60
+async function generateAppleClientSecret(config: CloudServerConfig): Promise<string> {
+ if (
+ !config.appleClientId ||
+ !config.appleTeamId ||
+ !config.appleKeyId ||
+ !config.applePrivateKey
+ ) {
+ throw new Error('Apple authentication is not configured')
+ }
+ const privateKey = await importPKCS8(config.applePrivateKey.replaceAll('\\n', '\n'), 'ES256')
+ const issuedAt = Math.floor(Date.now() / 1000)
+ return new SignJWT({})
+ .setProtectedHeader({ alg: 'ES256', kid: config.appleKeyId })
+ .setIssuer(config.appleTeamId)
+ .setSubject(config.appleClientId)
+ .setAudience(APPLE_AUDIENCE)
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(issuedAt + APPLE_SECRET_LIFETIME_SECONDS)
+ .sign(privateKey)
+}
+
+/** The sign-in providers the deployment configures; Apple's secret is signed when it is needed. */
+export function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {
+ const providers: BetterAuthOptions['socialProviders'] = {}
+ if (config.googleClientId && config.googleClientSecret) {
+ providers.google = {
+ clientId: config.googleClientId,
+ clientSecret: config.googleClientSecret
+ }
+ }
+ if (config.appleClientId) {
+ providers.apple = async () => {
+ const provider: {
+ clientId: string
+ clientSecret: string
+ appBundleIdentifier?: string
+ } = {
+ clientId: config.appleClientId ?? '',
+ clientSecret: await generateAppleClientSecret(config)
+ }
+ if (config.appleAppBundleIdentifier) {
+ provider.appBundleIdentifier = config.appleAppBundleIdentifier
+ }
+ return provider
+ }
+ }
+ return providers
+}
diff --git a/packages/cloud/src/server/collaboration/routes.ts b/packages/cloud/src/server/collaboration/routes.ts
index 462909712..5450d8bf3 100644
--- a/packages/cloud/src/server/collaboration/routes.ts
+++ b/packages/cloud/src/server/collaboration/routes.ts
@@ -3,7 +3,7 @@ import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
import type { CollaborationTicketService } from '#cloud/server/collaboration/service'
import type { CloudDatabase } from '#cloud/server/db'
import { DocumentNotFoundError } from '#cloud/server/documents'
-import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
import { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server/sharing'
import { validatedJSON } from '#cloud/server/validation'
import { Hono, type Context } from 'hono'
@@ -29,7 +29,7 @@ export function createCollaborationRoutes(
if (rateLimit) {
router.use(
'/documents/:documentId/collaboration-ticket',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.collaborationTicket,
diff --git a/packages/cloud/src/server/documents/routes.ts b/packages/cloud/src/server/documents/routes.ts
index 4b00592e3..58397d244 100644
--- a/packages/cloud/src/server/documents/routes.ts
+++ b/packages/cloud/src/server/documents/routes.ts
@@ -16,7 +16,7 @@ import {
} from '#cloud/server/documents/errors'
import type { DocumentService } from '#cloud/server/documents/service'
import { StorageQuotaExceededError } from '#cloud/server/quota'
-import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
import { validatedJSON } from '#cloud/server/validation'
import { Hono, type Context } from 'hono'
import type { Kysely } from 'kysely'
@@ -69,7 +69,7 @@ export function createDocumentRoutes(
if (rateLimit) {
router.use(
'/workspaces/:workspaceId/documents',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.documentCreation,
@@ -79,7 +79,7 @@ export function createDocumentRoutes(
)
router.use(
'/documents/:documentId/images',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.uploadCreation,
@@ -89,7 +89,7 @@ export function createDocumentRoutes(
)
router.use(
'/documents/:documentId/uploads',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.uploadCreation,
diff --git a/packages/cloud/src/server/pictures/index.ts b/packages/cloud/src/server/pictures/index.ts
index e82433eaa..c7453a718 100644
--- a/packages/cloud/src/server/pictures/index.ts
+++ b/packages/cloud/src/server/pictures/index.ts
@@ -1,4 +1,4 @@
-export { providerPictures } from './provider'
+export { providerPicture, providerPictures } from './provider'
export { createPictureRoutes } from './routes'
export {
createUserPictures,
diff --git a/packages/cloud/src/server/pictures/provider.ts b/packages/cloud/src/server/pictures/provider.ts
index 02f98acdf..9234a201e 100644
--- a/packages/cloud/src/server/pictures/provider.ts
+++ b/packages/cloud/src/server/pictures/provider.ts
@@ -1,25 +1,40 @@
-import { signInMethod } from '#cloud/server/auth/activity'
import type { BetterAuthPlugin } from 'better-auth'
-import { createAuthMiddleware } from 'better-auth/api'
+import { decodeJwt } from 'jose'
+import * as v from 'valibot'
import type { UserPictureService } from './service'
-/** Whether an endpoint signs in with another service, which may name the person's picture. */
-function providerSignIn(context: { path?: string } | null): boolean {
- const path = context?.path ?? ''
- return path.startsWith('/callback/') || path === '/sign-in/social'
+/** The providers whose ID token names the person's picture. */
+const PICTURE_PROVIDERS = new Set(['google'])
+const pictureClaimSchema = v.object({ picture: v.pipe(v.string(), v.url()) })
+
+/**
+ * The picture a linked account's provider names in the ID token Better Auth keeps on its account
+ * row, or null. The token came to Better Auth from the provider during its sign-in flow, which no
+ * client can write to the row.
+ */
+export function providerPicture(account: { providerId: string; idToken?: string | null }) {
+ if (!PICTURE_PROVIDERS.has(account.providerId) || !account.idToken) return null
+ try {
+ const claims = v.safeParse(pictureClaimSchema, decodeJwt(account.idToken))
+ return claims.success ? claims.output.picture : null
+ } catch {
+ return null
+ }
}
/**
- * Keeps the picture a Google account gave the person once a sign-in issues their session, so pages
- * show the server's copy and never load it from Google. Accounts made before the server kept
- * pictures move over the next time they sign in this way. Better Auth also takes an `image` on
- * email sign-up and user updates; only a provider's sign-in may set one through it, since the
- * server fetches it, and the server writes its own addresses itself.
+ * Keeps the picture a Google account names, so pages show the server's copy and never load it
+ * from Google. Better Auth writes the account's ID token when it is linked and at each sign-in
+ * with it, so accounts made before the server kept pictures move over the next time they sign in
+ * this way. Better Auth also takes an `image` on sign-up and user updates; none of those reach the
+ * account, since the server writes the addresses of the pictures it keeps itself.
*/
export function providerPictures(pictures: UserPictureService): BetterAuthPlugin {
- const refused = (image: unknown, context: { path?: string } | null) =>
- image !== undefined && image !== null && !providerSignIn(context)
+ const keep = async (account: { userId: string; providerId: string; idToken?: string | null }) => {
+ const picture = providerPicture(account)
+ if (picture) await pictures.copyFromProvider(account.userId, picture)
+ }
return {
id: 'openpencil-provider-pictures',
init: () => ({
@@ -27,30 +42,20 @@ export function providerPictures(pictures: UserPictureService): BetterAuthPlugin
databaseHooks: {
user: {
create: {
- before: async (user, context) =>
- refused(user.image, context) ? { data: { ...user, image: null } } : true
+ before: async (user) => ({ data: { ...user, image: null } })
},
update: {
// Better Auth merges what a hook returns into the update, so `image` is unset.
- before: async (user, context) =>
- refused(user.image, context) ? { data: { image: undefined } } : true
+ before: async (user) =>
+ user.image === undefined ? true : { data: { image: undefined } }
}
+ },
+ account: {
+ create: { after: keep },
+ update: { after: keep }
}
}
}
- }),
- hooks: {
- after: [
- {
- matcher: (context) => signInMethod(context) !== null,
- handler: createAuthMiddleware(async (context) => {
- const user = context.context.newSession?.user
- if (user?.image && !pictures.served(user.image)) {
- await pictures.copyFromProvider(user.id, user.image)
- }
- })
- }
- ]
- }
+ })
}
}
diff --git a/packages/cloud/src/server/pictures/service.ts b/packages/cloud/src/server/pictures/service.ts
index 861c61457..69bae8e42 100644
--- a/packages/cloud/src/server/pictures/service.ts
+++ b/packages/cloud/src/server/pictures/service.ts
@@ -76,6 +76,14 @@ async function boundedBody(response: Response, limit: number): Promise<Uint8Arra
return bytes
}
+type AccountPicture = { image: string | null; updatedAt: Date }
+
+function samePicture(current: AccountPicture | undefined, seen: AccountPicture | undefined) {
+ return (
+ current?.image === seen?.image && current?.updatedAt.getTime() === seen?.updatedAt.getTime()
+ )
+}
+
export type UserPictureOptions = {
publicURL: string
/** Fetches a linked account's picture; tests pass their own. */
@@ -94,27 +102,48 @@ export function createUserPictures(database: Kysely<CloudDatabase>, options: Use
return `${origin}${PICTURE_PATH}/${userId}/${checksum.slice(0, PICTURE_VERSION_LENGTH)}`
}
+ /** The address `bytes` are served from as the account's picture. */
+ function pictureAddress(userId: string, bytes: Uint8Array): string {
+ return address(userId, bytesToHex(sha256(bytes)))
+ }
+
/** Whether `image` is a picture this server serves, rather than another service's. */
function served(image: string): boolean {
return image.startsWith(`${origin}${PICTURE_PATH}/`)
}
+ /**
+ * Keeps `bytes` as the account's picture. A provider's picture is kept only while the account is
+ * unchanged since `seen`, read before the picture was fetched: every upload and removal moves
+ * `updatedAt`, so one made meanwhile stands, even one that left the image as it was. Returns
+ * whether the picture was kept.
+ */
async function save(
userId: string,
bytes: Uint8Array,
- source: 'upload' | 'provider'
- ): Promise<string> {
+ source: { from: 'upload' } | { from: 'provider'; seen: AccountPicture | undefined }
+ ): Promise<boolean> {
const format = pictureFormat(bytes)
if (!format) throw new PictureInvalidError()
const checksum = bytesToHex(sha256(bytes))
- const image = address(userId, checksum)
+ const image = pictureAddress(userId, bytes)
const createdAt = new Date()
- await database.transaction().execute(async (transaction) => {
+ return database.transaction().execute(async (transaction) => {
+ // Saves and removals lock the account first, so they take turns.
+ const current = await transaction
+ .selectFrom('user')
+ .select(['image', 'updatedAt'])
+ .where('id', '=', userId)
+ .forUpdate()
+ .executeTakeFirst()
+ if (source.from === 'provider' && !samePicture(current, source.seen)) return false
await transaction
.insertInto('userPicture')
- .values({ userId, bytes, format, checksum, source, createdAt })
+ .values({ userId, bytes, format, checksum, source: source.from, createdAt })
.onConflict((conflict) =>
- conflict.column('userId').doUpdateSet({ bytes, format, checksum, source, createdAt })
+ conflict
+ .column('userId')
+ .doUpdateSet({ bytes, format, checksum, source: source.from, createdAt })
)
.execute()
await transaction
@@ -122,12 +151,19 @@ export function createUserPictures(database: Kysely<CloudDatabase>, options: Use
.set({ image, updatedAt: createdAt })
.where('id', '=', userId)
.execute()
+ return true
})
- return image
}
async function remove(userId: string): Promise<void> {
await database.transaction().execute(async (transaction) => {
+ // The account first, in the same order saves lock, so the two never wait on each other.
+ await transaction
+ .selectFrom('user')
+ .select('id')
+ .where('id', '=', userId)
+ .forUpdate()
+ .execute()
await transaction.deleteFrom('userPicture').where('userId', '=', userId).execute()
await transaction
.updateTable('user')
@@ -141,8 +177,9 @@ export function createUserPictures(database: Kysely<CloudDatabase>, options: Use
served,
/** Keeps a picture the account's owner uploaded and shows it from now on. */
- upload(userId: string, bytes: Uint8Array): Promise<string> {
- return save(userId, bytes, 'upload')
+ async upload(userId: string, bytes: Uint8Array): Promise<string> {
+ await save(userId, bytes, { from: 'upload' })
+ return pictureAddress(userId, bytes)
},
/** Goes back to initials. */
@@ -166,6 +203,13 @@ export function createUserPictures(database: Kysely<CloudDatabase>, options: Use
*/
async copyFromProvider(userId: string, image: string): Promise<void> {
if (served(image)) return
+ // A picture the account already shows from this server, uploaded or kept before, stays.
+ const current = await database
+ .selectFrom('user')
+ .select(['image', 'updatedAt'])
+ .where('id', '=', userId)
+ .executeTakeFirst()
+ if (current?.image && served(current.image)) return
try {
if (!providerPicture(new URL(image))) throw new PictureInvalidError()
const response = await fetchPicture(image, {
@@ -174,7 +218,7 @@ export function createUserPictures(database: Kysely<CloudDatabase>, options: Use
})
const bytes = response.ok ? await boundedBody(response, CLOUD_PICTURE_MAX_BYTES) : null
if (!bytes) throw new PictureInvalidError()
- await save(userId, bytes, 'provider')
+ await save(userId, bytes, { from: 'provider', seen: current })
} catch (error) {
console.warn('Keeping a linked account picture failed', error)
await database
diff --git a/packages/cloud/src/server/rate-limit/index.ts b/packages/cloud/src/server/rate-limit/index.ts
index c016eccf2..2e4f90712 100644
--- a/packages/cloud/src/server/rate-limit/index.ts
+++ b/packages/cloud/src/server/rate-limit/index.ts
@@ -4,7 +4,9 @@ export {
CLOUD_RATE_LIMITS,
createActorRateLimiter,
createCloudRateLimiter,
+ createRouteRateLimiter,
createTrustedIPRateLimiter,
+ routeHasOwnBudget,
type RateLimitPolicy
} from './middleware'
export { PostgresRateLimitStore } from './postgres'
diff --git a/packages/cloud/src/server/rate-limit/middleware.ts b/packages/cloud/src/server/rate-limit/middleware.ts
index 0635dec5f..41da010e3 100644
--- a/packages/cloud/src/server/rate-limit/middleware.ts
+++ b/packages/cloud/src/server/rate-limit/middleware.ts
@@ -2,6 +2,7 @@ import type { CloudAPIEnvironment } from '#cloud/server/api/types'
import type { CloudDatabase } from '#cloud/server/db'
import type { Context, Env, Input } from 'hono'
import { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'
+import { matchedRoutes } from 'hono/route'
import type { Kysely } from 'kysely'
import { trustedClientIP, type ClientIdentityOptions } from './keys'
@@ -26,6 +27,26 @@ export const CLOUD_RATE_LIMITS = {
adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }
} as const satisfies Record<string, RateLimitPolicy>
+/**
+ * The limiters routes mount for their own budget, each with which requests it counts. A general
+ * limiter leaves those requests to it rather than counting them twice; the routes themselves say
+ * which have one, so the general limiter never matches paths.
+ */
+const routeBudgets = new WeakMap<object, (context: Context) => boolean>()
+
+/** Whether a limiter the request's route mounts for its own budget counts this request. */
+export function routeHasOwnBudget(context: Context): boolean {
+ return matchedRoutes(context).some((route) => routeBudgets.get(route.handler)?.(context))
+}
+
+function ownBudget<Limiter extends object>(
+ limiter: Limiter,
+ skip?: (context: Context) => boolean
+): Limiter {
+ routeBudgets.set(limiter, (context) => !skip?.(context))
+ return limiter
+}
+
type RateLimitOptions<E extends Env, P extends string, I extends Input> = {
database: Kysely<CloudDatabase>
secret: string
@@ -63,9 +84,11 @@ export function createTrustedIPRateLimiter(
options?: {
resource?: (context: Context) => string
skip?: (context: Context) => boolean
+ /** The limiter is a route's own budget, which general limiters leave to it. */
+ route?: boolean
}
) {
- return createCloudRateLimiter({
+ const limiter = createCloudRateLimiter({
database,
secret,
policy,
@@ -77,13 +100,14 @@ export function createTrustedIPRateLimiter(
trustedClientIP(context, client) === null || Boolean(options?.skip?.(context)),
handler
})
+ return options?.route ? ownBudget(limiter, options.skip) : limiter
}
export function createActorRateLimiter(
database: Kysely<CloudDatabase>,
secret: string,
policy: RateLimitPolicy,
- skip?: (context: Context<CloudAPIEnvironment, '*'>) => boolean,
+ skip?: (context: Context) => boolean,
resource?: (context: Context<CloudAPIEnvironment, '*'>) => string
) {
return createCloudRateLimiter<CloudAPIEnvironment, '*'>({
@@ -97,3 +121,17 @@ export function createActorRateLimiter(
skip
})
}
+
+/**
+ * A limiter a route mounts for its own budget, such as document creation; general limiters leave
+ * the requests it counts to it.
+ */
+export function createRouteRateLimiter(
+ database: Kysely<CloudDatabase>,
+ secret: string,
+ policy: RateLimitPolicy,
+ skip?: (context: Context) => boolean,
+ resource?: (context: Context<CloudAPIEnvironment, '*'>) => string
+) {
+ return ownBudget(createActorRateLimiter(database, secret, policy, skip, resource), skip)
+}
diff --git a/packages/cloud/src/server/sharing/routes.ts b/packages/cloud/src/server/sharing/routes.ts
index c8734b417..fae1bad7c 100644
--- a/packages/cloud/src/server/sharing/routes.ts
+++ b/packages/cloud/src/server/sharing/routes.ts
@@ -10,7 +10,7 @@ import {
} from '#cloud/contract'
import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
import type { CloudDatabase } from '#cloud/server/db'
-import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
import { sharingRoute } from '#cloud/server/sharing/http'
import type { DocumentSharingService } from '#cloud/server/sharing/service'
import { validatedJSON } from '#cloud/server/validation'
@@ -31,7 +31,7 @@ export function createDocumentSharingRoutes(
if (rateLimit) {
router.use(
'/documents/:documentId/invitations',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.invitationMutation,
diff --git a/packages/cloud/src/server/workspaces/routes.ts b/packages/cloud/src/server/workspaces/routes.ts
index faa39cc7a..23c99c103 100644
--- a/packages/cloud/src/server/workspaces/routes.ts
+++ b/packages/cloud/src/server/workspaces/routes.ts
@@ -6,7 +6,7 @@ import {
} from '#cloud/contract'
import type { CloudActor } from '#cloud/server/auth'
import type { CloudDatabase } from '#cloud/server/db'
-import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
import { validatedJSON } from '#cloud/server/validation'
import {
WorkspaceAlreadyMemberError,
@@ -61,7 +61,7 @@ export function createWorkspaceRoutes(
if (rateLimit) {
router.use(
'/',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.workspaceCreation,
@@ -71,7 +71,7 @@ export function createWorkspaceRoutes(
// Resending mails the invitation again, so it counts against the same budget as sending.
router.use(
'/:workspaceId/invitations/:invitationId/resend',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.invitationMutation,
@@ -81,7 +81,7 @@ export function createWorkspaceRoutes(
)
router.use(
'/:workspaceId/invitations',
- createActorRateLimiter(
+ createRouteRateLimiter(
rateLimit.database,
rateLimit.secret,
CLOUD_RATE_LIMITS.invitationMutation,
diff --git a/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts b/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts
index 6970ff07a..5062e140d 100644
--- a/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts
+++ b/packages/cloud/tests/integration/server/auth/mfa-assurance.test.ts
@@ -115,7 +115,7 @@ describe('deployment administrator MFA assurance', () => {
)
)
).status
- ).toBe(403)
+ ).toBe(404)
} finally {
await fixture.close()
}
@@ -187,7 +187,8 @@ describe('deployment administrator MFA assurance', () => {
account.sessionCookie
)
)
- expect(response.status).toBe(403)
+ // Cloud does not serve Better Auth's own administration at all.
+ expect(response.status).toBe(404)
}
const user = await fixture.database
.selectFrom('user')
diff --git a/packages/cloud/tests/integration/server/pictures/provider.test.ts b/packages/cloud/tests/integration/server/pictures/provider.test.ts
new file mode 100644
index 000000000..a372530c8
--- /dev/null
+++ b/packages/cloud/tests/integration/server/pictures/provider.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { pngHeader } from '#cloud-tests/helpers/pictures'
+import {
+ createUserPictures,
+ providerPictures,
+ type UserPictureService
+} from '#cloud/server/pictures'
+import { betterAuth } from 'better-auth'
+import { UnsecuredJWT } from 'jose'
+
+const PUBLIC_URL = 'https://cloud.example.com'
+const GOOGLE_PICTURE = 'https://lh3.googleusercontent.com/a/picture=s96-c'
+
+/** Better Auth with only the pictures plugin, writing through its own adapter so its hooks run. */
+async function pictureAuth() {
+ const runtime = await createCloudTestDatabase()
+ const requested: string[] = []
+ const pictures = createUserPictures(runtime.database, {
+ publicURL: PUBLIC_URL,
+ fetch: async (url) => {
+ requested.push(url)
+ return new Response(pngHeader(96, 96))
+ }
+ })
+ const auth = betterAuth({
+ baseURL: PUBLIC_URL,
+ secret: 'a test secret that is long enough for better auth',
+ database: { db: runtime.database, type: 'postgres', casing: 'camel' },
+ advanced: { database: { generateId: 'uuid' } },
+ plugins: [providerPictures(pictures)]
+ })
+ const adapter = (await auth.$context).internalAdapter
+ const image = async (userId: string) =>
+ (
+ await runtime.database
+ .selectFrom('user')
+ .select('image')
+ .where('id', '=', userId)
+ .executeTakeFirstOrThrow()
+ ).image
+ return { runtime, adapter, requested, image }
+}
+
+describe('provider pictures', () => {
+ test('drops an image any write through Better Auth names', async () => {
+ const { runtime, adapter, image } = await pictureAuth()
+ try {
+ const user = await adapter.createUser(
+ { email: '[email protected]', name: 'Image', image: 'https://pictures.example.com/me.png' },
+ { method: 'email-password' }
+ )
+ expect(await image(user.id)).toBeNull()
+ await adapter.updateUser(user.id, { image: GOOGLE_PICTURE, name: 'Renamed' })
+ expect(await image(user.id)).toBeNull()
+ } finally {
+ await runtime.close()
+ }
+ })
+
+ test("keeps the picture a linked Google account's token names, and an upload over it", async () => {
+ const { runtime, adapter, requested, image } = await pictureAuth()
+ try {
+ const user = await adapter.createUser(
+ { email: '[email protected]', name: 'Google' },
+ { method: 'email-password' }
+ )
+ const idToken = new UnsecuredJWT({ picture: GOOGLE_PICTURE }).encode()
+ const account = await adapter.linkAccount({
+ userId: user.id,
+ providerId: 'google',
+ accountId: 'google-subject',
+ idToken
+ })
+ expect(requested).toEqual([GOOGLE_PICTURE])
+ expect(await image(user.id)).toStartWith(`${PUBLIC_URL}/api/pictures/${user.id}/`)
+
+ // Signing in again rewrites the account's token; the picture the account shows stays.
+ await adapter.updateAccount(account.id, { idToken })
+ expect(requested).toHaveLength(1)
+ const kept = await image(user.id)
+ await adapter.updateUser(user.id, { image: GOOGLE_PICTURE, name: 'Renamed' })
+ expect(await image(user.id)).toBe(kept)
+ } finally {
+ await runtime.close()
+ }
+ })
+})
+
+/**
+ * A copy of the Google picture held mid-fetch: `during` runs once the fetch has begun, past the
+ * check before it, and the picture then arrives. Returns what the account shows afterwards.
+ */
+async function copyWhile<Result>(
+ image: string | null,
+ during: (pictures: UserPictureService, userId: string) => Promise<Result>
+) {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const userId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('user')
+ .values({ id: userId, name: 'Racer', email: '[email protected]', emailVerified: true, image })
+ .execute()
+ let answer: (response: Response) => void = () => undefined
+ let fetching: () => void = () => undefined
+ const fetchStarted = new Promise<void>((resolve) => {
+ fetching = resolve
+ })
+ const pictures = createUserPictures(runtime.database, {
+ publicURL: PUBLIC_URL,
+ fetch: () =>
+ new Promise<Response>((resolve) => {
+ answer = resolve
+ fetching()
+ })
+ })
+ const copying = pictures.copyFromProvider(userId, GOOGLE_PICTURE)
+ await fetchStarted
+ const result = await during(pictures, userId)
+ answer(new Response(pngHeader(96, 96)))
+ await copying
+ const { image: shown } = await runtime.database
+ .selectFrom('user')
+ .select('image')
+ .where('id', '=', userId)
+ .executeTakeFirstOrThrow()
+ return { result, shown }
+ } finally {
+ await runtime.close()
+ }
+}
+
+describe('a provider picture fetched meanwhile', () => {
+ test('does not replace an upload', async () => {
+ const { result, shown } = await copyWhile(null, (pictures, userId) =>
+ pictures.upload(userId, pngHeader(256, 256))
+ )
+ expect(shown).toBe(result)
+ })
+
+ test('does not undo a removal', async () => {
+ // An account from before the server kept pictures shows Google's address until it signs in.
+ const { shown } = await copyWhile(GOOGLE_PICTURE, (pictures, userId) => pictures.remove(userId))
+ expect(shown).toBeNull()
+ })
+
+ test('does not undo an upload removed again', async () => {
+ const { shown } = await copyWhile(null, async (pictures, userId) => {
+ await pictures.upload(userId, pngHeader(256, 256))
+ await pictures.remove(userId)
+ })
+ expect(shown).toBeNull()
+ })
+})
diff --git a/packages/cloud/tests/integration/server/rate-limit/budgets.test.ts b/packages/cloud/tests/integration/server/rate-limit/budgets.test.ts
new file mode 100644
index 000000000..5796908d1
--- /dev/null
+++ b/packages/cloud/tests/integration/server/rate-limit/budgets.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import type { CloudAPIEnvironment } from '#cloud/server/api'
+import {
+ createActorRateLimiter,
+ createRouteRateLimiter,
+ routeHasOwnBudget
+} from '#cloud/server/rate-limit'
+import { Hono } from 'hono'
+
+const SECRET = 'a rate limit secret'
+const policy = (namespace: string, limit: number) => ({ namespace, windowMs: 60_000, limit })
+
+describe('rate limit budgets', () => {
+ test("leaves a route's own requests to its own budget", async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const routes = new Hono<CloudAPIEnvironment>()
+ .use(
+ '/documents',
+ createRouteRateLimiter(
+ runtime.database,
+ SECRET,
+ policy('documents', 3),
+ (context) => context.req.method !== 'POST'
+ )
+ )
+ .post('/documents', (context) => context.text('created'))
+ .delete('/documents', (context) => context.text('deleted'))
+ .post('/rename', (context) => context.text('renamed'))
+ const app = new Hono<CloudAPIEnvironment>()
+ .use('/*', async (context, next) => {
+ context.set('actor', { userId: 'ada', email: '[email protected]', name: 'Ada' })
+ await next()
+ })
+ .use(
+ '/*',
+ createActorRateLimiter(runtime.database, SECRET, policy('general', 1), (context) =>
+ routeHasOwnBudget(context)
+ )
+ )
+ .route('/', routes)
+ const status = async (method: string, path: string) =>
+ (await app.request(path, { method })).status
+
+ // Three creations fit the route's own budget, though the general one allows a single request.
+ for (const _ of [1, 2, 3]) expect(await status('POST', '/documents')).toBe(200)
+ expect(await status('POST', '/documents')).toBe(429)
+ // A request the route's limiter does not count is the general limiter's.
+ expect(await status('DELETE', '/documents')).toBe(200)
+ expect(await status('POST', '/rename')).toBe(429)
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/server/auth/activity.test.ts b/packages/cloud/tests/server/auth/activity.test.ts
index 5c6688ba7..281a3f2ed 100644
--- a/packages/cloud/tests/server/auth/activity.test.ts
+++ b/packages/cloud/tests/server/auth/activity.test.ts
@@ -1,24 +1,39 @@
import { describe, expect, test } from 'bun:test'
-import { signInMethod } from '#cloud/server/auth/activity'
+import { signInEndpoints, signInMethod } from '#cloud/server/auth/activity'
import { describeUserAgent } from '#cloud/server/auth/user-agent'
+import { passkey } from '@better-auth/passkey'
+import { deviceAuthorization, twoFactor } from 'better-auth/plugins'
+
+// The sign-in endpoints of the plugins the server mounts, from the plugins' own paths.
+const methods = signInEndpoints({
+ twoStep: twoFactor().endpoints,
+ passkeys: passkey({
+ rpID: 'cloud.example.com',
+ rpName: 'Cloud',
+ origin: 'https://cloud.example.com'
+ }).endpoints,
+ devices: deviceAuthorization().endpoints
+})
describe('sign-in activity', () => {
test('names how each Better Auth endpoint signed someone in', () => {
- expect(signInMethod({ path: '/sign-in/email' })).toBe('password')
- expect(signInMethod({ path: '/callback/:id', params: { id: 'google' } })).toBe('google')
- expect(signInMethod({ path: '/callback/:id', params: { id: 'apple' } })).toBe('apple')
- expect(signInMethod({ path: '/callback/:id', params: { id: 'github' } })).toBe('other')
- expect(signInMethod({ path: '/passkey/verify-authentication' })).toBe('passkey')
- expect(signInMethod({ path: '/two-factor/verify-totp' })).toBe('two-step')
- expect(signInMethod({ path: '/verify-email' })).toBe('email-link')
- expect(signInMethod({ path: '/device/token' })).toBe('desktop')
+ expect(signInMethod({ path: '/sign-in/email' }, methods)).toBe('password')
+ expect(signInMethod({ path: '/callback/:id', params: { id: 'google' } }, methods)).toBe(
+ 'google'
+ )
+ expect(signInMethod({ path: '/callback/:id', params: { id: 'apple' } }, methods)).toBe('apple')
+ expect(signInMethod({ path: '/callback/:id', params: { id: 'github' } }, methods)).toBe('other')
+ expect(signInMethod({ path: '/passkey/verify-authentication' }, methods)).toBe('passkey')
+ expect(signInMethod({ path: '/two-factor/verify-totp' }, methods)).toBe('two-step')
+ expect(signInMethod({ path: '/verify-email' }, methods)).toBe('email-link')
+ expect(signInMethod({ path: '/device/token' }, methods)).toBe('desktop')
})
test('ignores endpoints that only refresh or change a session', () => {
- expect(signInMethod({ path: '/get-session' })).toBeNull()
- expect(signInMethod({ path: '/update-user' })).toBeNull()
- expect(signInMethod({})).toBeNull()
+ expect(signInMethod({ path: '/get-session' }, methods)).toBeNull()
+ expect(signInMethod({ path: '/update-user' }, methods)).toBeNull()
+ expect(signInMethod({}, methods)).toBeNull()
})
test('reads a browser and system from a user agent, and nothing from none', () => {
diff --git a/packages/cloud/tests/server/pictures/service.test.ts b/packages/cloud/tests/server/pictures/service.test.ts
index 92ff7d119..920e0b41b 100644
--- a/packages/cloud/tests/server/pictures/service.test.ts
+++ b/packages/cloud/tests/server/pictures/service.test.ts
@@ -2,8 +2,9 @@ import { describe, expect, test } from 'bun:test'
import { pngHeader } from '#cloud-tests/helpers/pictures'
import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'
-import { pictureFormat } from '#cloud/server/pictures'
+import { pictureFormat, providerPicture } from '#cloud/server/pictures'
import { utf8ToBytes } from '@noble/hashes/utils.js'
+import { UnsecuredJWT } from 'jose'
describe('picture format', () => {
test('keeps PNG and JPEG pictures of a reasonable size', () => {
@@ -24,3 +25,20 @@ describe('picture format', () => {
expect(pictureFormat(padded)).toBeNull()
})
})
+
+describe('provider picture', () => {
+ const token = (claims: Record<string, unknown>) => new UnsecuredJWT(claims).encode()
+
+ test("reads the picture a Google account's ID token names", () => {
+ const picture = 'https://lh3.googleusercontent.com/a/picture=s96-c'
+ expect(providerPicture({ providerId: 'google', idToken: token({ picture }) })).toBe(picture)
+ })
+
+ test('names nothing for other providers, missing tokens, or unreadable claims', () => {
+ const picture = 'https://lh3.googleusercontent.com/a/picture=s96-c'
+ expect(providerPicture({ providerId: 'apple', idToken: token({ picture }) })).toBeNull()
+ expect(providerPicture({ providerId: 'google', idToken: null })).toBeNull()
+ expect(providerPicture({ providerId: 'google', idToken: 'not a token' })).toBeNull()
+ expect(providerPicture({ providerId: 'google', idToken: token({ picture: 42 }) })).toBeNull()
+ })
+})
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index 4f984ee5b..eebec1b89 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -227,10 +227,12 @@ picture's SHA-256: a new picture is a new address. Responses are cached for one
picture an administrator removes may stay visible until the cache expires. The
page crops and shrinks a picture to a 256-pixel JPEG; the server accepts PNG or JPEG of at most
256 KB and 1024 pixels a side, reading the type and size from the bytes. A Google picture is
-fetched once a sign-in issues its session and kept the same way; one that cannot be fetched leaves
-initials, never a link to Google. The server fetches only from Google's picture host and follows no
-redirects. Only a provider's sign-in may write `user.image` through Better Auth; an address
-sent with email sign-up or a user update is dropped.
+fetched when Better Auth writes the account's ID token, as it does when the account is linked and
+at each sign-in with it, from the token's `picture` claim, and kept the same way unless the person
+already shows a picture of their own; one that cannot be fetched leaves initials, never a link to
+Google. The server fetches only from Google's picture host and follows no redirects. Nothing written
+through Better Auth sets `user.image`; the server writes the addresses of the pictures it keeps
+itself.
## Portal