A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api/auth): add entry, handoff, code and sign-in link routes
Hampusa9914120b9e3
diff --git a/fluxer_api/src/api/auth/AuthController.ts b/fluxer_api/src/api/auth/AuthController.tsindex 7b1c952de..10fef56b4 100644--- a/fluxer_api/src/api/auth/AuthController.ts+++ b/fluxer_api/src/api/auth/AuthController.ts@@ -1,12 +1,20 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {addressLookupCaptchaSteps, budgetEnvFor} from '@app/api/auth/AccountBudgets';+import {normalizeEmailKey} from '@app/api/auth/AccountCodes';import * as AuthEmail from '@app/api/auth/AuthEmail';import * as AuthLogin from '@app/api/auth/AuthLogin';import * as AuthMfa from '@app/api/auth/AuthMfa';import * as AuthPassword from '@app/api/auth/AuthPassword';+import {+ assertAccountCreationPastSetup,+ instantAccountsAvailable,+ isInstantAccountRequest,+} from '@app/api/auth/AuthRegistration';import * as AuthSession from '@app/api/auth/AuthSession';-+import {redeemSignInLink} from '@app/api/auth/SignInLinks';import {requireSudoMode} from '@app/api/auth/services/SudoVerificationService';+import {usesUsernameSignIn} from '@app/api/instance/AccountIdentityModeCache';import {onUsernameInstance,RequireEmailAccountIdentity,@@ -14,13 +22,16 @@ import {RequireUsernameLookup,} from '@app/api/middleware/AccountIdentityMiddleware';import {DefaultUserOnly, LoginRequired} from '@app/api/middleware/AuthMiddleware';-import {CaptchaMiddleware} from '@app/api/middleware/CaptchaMiddleware';-import {LocalAuthMiddleware} from '@app/api/middleware/LocalAuthMiddleware';+import {CaptchaMiddleware, EscalatingCaptchaMiddleware} from '@app/api/middleware/CaptchaMiddleware';+import {LocalAuthMiddleware, MfaTicketAuthMiddleware} from '@app/api/middleware/LocalAuthMiddleware';import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';import {SudoModeMiddleware} from '@app/api/middleware/SudoModeMiddleware';import {RateLimitConfigs} from '@app/api/RateLimitConfig';-import type {HonoApp} from '@app/api/types/HonoEnv';+import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';+import {scheduleAbandonedOnLastLogout} from '@app/api/user/AccountCleanup';+import {tierContextFrom} from '@app/api/user/AccountTier';+import {isJsonRecord} from '@app/api/utils/JsonBoundaryUtils';import {requireRequestClientIp} from '@app/api/utils/RequestClientIp';import {Validator} from '@app/api/Validator';import {@@ -51,6 +62,7 @@ import {RegisterRequest,ResetPasswordRequest,ResetPasswordTokenParam,+ SignInLinkRequest,SsoCompleteRequest,SsoCompleteResponse,SsoStartRequest,@@ -68,6 +80,33 @@ import {WebAuthnAuthenticationOptionsResponse,WebAuthnMfaRequest,} from '@fluxer/schema/src/domains/auth/AuthSchemas';+import type {Context} from 'hono';++function optionalString(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 ? value : null;+}++async function registrationCaptchaSteps(ctx: Context<HonoEnv>): Promise<number> {+ const body: unknown = await ctx.req.json();+ const fields = isJsonRecord(body) ? body : {};+ const data = {email: optionalString(fields.email), password: optionalString(fields.password)};+ const clientIp = requireRequestClientIp(ctx);+ if (isInstantAccountRequest(data, {usernameMode: usesUsernameSignIn()})) {+ const registrationUrlCode = optionalString(fields.registration_url_code);+ if (!(await instantAccountsAvailable(ctx.get('instanceConfigRepository'), registrationUrlCode))) return 0;+ if (optionalString(fields.setup_token) === null) {+ await assertAccountCreationPastSetup(ctx.get('apiContext'), ctx.get('instanceConfigRepository'), clientIp);+ }+ return await ctx.get('authRequestService').instantAccountChallengeSteps(ctx.req.raw, clientIp, registrationUrlCode);+ }+ if (!data.email || usesUsernameSignIn()) return 0;+ const lookupSteps = await addressLookupCaptchaSteps(budgetEnvFor(ctx.get('apiContext').services, ctx.req.raw), {+ clientIp,+ emailKey: normalizeEmailKey(data.email),+ requester: 'unknown',+ });+ return lookupSteps ?? 0;+}export function AuthController(app: HonoApp) {app.get(@@ -123,7 +162,7 @@ export function AuthController(app: HonoApp) {async (ctx) => {const result = await ctx.get('authRequestService')- .completeSso(ctx.req.valid('json'), ctx.req.raw, ctx.get('requestCache'));+ .completeSso(ctx.req.valid('json'), ctx.req.raw, ctx.get('requestCache'), requireRequestClientIp(ctx));return ctx.json(result);},);@@ -131,8 +170,8 @@ export function AuthController(app: HonoApp) {'/auth/register',LocalAuthMiddleware,RateLimitMiddleware(RateLimitConfigs.AUTH_REGISTER),- CaptchaMiddleware,Validator('json', RegisterRequest, {schemaFor: onUsernameInstance(UsernameInstanceRegisterRequest)}),+ EscalatingCaptchaMiddleware(registrationCaptchaSteps),OpenAPI({operationId: 'register_account',summary: 'Register account',@@ -141,13 +180,14 @@ export function AuthController(app: HonoApp) {security: [],tags: ['Auth'],description:- 'Create a new user account. Email instances take an email and password, and the account must verify its email before logging in. Username instances take a username and password, and an email sent by an older client is discarded. Requires a solved captcha challenge (X-Captcha-Token).',+ 'Create a new user account. A body without an email and a password creates an account without an email from global_name: the username is derived from the display name and given a tag, and the account signs in on this device only until it is claimed (an email on email instances, a password on username instances). On email instances an email sent here is stored on the account and waits for confirmation. An address stored on another account, confirmed or not, answers EMAIL_ALREADY_IN_USE. Username instances take a username and password, and an email sent by an older client is discarded. The date of birth can be left out where the instance collects it, and the app then asks for it before anything else. Requires a solved captcha challenge (X-Captcha-Token), which costs more after recent sign-ups without an email from the same network.',}),async (ctx) => {const result = await ctx.get('authRequestService').register({data: ctx.req.valid('json'),request: ctx.req.raw,requestCache: ctx.get('requestCache'),+ tierContext: tierContextFrom(ctx),});return ctx.json(result);},@@ -179,9 +219,9 @@ export function AuthController(app: HonoApp) {);app.post('/auth/login/mfa/totp',- LocalAuthMiddleware,RateLimitMiddleware(RateLimitConfigs.AUTH_LOGIN_MFA),Validator('json', MfaTotpRequest),+ MfaTicketAuthMiddleware,OpenAPI({operationId: 'login_with_totp',summary: 'Login with TOTP',@@ -210,12 +250,13 @@ export function AuthController(app: HonoApp) {security: ['botToken', 'bearerToken', 'sessionToken'],tags: ['Auth'],description:- 'Invalidate the current authentication token and end the session. The auth token in the Authorization header will no longer be valid. A bot token has no session to end, so the call answers 204 and the token stays valid.',+ 'Invalidate the current authentication token and end the session. The auth token in the Authorization header will no longer be valid. A bot token has no session to end, so the call answers 204 and the token stays valid. Ending the last session of an account that cannot sign in again, because it has no email, password or passkey, schedules that account for deletion after 24 hours.',}),async (ctx) => {const authToken = ctx.get('authToken');if (authToken) {await AuthSession.revokeToken(ctx.get('apiContext'), authToken);+ await scheduleAbandonedOnLastLogout(ctx.get('apiContext'), ctx.get('user'));}return ctx.body(null, 204);},@@ -446,6 +487,28 @@ export function AuthController(app: HonoApp) {return ctx.body(null, 204);},);+ app.post(+ '/auth/sign-in-link',+ RateLimitMiddleware(RateLimitConfigs.AUTH_AUTHORIZE_IP),+ Validator('json', SignInLinkRequest),+ OpenAPI({+ operationId: 'redeem_sign_in_link',+ summary: 'Redeem sign-in link',+ responseSchema: AuthTokenWithUserIdResponse,+ statusCode: 200,+ security: [],+ tags: ['Auth'],+ description:+ 'Sign in with the token from a one-time sign-in link that the instance operator created for an admin account. Authorizes the IP address of the request and returns an authentication token. The token works once and expires after 15 minutes.',+ }),+ async (ctx) => {+ const result = await redeemSignInLink(ctx.get('apiContext'), ctx.get('adminService').auditService, {+ token: ctx.req.valid('json').token,+ request: ctx.req.raw,+ });+ return ctx.json(await ctx.get('authRequestService').toAuthTokenResponse(result));+ },+ );app.post('/auth/ip-authorization/resend',LocalAuthMiddleware,@@ -536,9 +599,9 @@ export function AuthController(app: HonoApp) {);app.post('/auth/login/mfa/webauthn/authentication-options',- LocalAuthMiddleware,RateLimitMiddleware(RateLimitConfigs.AUTH_LOGIN_MFA),Validator('json', MfaTicketRequest),+ MfaTicketAuthMiddleware,OpenAPI({operationId: 'get_webauthn_mfa_options',summary: 'Get WebAuthn MFA options',@@ -561,9 +624,9 @@ export function AuthController(app: HonoApp) {);app.post('/auth/login/mfa/webauthn',- LocalAuthMiddleware,RateLimitMiddleware(RateLimitConfigs.AUTH_LOGIN_MFA),Validator('json', WebAuthnMfaRequest),+ MfaTicketAuthMiddleware,OpenAPI({operationId: 'login_with_webauthn_mfa',summary: 'Login with WebAuthn MFA',diff --git a/fluxer_api/src/api/auth/AuthRequestService.ts b/fluxer_api/src/api/auth/AuthRequestService.tsindex 39dec6f17..cbf661c2b 100644--- a/fluxer_api/src/api/auth/AuthRequestService.ts+++ b/fluxer_api/src/api/auth/AuthRequestService.ts@@ -3,6 +3,8 @@import type {ApiContext} from '@app/api/ApiContext';import * as AuthEmail from '@app/api/auth/AuthEmail';import * as AuthEmailRevert from '@app/api/auth/AuthEmailRevert';+import * as AuthIdentify from '@app/api/auth/AuthIdentify';+import * as AuthInstantAccounts from '@app/api/auth/AuthInstantAccounts';import * as AuthLogin from '@app/api/auth/AuthLogin';import * as AuthMfa from '@app/api/auth/AuthMfa';import * as AuthPassword from '@app/api/auth/AuthPassword';@@ -17,6 +19,7 @@ import {Logger} from '@app/api/Logger';import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';import type {User} from '@app/api/models/User';+import type {TierContext} from '@app/api/user/AccountTier';import {classifyWebPushOrigin,encodePushSessionIdHash,@@ -31,18 +34,25 @@ import {generateUsernameSuggestions} from '@app/api/utils/UsernameSuggestionUtilimport {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';import type {+ AccountHandoffRedeemRequest,+ AccountHandoffRequest,+ AccountHandoffResponse,AuthLoginResponse,AuthorizeIpRequest,AuthRegisterResponse,+ AuthRegisterSuccessResponse,AuthTokenWithUserIdResponse,+ EmailCodeSendResponse,+ EmailCodeVerifyRequest,+ EmailCodeVerifyResponse,EmailRevertRequest,HandoffCompleteRequest,HandoffCompleteResponse,HandoffInfoResponse,HandoffInitiateResponse,HandoffStatusResponse,+ IdentifyResponse,IpAuthorizationPollResponse,LoginRequest,LogoutAuthSessionsRequest,@@ -51,6 +61,7 @@ import type {RegisterRequest,ResetPasswordRequest,SsoCompleteRequest,+ SsoCompleteResponse,SsoStartRequest,UsernameAvailabilityResponse,UsernameSuggestionsResponse,@@ -64,6 +75,7 @@ interface AuthRegisterRequest {data: RegisterRequest;request: Request;requestCache: RequestCache;+ tierContext: TierContext;}interface AuthLoginRequest {@@ -160,22 +172,20 @@ export class AuthRequestService {});}- completeSso(data: SsoCompleteRequest, request: Request, requestCache: RequestCache) {+ completeSso(data: SsoCompleteRequest, request: Request, requestCache: RequestCache, clientIp: string) {return this.toSsoCompleteResponse(- this.ssoService.completeLogin({code: data.code, state: data.state, request, requestCache}),+ this.ssoService.completeLogin({code: data.code, state: data.state, request, requestCache, clientIp}),);}- async register({data, request, requestCache}: AuthRegisterRequest): Promise<AuthRegisterResponse> {+ async register({data, request, requestCache, tierContext}: AuthRegisterRequest): Promise<AuthRegisterResponse> {const result = await AuthRegistration.register(this.apiContext, this.registrationDependencies, {data,request,requestCache,+ tierContext,});- if ('registration_pending_approval' in result) {- return result;- }- return await this.toAuthTokenResponse(result);+ return toAuthRegisterResponse(result);}async login({data, request, captchaVerified}: AuthLoginRequest): Promise<AuthLoginResponse> {@@ -184,7 +194,7 @@ export class AuthRequestService {}async loginMfaTotp({code, ticket, request}: AuthLoginMfaRequest): Promise<AuthTokenWithUserIdResponse> {- const result = await AuthLogin.loginMfaTotp(this.apiContext, {code, ticket, request});+ const result = await AuthLogin.loginMfaTotp(this.apiContext, {code, ticket, request, ssoLinks: this.ssoService});return await this.toAuthTokenResponse(result);}@@ -273,6 +283,7 @@ export class AuthRequestService {challenge: data.challenge,ticket: data.ticket,request,+ ssoLinks: this.ssoService,});return await this.toAuthTokenResponse(result);}@@ -285,6 +296,104 @@ export class AuthRequestService {return {available: !(await isUsernameTaken(this.apiContext.services.users, username))};}+ identify(params: {+ identifier: string;+ deviceProof: string | undefined;+ registrationUrlCode: string | null | undefined;+ request: Request;+ clientIp: string;+ captcha: AuthIdentify.CaptchaGate;+ }): Promise<IdentifyResponse> {+ return AuthIdentify.identify(this.apiContext, params);+ }++ sendEmailCode(params: {+ ticket: string;+ registrationUrlCode: string | null | undefined;+ request: Request;+ clientIp: string;+ captcha: AuthIdentify.CaptchaGate;+ }): Promise<EmailCodeSendResponse> {+ return AuthIdentify.sendEmailCode(this.apiContext, params);+ }++ async verifyEmailCode(params: {+ data: EmailCodeVerifyRequest;+ request: Request;+ clientIp: string;+ requestCache: RequestCache;+ tierContext: TierContext;+ captcha: AuthIdentify.CaptchaGate;+ }): Promise<EmailCodeVerifyResponse> {+ const {data} = params;+ const result = await AuthIdentify.verifyEmailCode(this.apiContext, this.registrationDependencies, {+ ticket: data.ticket,+ code: data.code,+ consent: data.consent,+ registrationUrlCode: data.registration_url_code,+ inviteCode: data.invite_code,+ request: params.request,+ clientIp: params.clientIp,+ requestCache: params.requestCache,+ tierContext: params.tierContext,+ captcha: params.captcha,+ });+ if (result.kind === 'sign_up') return toAuthRegisterResponse(result.result);+ if (result.kind === 'mfa') return result.mfa;+ return {+ token: result.token,+ user_id: result.user.id.toString(),+ user: mapUserToPartialResponse(result.user),+ device_proof: result.deviceProof,+ };+ }++ instantAccountChallengeSteps(+ request: Request,+ clientIp: string,+ registrationUrlCode: string | null = null,+ ): Promise<number> {+ return AuthInstantAccounts.instantAccountChallengeSteps(this.apiContext, request, clientIp, registrationUrlCode);+ }++ createAccountHandoff(params: {data: AccountHandoffRequest; clientIp: string}): Promise<AccountHandoffResponse> {+ return AuthInstantAccounts.createAccountHandoff(this.apiContext, {+ globalName: params.data.global_name,+ nonceHash: params.data.nonce_hash,+ locale: params.data.locale,+ registrationUrlCode: params.data.registration_url_code,+ clientIp: params.clientIp,+ });+ }++ async redeemHandoff(params: {+ data: AccountHandoffRedeemRequest;+ request: Request;+ requestCache: RequestCache;+ tierContext: TierContext;+ }): Promise<AuthRegisterSuccessResponse> {+ const {user, token, deviceProof, entry} = await AuthInstantAccounts.redeemHandoff(+ this.apiContext,+ this.registrationDependencies,+ {+ handoffCode: params.data.handoff_code,+ nonce: params.data.nonce,+ consent: params.data.consent,+ globalName: params.data.global_name,+ request: params.request,+ requestCache: params.requestCache,+ tierContext: params.tierContext,+ },+ );+ return {+ token,+ user_id: user.id.toString(),+ user: mapUserToPartialResponse(user),+ device_proof: deviceProof,+ entry,+ };+ }+async initiateHandoff({request, returnUri}: AuthHandoffInitiateRequest): Promise<HandoffInitiateResponse> {const origin = AuthSession.resolveSessionOrigin(this.apiContext, request);const result = await this.desktopHandoffService.initiateHandoff({@@ -407,7 +516,7 @@ export class AuthRequestService {return mapUserToPartialResponse(user);}- private async toAuthTokenResponse(result: {user_id: string; token: string}): Promise<AuthTokenWithUserIdResponse> {+ async toAuthTokenResponse(result: {user_id: string; token: string}): Promise<AuthTokenWithUserIdResponse> {return {...result,user: await this.getUserPartial(result.user_id),@@ -415,14 +524,10 @@ export class AuthRequestService {}private async toSsoCompleteResponse(- resultPromise: Promise<{user_id: string; token: string; redirect_to: string}>,- ): Promise<AuthTokenWithUserIdResponse & {redirect_to: string}> {- const result = await resultPromise;- const tokenResponse = await this.toAuthTokenResponse(result);- return {- ...tokenResponse,- redirect_to: result.redirect_to,- };+ resultPromise: ReturnType<SsoService['completeLogin']>,+ ): Promise<SsoCompleteResponse> {+ const {redirect_to, ...result} = await resultPromise;+ return {...(await this.toAuthLoginResponse(result)), redirect_to};}private async toAuthLoginResponse(@@ -449,3 +554,16 @@ export class AuthRequestService {};}}++function toAuthRegisterResponse(result: AuthRegistration.AccountCreationResult): AuthRegisterResponse {+ if (result.pendingApproval) {+ return {registration_pending_approval: true, user_id: result.user.id.toString()};+ }+ return {+ token: result.token,+ user_id: result.user.id.toString(),+ user: mapUserToPartialResponse(result.user),+ device_proof: result.deviceProof,+ entry: result.entry,+ };+}