Skip to content

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

TypeScript fluxerfluxerapp

fix: admin API key page fixes (#1360)

Jiralite097fa9d9ce93
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.json
index b51b8ac7a..6bf04aa5a 100644
--- a/fluxer_admin/openapi-admin.json
+++ b/fluxer_admin/openapi-admin.json
@@ -9718,7 +9718,7 @@
"acls": {
"type": "array",
"items": {"type": "string"},
- "maxItems": 100,
+ "maxItems": 115,
"description": "List of access control permissions for the key"
}
},
@@ -10061,11 +10061,11 @@
"ValidationErrorItem": {
"type": "object",
"properties": {
- "field": {"type": "string", "description": "Field path that failed validation"},
+ "path": {"type": "string", "description": "Field path that failed validation"},
"code": {"type": "string", "description": "Machine-readable validation error code"},
"message": {"type": "string", "description": "Human-readable validation error message"}
},
- "required": ["field", "code", "message"]
+ "required": ["path", "message"]
},
"CreateAdminApiKeyRequest": {
"type": "object",
@@ -10081,7 +10081,7 @@
"acls": {
"type": "array",
"items": {"type": "string"},
- "maxItems": 100,
+ "maxItems": 115,
"description": "List of access control permissions for the key"
}
},
@@ -10111,7 +10111,7 @@
"acls": {
"type": "array",
"items": {"type": "string"},
- "maxItems": 100,
+ "maxItems": 115,
"description": "List of access control permissions for the key"
}
},
diff --git a/fluxer_admin/src/routes/admin.rs b/fluxer_admin/src/routes/admin.rs
index 979d12648..4a788e017 100644
--- a/fluxer_admin/src/routes/admin.rs
+++ b/fluxer_admin/src/routes/admin.rs
@@ -1,12 +1,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+use super::ActionQuery;
use crate::{
acl,
api::client::{AdminApiClient, ApiResultExt},
+ config::AdminConfig,
middleware::{
auth::AuthContext,
csrf::CsrfToken,
flash::{self, FlashData},
+ htmx,
},
state::AppState,
templates,
@@ -19,8 +22,6 @@ use axum::{
routing::get,
};
-use super::ActionQuery;
-
pub fn router() -> Router<AppState> {
Router::new().route(
"/admin-api-keys",
@@ -32,6 +33,7 @@ async fn admin_api_keys_page(
State(state): State<AppState>,
auth: axum::Extension<AuthContext>,
csrf: axum::Extension<CsrfToken>,
+ flash: Option<axum::Extension<FlashData>>,
) -> Response {
let config = state.config();
let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);
@@ -40,10 +42,12 @@ async fn admin_api_keys_page(
.await
.log_error("load admin api keys");
let available_acls = available_acls(&auth.0);
+ let flash = flash.map(|flash| flash.0.to_flash_message());
let markup = templates::pages::admin_api_keys::admin_api_keys_page(
config,
&auth.0,
&csrf.0.0,
+ flash.as_ref(),
None,
keys.as_deref(),
&available_acls,
@@ -60,13 +64,14 @@ async fn admin_api_keys_post(
) -> Response {
let config = state.config();
let base = &config.base_path;
+ let is_htmx = htmx::is_htmx_request(request.headers());
let form = match MultiValueForm::from_request(request).await {
Some(form) => form,
None => {
- return flash::redirect_with_flash(
- &format!("{base}/admin-api-keys"),
+ return admin_api_key_flash_response(
+ config,
FlashData::error("Invalid form data"),
- config.is_production(),
+ is_htmx,
);
}
};
@@ -76,40 +81,39 @@ async fn admin_api_keys_post(
"create" => {
let name = form.clean("name").unwrap_or_default();
let acls = form.list_values_any(&["acls[]", "acls"]);
- if !name.is_empty() {
- return match client.create_api_key(&name, &acls).await {
- Ok(created) => {
- let keys = client
- .list_api_keys()
- .await
- .log_error("reload admin api keys after create");
- let available_acls = available_acls(&auth.0);
- let markup = templates::pages::admin_api_keys::admin_api_keys_page(
- config,
- &auth.0,
- &csrf.0.0,
- Some(&created),
- keys.as_deref(),
- &available_acls,
- );
- Html(markup.into_string()).into_response()
- }
- Err(error) => {
- tracing::warn!(%error, "admin API request failed: create API key");
- flash::redirect_with_flash(
- &format!("{base}/admin-api-keys"),
- FlashData::error("Failed to create API key"),
- config.is_production(),
- )
- }
- };
- }
+ return match client.create_api_key(&name, &acls).await {
+ Ok(created) => {
+ let keys = client
+ .list_api_keys()
+ .await
+ .log_error("reload admin api keys after create");
+ let available_acls = available_acls(&auth.0);
+ let markup = templates::pages::admin_api_keys::admin_api_keys_page(
+ config,
+ &auth.0,
+ &csrf.0.0,
+ None,
+ Some(&created),
+ keys.as_deref(),
+ &available_acls,
+ );
+ Html(markup.into_string()).into_response()
+ }
+ Err(error) => {
+ tracing::warn!(%error, "admin API request failed: create API key");
+ admin_api_key_flash_response(
+ config,
+ FlashData::error("Failed to create API key."),
+ is_htmx,
+ )
+ }
+ };
}
"revoke" => {
if let Some(key_id) = form.clean("key_id") {
let result = client.revoke_api_key(&key_id).await;
let flash = match result.log_error("revoke API key") {
- Some(_) => FlashData::success("API key revoked"),
+ Some(_) => FlashData::success("API key revoked."),
None => FlashData::error("Failed to revoke API key"),
};
return flash::redirect_with_flash(
@@ -123,11 +127,27 @@ async fn admin_api_keys_post(
}
flash::redirect_with_flash(
&format!("{base}/admin-api-keys"),
- FlashData::success(format!("API key action '{action}' completed")),
+ FlashData::success(format!("API key action '{action}' completed.")),
config.is_production(),
)
}
+fn admin_api_key_flash_response(
+ config: &AdminConfig,
+ flash_data: FlashData,
+ is_htmx: bool,
+) -> Response {
+ if is_htmx {
+ htmx::toast_response(&flash_data)
+ } else {
+ flash::redirect_with_flash(
+ &format!("{}/admin-api-keys", config.base_path),
+ flash_data,
+ config.is_production(),
+ )
+ }
+}
+
fn available_acls(auth: &AuthContext) -> Vec<&'static str> {
let admin_acls = auth
.admin_user
diff --git a/fluxer_admin/src/templates/layout_scripts.rs b/fluxer_admin/src/templates/layout_scripts.rs
index d44da2558..b5f2a0837 100644
--- a/fluxer_admin/src/templates/layout_scripts.rs
+++ b/fluxer_admin/src/templates/layout_scripts.rs
@@ -352,6 +352,7 @@ pub const HTMX_FLASH_SCRIPT: &str = r#"
window.clearTimeout(hideTimer);
hideTimer = 0;
}
+ if (activeToast && !activeToast.isConnected) activeToast = null;
if (!activeToast) {
activeToast = document.createElement('div');
activeToast.setAttribute('role', 'status');
diff --git a/fluxer_admin/src/templates/pages/admin_api_keys.rs b/fluxer_admin/src/templates/pages/admin_api_keys.rs
index f0de99144..9aad1319d 100644
--- a/fluxer_admin/src/templates/pages/admin_api_keys.rs
+++ b/fluxer_admin/src/templates/pages/admin_api_keys.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::{
- api::types::{CreateAdminApiKeyResponse, ListAdminApiKeyEntry},
+ api::types::{CreateAdminApiKeyResponse, FlashMessage, ListAdminApiKeyEntry},
config::AdminConfig,
middleware::auth::AuthContext,
templates::{
@@ -23,7 +23,7 @@ fn created_key_banner(key: &CreateAdminApiKeyResponse) -> Markup {
let key_id = &key.key_id;
alert(
AlertVariant::Success,
- Some("API Key Created Successfully"),
+ Some("API Key created successfully."),
html! {
div class="flex flex-col gap-2" {
p class="text-sm text-green-700" {
@@ -62,7 +62,8 @@ fn create_form(base: &str, csrf_token: &str, acls: &[&str]) -> Markup {
}
}
form id="create-key-form" method="post"
- action={(base) "/admin-api-keys?action=create"} {
+ action={(base) "/admin-api-keys?action=create"}
+ data-admin-result-form="true" hx-push-url="false" {
(csrf_input(csrf_token))
div class="flex flex-col gap-4" {
div class="flex flex-col gap-2" {
@@ -94,7 +95,7 @@ fn create_form(base: &str, csrf_token: &str, acls: &[&str]) -> Markup {
}
div class="grid grid-cols-1 gap-3 md:grid-cols-2" {
@for acl in acls {
- (checkbox("acls", acl, acl, true, true))
+ (checkbox("acls", acl, acl, false, true))
}
}
}
@@ -151,7 +152,8 @@ fn api_key_item(base: &str, csrf_token: &str, key: &ListAdminApiKeyEntry) -> Mar
}
form method="post"
action={(base) "/admin-api-keys?action=revoke"}
- class="flex-shrink-0 self-stretch sm:self-start" {
+ class="flex-shrink-0 self-stretch sm:self-start"
+ data-admin-result-form="true" hx-push-url="false" {
(csrf_input(csrf_token))
input type="hidden" name="key_id" value=(key_id);
button type="submit"
@@ -194,6 +196,7 @@ pub fn admin_api_keys_page(
config: &AdminConfig,
auth: &AuthContext,
csrf_token: &str,
+ flash: Option<&FlashMessage>,
created_key: Option<&CreateAdminApiKeyResponse>,
keys: Option<&[ListAdminApiKeyEntry]>,
available_acls: &[&str],
@@ -201,7 +204,7 @@ pub fn admin_api_keys_page(
let base = &config.base_path;
let content = html! {
(page_header("Admin API Keys", Some("Create and manage API keys for admin access")))
- div class="space-y-6" {
+ div class="space-y-6" hx-history=[created_key.is_some().then_some("false")] {
@if let Some(ck) = created_key {
(created_key_banner(ck))
}
@@ -214,7 +217,7 @@ pub fn admin_api_keys_page(
auth,
"Admin API Keys",
"admin-api-keys",
- None,
+ flash,
content,
)
}
diff --git a/fluxer_admin/tests/htmx_acceptance.rs b/fluxer_admin/tests/htmx_acceptance.rs
index 0fc1ff49d..c0a306149 100644
--- a/fluxer_admin/tests/htmx_acceptance.rs
+++ b/fluxer_admin/tests/htmx_acceptance.rs
@@ -16,12 +16,43 @@ use tokio::net::TcpListener;
use tower::ServiceExt;
const SECRET_KEY: &str = "htmx-acceptance-test-secret";
+const ADMIN_API_KEY_SECRET: &str = "fa_1900000000000000001_OneTimeSecretForAcceptance";
struct TestApp {
router: Router,
session_cookie: String,
}
+#[tokio::test]
+async fn admin_api_key_create_form_renders_the_one_time_secret() {
+ let app = setup().await;
+ let (headers, page) = get_with_headers(&app, "/admin-api-keys", &[]).await;
+ let csrf_token = csrf_cookie(&headers)
+ .unwrap_or_else(|| panic!("Admin API keys page did not set csrf_token cookie\n{page}"));
+ assert!(page.contains(r#"data-admin-result-form="true""#), "{page}");
+
+ let (status, _, response_body) = post_form_with_headers(
+ &app,
+ "/admin-api-keys?action=create",
+ &[
+ ("HX-Request", "true"),
+ ("HX-Boosted", "true"),
+ ("HX-Target", "body"),
+ (
+ "Cookie",
+ &format!("{}; csrf_token={}", app.session_cookie, csrf_token),
+ ),
+ ],
+ &format!("_csrf={csrf_token}&name=Acceptance+Key&acls=*"),
+ )
+ .await;
+
+ assert_eq!(status, StatusCode::OK, "{response_body}");
+ assert_full_layout(&response_body);
+ assert!(response_body.contains(r#"hx-history="false""#));
+ assert!(response_body.contains(ADMIN_API_KEY_SECRET));
+}
+
#[tokio::test]
async fn search_routes_return_layout_or_fragments_by_hx_target() {
let app = setup().await;
@@ -680,6 +711,15 @@ async fn spawn_mock_api() -> String {
async fn mock_api(method: Method, uri: Uri) -> Response {
match (method, uri.path()) {
(Method::GET, "/admin/users/me") => json_response(json!({ "user": admin_user() })),
+ (Method::GET, "/admin/api-keys") => json_response(json!([])),
+ (Method::POST, "/admin/api-keys") => json_response(json!({
+ "key_id": "1900000000000000001",
+ "key": ADMIN_API_KEY_SECRET,
+ "name": "Acceptance key",
+ "created_at": "2026-07-10T15:00:00.000Z",
+ "expires_at": null,
+ "acls": ["*"]
+ })),
(Method::POST, "/admin/users/search") => {
json_response(json!({ "users": [searched_user()], "total": 1 }))
}
diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.json
index 0c8d655fd..9887d235c 100644
--- a/fluxer_api/src/api/openapi/openapi.json
+++ b/fluxer_api/src/api/openapi/openapi.json
@@ -25771,11 +25771,11 @@
"ValidationErrorItem": {
"type": "object",
"properties": {
- "field": {"type": "string", "description": "Field path that failed validation"},
+ "path": {"type": "string", "description": "Field path that failed validation"},
"code": {"type": "string", "description": "Machine-readable validation error code"},
"message": {"type": "string", "description": "Human-readable validation error message"}
},
- "required": ["field", "code", "message"]
+ "required": ["path", "message"]
},
"ApplicationsMeResponse": {
"type": "object",
diff --git a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
index 9f1d3bd95..319c0b499 100644
--- a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
@@ -191,7 +191,7 @@ export class UserAccountSettingsService {
if (data.trusted_domains !== undefined) {
const domainsSet = new Set(data.trusted_domains);
if (domainsSet.has('*') && domainsSet.size > 1) {
- throw ValidationError.fromField(
+ throw ValidationError.fromPath(
'trusted_domains',
'INVALID_TRUSTED_DOMAINS',
'Cannot combine wildcard (*) with specific domains',
@@ -219,7 +219,7 @@ export class UserAccountSettingsService {
data.sensitive_content_friend_dm_filter === SensitiveMediaFilterLevel.BLUR ||
data.sensitive_content_friend_dm_filter === SensitiveMediaFilterLevel.BLOCK;
if (!allowed) {
- throw ValidationError.fromField(
+ throw ValidationError.fromPath(
'sensitive_content_friend_dm_filter',
'AGE_RESTRICTED',
'Non-adult users can only set friend DM filter to blur or block',
@@ -228,14 +228,14 @@ export class UserAccountSettingsService {
updatedRowData.sensitive_content_friend_dm_filter = data.sensitive_content_friend_dm_filter;
}
if (data.sensitive_content_non_friend_dm_filter !== undefined) {
- throw ValidationError.fromField(
+ throw ValidationError.fromPath(
'sensitive_content_non_friend_dm_filter',
'AGE_RESTRICTED',
'Non-adult users cannot modify the non-friend DM content filter',
);
}
if (data.sensitive_content_guild_filter !== undefined) {
- throw ValidationError.fromField(
+ throw ValidationError.fromPath(
'sensitive_content_guild_filter',
'AGE_RESTRICTED',
'Non-adult users cannot modify the guild content filter',
@@ -498,7 +498,7 @@ export class UserAccountSettingsService {
function normalizeSyncedPreferencesSnapshot(value: string | null | undefined): string | null {
if (value == null || value === '') return null;
if (encodedSyncedPreferencesByteLength(value) > SYNCED_PREFERENCES_MAX_BYTES) {
- throw ValidationError.fromField(
+ throw ValidationError.fromPath(
'synced_preferences',
'TOO_LARGE',
`synced_preferences exceeds ${SYNCED_PREFERENCES_MAX_BYTES} bytes`,
@@ -508,7 +508,7 @@ function normalizeSyncedPreferencesSnapshot(value: string | null | undefined): s
try {
decoded = decodeSyncedPreferences(value);
} catch (error) {
- throw ValidationError.fromField(
+ throw ValidationError.fromPath(
'synced_preferences',
'INVALID_FORMAT',
error instanceof Error ? error.message : 'invalid synced_preferences encoding',
diff --git a/packages/errors/src/ValidationError.ts b/packages/errors/src/ValidationError.ts
index abf783900..3f63fed59 100644
--- a/packages/errors/src/ValidationError.ts
+++ b/packages/errors/src/ValidationError.ts
@@ -4,8 +4,8 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import {FluxerError} from '@fluxer/errors/src/FluxerError';
-interface FieldError {
- field: string;
+interface PathError {
+ path: string;
code: string;
message: string;
}
@@ -13,11 +13,11 @@ interface FieldError {
interface ValidationErrorOptions {
code?: string;
message?: string;
- errors: Array<FieldError>;
+ errors: Array<PathError>;
}
export class ValidationError extends FluxerError {
- readonly errors: Array<FieldError>;
+ readonly errors: Array<PathError>;
constructor(options: ValidationErrorOptions) {
super({
@@ -46,13 +46,13 @@ export class ValidationError extends FluxerError {
);
}
- static fromField(field: string, code: string, message: string): ValidationError {
+ static fromPath(path: string, code: string, message: string): ValidationError {
return new ValidationError({
- errors: [{field, code, message}],
+ errors: [{path, code, message}],
});
}
- static fromFields(errors: Array<FieldError>): ValidationError {
+ static fromPaths(errors: Array<PathError>): ValidationError {
return new ValidationError({errors});
}
}
diff --git a/packages/errors/src/__tests__/DomainErrors.test.ts b/packages/errors/src/__tests__/DomainErrors.test.ts
index a77dfb27d..9d0494168 100644
--- a/packages/errors/src/__tests__/DomainErrors.test.ts
+++ b/packages/errors/src/__tests__/DomainErrors.test.ts
@@ -136,8 +136,8 @@ describe('Domain Errors', () => {
});
it('should create from multiple fields using static method', () => {
const error = InputValidationError.createMultiple([
- {field: 'email', message: 'Invalid email'},
- {field: 'password', message: 'Password too short'},
+ {path: 'email', message: 'Invalid email'},
+ {path: 'password', message: 'Password too short'},
]);
expect(error.data).toEqual({
errors: [
diff --git a/packages/errors/src/__tests__/ValidationError.test.ts b/packages/errors/src/__tests__/ValidationError.test.ts
index 3a6ff873c..35eb72bc0 100644
--- a/packages/errors/src/__tests__/ValidationError.test.ts
+++ b/packages/errors/src/__tests__/ValidationError.test.ts
@@ -9,7 +9,7 @@ interface ValidationErrorBody {
code: string;
message: string;
errors: Array<{
- field: string;
+ path: string;
code: string;
message: string;
}>;
@@ -17,43 +17,43 @@ interface ValidationErrorBody {
describe('ValidationError', () => {
describe('constructor', () => {
- it('should create error with single field error', () => {
+ it('should create error with single path error', () => {
const error = new ValidationError({
- errors: [{field: 'email', code: 'INVALID_EMAIL', message: 'Invalid email format'}],
+ errors: [{path: 'email', code: 'INVALID_EMAIL', message: 'Invalid email format'}],
});
expect(error.status).toBe(HttpStatus.BAD_REQUEST);
expect(error.code).toBe('VALIDATION_ERROR');
expect(error.message).toBe('Validation failed');
expect(error.name).toBe('ValidationError');
- expect(error.errors).toEqual([{field: 'email', code: 'INVALID_EMAIL', message: 'Invalid email format'}]);
+ expect(error.errors).toEqual([{path: 'email', code: 'INVALID_EMAIL', message: 'Invalid email format'}]);
});
- it('should create error with multiple field errors', () => {
- const fieldErrors = [
- {field: 'email', code: 'REQUIRED', message: 'Email is required'},
- {field: 'password', code: 'TOO_SHORT', message: 'Password must be at least 8 characters'},
- {field: 'username', code: 'INVALID_CHARS', message: 'Username contains invalid characters'},
+ it('should create error with multiple path errors', () => {
+ const pathErrors = [
+ {path: 'email', code: 'REQUIRED', message: 'Email is required'},
+ {path: 'password', code: 'TOO_SHORT', message: 'Password must be at least 8 characters'},
+ {path: 'username', code: 'INVALID_CHARS', message: 'Username contains invalid characters'},
];
- const error = new ValidationError({errors: fieldErrors});
+ const error = new ValidationError({errors: pathErrors});
expect(error.errors).toHaveLength(3);
- expect(error.errors).toEqual(fieldErrors);
+ expect(error.errors).toEqual(pathErrors);
});
it('should allow custom code', () => {
const error = new ValidationError({
code: 'INVALID_FORM_BODY',
- errors: [{field: 'name', code: 'REQUIRED', message: 'Name is required'}],
+ errors: [{path: 'name', code: 'REQUIRED', message: 'Name is required'}],
});
expect(error.code).toBe('INVALID_FORM_BODY');
});
it('should allow custom message', () => {
const error = new ValidationError({
message: 'Input validation failed',
- errors: [{field: 'name', code: 'REQUIRED', message: 'Name is required'}],
+ errors: [{path: 'name', code: 'REQUIRED', message: 'Name is required'}],
});
expect(error.message).toBe('Input validation failed');
});
it('should be instance of FluxerError', () => {
const error = new ValidationError({
- errors: [{field: 'field', code: 'CODE', message: 'message'}],
+ errors: [{path: 'field', code: 'CODE', message: 'message'}],
});
expect(error).toBeInstanceOf(FluxerError);
});
@@ -61,7 +61,7 @@ describe('ValidationError', () => {
describe('getResponse', () => {
it('should return JSON response with errors array', async () => {
const error = new ValidationError({
- errors: [{field: 'email', code: 'INVALID', message: 'Invalid email'}],
+ errors: [{path: 'email', code: 'INVALID', message: 'Invalid email'}],
});
const response = error.getResponse();
expect(response.status).toBe(400);
@@ -70,25 +70,25 @@ describe('ValidationError', () => {
expect(body).toEqual({
code: 'VALIDATION_ERROR',
message: 'Validation failed',
- errors: [{field: 'email', code: 'INVALID', message: 'Invalid email'}],
+ errors: [{path: 'email', code: 'INVALID', message: 'Invalid email'}],
});
});
it('should include multiple errors in response', async () => {
- const fieldErrors = [
- {field: 'email', code: 'REQUIRED', message: 'Email is required'},
- {field: 'password', code: 'TOO_SHORT', message: 'Password too short'},
+ const pathErrors = [
+ {path: 'email', code: 'REQUIRED', message: 'Email is required'},
+ {path: 'password', code: 'TOO_SHORT', message: 'Password too short'},
];
- const error = new ValidationError({errors: fieldErrors});
+ const error = new ValidationError({errors: pathErrors});
const response = error.getResponse();
const body = (await response.json()) as ValidationErrorBody;
expect(body.errors).toHaveLength(2);
- expect(body.errors).toEqual(fieldErrors);
+ expect(body.errors).toEqual(pathErrors);
});
it('should include custom code and message in response', async () => {
const error = new ValidationError({
code: 'CUSTOM_VALIDATION',
message: 'Custom validation message',
- errors: [{field: 'field', code: 'CODE', message: 'message'}],
+ errors: [{path: 'field', code: 'CODE', message: 'message'}],
});
const response = error.getResponse();
const body = (await response.json()) as ValidationErrorBody;
@@ -96,79 +96,79 @@ describe('ValidationError', () => {
expect(body.message).toBe('Custom validation message');
});
});
- describe('fromField static method', () => {
- it('should create ValidationError from single field', () => {
- const error = ValidationError.fromField('username', 'TAKEN', 'Username is already taken');
+ describe('fromPath static method', () => {
+ it('should create ValidationError from single path', () => {
+ const error = ValidationError.fromPath('username', 'TAKEN', 'Username is already taken');
expect(error).toBeInstanceOf(ValidationError);
- expect(error.errors).toEqual([{field: 'username', code: 'TAKEN', message: 'Username is already taken'}]);
+ expect(error.errors).toEqual([{path: 'username', code: 'TAKEN', message: 'Username is already taken'}]);
});
it('should have default code and message', () => {
- const error = ValidationError.fromField('field', 'code', 'message');
+ const error = ValidationError.fromPath('field', 'code', 'message');
expect(error.code).toBe('VALIDATION_ERROR');
expect(error.message).toBe('Validation failed');
});
});
- describe('fromFields static method', () => {
- it('should create ValidationError from multiple fields', () => {
- const fieldErrors = [
- {field: 'email', code: 'REQUIRED', message: 'Email is required'},
- {field: 'password', code: 'WEAK', message: 'Password is too weak'},
+ describe('fromPaths static method', () => {
+ it('should create ValidationError from multiple paths', () => {
+ const pathErrors = [
+ {path: 'email', code: 'REQUIRED', message: 'Email is required'},
+ {path: 'password', code: 'WEAK', message: 'Password is too weak'},
];
- const error = ValidationError.fromFields(fieldErrors);
+ const error = ValidationError.fromPaths(pathErrors);
expect(error).toBeInstanceOf(ValidationError);
- expect(error.errors).toEqual(fieldErrors);
+ expect(error.errors).toEqual(pathErrors);
});
it('should handle empty array', () => {
- const error = ValidationError.fromFields([]);
+ const error = ValidationError.fromPaths([]);
expect(error.errors).toEqual([]);
});
});
describe('error data structure', () => {
it('should store errors in data property', () => {
- const fieldErrors = [{field: 'test', code: 'TEST', message: 'Test error'}];
- const error = new ValidationError({errors: fieldErrors});
- expect(error.data).toEqual({errors: fieldErrors});
+ const pathErrors = [{path: 'test', code: 'TEST', message: 'Test error'}];
+ const error = new ValidationError({errors: pathErrors});
+ expect(error.data).toEqual({errors: pathErrors});
});
it('should serialize correctly with toJSON', () => {
const error = new ValidationError({
- errors: [{field: 'field', code: 'CODE', message: 'message'}],
+ errors: [{path: 'field', code: 'CODE', message: 'message'}],
});
const json = error.toJSON();
expect(json).toEqual({
code: 'VALIDATION_ERROR',
message: 'Validation failed',
- errors: [{field: 'field', code: 'CODE', message: 'message'}],
+ errors: [{path: 'field', code: 'CODE', message: 'message'}],
});
});
});
describe('edge cases', () => {
- it('should handle field errors with special characters', () => {
+ it('should handle paths with special characters', () => {
const error = new ValidationError({
- errors: [{field: 'user.email', code: 'INVALID', message: "Email can't be empty"}],
+ errors: [{path: 'user.email', code: 'INVALID', message: "Email can't be empty"}],
});
- expect(error.errors[0].field).toBe('user.email');
+ expect(error.errors[0].path).toBe('user.email');
expect(error.errors[0].message).toBe("Email can't be empty");
});
it('should handle nested field paths', () => {
const error = new ValidationError({
errors: [
- {field: 'address.street', code: 'REQUIRED', message: 'Street is required'},
- {field: 'address.city', code: 'REQUIRED', message: 'City is required'},
- {field: 'address.zip', code: 'INVALID_FORMAT', message: 'Invalid ZIP code format'},
+ {path: 'address.street', code: 'REQUIRED', message: 'Street is required'},
+ {path: 'address.city', code: 'REQUIRED', message: 'City is required'},
+ {path: 'address.zip', code: 'INVALID_FORMAT', message: 'Invalid ZIP code format'},
],
});
expect(error.errors).toHaveLength(3);
- expect(error.errors[0].field).toBe('address.street');
+ expect(error.errors[0].path).toBe('address.street');
});
it('should handle array index field paths', () => {
const error = new ValidationError({
errors: [
- {field: 'items[0].name', code: 'REQUIRED', message: 'Item name is required'},
- {field: 'items[1].quantity', code: 'MIN', message: 'Quantity must be at least 1'},
+ {path: 'items[0].name', code: 'REQUIRED', message: 'Item name is required'},
+ {path: 'items[1].quantity', code: 'MIN', message: 'Quantity must be at least 1'},
],
});
expect(error.errors).toHaveLength(2);
- expect(error.errors[0].field).toBe('items[0].name');
+ expect(error.errors[0].path).toBe('items[0].name');
});
});
});
diff --git a/packages/errors/src/domains/core/InputValidationError.ts b/packages/errors/src/domains/core/InputValidationError.ts
index 78da2f1e3..c511f983f 100644
--- a/packages/errors/src/domains/core/InputValidationError.ts
+++ b/packages/errors/src/domains/core/InputValidationError.ts
@@ -27,13 +27,8 @@ export class InputValidationError extends BadRequestError {
return new InputValidationError([{path, message}]);
}
- static createMultiple(
- errors: Array<{
- field: string;
- message: string;
- }>,
- ): InputValidationError {
- return new InputValidationError(errors.map((e) => ({path: e.field, message: e.message})));
+ static createMultiple(errors: Array<ValidationError>): InputValidationError {
+ return new InputValidationError(errors);
}
static fromCode(path: string, code: ValidationErrorCode, variables?: Record<string, unknown>): InputValidationError {
diff --git a/packages/openapi/src/converters/BuiltInSchemas.ts b/packages/openapi/src/converters/BuiltInSchemas.ts
index d9d4553a8..d2d873765 100644
--- a/packages/openapi/src/converters/BuiltInSchemas.ts
+++ b/packages/openapi/src/converters/BuiltInSchemas.ts
@@ -207,7 +207,7 @@ export const APIErrorCodeSchema = {
export const ValidationErrorItemSchema: OpenAPISchema = {
type: 'object',
properties: {
- field: {
+ path: {
type: 'string',
description: 'Field path that failed validation',
},
@@ -220,5 +220,5 @@ export const ValidationErrorItemSchema: OpenAPISchema = {
description: 'Human-readable validation error message',
},
},
- required: ['field', 'code', 'message'],
+ required: ['path', 'message'],
};
diff --git a/packages/schema/src/domains/admin/AdminSchemas.ts b/packages/schema/src/domains/admin/AdminSchemas.ts
index d9d55fda9..68c9ac6fc 100644
--- a/packages/schema/src/domains/admin/AdminSchemas.ts
+++ b/packages/schema/src/domains/admin/AdminSchemas.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {
GIFT_CODE_DURATION_TYPE_DEFINITIONS,
MAX_GIFT_CODES_PER_REQUEST,
@@ -44,6 +45,8 @@ import {
import {EmailType} from '@fluxer/schema/src/primitives/UserValidators';
import {z} from 'zod';
+const ADMIN_ACL_COUNT = Object.keys(AdminACLs).length;
+
const ReportStatusSchema = withOpenApiType(
createInt32EnumType(
[
@@ -846,7 +849,7 @@ export const CreateAdminApiKeyRequest = z.object({
.refine((value) => value.trim().length > 0, 'Name cannot be empty')
.describe('Display name for the API key'),
expires_in_days: z.number().int().min(1).max(365).optional().describe('Number of days until the key expires'),
- acls: z.array(z.string()).max(100).describe('List of access control permissions for the key'),
+ acls: z.array(z.string()).max(ADMIN_ACL_COUNT).describe('List of access control permissions for the key'),
});
export type CreateAdminApiKeyRequest = z.infer<typeof CreateAdminApiKeyRequest>;
@@ -857,7 +860,7 @@ export const CreateAdminApiKeyResponse = z.object({
name: z.string().describe('Display name for the API key'),
created_at: z.string().describe('ISO 8601 timestamp when the key was created'),
expires_at: z.string().nullable().describe('ISO 8601 timestamp when the key expires, or null if no expiration'),
- acls: z.array(z.string()).max(100).describe('List of access control permissions for the key'),
+ acls: z.array(z.string()).max(ADMIN_ACL_COUNT).describe('List of access control permissions for the key'),
});
export type CreateAdminApiKeyResponse = z.infer<typeof CreateAdminApiKeyResponse>;
@@ -869,7 +872,7 @@ export const ListAdminApiKeyResponse = z.object({
last_used_at: z.string().nullable().describe('ISO 8601 timestamp when the key was last used, or null if never used'),
expires_at: z.string().nullable().describe('ISO 8601 timestamp when the key expires, or null if no expiration'),
created_by_user_id: SnowflakeStringType.describe('User ID of the admin who created this key'),
- acls: z.array(z.string()).max(100).describe('List of access control permissions for the key'),
+ acls: z.array(z.string()).max(ADMIN_ACL_COUNT).describe('List of access control permissions for the key'),
});
export type ListAdminApiKeyResponse = z.infer<typeof ListAdminApiKeyResponse>;