Skip to content

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

TypeScript fluxerfluxerapp

feat(api/admin): create users and admin-only sign-in links

Hampusff44a31ca9fe
diff --git a/fluxer_api/src/api/admin/controllers/UserAdminController.ts b/fluxer_api/src/api/admin/controllers/UserAdminController.ts
index 651ecb0b9..c646bf5ed 100644
--- a/fluxer_api/src/api/admin/controllers/UserAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/UserAdminController.ts
@@ -3,6 +3,7 @@
import {AdminAuditReadActions} from '@app/api/admin/AdminAuditActions';
import {recordAdminRead} from '@app/api/admin/AdminAuditRecorder';
import {mapUserToAdminResponse} from '@app/api/admin/models/UserTypes';
+import {createSignInLink} from '@app/api/auth/SignInLinks';
import {createUserID} from '@app/api/BrandedTypes';
import {enforcementActor} from '@app/api/enforcement/EnforcementActor';
import {
@@ -14,18 +15,26 @@ import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
-import type {HonoApp} from '@app/api/types/HonoEnv';
+import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
import {inputValidationErrorFromZodIssues, Validator} from '@app/api/Validator';
+import {EmailDeliveryStates} from '@fluxer/constants/src/AccountConfigConstants';
+import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {EmailDeliveryOffError} from '@fluxer/errors/src/domains/auth/EmailDeliveryOffError';
+import {UsernameSignInOnlyError} from '@fluxer/errors/src/domains/auth/UsernameSignInOnlyError';
+import {AccessDeniedError} from '@fluxer/errors/src/domains/core/AccessDeniedError';
import {ListUserGuildsResponse} from '@fluxer/schema/src/domains/admin/AdminGuildSchemas';
import {SearchUsersResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import {
AdminAclListResponse,
AdminPasswordResetLinkResponse,
+ AdminSignInLinkResponse,
AdminUserAclsRequest,
AdminUserBotStatusRequest,
AdminUserChangeLogQuery,
AdminUserClearFieldsRequest,
+ AdminUserCreateRequest,
+ AdminUserCreateResponse,
AdminUserDeletionCancelRequest,
AdminUserDeletionScheduleRequest,
AdminUserDmChannelListQuery,
@@ -61,6 +70,25 @@ import {
} from '@fluxer/schema/src/domains/admin/EnforcementSchemas';
import {WebAuthnCredentialListResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';
import {UserIdParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';
+import {createMiddleware} from 'hono/factory';
+
+const RequireUsernameIdentityOrNoEmailDelivery = createMiddleware<HonoEnv>(async (ctx, next) => {
+ const repository = ctx.get('instanceConfigRepository');
+ if (
+ (await repository.getAccountIdentityMode()) !== AccountIdentityModes.USERNAME &&
+ (await repository.getEmailDeliveryState()) === EmailDeliveryStates.ON
+ ) {
+ throw new UsernameSignInOnlyError();
+ }
+ await next();
+});
+
+const RequireEmailDeliveryOn = createMiddleware<HonoEnv>(async (ctx, next) => {
+ if ((await ctx.get('instanceConfigRepository').getEmailDeliveryState()) !== EmailDeliveryStates.ON) {
+ throw new EmailDeliveryOffError();
+ }
+ await next();
+});
export function UserAdminController(app: HonoApp) {
app.get(
@@ -105,7 +133,7 @@ export function UserAdminController(app: HonoApp) {
async (ctx) => {
const canReviewRegistrations = hasAdminACL(ctx.get('adminUserAcls'), AdminACLs.REGISTRATION_REVIEW);
const [user, pendingRegistrations] = await Promise.all([
- mapUserToAdminResponse(ctx.get('user'), ctx.get('cacheService')),
+ mapUserToAdminResponse(ctx.get('user'), ctx.get('cacheService'), undefined, ctx.get('requestLocale')),
canReviewRegistrations ? getInstanceConfigRepository().getPendingRegistrations() : null,
]);
return ctx.json({user, pending_registration_count: pendingRegistrations?.length ?? null});
@@ -124,14 +152,16 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Lists and searches users. Exactly one selector is honoured, in this precedence order: user_id, resolve, email, last_active_ip, then the indexed q search. The resolve selector takes one exact identifier, which may be a username#discriminator tag, a user ID, an email address, or a Stripe subscription ID. The email and user_id selectors ignore limit and offset. Requires USER_LOOKUP permission.',
+ 'Lists and searches users. Exactly one selector is honoured, in this precedence order: user_id, resolve, email, last_active_ip, acl, then the indexed q search. The acl selector lists the users granted one admin permission, ordered by user ID. The resolve selector takes one exact identifier, which may be a username#discriminator tag, a user ID, an email address, or a Stripe subscription ID. The email and user_id selectors ignore limit and offset. Requires USER_LOOKUP permission.',
}),
async (ctx) => {
const adminService = ctx.get('adminService');
const adminUserAcls = ctx.get('adminUserAcls');
const query = ctx.req.valid('query');
- const userIds =
- query.user_id === undefined ? undefined : Array.isArray(query.user_id) ? query.user_id : [query.user_id];
+ let userIds: Array<string> | undefined;
+ if (query.user_id !== undefined) {
+ userIds = Array.isArray(query.user_id) ? query.user_id : [query.user_id];
+ }
if (userIds || query.resolve !== undefined) {
if (!userIds && query.resolve?.includes('@')) {
requireGrantedAdminACLs(adminUserAcls, [AdminACLs.USER_VIEW_EMAIL]);
@@ -140,7 +170,11 @@ export function UserAdminController(app: HonoApp) {
if (!parsed.success) {
throw inputValidationErrorFromZodIssues(parsed.error.issues);
}
- const {users} = await adminService.userService.lookupService.lookupUser(parsed.data, adminUserAcls);
+ const {users} = await adminService.userService.lookupService.lookupUser(
+ parsed.data,
+ adminUserAcls,
+ ctx.get('requestLocale'),
+ );
await recordAdminRead(ctx, {
targetType: 'user',
targetId: 0n,
@@ -155,7 +189,14 @@ export function UserAdminController(app: HonoApp) {
});
return ctx.json({users, total: users.length});
}
- const selector = query.email?.trim() ? 'email' : query.last_active_ip?.trim() ? 'last_active_ip' : 'search';
+ let selector: 'email' | 'last_active_ip' | 'acl' | 'search' = 'search';
+ if (query.email?.trim()) {
+ selector = 'email';
+ } else if (query.last_active_ip?.trim()) {
+ selector = 'last_active_ip';
+ } else if (query.acl !== undefined) {
+ selector = 'acl';
+ }
if (selector === 'email') {
requireGrantedAdminACLs(adminUserAcls, [AdminACLs.USER_VIEW_EMAIL]);
} else if (selector === 'last_active_ip') {
@@ -166,10 +207,12 @@ export function UserAdminController(app: HonoApp) {
query: query.q,
email: query.email,
last_active_ip: query.last_active_ip,
+ acl: selector === 'acl' ? query.acl : undefined,
limit: query.limit,
offset: query.offset,
},
adminUserAcls,
+ ctx.get('requestLocale'),
);
await recordAdminRead(ctx, {
targetType: 'user',
@@ -178,6 +221,7 @@ export function UserAdminController(app: HonoApp) {
metadata: {
selector,
has_query: selector === 'search' && query.q?.trim() ? true : undefined,
+ acl: selector === 'acl' ? query.acl : undefined,
limit: selector === 'email' ? undefined : query.limit,
offset: selector === 'email' ? undefined : query.offset,
result_count: response.users.length,
@@ -187,6 +231,33 @@ export function UserAdminController(app: HonoApp) {
return ctx.json(response);
},
);
+ app.post(
+ '/admin/users',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.WILDCARD),
+ Validator('json', AdminUserCreateRequest),
+ OpenAPI({
+ operationId: 'create_admin_user',
+ summary: 'Create user',
+ responseSchema: AdminUserCreateResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'Create an account with no password and return a one-time password reset link for it. Hand the link to the new user, who opens it to choose a password. It works once and expires after an hour. On an instance where people sign in with email, an email address is required, and it is verified like a new registration when the instance sends email. Set admin to give the account full admin access. Creates audit log entries. Requires the * permission.',
+ }),
+ async (ctx) => {
+ const adminService = ctx.get('adminService');
+ return ctx.json(
+ await adminService.userService.creationService.createUser(
+ ctx.req.valid('json'),
+ ctx.get('adminUserId'),
+ ctx.get('auditLogReason'),
+ ctx.get('adminUserAcls'),
+ ),
+ );
+ },
+ );
app.get(
'/admin/users/:user_id',
RateLimitMiddleware(RateLimitConfigs.ADMIN_LOOKUP),
@@ -206,7 +277,11 @@ export function UserAdminController(app: HonoApp) {
const adminService = ctx.get('adminService');
const adminUserAcls = ctx.get('adminUserAcls');
const {user_id: userId} = ctx.req.valid('param');
- const response = await adminService.userService.lookupService.lookupUser({user_ids: [userId]}, adminUserAcls);
+ const response = await adminService.userService.lookupService.lookupUser(
+ {user_ids: [userId]},
+ adminUserAcls,
+ ctx.get('requestLocale'),
+ );
await recordAdminRead(ctx, {
targetType: 'user',
targetId: userId,
@@ -585,7 +660,7 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Clears profile fields such as the bio, avatar or display name. An enforcement basis saves the old values as evidence, records a profile reset decision and sends its notice by system DM and email. Creates audit log entry. Requires USER_UPDATE_PROFILE permission.',
+ 'Clears profile fields such as the bio, avatar or display name. An enforcement basis saves the old values as evidence, records a profile reset decision and sends its notice by system DM and email, leaving out the system DM when the instance has direct messages turned off. Creates audit log entry. Requires USER_UPDATE_PROFILE permission.',
}),
async (ctx) => {
const {user_id: userId} = ctx.req.valid('param');
@@ -795,6 +870,7 @@ export function UserAdminController(app: HonoApp) {
RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
requireAdminACL(AdminACLs.USER_UPDATE_EMAIL),
RequireEmailAccountIdentity,
+ RequireEmailDeliveryOn,
Validator('param', UserIdParam),
OpenAPI({
operationId: 'send_admin_user_password_reset',
@@ -804,7 +880,7 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Send password reset email to user with reset link. User must use link within expiry window. Creates audit log entry. Requires USER_UPDATE_EMAIL permission.',
+ 'Send password reset email to user with reset link. User must use link within expiry window. Creates audit log entry. Requires USER_UPDATE_EMAIL permission. Fails with EMAIL_DELIVERY_OFF while the instance does not send email.',
}),
async (ctx) => {
const adminService = ctx.get('adminService');
@@ -819,7 +895,7 @@ export function UserAdminController(app: HonoApp) {
'/admin/users/:user_id/password-reset-link',
RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
requireAdminACL(AdminACLs.USER_CREATE_PASSWORD_RESET_LINK),
- RequireUsernameAccountIdentity,
+ RequireUsernameIdentityOrNoEmailDelivery,
Validator('param', UserIdParam),
OpenAPI({
operationId: 'create_admin_user_password_reset_link',
@@ -829,7 +905,7 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Create a one-time password reset link on an instance where people sign in with a username. Hand the link to the user yourself. It works once and expires after an hour. Deletes the recovery kit of the account. Creates audit log entry. Requires USER_CREATE_PASSWORD_RESET_LINK permission and every ACL the target account holds. Fails with USERNAME_SIGN_IN_ONLY on email instances.',
+ 'Create a one-time password reset link on an instance where people sign in with a username, or on an email instance that does not send email. Hand the link to the user yourself. It works once and expires after an hour. Deletes the recovery kit of the account. Creates audit log entry. Requires USER_CREATE_PASSWORD_RESET_LINK permission and every ACL the target account holds. Fails with USERNAME_SIGN_IN_ONLY on an email instance that sends email, where people reset their password themselves.',
}),
async (ctx) => {
const adminService = ctx.get('adminService');
@@ -846,6 +922,35 @@ export function UserAdminController(app: HonoApp) {
);
},
);
+ app.post(
+ '/admin/users/:user_id/sign-in-link',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.WILDCARD),
+ Validator('param', UserIdParam),
+ OpenAPI({
+ operationId: 'create_admin_user_sign_in_link',
+ summary: 'Create admin sign-in link',
+ responseSchema: AdminSignInLinkResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ description:
+ 'Create a one-time sign-in link for an account that holds `*`. Opening the link signs that account in and authorizes the IP address of the browser, without a password or an email. It works once and expires after 15 minutes. Only served on the operator socket. Creates audit log entry, and using the link creates another.',
+ }),
+ async (ctx) => {
+ if (ctx.get('authTokenType') !== 'operator') {
+ throw new AccessDeniedError();
+ }
+ const {user_id: userId} = ctx.req.valid('param');
+ return ctx.json(
+ await createSignInLink(ctx.get('apiContext'), ctx.get('adminService').auditService, {
+ userId: createUserID(userId),
+ adminUserId: ctx.get('adminUserId'),
+ auditLogReason: ctx.get('auditLogReason'),
+ }),
+ );
+ },
+ );
app.delete(
'/admin/users/:user_id/recovery-kit',
RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
@@ -933,7 +1038,7 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Record a warning decision and send its notice by email and system DM. Nothing about the account changes. The X-Audit-Log-Reason header is required and becomes the first note. Refused for reasons that only allow a suspension or content removal. Requires USER_UPDATE_FLAGS permission, plus MESSAGE_LOOKUP for evidence and REPORT_VIEW and REPORT_RESOLVE for reports.',
+ 'Record a warning decision and send its notice by email and system DM, leaving out the system DM when the instance has direct messages turned off. Nothing about the account changes. The X-Audit-Log-Reason header is required and becomes the first note. Refused for reasons that only allow a suspension or content removal. Requires USER_UPDATE_FLAGS permission, plus MESSAGE_LOOKUP for evidence and REPORT_VIEW and REPORT_RESOLVE for reports.',
}),
async (ctx) => {
const {user_id: userId} = ctx.req.valid('param');
@@ -958,7 +1063,7 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Record an enforcement decision that limits one feature and send its notice by email and system DM. Direct messages set SPAMMER and are allowed for spam, automation, fraud and malware reasons only. Reports set REPORT_BANNED until ends_at, 90 days by default and at most 365, and expire on their own. Purchases set PURCHASE_DISABLED for payment reasons. The X-Audit-Log-Reason header is required and becomes the first note. Requires USER_UPDATE_FLAGS permission, plus MESSAGE_LOOKUP for evidence and REPORT_VIEW and REPORT_RESOLVE for reports.',
+ 'Record an enforcement decision that limits one feature and send its notice by email and system DM, leaving out the system DM when the instance has direct messages turned off. Direct messages set SPAMMER and are allowed for spam, automation, fraud and malware reasons only. Reports set REPORT_BANNED until ends_at, 90 days by default and at most 365, and expire on their own. Purchases set PURCHASE_DISABLED for payment reasons. The X-Audit-Log-Reason header is required and becomes the first note. Requires USER_UPDATE_FLAGS permission, plus MESSAGE_LOOKUP for evidence and REPORT_VIEW and REPORT_RESOLVE for reports.',
}),
async (ctx) => {
const {user_id: userId} = ctx.req.valid('param');
@@ -1104,7 +1209,7 @@ export function UserAdminController(app: HonoApp) {
security: 'adminApiKey',
tags: 'Admin',
description:
- 'Set or update user trait attributes and profile metadata. Traits customize user display and features. Creates audit log entry. Requires USER_UPDATE_TRAITS permission.',
+ 'Set or update user trait attributes and profile metadata. Traits customize user display and features. Trait names are stored in lowercase, and limit rules match them without regard to case. Creates audit log entry. Requires USER_UPDATE_TRAITS permission.',
}),
async (ctx) => {
const adminService = ctx.get('adminService');
@@ -1112,9 +1217,10 @@ export function UserAdminController(app: HonoApp) {
const auditLogReason = ctx.get('auditLogReason');
const adminUserAcls = ctx.get('adminUserAcls');
const {user_id: userId} = ctx.req.valid('param');
+ const {traits} = ctx.req.valid('json');
return ctx.json(
await adminService.userService.securityService.setUserTraits(
- {user_id: userId, ...ctx.req.valid('json')},
+ {user_id: userId, traits: [...new Set(traits.map((trait) => trait.toLowerCase()))]},
adminUserId,
auditLogReason,
adminUserAcls,
diff --git a/fluxer_api/src/api/admin/services/AdminUserCreationService.ts b/fluxer_api/src/api/admin/services/AdminUserCreationService.ts
new file mode 100644
index 000000000..db1fc12e9
--- /dev/null
+++ b/fluxer_api/src/api/admin/services/AdminUserCreationService.ts
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {ApiContext} from '@app/api/ApiContext';
+import {mapUserToAdminResponse} from '@app/api/admin/models/UserTypes';
+import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService';
+import type {AdminUserSecurityService} from '@app/api/admin/services/AdminUserSecurityService';
+import {sendVerificationEmail} from '@app/api/auth/AuthEmail';
+import {resolveRegistrationUsername} from '@app/api/auth/AuthRegistration';
+import {createUserID, type UserID} from '@app/api/BrandedTypes';
+import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';
+import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';
+import type {DiscriminatorService} from '@app/api/infrastructure/DiscriminatorService';
+import {withAccountIdentitySetupLock} from '@app/api/instance/AccountIdentitySetupLock';
+import {instanceCollectsDateOfBirth} from '@app/api/instance/DateOfBirthCollectionCache';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import type {User} from '@app/api/models/User';
+import {UserSettings} from '@app/api/models/UserSettings';
+import {reserveUsername, type UsernameReservation} from '@app/api/user/UniqueUsernames';
+import {DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
+import {EmailDeliveryStates} from '@fluxer/constants/src/AccountConfigConstants';
+import {AccountIdentityModes, TagStyles} from '@fluxer/constants/src/AccountIdentityConstants';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {ProfileFieldPrivacyFlags} from '@fluxer/constants/src/UserConstants';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {UsernameSignInOnlyError} from '@fluxer/errors/src/domains/auth/UsernameSignInOnlyError';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import type {AdminUserCreateRequest, AdminUserCreateResponse} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';
+
+interface AdminUserCreationServiceDeps {
+ apiContext: ApiContext;
+ auditService: AdminAuditService;
+ discriminatorService: DiscriminatorService;
+ securityService: AdminUserSecurityService;
+}
+
+export class AdminUserCreationService {
+ constructor(private readonly deps: AdminUserCreationServiceDeps) {}
+
+ async createUser(
+ data: AdminUserCreateRequest,
+ adminUserId: UserID,
+ auditLogReason: string | null,
+ acls: ReadonlySet<string>,
+ ): Promise<AdminUserCreateResponse> {
+ const {config, cache} = this.deps.apiContext.services;
+ const repository = getInstanceConfigRepository();
+ const user =
+ !config.instance.selfHosted || (await repository.isAccountIdentityLocked())
+ ? await this.createAccount(data)
+ : await withAccountIdentitySetupLock(cache, () => this.createAccount(data));
+ await this.deps.auditService.createAuditLog({
+ adminUserId,
+ targetType: 'user',
+ targetId: BigInt(user.id),
+ action: 'create_user',
+ auditLogReason,
+ metadata: new Map([
+ ['username', user.username],
+ ['admin', String(data.admin)],
+ ]),
+ });
+ const passwordReset = await this.deps.securityService.createPasswordResetLink(
+ {user_id: user.id},
+ adminUserId,
+ auditLogReason,
+ acls,
+ );
+ return {
+ user: await mapUserToAdminResponse(user, cache, acls),
+ password_reset: passwordReset,
+ };
+ }
+
+ private async createAccount(data: AdminUserCreateRequest): Promise<User> {
+ const {users, snowflake, cache} = this.deps.apiContext.services;
+ const repository = getInstanceConfigRepository();
+ const accountIdentity = await repository.getAccountIdentity();
+ const usernameMode = accountIdentity.mode === AccountIdentityModes.USERNAME;
+ const uniqueUsernames = accountIdentity.tagStyle === TagStyles.NONE;
+ const emailEnabled = (await repository.getEmailDeliveryState()) === EmailDeliveryStates.ON;
+ const email = data.email ?? null;
+ if (usernameMode && email !== null) {
+ throw new UsernameSignInOnlyError();
+ }
+ if (!usernameMode && email === null) {
+ throw InputValidationError.fromCode('email', ValidationErrorCodes.EMAIL_IS_REQUIRED);
+ }
+ if (email !== null && (await users.findByEmail(email))) {
+ throw InputValidationError.fromCode('email', ValidationErrorCodes.EMAIL_ALREADY_IN_USE);
+ }
+ const {username, discriminator} = await resolveRegistrationUsername({
+ users,
+ discriminatorService: this.deps.discriminatorService,
+ uniqueUsernames,
+ requestedUsername: data.username,
+ explicitlyRequested: true,
+ globalName: undefined,
+ });
+ const userId = createUserID(await snowflake.generate());
+ const now = new Date();
+ const traits = new Set<string>();
+ if (instanceCollectsDateOfBirth()) traits.add(DOB_DEFERRED_TRAIT);
+ const userRow: UserRow = {
+ ...EMPTY_USER_ROW,
+ user_id: userId,
+ username,
+ discriminator,
+ global_name: null,
+ bot: false,
+ system: false,
+ email,
+ email_verified: email === null || !emailEnabled,
+ email_bounced: false,
+ password_hash: null,
+ password_last_changed_at: null,
+ authenticator_types: new Set(),
+ timezone_privacy_flags: ProfileFieldPrivacyFlags.EVERYONE,
+ flags: 0n,
+ terms_agreed_at: null,
+ privacy_agreed_at: null,
+ last_active_at: now,
+ acls: data.admin ? new Set([AdminACLs.WILDCARD]) : null,
+ traits: traits.size > 0 ? traits : null,
+ version: 1,
+ };
+ let reservation: UsernameReservation | null = null;
+ let user: User;
+ try {
+ if (uniqueUsernames) {
+ reservation = await reserveUsername({users, cache}, username);
+ }
+ user = await users.create(userRow);
+ } finally {
+ await reservation?.release();
+ }
+ await users.upsertSettings(UserSettings.getDefaultUserSettings({userId, locale: 'en-US', isAdult: true}));
+ await emitActivity(
+ 'registration',
+ user.id.toString(),
+ {
+ user_id: user.id.toString(),
+ method: 'other',
+ source: 'app',
+ email,
+ username,
+ username_user_chosen: true,
+ global_name: null,
+ locale: user.locale,
+ timezone: null,
+ invite_code: null,
+ flags: user.flags.toString(),
+ date_of_birth: user.dateOfBirth,
+ },
+ null,
+ user.id.toString(),
+ );
+ if (email !== null && emailEnabled) {
+ await sendVerificationEmail(this.deps.apiContext, {user, email});
+ }
+ return user;
+ }
+}
diff --git a/fluxer_api/src/api/admin/services/AdminUserService.ts b/fluxer_api/src/api/admin/services/AdminUserService.ts
index ab61c2067..7f44e392c 100644
--- a/fluxer_api/src/api/admin/services/AdminUserService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserService.ts
@@ -4,6 +4,7 @@ import type {ApiContext} from '@app/api/ApiContext';
import {mapUserToAdminResponse, resolveAdminUsers} from '@app/api/admin/models/UserTypes';
import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService';
import type {AdminBanManagementService} from '@app/api/admin/services/AdminBanManagementService';
+import {AdminUserCreationService} from '@app/api/admin/services/AdminUserCreationService';
import {AdminUserDeletionService} from '@app/api/admin/services/AdminUserDeletionService';
import {AdminUserLookupService} from '@app/api/admin/services/AdminUserLookupService';
import {AdminUserProfileService} from '@app/api/admin/services/AdminUserProfileService';
@@ -27,7 +28,6 @@ import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import type {PartialUserChangePropagationDeps} from '@app/api/user/services/PartialUserChangePropagation';
import type {UserContactChangeLogService} from '@app/api/user/services/UserContactChangeLogService';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
CancelBulkMessageDeletionRequest,
ListUserChangeLogRequest,
@@ -61,6 +61,7 @@ export class AdminUserService {
readonly profileService: AdminUserProfileService;
readonly securityService: AdminUserSecurityService;
readonly deletionService: AdminUserDeletionService;
+ readonly creationService: AdminUserCreationService;
private readonly userUpdateDeps: PartialUserChangePropagationDeps;
private readonly contactChangeLogService: UserContactChangeLogService;
private readonly auditService: AdminAuditService;
@@ -101,6 +102,12 @@ export class AdminUserService {
auditService: deps.auditService,
userUpdateDeps: this.userUpdateDeps,
});
+ this.creationService = new AdminUserCreationService({
+ apiContext: deps.apiContext,
+ auditService: deps.auditService,
+ discriminatorService: deps.discriminatorService,
+ securityService: this.securityService,
+ });
this.deletionService = new AdminUserDeletionService({
apiContext: deps.apiContext,
auditService: deps.auditService,
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditCoverage.ts b/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditCoverage.ts
index 057079eef..fac2243de 100644
--- a/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditCoverage.ts
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/AdminAuditCoverage.ts
@@ -2,6 +2,7 @@
import {getAdminAuditAccess} from '@app/api/admin/AdminAuditActions';
import type {AdminAuditLog} from '@app/api/admin/AdminRepository';
+import {markOperatorRequest} from '@app/api/admin/operator/OperatorRequests';
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {getAdminRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
@@ -22,6 +23,7 @@ interface AdminAuditCoverageRequest {
body?: unknown;
headers?: Record<string, string>;
expectStatus?: number;
+ operator?: boolean;
}
interface AdminAuditExpectedEntry {
@@ -73,6 +75,24 @@ function describeEntry(log: AdminAuditLog) {
};
}
+async function operatorRequest(
+ harness: ApiTestHarness,
+ method: AdminRouteMethod,
+ request: AdminAuditCoverageRequest,
+): Promise<Response> {
+ const raw = new Request(new URL(request.path, 'http://localhost'), {
+ method,
+ headers: {
+ 'content-type': 'application/json',
+ 'X-Audit-Log-Reason': ADMIN_AUDIT_COVERAGE_REASON,
+ ...request.headers,
+ },
+ body: request.body === undefined ? undefined : JSON.stringify(request.body),
+ });
+ markOperatorRequest(raw);
+ return harness.app.fetch(raw);
+}
+
export function describeAdminAuditCoverage(area: string, cases: ReadonlyArray<AdminAuditCoverageCase>): void {
describe(`Admin audit coverage: ${area}`, () => {
let harness: ApiTestHarness | undefined;
@@ -92,16 +112,18 @@ export function describeAdminAuditCoverage(area: string, cases: ReadonlyArray<Ad
const prepared = await coverageCase.prepare({harness, admin});
const {request} = prepared;
const before = new Set((await listAuditLogs()).map((log) => log.logId.toString()));
- const response = await harness.requestJson({
- path: request.path,
- method: coverageCase.method,
- body: request.body,
- headers: {
- Authorization: admin.token,
- 'X-Audit-Log-Reason': ADMIN_AUDIT_COVERAGE_REASON,
- ...request.headers,
- },
- });
+ const response = request.operator
+ ? await operatorRequest(harness, coverageCase.method, request)
+ : await harness.requestJson({
+ path: request.path,
+ method: coverageCase.method,
+ body: request.body,
+ headers: {
+ Authorization: admin.token,
+ 'X-Audit-Log-Reason': ADMIN_AUDIT_COVERAGE_REASON,
+ ...request.headers,
+ },
+ });
const expectedStatus = request.expectStatus ?? 200;
if (response.status !== expectedStatus) {
throw new Error(`Expected ${expectedStatus}, got ${response.status}: ${await response.text()}`);
@@ -118,7 +140,7 @@ export function describeAdminAuditCoverage(area: string, cases: ReadonlyArray<Ad
const expectedAccess = coverageCase.method === 'GET' ? 'read' : 'write';
expect(getAdminAuditAccess(expected.action)).toBe(expectedAccess);
for (const log of recorded) {
- expect(log.adminUserId.toString()).toBe(admin.userId);
+ expect(log.adminUserId.toString()).toBe(request.operator ? '0' : admin.userId);
expect(log.auditLogReason).toEqual(coverageCase.auditLogReason ?? ADMIN_AUDIT_COVERAGE_REASON);
expect(getAdminAuditAccess(log.action)).toBe(expectedAccess);
}
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/UserWriteAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/UserWriteAdminAuditCases.ts
index e890e9b2d..752c1f0a6 100644
--- a/fluxer_api/src/api/admin/tests/audit_coverage/UserWriteAdminAuditCases.ts
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/UserWriteAdminAuditCases.ts
@@ -10,6 +10,7 @@ import {
createUniqueEmail,
createUniqueUsername,
generateTotpCode,
+ setUserACLs,
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
import {
@@ -340,6 +341,22 @@ export const UserWriteAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
};
},
},
+ {
+ method: 'POST',
+ route: '/admin/users',
+ async prepare() {
+ const username = createUniqueUsername('created');
+ return {
+ request: {path: '/admin/users', body: {username, email: createUniqueEmail('created')}},
+ expected: {
+ action: 'create_user',
+ targetType: 'user',
+ targetId: expect.any(String),
+ metadata: {username, admin: 'false'},
+ },
+ };
+ },
+ },
{
method: 'POST',
route: '/admin/users/:user_id/password-reset-link',
@@ -362,6 +379,22 @@ export const UserWriteAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
};
},
},
+ {
+ method: 'POST',
+ route: '/admin/users/:user_id/sign-in-link',
+ async prepare({harness}) {
+ const target = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.WILDCARD]);
+ return {
+ request: {path: `/admin/users/${target.userId}/sign-in-link`, operator: true},
+ expected: {
+ action: 'create_sign_in_link',
+ targetType: 'user',
+ targetId: target.userId,
+ metadata: {via: 'rexctl'},
+ },
+ };
+ },
+ },
{
method: 'DELETE',
route: '/admin/users/:user_id/recovery-kit',
@@ -644,7 +677,12 @@ export const UserWriteAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
action: 'change_dob',
targetType: 'user',
targetId: target.userId,
- metadata: {old_dob: (await loadUser(target)).dateOfBirth!, new_dob: '1995-06-15'},
+ metadata: {
+ old_dob: (await loadUser(target)).dateOfBirth!,
+ new_dob: '1995-06-15',
+ cleared_below_minimum_age: 'false',
+ outside_plausible_range: 'false',
+ },
},
};
},
diff --git a/fluxer_api/src/api/auth/SignInLinks.ts b/fluxer_api/src/api/auth/SignInLinks.ts
new file mode 100644
index 000000000..7f57066c7
--- /dev/null
+++ b/fluxer_api/src/api/auth/SignInLinks.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {ApiContext} from '@app/api/ApiContext';
+import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService';
+import {emitLogin} from '@app/api/auth/AuthLogin';
+import * as AuthSession from '@app/api/auth/AuthSession';
+import * as AuthUtility from '@app/api/auth/AuthUtility';
+import {createUserID, type UserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
+import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';
+import {randomBase64Url, sha256Hex} from '@app/api/utils/SecretHash';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {MissingACLError} from '@fluxer/errors/src/domains/core/MissingACLError';
+import type {AdminSignInLinkResponse} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';
+import {seconds} from 'itty-time';
+
+const SIGN_IN_LINK_KEY_PREFIX = 'sign_in_link:';
+const SIGN_IN_LINK_TOKEN_BYTES = 32;
+const SIGN_IN_LINK_TTL_SECONDS = seconds('15 minutes');
+
+interface SignInLinkRecord {
+ user_id: string;
+ created_at: number;
+}
+
+function signInLinkKey(token: string): string {
+ return `${SIGN_IN_LINK_KEY_PREFIX}${sha256Hex(token)}`;
+}
+
+function invalidSignInLink(): InputValidationError {
+ return InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN);
+}
+
+function isAdmin(acls: ReadonlySet<string>): boolean {
+ return acls.has(AdminACLs.WILDCARD);
+}
+
+export async function createSignInLink(
+ ctx: ApiContext,
+ auditService: AdminAuditService,
+ args: {userId: UserID; adminUserId: UserID; auditLogReason: string | null},
+): Promise<AdminSignInLinkResponse> {
+ const user = await ctx.services.users.findUnique(args.userId);
+ if (!user) {
+ throw new UnknownUserError();
+ }
+ AuthUtility.assertNonBotUser(ctx, user);
+ if (!isAdmin(user.acls)) {
+ throw new MissingACLError(AdminACLs.WILDCARD);
+ }
+ const token = randomBase64Url(SIGN_IN_LINK_TOKEN_BYTES);
+ const createdAt = Date.now();
+ const record: SignInLinkRecord = {user_id: user.id.toString(), created_at: createdAt};
+ await ctx.services.cache.set(signInLinkKey(token), record, SIGN_IN_LINK_TTL_SECONDS);
+ await auditService.createAuditLog({
+ adminUserId: args.adminUserId,
+ targetType: 'user',
+ targetId: BigInt(user.id),
+ action: 'create_sign_in_link',
+ auditLogReason: args.auditLogReason,
+ metadata: new Map(),
+ });
+ return {
+ url: `${Config.email.appBaseUrl}/login#sign_in_link=${token}`,
+ expires_at: new Date(createdAt + SIGN_IN_LINK_TTL_SECONDS * 1000).toISOString(),
+ };
+}
+
+export async function redeemSignInLink(
+ ctx: ApiContext,
+ auditService: AdminAuditService,
+ args: {token: string; request: Request},
+): Promise<{user_id: string; token: string}> {
+ const record = await ctx.services.cache.getAndDelete<SignInLinkRecord>(signInLinkKey(args.token));
+ if (!record) {
+ throw invalidSignInLink();
+ }
+ const found = await ctx.services.users.findUnique(createUserID(BigInt(record.user_id)));
+ if (!found || !isAdmin(found.acls)) {
+ throw invalidSignInLink();
+ }
+ if (found.passwordLastChangedAt !== null && record.created_at < found.passwordLastChangedAt.getTime()) {
+ throw invalidSignInLink();
+ }
+ AuthUtility.assertNonBotUser(ctx, found);
+ const user = await AuthUtility.assertSignInAllowed(ctx, found);
+ const clientIp = requireConfiguredClientIp(args.request, ctx.services.config.proxy);
+ await ctx.services.users.createAuthorizedIp(user.id, clientIp);
+ const [token] = await AuthSession.createAuthSession(ctx, {
+ user,
+ origin: AuthSession.resolveSessionOrigin(ctx, args.request),
+ });
+ await auditService.createAuditLog({
+ adminUserId: user.id,
+ targetType: 'user',
+ targetId: BigInt(user.id),
+ action: 'use_sign_in_link',
+ auditLogReason: null,
+ metadata: new Map([['via', 'rexctl']]),
+ });
+ emitLogin(user, true, {newIp: true, method: 'other'});
+ return {user_id: user.id.toString(), token};
+}