Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(api/auth): sign-in SSO link MFA, underage block, IP limit

Hampus2e69a80c2ad1
diff --git a/fluxer_api/src/api/auth/AuthLogin.ts b/fluxer_api/src/api/auth/AuthLogin.ts
index 07f6f2fef..bd1d3943b 100644
--- a/fluxer_api/src/api/auth/AuthLogin.ts
+++ b/fluxer_api/src/api/auth/AuthLogin.ts
@@ -6,6 +6,7 @@ import {applyPendingRecovery} from '@app/api/auth/AuthRecoveryKit';
import * as AuthSession from '@app/api/auth/AuthSession';
import * as AuthUtility from '@app/api/auth/AuthUtility';
import {getLocalPartAtInstance, usernameFromInstanceLocalPart} from '@app/api/auth/InstanceAddress';
+import type {SsoService} from '@app/api/auth/services/SsoService';
import {resolveWebAuthnSecondFactor} from '@app/api/auth/services/WebAuthnSecondFactor';
import {
createInviteCode,
@@ -16,6 +17,7 @@ import {
} from '@app/api/BrandedTypes';
import {getContentMessage} from '@app/api/content_i18n/ContentI18n';
import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';
+import type {LoginMethod} from '@app/api/infrastructure/activity/Contract.generated';
import {
REGISTRATION_PENDING_APPROVAL_TRAIT,
REGISTRATION_REJECTED_TRAIT,
@@ -26,7 +28,9 @@ import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {AuthSession as AuthSessionModel} from '@app/api/models/AuthSession';
import type {User} from '@app/api/models/User';
+import {tierContextFromRequest} from '@app/api/user/AccountTier';
import {findPersonByLoginHandle, type ParsedLoginHandle, parseLoginHandle} from '@app/api/user/UniqueUsernames';
+import {BELOW_MINIMUM_AGE_TRAIT} from '@app/api/user/UserTraits';
import {lookupGeoip} from '@app/api/utils/IpUtils';
import {verifyPassword} from '@app/api/utils/PasswordUtils';
import * as RandomUtils from '@app/api/utils/RandomUtils';
@@ -35,6 +39,7 @@ import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';
import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
import {UserAuthenticatorTypes, UserFlags} from '@fluxer/constants/src/UserConstants';
import {type ValidationErrorCode, ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {AccountBelowMinimumAgeError} from '@fluxer/errors/src/domains/auth/AccountBelowMinimumAgeError';
import {IpAuthorizationRequiredError} from '@fluxer/errors/src/domains/auth/IpAuthorizationRequiredError';
import {IpAuthorizationResendCooldownError} from '@fluxer/errors/src/domains/auth/IpAuthorizationResendCooldownError';
import {IpAuthorizationResendLimitExceededError} from '@fluxer/errors/src/domains/auth/IpAuthorizationResendLimitExceededError';
@@ -42,7 +47,6 @@ import {MfaNotEnabledError} from '@fluxer/errors/src/domains/auth/MfaNotEnabledE
import {RegistrationPendingApprovalError} from '@fluxer/errors/src/domains/auth/RegistrationPendingApprovalError';
import {RegistrationRejectedError} from '@fluxer/errors/src/domains/auth/RegistrationRejectedError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';
import type {LoginRequest} from '@fluxer/schema/src/domains/auth/AuthSchemas';
import {EmailType} from '@fluxer/schema/src/primitives/UserValidators';
@@ -59,10 +63,13 @@ interface LoginParams {
captchaVerified?: boolean;
}
+export type SsoPendingLinks = Pick<SsoService, 'completePendingLink'>;
+
interface LoginMfaTotpParams {
code: string;
ticket: string;
request: Request;
+ ssoLinks: SsoPendingLinks;
}
interface LoginMfaWebAuthnParams {
@@ -70,6 +77,7 @@ interface LoginMfaWebAuthnParams {
challenge: string;
ticket: string;
request: Request;
+ ssoLinks: SsoPendingLinks;
}
export interface LoginDependencies {
@@ -110,7 +118,6 @@ interface LoginIdentifier {
export interface IpAuthorizationTicketCache {
userId: string;
email: string;
- username: string;
origin: AuthSession.SessionOrigin;
authToken: string;
clientLocation: string;
@@ -128,10 +135,15 @@ function getTokenCacheKey(token: string): string {
return `ip-auth-token:${token}`;
}
-function emitLogin(user: User, ok: boolean, details: {failure?: string; mfa?: boolean; newIp?: boolean} = {}): void {
+export function emitLogin(
+ user: User,
+ ok: boolean,
+ details: {failure?: string; mfa?: boolean; newIp?: boolean; method?: LoginMethod} = {},
+): void {
void emitActivity('login', user.id.toString(), {
user_id: user.id.toString(),
ok,
+ method: details.method ?? 'password',
failure: details.failure ?? null,
mfa: details.mfa ?? false,
new_ip: details.newIp ?? false,
@@ -159,12 +171,10 @@ export async function resendIpAuthorization(
if (secondsSinceCreation < minDelay) {
throw new IpAuthorizationResendCooldownError(minDelay - secondsSinceCreation);
}
- await email.sendIpAuthorizationEmail(
+ await email.send(
+ 'ip_authorization',
payload.email,
- payload.username,
- payload.authToken,
- payload.origin.ip,
- payload.clientLocation,
+ {authorizationToken: payload.authToken, ipAddress: payload.origin.ip, location: payload.clientLocation},
payload.locale ?? null,
);
const ttl = await cache.ttl(cacheKey);
@@ -199,14 +209,19 @@ export async function completeIpAuthorization(
if (!payload) {
throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN);
}
- const repoResult = await ctx.services.users.authorizeIpByToken(token);
- if (!repoResult || repoResult.userId.toString() !== payload.userId) {
- throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN);
- }
const user = await users.findUnique(createUserID(BigInt(payload.userId)));
if (!user) {
throw new UnknownUserError();
}
+ if (user.passwordLastChangedAt !== null && payload.createdAt < user.passwordLastChangedAt.getTime()) {
+ await cache.delete(cacheKey);
+ await cache.delete(getTokenCacheKey(token));
+ throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN);
+ }
+ const repoResult = await ctx.services.users.authorizeIpByToken(token);
+ if (!repoResult || repoResult.userId.toString() !== payload.userId) {
+ throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN);
+ }
AuthUtility.assertNonBotUser(ctx, user);
await users.createAuthorizedIp(user.id, payload.origin.ip);
const [sessionToken] = await AuthSession.createAuthSession(ctx, {user, origin: payload.origin});
@@ -241,10 +256,12 @@ export async function login(
await enforceRateLimits(identifier.rateLimits);
const clientIp = requireConfiguredClientIp(request, config.proxy);
const sourceKey = getSameIpDecisionKey(clientIp) ?? clientIp;
- await enforceRateLimits([
- ...identifier.sourceRateLimits(sourceKey),
- {identifier: `login:ip:${sourceKey}`, maxAttempts: 10, windowMs: ms('30 minutes')},
- ]);
+ await enforceRateLimits(identifier.sourceRateLimits(sourceKey));
+ const ipFailureLimit = {identifier: `login:ip:${sourceKey}`, maxAttempts: 10, windowMs: ms('30 minutes')};
+ const ipFailureState = await rateLimit.peekLimit(ipFailureLimit);
+ if (!ipFailureState.allowed && !skipRateLimits) {
+ throw createRateLimitError(ipFailureState);
+ }
const failureLimit = identifier.failureRateLimit;
const failureState = failureLimit ? await rateLimit.peekLimit(failureLimit) : null;
const failureLockout =
@@ -259,6 +276,7 @@ export async function login(
throw createRateLimitError(failureLockout);
}
const rejectCredentials = async (): Promise<never> => {
+ await rateLimit.checkLimit(ipFailureLimit);
if (failureLimit) {
await rateLimit.checkLimit(failureLimit);
}
@@ -305,6 +323,9 @@ export async function login(
if (currentUser.traits.has(REGISTRATION_REJECTED_TRAIT)) {
throw new RegistrationRejectedError();
}
+ if (currentUser.traits.has(BELOW_MINIMUM_AGE_TRAIT)) {
+ throw new AccountBelowMinimumAgeError();
+ }
const isAppStoreReviewer = (currentUser.flags & UserFlags.APP_STORE_REVIEWER) !== 0n;
let newIp = false;
if (!hasMfa && !isAppStoreReviewer) {
@@ -328,7 +349,6 @@ export async function login(
const cachePayload: IpAuthorizationTicketCache = {
userId: currentUser.id.toString(),
email: currentUser.email!,
- username: currentUser.username,
origin: AuthSession.resolveSessionOrigin(ctx, request),
authToken,
clientLocation,
@@ -343,12 +363,10 @@ export async function login(
ticket: string;
}>(`ip-auth-token:${authToken}`, {ticket}, ttlSeconds);
await users.createIpAuthorizationToken(currentUser.id, authToken, currentUser.email!);
- await email.sendIpAuthorizationEmail(
+ await email.send(
+ 'ip_authorization',
currentUser.email!,
- currentUser.username,
- authToken,
- clientIp,
- clientLocation,
+ {authorizationToken: authToken, ipAddress: clientIp, location: clientLocation},
currentUser.locale,
);
emitLogin(currentUser, false, {failure: 'ip_authorization_required', newIp: true});
@@ -370,6 +388,7 @@ export async function login(
userId: currentUser.id,
inviteCode: createInviteCode(data.invite_code),
requestCache: createRequestCache(),
+ tierContext: tierContextFromRequest(request),
});
} catch (error) {
Logger.warn({inviteCode: data.invite_code, error}, 'Failed to auto-join invite on login');
@@ -476,7 +495,7 @@ export async function consumeMfaAttempt(
export async function loginMfaTotp(
ctx: ApiContext,
- {code, ticket, request}: LoginMfaTotpParams,
+ {code, ticket, request, ssoLinks}: LoginMfaTotpParams,
): Promise<LoginTokenResult> {
const user = await requireMfaTicketUser(ctx, ticket);
const hasTotp = Boolean(user.totpSecret) && user.authenticatorTypes.has(UserAuthenticatorTypes.TOTP);
@@ -493,7 +512,7 @@ export async function loginMfaTotp(
if (!isValid) {
throw InputValidationError.fromCode('code', ValidationErrorCodes.INVALID_CODE);
}
- const [token] = await completeMfaLogin(ctx, user, ticket, request);
+ const [token] = await completeMfaLogin(ctx, user, ticket, request, ssoLinks);
return {user_id: user.id.toString(), token};
}
@@ -510,9 +529,17 @@ export async function completeMfaLogin(
user: User,
ticket: string,
request: Request,
+ ssoLinks: SsoPendingLinks,
): Promise<[token: string, AuthSessionModel]> {
const {cache, rateLimit} = ctx.services;
- const sessionUser = await applyPendingRecovery(ctx, user, ticket);
+ const sessionUser = await ssoLinks.completePendingLink(await applyPendingRecovery(ctx, user, ticket), ticket);
+ if (await cache.get<boolean>(mfaTicketNetworkKey(ticket))) {
+ await cache.delete(mfaTicketNetworkKey(ticket));
+ await ctx.services.users.createAuthorizedIp(
+ sessionUser.id,
+ requireConfiguredClientIp(request, ctx.services.config.proxy),
+ );
+ }
await cache.delete(`mfa-ticket:${ticket}`);
await rateLimit.resetLimit(`mfa:ticket:${ticket}`);
await rateLimit.resetLimit(`mfa:user:${user.id}`);
@@ -523,7 +550,7 @@ export async function completeMfaLogin(
export async function loginMfaWebAuthn(
ctx: ApiContext,
- {response, challenge, ticket, request}: LoginMfaWebAuthnParams,
+ {response, challenge, ticket, request, ssoLinks}: LoginMfaWebAuthnParams,
): Promise<LoginTokenResult> {
const user = await requireMfaTicketUser(ctx, ticket);
if (!(await resolveWebAuthnSecondFactor(ctx, user))) {
@@ -531,18 +558,26 @@ export async function loginMfaWebAuthn(
}
await consumeMfaAttempt(ctx, {userId: user.id.toString(), ticket, field: 'ticket'});
await AuthMfa.verifyWebAuthnAuthentication(ctx, user.id, response, challenge, 'mfa', ticket);
- const [token] = await completeMfaLogin(ctx, user, ticket, request);
+ const [token] = await completeMfaLogin(ctx, user, ticket, request, ssoLinks);
return {user_id: user.id.toString(), token};
}
+function mfaTicketNetworkKey(ticket: string): string {
+ return `mfa-ticket-network:${ticket}`;
+}
+
export async function createMfaTicketResponse(
ctx: ApiContext,
user: User,
webauthnIsSecondFactor: boolean,
+ options: {authorizeNetwork?: boolean} = {},
): Promise<LoginMfaResult> {
const {cache} = ctx.services;
const ticket = createMfaTicket(await RandomUtils.randomString(64));
await cache.set(`mfa-ticket:${ticket}`, user.id.toString(), seconds('5 minutes'));
+ if (options.authorizeNetwork) {
+ await cache.set(mfaTicketNetworkKey(ticket), true, seconds('5 minutes'));
+ }
const hasTotp = user.authenticatorTypes.has(UserAuthenticatorTypes.TOTP);
const hasBackupCodes = await AuthMfa.hasUnconsumedBackupCodes(ctx, user.id);
const allowedMethods: Array<string> = [];
diff --git a/fluxer_api/src/api/auth/PasskeyBridgeController.ts b/fluxer_api/src/api/auth/PasskeyBridgeController.ts
index e6ecbb895..94519596c 100644
--- a/fluxer_api/src/api/auth/PasskeyBridgeController.ts
+++ b/fluxer_api/src/api/auth/PasskeyBridgeController.ts
@@ -167,6 +167,7 @@ export function PasskeyBridgeController(app: HonoApp) {
ctx.req.header('origin'),
ctx.req.valid('json'),
ctx.req.raw,
+ ctx.get('ssoService'),
),
);
},
diff --git a/fluxer_api/src/api/auth/services/PasskeyBridgeService.ts b/fluxer_api/src/api/auth/services/PasskeyBridgeService.ts
index 238ba2ec3..cb351b8db 100644
--- a/fluxer_api/src/api/auth/services/PasskeyBridgeService.ts
+++ b/fluxer_api/src/api/auth/services/PasskeyBridgeService.ts
@@ -374,6 +374,7 @@ export async function redeemPasskeyBridgeLogin(
origin: string | undefined,
data: PasskeyBridgeRedeemRequest,
request: Request,
+ ssoLinks: AuthLogin.SsoPendingLinks,
): Promise<PasskeyBridgeLoginRedeemResponse> {
const completed = await redeemPasskeyBridge(ctx, ceremonyId, origin, data, ['login', 'login_mfa'], null);
if (!completed) {
@@ -387,7 +388,7 @@ export async function redeemPasskeyBridgeLogin(
if (!(await resolveWebAuthnSecondFactor(ctx, user))) {
throw new MfaNotEnabledError();
}
- [token, authSession] = await AuthLogin.completeMfaLogin(ctx, user, completed.record.ticket!, request);
+ [token, authSession] = await AuthLogin.completeMfaLogin(ctx, user, completed.record.ticket!, request, ssoLinks);
} else {
user = await ctx.services.users.findUniqueAssert(completed.userId);
[token, authSession] = await AuthLogin.createLoginSession(ctx, user, request);
diff --git a/fluxer_api/src/api/auth/tests/SsoFlow.test.ts b/fluxer_api/src/api/auth/tests/SsoFlow.test.ts
index bb73722c6..b0efeebd3 100644
--- a/fluxer_api/src/api/auth/tests/SsoFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/SsoFlow.test.ts
@@ -3,11 +3,13 @@
import {
createAuthHarness,
createTestAccount,
+ createTotpSecret,
createUniqueEmail,
disableSso,
enableSso,
setUserACLs,
type TestAccount,
+ totpCodeNow,
} from '@app/api/auth/tests/AuthTestUtils';
import {Config} from '@app/api/Config';
import {createChannelInvite, setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
@@ -30,10 +32,18 @@ interface SsoCompleteResponse {
redirect_to: string;
}
+interface SsoMfaChallengeResponse {
+ mfa: true;
+ ticket: string;
+ backup_codes: boolean;
+ redirect_to: string;
+}
+
interface SsoStatusResponse {
enabled: boolean;
enforced: boolean;
display_name?: string;
+ button_label: string | null;
redirect_uri: string;
}
@@ -703,6 +713,85 @@ describe('Auth SSO flow', () => {
.execute();
expect(secondLogin.user_id).not.toBe(firstLogin.user_id);
});
+ async function signInWithSso(code: string): Promise<SsoCompleteResponse> {
+ const startData = await createBuilderWithoutAuth<SsoStartResponse>(harness)
+ .post('/auth/sso/start')
+ .body({})
+ .execute();
+ return createBuilderWithoutAuth<SsoCompleteResponse>(harness)
+ .post('/auth/sso/complete')
+ .body({code, state: startData.state})
+ .execute();
+ }
+ it('joins an existing account to the single community when it signs in', async () => {
+ await enableSso(harness, admin.token, {enforced: false});
+ const email = createUniqueEmail('sso-existing-single');
+ const first = await signInWithSso(email);
+ const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
+ await getInstanceConfigRepository().setInstancePolicyConfig({
+ single_community_enabled: true,
+ single_community_guild_id: guild.id,
+ });
+ await createBuilder(harness, owner.token)
+ .get(`/guilds/${guild.id}/members/${first.user_id}`)
+ .expect(404)
+ .execute();
+ const second = await signInWithSso(email);
+ expect(second.user_id).toBe(first.user_id);
+ await createBuilder(harness, owner.token)
+ .get(`/guilds/${guild.id}/members/${first.user_id}`)
+ .expect(200)
+ .execute();
+ });
+ it('keeps a banned account out of the single community when it signs in', async () => {
+ await enableSso(harness, admin.token, {enforced: false});
+ const email = createUniqueEmail('sso-existing-banned');
+ const first = await signInWithSso(email);
+ const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
+ await createBuilder(harness, owner.token)
+ .put(`/guilds/${guild.id}/bans/${first.user_id}`)
+ .body({})
+ .expect(204)
+ .execute();
+ await getInstanceConfigRepository().setInstancePolicyConfig({
+ single_community_enabled: true,
+ single_community_guild_id: guild.id,
+ });
+ const second = await signInWithSso(email);
+ expect(second.token).toBeTruthy();
+ await createBuilder(harness, owner.token)
+ .get(`/guilds/${guild.id}/members/${first.user_id}`)
+ .expect(404)
+ .execute();
+ });
+ it('asks for the second factor before linking an account that has one', async () => {
+ await disableSso(harness, admin.token);
+ const account = await createTestAccount(harness);
+ const secret = createTotpSecret();
+ const enabled = await createBuilder<{backup_codes: Array<{code: string}>}>(harness, account.token)
+ .post('/users/@me/mfa/totp/enable')
+ .body({secret, code: totpCodeNow(secret), password: account.password})
+ .execute();
+ await enableSso(harness, admin.token);
+ const startData = await createBuilderWithoutAuth<SsoStartResponse>(harness)
+ .post('/auth/sso/start')
+ .body({redirect_to: '/channels/@me'})
+ .execute();
+ const challenge = await createBuilderWithoutAuth<SsoMfaChallengeResponse>(harness)
+ .post('/auth/sso/complete')
+ .body({code: account.email, state: startData.state})
+ .execute();
+ expect(challenge).toMatchObject({mfa: true, backup_codes: true, redirect_to: '/channels/@me'});
+ expect(challenge).not.toHaveProperty('token');
+ const linked = await createBuilderWithoutAuth<SsoCompleteResponse>(harness)
+ .post('/auth/login/mfa/totp')
+ .body({ticket: challenge.ticket, code: enabled.backup_codes[0]!.code})
+ .execute();
+ expect(linked.user_id).toBe(account.userId);
+ const again = await signInWithSso(account.email);
+ expect(again.user_id).toBe(account.userId);
+ expect(again.token).toBeTruthy();
+ });
it('rejects unverified provider email claims', async () => {
const email = createUniqueEmail('sso-unverified');
const startData = await createBuilderWithoutAuth<SsoStartResponse>(harness)
@@ -776,5 +865,50 @@ describe('Auth SSO flow', () => {
expect(status.enforced).toBe(false);
await disableSso(harness, admin.token);
});
+ it('reports the configured button text in the status and discovery documents', async () => {
+ await enableSso(harness, admin.token, {enforced: false, button_label: ' Sign in with Acme ID '});
+ const status = await createBuilderWithoutAuth<SsoStatusResponse>(harness).get('/auth/sso/status').execute();
+ expect(status.button_label).toBe('Sign in with Acme ID');
+ const discovery = await createBuilderWithoutAuth<{sso: SsoStatusResponse}>(harness)
+ .get('/.well-known/fluxer')
+ .execute();
+ expect(discovery.sso.button_label).toBe('Sign in with Acme ID');
+ const adminConfig = await createBuilder<{sso: {button_label: string | null}}>(harness, admin.token)
+ .get('/admin/instance/config')
+ .execute();
+ expect(adminConfig.sso.button_label).toBe('Sign in with Acme ID');
+ await createBuilder(harness, admin.token)
+ .patch('/admin/instance/config')
+ .body({sso: {button_label: ' '}})
+ .execute();
+ const cleared = await createBuilderWithoutAuth<SsoStatusResponse>(harness).get('/auth/sso/status').execute();
+ expect(cleared.button_label).toBeNull();
+ await disableSso(harness, admin.token);
+ });
+ it('keeps the button text when another SSO field changes', async () => {
+ await enableSso(harness, admin.token, {enforced: false, button_label: 'Use Acme ID'});
+ await createBuilder(harness, admin.token)
+ .patch('/admin/instance/config')
+ .body({sso: {display_name: 'Acme'}})
+ .execute();
+ const status = await createBuilderWithoutAuth<SsoStatusResponse>(harness).get('/auth/sso/status').execute();
+ expect(status.button_label).toBe('Use Acme ID');
+ await disableSso(harness, admin.token);
+ });
+ for (const [name, label] of [
+ ['too long', 'a'.repeat(65)],
+ ['with a line break', 'Sign in\nwith Acme'],
+ ['with a bidirectional override', 'Sign in \u202Ewith Acme'],
+ ] as const) {
+ it(`rejects button text ${name}`, async () => {
+ await createBuilder(harness, admin.token)
+ .patch('/admin/instance/config')
+ .body({sso: {button_label: label}})
+ .expect(400)
+ .execute();
+ const status = await createBuilderWithoutAuth<SsoStatusResponse>(harness).get('/auth/sso/status').execute();
+ expect(status.button_label).toBeNull();
+ });
+ }
});
});
diff --git a/fluxer_api/src/api/middleware/LocalAuthMiddleware.ts b/fluxer_api/src/api/middleware/LocalAuthMiddleware.ts
index 3720f20ca..f6a6ae3eb 100644
--- a/fluxer_api/src/api/middleware/LocalAuthMiddleware.ts
+++ b/fluxer_api/src/api/middleware/LocalAuthMiddleware.ts
@@ -1,13 +1,25 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {HonoEnv} from '@app/api/types/HonoEnv';
-import {SsoRequiredError} from '@fluxer/errors/src/domains/auth/SsoRequiredError';
+import {SsoRequiredError, SsoRequiredReasons} from '@fluxer/errors/src/domains/auth/SsoRequiredError';
import {createMiddleware} from 'hono/factory';
export const LocalAuthMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
const ssoService = ctx.get('ssoService');
if (await ssoService.isEnforced()) {
- throw new SsoRequiredError();
+ throw new SsoRequiredError(SsoRequiredReasons.SIGN_IN);
+ }
+ await next();
+});
+
+export const MfaTicketAuthMiddleware = createMiddleware<
+ HonoEnv,
+ string,
+ {in: {json: {ticket: string}}; out: {json: {ticket: string}}}
+>(async (ctx, next) => {
+ const ssoService = ctx.get('ssoService');
+ if ((await ssoService.isEnforced()) && !(await ssoService.isPendingLinkTicket(ctx.req.valid('json').ticket))) {
+ throw new SsoRequiredError(SsoRequiredReasons.SIGN_IN);
}
await next();
});
diff --git a/fluxer_api/src/api/middleware/SsoManagedCredentialsMiddleware.ts b/fluxer_api/src/api/middleware/SsoManagedCredentialsMiddleware.ts
new file mode 100644
index 000000000..5fc0811cb
--- /dev/null
+++ b/fluxer_api/src/api/middleware/SsoManagedCredentialsMiddleware.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {SsoService} from '@app/api/auth/services/SsoService';
+import type {User} from '@app/api/models/User';
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {isSsoLinkedUser} from '@app/api/user/UserHelpers';
+import {SsoRequiredError, SsoRequiredReasons} from '@fluxer/errors/src/domains/auth/SsoRequiredError';
+import {createMiddleware} from 'hono/factory';
+
+export async function assertCredentialsNotSsoManaged(ssoService: SsoService, user: User): Promise<void> {
+ if (isSsoLinkedUser(user) && (await ssoService.isEnforced())) {
+ throw new SsoRequiredError(SsoRequiredReasons.MANAGED_CREDENTIALS);
+ }
+}
+
+export const SsoManagedCredentialsMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
+ await assertCredentialsNotSsoManaged(ctx.get('ssoService'), ctx.get('user'));
+ await next();
+});