A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(badges): let operators replace built-in badge images (#3725)
Hampusd0c7a51e9392
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.jsonindex f73d42b2d..ebea3791e 100644--- a/fluxer_admin/openapi-admin.json+++ b/fluxer_admin/openapi-admin.json@@ -1254,6 +1254,132 @@}}},+ "/admin/badges/built-in/{kind}": {+ "put": {+ "operationId": "replace_admin_built_in_badge_image",+ "summary": "Replace built-in badge image",+ "tags": ["Admin"],+ "responses": {+ "200": {+ "description": "Success",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AdminCustomBadgeListResponse"}}}+ },+ "400": {+ "description": "Bad Request - The request was malformed or contained invalid data",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "401": {+ "description": "Unauthorized - Authentication is required or the token is invalid",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "403": {+ "description": "Forbidden - You do not have permission to perform this action",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "429": {+ "description": "Too Many Requests - You are being rate limited",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},+ "headers": {+ "Retry-After": {+ "description": "Number of seconds to wait before retrying (only on 429)",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Limit": {+ "description": "The number of requests that can be made in the current window",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Remaining": {+ "description": "The number of remaining requests that can be made",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Reset": {+ "description": "Unix timestamp when the rate limit resets",+ "schema": {"type": "integer"}+ }+ }+ },+ "500": {+ "description": "Internal Server Error - An unexpected error occurred",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ }+ },+ "description": "Shows an uploaded image everywhere a built-in profile or community badge appears. The name, tooltip and meaning of the badge stay the same. Creates audit log entry. Requires BADGE_UPDATE permission.",+ "security": [{"adminApiKey": []}],+ "parameters": [+ {+ "name": "kind",+ "in": "path",+ "required": true,+ "schema": {"allOf": [{"$ref": "#/components/schemas/BuiltInBadgeKindSchema"}]},+ "description": "A built-in badge whose image can be replaced: the staff or premium profile badge, or a community badge starting with guild_"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ReplaceBuiltInBadgeImageRequest"}}}+ }+ },+ "delete": {+ "operationId": "reset_admin_built_in_badge_image",+ "summary": "Use built-in badge image",+ "tags": ["Admin"],+ "responses": {+ "200": {+ "description": "Success",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AdminCustomBadgeListResponse"}}}+ },+ "400": {+ "description": "Bad Request - The request was malformed or contained invalid data",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "401": {+ "description": "Unauthorized - Authentication is required or the token is invalid",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "403": {+ "description": "Forbidden - You do not have permission to perform this action",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "429": {+ "description": "Too Many Requests - You are being rate limited",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},+ "headers": {+ "Retry-After": {+ "description": "Number of seconds to wait before retrying (only on 429)",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Limit": {+ "description": "The number of requests that can be made in the current window",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Remaining": {+ "description": "The number of remaining requests that can be made",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Reset": {+ "description": "Unix timestamp when the rate limit resets",+ "schema": {"type": "integer"}+ }+ }+ },+ "500": {+ "description": "Internal Server Error - An unexpected error occurred",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ }+ },+ "description": "Goes back to the built-in artwork for a built-in profile or community badge and deletes the uploaded image. Creates audit log entry. Requires BADGE_UPDATE permission.",+ "security": [{"adminApiKey": []}],+ "parameters": [+ {+ "name": "kind",+ "in": "path",+ "required": true,+ "schema": {"allOf": [{"$ref": "#/components/schemas/BuiltInBadgeKindSchema"}]},+ "description": "A built-in badge whose image can be replaced: the staff or premium profile badge, or a community badge starting with guild_"+ }+ ]+ }+ },"/admin/badges/order": {"put": {"operationId": "reorder_admin_badges",@@ -19598,11 +19724,33 @@"type": "array","items": {"$ref": "#/components/schemas/AdminCustomBadgeResponse"},"description": "Badges defined on this instance, in display order"+ },+ "built_in": {+ "maxItems": 5,+ "type": "array",+ "items": {"$ref": "#/components/schemas/AdminBuiltInBadgeImageResponse"},+ "description": "Every built-in badge and the image this instance shows for it"}},- "required": ["badges"],+ "required": ["badges", "built_in"],"additionalProperties": false},+ "BuiltInBadgeKindSchema": {+ "type": "string",+ "enum": ["staff", "premium", "guild_verified", "guild_partnered", "guild_discoverable"],+ "description": "A built-in badge whose image can be replaced: the staff or premium profile badge, or a community badge starting with guild_"+ },+ "ReplaceBuiltInBadgeImageRequest": {+ "type": "object",+ "properties": {+ "image": {+ "type": "string",+ "maxLength": 16000000,+ "description": "The badge image as a base64 data URL. PNG, JPEG, GIF, WebP and SVG images are accepted"+ }+ },+ "required": ["image"]+ },"CreateCustomBadgeRequest": {"type": "object","properties": {@@ -20140,6 +20288,24 @@"enum": ["user", "guild"],"type": "string"},+ "AdminBuiltInBadgeImageResponse": {+ "type": "object",+ "properties": {+ "kind": {"allOf": [{"$ref": "#/components/schemas/BuiltInBadgeKindSchema"}]},+ "asset_url": {+ "nullable": true,+ "description": "URL of the image shown in place of the built-in artwork, or null when the built-in artwork is used",+ "type": "string"+ },+ "built_in_asset": {+ "nullable": true,+ "description": "Hash of the built-in artwork at {static_cdn}/badges/{hash}.webp, or null for a guild badge, which clients draw themselves",+ "type": "string"+ }+ },+ "required": ["kind", "asset_url", "built_in_asset"],+ "additionalProperties": false+ },"BanProfileSubstringRequest": {"type": "object","properties": {diff --git a/fluxer_admin/src/api/badges.rs b/fluxer_admin/src/api/badges.rsindex 5ac2d7290..9cc681d6f 100644--- a/fluxer_admin/src/api/badges.rs+++ b/fluxer_admin/src/api/badges.rs@@ -84,6 +84,33 @@ impl AdminApiClient {Ok(())}+ pub async fn replace_built_in_badge_image(+ &self,+ kind: &str,+ image: &str,+ ) -> ApiResult<AdminCustomBadgeList> {+ let body = generated_types::ReplaceBuiltInBadgeImageRequest {+ image: image.try_into().map_err(parse_error)?,+ };+ let kind: generated_types::BuiltInBadgeKindSchema = kind.parse().map_err(parse_error)?;+ let response = self+ .generated()+ .replace_admin_built_in_badge_image(kind, &body)+ .await+ .map_err(|e| self.generated_error(e))?;+ self.generated_value(response.into_inner())+ }++ pub async fn reset_built_in_badge_image(&self, kind: &str) -> ApiResult<AdminCustomBadgeList> {+ let kind: generated_types::BuiltInBadgeKindSchema = kind.parse().map_err(parse_error)?;+ let response = self+ .generated()+ .reset_admin_built_in_badge_image(kind)+ .await+ .map_err(|e| self.generated_error(e))?;+ self.generated_value(response.into_inner())+ }+pub async fn reorder_badges(&self, ids: &[String]) -> ApiResult<AdminCustomBadgeList> {let body = generated_types::ReorderCustomBadgesRequest {badge_ids: ids.iter().map(|id| snowflake(id)).collect(),diff --git a/fluxer_admin/src/api/types/badges.rs b/fluxer_admin/src/api/types/badges.rsindex 6e13589e7..b023b037a 100644--- a/fluxer_admin/src/api/types/badges.rs+++ b/fluxer_admin/src/api/types/badges.rs@@ -53,9 +53,44 @@ impl AdminCustomBadge {}}+#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct BuiltInBadgeImage {+ pub kind: String,+ pub asset_url: Option<String>,+ #[serde(default)]+ pub built_in_asset: Option<String>,+}++impl BuiltInBadgeImage {+ pub fn image_url(&self) -> Option<String> {+ self.asset_url.as_ref().map(|url| format!("{url}?size=96"))+ }++ pub fn badge_type(&self) -> CustomBadgeType {+ if self.kind.starts_with("guild_") {+ CustomBadgeType::Guild+ } else {+ CustomBadgeType::User+ }+ }++ pub fn label(&self) -> &str {+ match self.kind.as_str() {+ "staff" => "Staff",+ "premium" => "Premium",+ "guild_verified" => "Verified",+ "guild_partnered" => "Partnered",+ "guild_discoverable" => "Discoverable",+ other => other,+ }+ }+}+#[derive(Clone, Debug, Deserialize, Serialize)]pub struct AdminCustomBadgeList {pub badges: Vec<AdminCustomBadge>,+ #[serde(default)]+ pub built_in: Vec<BuiltInBadgeImage>,}#[derive(Clone, Copy, Debug, Eq, PartialEq)]@@ -82,6 +117,15 @@ impl BadgeMove {}impl AdminCustomBadgeList {+ pub fn built_in_of_type(+ &self,+ badge_type: CustomBadgeType,+ ) -> impl Iterator<Item = &BuiltInBadgeImage> {+ self.built_in+ .iter()+ .filter(move |badge| badge.badge_type() == badge_type)+ }+pub fn of_type(&self, badge_type: CustomBadgeType) -> impl Iterator<Item = &AdminCustomBadge> {self.badges.iter()diff --git a/fluxer_admin/src/routes/badges.rs b/fluxer_admin/src/routes/badges.rsindex 02b34b9c9..a2e6c783c 100644--- a/fluxer_admin/src/routes/badges.rs+++ b/fluxer_admin/src/routes/badges.rs@@ -29,6 +29,8 @@ pub fn router() -> Router<AppState> {.route("/badges/{badge_id}", post(update_badge)).route("/badges/{badge_id}/delete", post(delete_badge)).route("/badges/{badge_id}/move/{direction}", post(move_badge))+ .route("/badges/built-in/{kind}", post(replace_built_in_image))+ .route("/badges/built-in/{kind}/reset", post(reset_built_in_image)).layer(DefaultBodyLimit::max(BADGE_IMAGE_MAX_BYTES + 64 * 1024))}@@ -183,6 +185,64 @@ async fn delete_badge(flash::redirect_with_flash(&back, flash, config.secure_cookies())}+async fn replace_built_in_image(+ State(state): State<AppState>,+ auth: axum::Extension<AuthContext>,+ Path(kind): Path<String>,+ mut multipart: Multipart,+) -> Response {+ let config = state.config();+ let back = format!("{}/badges", config.base_path);+ let mut image = None;+ while let Ok(Some(field)) = multipart.next_field().await {+ if field.name() != Some("image") {+ continue;+ }+ let content_type = field.content_type().unwrap_or_default().to_owned();+ let Ok(bytes) = field.bytes().await else {+ return flash::redirect_error(config, &back, "The image must be under 10 MB");+ };+ if bytes.is_empty() {+ continue;+ }+ if !BADGE_IMAGE_TYPES.contains(&content_type.as_str()) {+ return flash::redirect_error(+ config,+ &back,+ "Choose a PNG, JPEG, GIF, WebP or SVG image",+ );+ }+ image = Some(format!(+ "data:{content_type};base64,{}",+ STANDARD.encode(&bytes)+ ));+ }+ let Some(image) = image else {+ return flash::redirect_error(config, &back, "Choose an image to upload");+ };+ let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);+ let flash = match client.replace_built_in_badge_image(&kind, &image).await {+ Ok(_) => FlashData::success("Badge image replaced"),+ Err(error) => failure("replace the image of", &error),+ };+ flash::redirect_with_flash(&back, flash, config.secure_cookies())+}++async fn reset_built_in_image(+ State(state): State<AppState>,+ auth: axum::Extension<AuthContext>,+ Path(kind): Path<String>,+) -> Response {+ let config = state.config();+ let back = format!("{}/badges", config.base_path);+ let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);+ let flash = match client.reset_built_in_badge_image(&kind).await {+ Ok(_) => FlashData::success("Badge uses the built-in image again"),+ Err(error) => failure("reset the image of", &error),+ };+ flash::redirect_with_flash(&back, flash, config.secure_cookies())+}+async fn move_badge(State(state): State<AppState>,auth: axum::Extension<AuthContext>,diff --git a/fluxer_admin/src/styles/app.css b/fluxer_admin/src/styles/app.cssindex 4b35f3867..7cd06bbee 100644--- a/fluxer_admin/src/styles/app.css+++ b/fluxer_admin/src/styles/app.css@@ -317,3 +317,13 @@ input:disabled + .checkbox-custom {:root:not([data-theme="dark"]) .theme-toggle-to-light {display: none;}++.built-in-guild-badge {+ --guild-badge-seal: var(--brand-primary);+ --guild-badge-icon: #fff;+}++:root[data-theme="dark"] .built-in-guild-badge {+ --guild-badge-seal: #fff;+ --guild-badge-icon: var(--brand-primary);+}diff --git a/fluxer_admin/src/templates/pages/badges.rs b/fluxer_admin/src/templates/pages/badges.rsindex 2d01e2d57..23d037c1d 100644--- a/fluxer_admin/src/templates/pages/badges.rs+++ b/fluxer_admin/src/templates/pages/badges.rs@@ -4,7 +4,7 @@ use crate::{acl,api::types::{AdminCustomBadge, AdminCustomBadgeList, BADGE_IMAGE_MAX_BYTES, BADGE_IMAGE_TYPES,- BadgeMove, CustomBadgeType,+ BadgeMove, BuiltInBadgeImage, CustomBadgeType,},config::AdminConfig,middleware::auth::AuthContext,@@ -52,6 +52,8 @@ pub fn badges_page(div class="space-y-6" {(badge_section(config, list, CustomBadgeType::User, &permissions, csrf_token))(badge_section(config, list, CustomBadgeType::Guild, &permissions, csrf_token))+ (built_in_section(config, list, CustomBadgeType::User, &permissions, csrf_token))+ (built_in_section(config, list, CustomBadgeType::Guild, &permissions, csrf_token))@if permissions.create {(create_form(config, csrf_token))}@@ -96,6 +98,118 @@ fn badge_section()}+const BADGE_ACTION_BUTTON_CLASS: &str = "rounded-lg border border-neutral-200 px-3 py-2 font-medium text-sm cursor-pointer hover:border-neutral-300";++const GUILD_BADGE_SEAL_PATH: &str = "M240 128C240 138.44 232.49 146.27 225.86 153.18C222.09 157.12 218.19 161.18 216.72 164.75C215.36 168.02 215.28 173.44 215.2 178.69C215.05 188.45 214.89 199.51 207.2 207.2C199.51 214.89 188.45 215.05 178.69 215.2C173.44 215.28 168.02 215.36 164.75 216.72C161.18 218.19 157.12 222.09 153.18 225.86C146.27 232.49 138.44 240 128 240C117.56 240 109.73 232.49 102.82 225.86C98.88 222.09 94.82 218.19 91.25 216.72C87.98 215.36 82.56 215.28 77.31 215.2C67.55 215.05 56.49 214.89 48.8 207.2C41.11 199.51 40.95 188.45 40.8 178.69C40.72 173.44 40.64 168.02 39.28 164.75C37.81 161.18 33.91 157.12 30.14 153.18C23.51 146.27 16 138.44 16 128C16 117.56 23.51 109.73 30.14 102.82C33.91 98.88 37.81 94.82 39.28 91.25C40.64 87.98 40.72 82.56 40.8 77.31C40.95 67.55 41.11 56.49 48.8 48.8C56.49 41.11 67.55 40.95 77.31 40.8C82.56 40.72 87.98 40.64 91.25 39.28C94.82 37.81 98.88 33.91 102.82 30.14C109.73 23.51 117.56 16 128 16C138.44 16 146.27 23.51 153.18 30.14C157.12 33.91 161.18 37.81 164.75 39.28C168.02 40.64 173.44 40.72 178.69 40.8C188.45 40.95 199.51 41.11 207.2 48.8C214.89 56.49 215.05 67.55 215.2 77.31C215.28 82.56 215.36 87.98 216.72 91.25C218.19 94.82 222.09 98.88 225.86 102.82C232.49 109.73 240 117.56 240 128Z";++const VERIFIED_MARK_PATH: &str = "M185.655 109.455L121.455 173.655C119.955 175.154 117.921 175.996 115.8 175.996C113.679 175.996 111.645 175.154 110.145 173.655L74.3349 137.655C72.8373 136.155 71.9961 134.122 71.9961 132.003C71.9961 129.883 72.8373 127.85 74.3349 126.35L84.3349 116.35C85.8342 114.857 87.864 114.019 89.9799 114.019C92.0958 114.019 94.1256 114.857 95.6249 116.35L116 136.11L164.38 88.325C165.879 86.8304 167.91 85.9912 170.027 85.9912C172.145 85.9912 174.175 86.8304 175.675 88.325L185.65 98.095C186.4 98.8384 186.996 99.7229 187.402 100.698C187.809 101.672 188.018 102.718 188.019 103.774C188.019 104.83 187.811 105.876 187.405 106.851C186.999 107.826 186.404 108.711 185.655 109.455Z";++const PARTNERED_MARK_PATH: &str = "M112.732 144.785L110.823 146.945C106.987 150.791 102.1 153.41 96.7796 154.471C91.4591 155.533 85.9441 154.988 80.9322 152.907C75.9203 150.826 71.6365 147.301 68.6226 142.778C65.6087 138.256 64 132.939 64 127.5C64 122.061 65.6087 116.744 68.6226 112.222C71.6365 107.699 75.9203 104.175 80.9322 102.093C85.9441 100.012 91.4591 99.4673 96.7796 100.529C102.1 101.59 106.987 104.209 110.823 108.055L145.177 146.945C149.013 150.791 153.9 153.41 159.22 154.471C164.541 155.533 170.056 154.988 175.068 152.907C180.08 150.826 184.363 147.301 187.377 142.778C190.391 138.256 192 132.939 192 127.5C192 122.061 190.391 116.744 187.377 112.222C184.363 107.699 180.08 104.175 175.068 102.093C170.056 100.012 164.541 99.4673 159.22 100.529C153.9 101.59 149.013 104.209 145.177 108.055L143.268 110.215";++const DISCOVERABLE_MARK_PATH: &str = "M184 168H176V132L177.17 133.17C177.922 133.921 178.941 134.342 180.004 134.341C181.066 134.34 182.084 133.917 182.835 133.165C183.586 132.413 184.007 131.394 184.006 130.332C184.005 129.269 183.582 128.251 182.83 127.5L133.655 78.3401C132.155 76.8409 130.121 75.9988 128 75.9988C125.879 75.9988 123.845 76.8409 122.345 78.3401L73.17 127.5C72.4201 128.251 71.9991 129.268 71.9995 130.329C72 131.39 72.4219 132.408 73.1725 133.158C73.9231 133.907 74.9408 134.328 76.0018 134.328C77.0628 134.328 78.0801 133.906 78.83 133.155L80 132V168H72C70.9391 168 69.9217 168.421 69.1716 169.172C68.4214 169.922 68 170.939 68 172C68 173.061 68.4214 174.078 69.1716 174.828C69.9217 175.579 70.9391 176 72 176H184C185.061 176 186.078 175.579 186.828 174.828C187.579 174.078 188 173.061 188 172C188 170.939 187.579 169.922 186.828 169.172C186.078 168.421 185.061 168 184 168ZM140 168H116V144C116 143.47 116.211 142.961 116.586 142.586C116.961 142.211 117.47 142 118 142H138C138.53 142 139.039 142.211 139.414 142.586C139.789 142.961 140 143.47 140 144V168Z";++fn guild_badge_svg(kind: &str) -> Markup {+ let mark = match kind {+ "guild_partnered" => html! {+ path d=(PARTNERED_MARK_PATH)+ style="fill: none; stroke: var(--guild-badge-icon); stroke-width: 16; stroke-linecap: round; stroke-linejoin: round" {}+ },+ "guild_discoverable" => {+ html! { path d=(DISCOVERABLE_MARK_PATH) style="fill: var(--guild-badge-icon)" {} }+ }+ _ => html! { path d=(VERIFIED_MARK_PATH) style="fill: var(--guild-badge-icon)" {} },+ };+ html! {+ svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none" aria-hidden="true"+ class="built-in-guild-badge h-10 w-10 shrink-0" {+ path d=(GUILD_BADGE_SEAL_PATH) style="fill: var(--guild-badge-seal)" {}+ (mark)+ }+ }+}++fn built_in_image(config: &AdminConfig, badge: &BuiltInBadgeImage) -> Markup {+ let class = "h-10 w-10 shrink-0 rounded object-contain";+ if let Some(url) = badge.image_url() {+ return html! { img src=(url) alt=(badge.label()) title=(badge.label()) class=(class); };+ }+ match &badge.built_in_asset {+ Some(asset) => html! {+ img src={(config.static_cdn_endpoint.trim_end_matches('/')) "/badges/" (asset) ".webp"}+ alt=(badge.label()) title=(badge.label()) class=(class);+ },+ None => html! { span title=(badge.label()) { (guild_badge_svg(&badge.kind)) } },+ }+}++fn built_in_section(+ config: &AdminConfig,+ list: &AdminCustomBadgeList,+ badge_type: CustomBadgeType,+ permissions: &BadgePermissions,+ csrf_token: &str,+) -> Markup {+ let title = match badge_type {+ CustomBadgeType::User => "Built-in user badges",+ CustomBadgeType::Guild => "Built-in guild badges",+ };+ card_with_header(+ title,+ html! {+ p class="mb-4 text-sm text-neutral-600" {+ "Upload an image to show it everywhere this badge appears. The badge keeps its name and meaning."+ }+ div class="divide-y divide-neutral-100" {+ @for badge in list.built_in_of_type(badge_type) {+ (built_in_row(config, badge, permissions, csrf_token))+ }+ }+ },+ )+}++fn built_in_row(+ config: &AdminConfig,+ badge: &BuiltInBadgeImage,+ permissions: &BadgePermissions,+ csrf_token: &str,+) -> Markup {+ let base = &config.base_path;+ let prefix = format!("built-in-{}", badge.kind);+ html! {+ div class="flex flex-col gap-3 py-4 first:pt-0 last:pb-0" {+ div class="flex items-center gap-3" {+ (built_in_image(config, badge))+ div class="flex min-w-0 flex-col gap-1" {+ span class="font-medium text-neutral-900" { (badge.label()) }+ span class="text-sm text-neutral-600" {+ (if badge.asset_url.is_some() { "Shows your image" } else { "Shows the built-in image" })+ }+ }+ }+ @if permissions.update {+ div class="flex flex-wrap items-start gap-2" {+ details class="rounded-lg border border-neutral-200 open:basis-full" {+ summary class="cursor-pointer rounded-lg px-3 py-2 font-medium text-sm" { "Replace image" }+ form method="post" enctype="multipart/form-data"+ action={(base) "/badges/built-in/" (badge.kind) "?_csrf=" (csrf_token)}+ class="flex flex-col gap-3 border-neutral-200 border-t p-3" {+ (image_field(&prefix, true))+ div { (submit_button("Replace image")) }+ }+ }+ @if badge.asset_url.is_some() {+ form method="post" action={(base) "/badges/built-in/" (badge.kind) "/reset"} {+ (csrf_input(csrf_token))+ button type="submit" class=(BADGE_ACTION_BUTTON_CLASS) { "Use the built-in image" }+ }+ }+ }+ }+ }+ }+}+struct BadgePosition {first: bool,last: bool,diff --git a/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts b/fluxer_api/src/api/admin/controllers/BadgeAdminController.tsindex 0cb91c6ee..a1bcd7cf5 100644--- a/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts@@ -14,9 +14,11 @@ import {AdminACLs} from '@fluxer/constants/src/AdminACLs';import {AdminCustomBadgeListResponse,AdminCustomBadgeResponse,+ BuiltInBadgeKindParam,CreateCustomBadgeRequest,CustomBadgeIdParam,ReorderCustomBadgesRequest,+ ReplaceBuiltInBadgeImageRequest,UpdateCustomBadgeRequest,UpdateUserCustomBadgesRequest,} from '@fluxer/schema/src/domains/admin/AdminBadgeSchemas';@@ -102,6 +104,63 @@ export function BadgeAdminController(app: HonoApp) {return ctx.json(response);},);+ app.put(+ '/admin/badges/built-in/:kind',+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),+ requireAdminACL(AdminACLs.BADGE_UPDATE),+ Validator('param', BuiltInBadgeKindParam),+ Validator('json', ReplaceBuiltInBadgeImageRequest),+ OpenAPI({+ operationId: 'replace_admin_built_in_badge_image',+ summary: 'Replace built-in badge image',+ description:+ 'Shows an uploaded image everywhere a built-in profile or community badge appears. The name, tooltip and meaning of the badge stay the same. Creates audit log entry. Requires BADGE_UPDATE permission.',+ responseSchema: AdminCustomBadgeListResponse,+ statusCode: 200,+ security: 'adminApiKey',+ tags: 'Admin',+ }),+ async (ctx) => {+ const {kind} = ctx.req.valid('param');+ const response = await ctx+ .get('adminService')+ .badgeService.replaceBuiltInBadgeImage(kind, ctx.req.valid('json').image);+ await recordAdminWrite(ctx, {+ targetType: 'badge',+ targetId: 0n,+ action: 'replace_built_in_badge_image',+ metadata: {kind},+ });+ return ctx.json(response);+ },+ );+ app.delete(+ '/admin/badges/built-in/:kind',+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),+ requireAdminACL(AdminACLs.BADGE_UPDATE),+ Validator('param', BuiltInBadgeKindParam),+ OpenAPI({+ operationId: 'reset_admin_built_in_badge_image',+ summary: 'Use built-in badge image',+ description:+ 'Goes back to the built-in artwork for a built-in profile or community badge and deletes the uploaded image. Creates audit log entry. Requires BADGE_UPDATE permission.',+ responseSchema: AdminCustomBadgeListResponse,+ statusCode: 200,+ security: 'adminApiKey',+ tags: 'Admin',+ }),+ async (ctx) => {+ const {kind} = ctx.req.valid('param');+ const response = await ctx.get('adminService').badgeService.resetBuiltInBadgeImage(kind);+ await recordAdminWrite(ctx, {+ targetType: 'badge',+ targetId: 0n,+ action: 'reset_built_in_badge_image',+ metadata: {kind},+ });+ return ctx.json(response);+ },+ );app.patch('/admin/badges/:badge_id',RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),diff --git a/fluxer_api/src/api/admin/services/AdminBadgeService.ts b/fluxer_api/src/api/admin/services/AdminBadgeService.tsindex dfa41a1e6..11d28e588 100644--- a/fluxer_api/src/api/admin/services/AdminBadgeService.ts+++ b/fluxer_api/src/api/admin/services/AdminBadgeService.ts@@ -13,13 +13,24 @@ import {customBadgeAssetReferenceFromOwnUrl,customBadgeImageUrl,} from '@app/api/instance/InstanceAssetReferences';-import type {CustomBadgeDefinition, InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';+import type {+ BuiltInBadgeImages,+ CustomBadgeDefinition,+ InstanceConfigRepository,+} from '@app/api/instance/InstanceConfigRepository';+import {PROFILE_BADGE_ASSETS} from '@app/api/user/profile_badges/ProfileBadgeAssets';import type {UserRepository} from '@app/api/user/repositories/UserRepository';-import {type CustomBadgeType, MAX_CUSTOM_BADGES_PER_TYPE} from '@fluxer/constants/src/BadgeConstants';+import {+ BUILT_IN_BADGE_KINDS,+ type BuiltInBadgeKind,+ type CustomBadgeType,+ MAX_CUSTOM_BADGES_PER_TYPE,+} from '@fluxer/constants/src/BadgeConstants';import {MaxBadgesError} from '@fluxer/errors/src/domains/badge/MaxBadgesError';import {UnknownBadgeError} from '@fluxer/errors/src/domains/badge/UnknownBadgeError';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';import type {+ AdminBuiltInBadgeImageResponse,AdminCustomBadgeListResponse,AdminCustomBadgeResponse,CreateCustomBadgeRequest,@@ -48,6 +59,21 @@ function mapCustomBadgeToAdminResponse(badge: CustomBadgeDefinition): AdminCusto};}+function builtInBadgeAsset(kind: BuiltInBadgeKind): string | null {+ return kind === 'staff' || kind === 'premium' ? PROFILE_BADGE_ASSETS[kind] : null;+}++function mapBuiltInBadgeImages(images: BuiltInBadgeImages): Array<AdminBuiltInBadgeImageResponse> {+ return BUILT_IN_BADGE_KINDS.map((kind) => {+ const asset = images[kind];+ return {+ kind,+ asset_url: asset ? customBadgeImageUrl(asset, Config.endpoints.media) : null,+ built_in_asset: builtInBadgeAsset(kind),+ };+ });+}+function findBadge(badges: ReadonlyArray<CustomBadgeDefinition>, badgeId: string): CustomBadgeDefinition {const badge = badges.find((candidate) => candidate.id === badgeId);if (!badge) {@@ -78,8 +104,49 @@ export class AdminBadgeService {constructor(private readonly deps: AdminBadgeServiceDeps) {}async listBadges(): Promise<AdminCustomBadgeListResponse> {- const badges = await this.deps.instanceConfigRepository.getCustomBadges();- return {badges: badges.map(mapCustomBadgeToAdminResponse)};+ const {instanceConfigRepository} = this.deps;+ const [badges, builtIn] = await Promise.all([+ instanceConfigRepository.getCustomBadges(),+ instanceConfigRepository.getBuiltInBadgeImages(),+ ]);+ return {badges: badges.map(mapCustomBadgeToAdminResponse), built_in: mapBuiltInBadgeImages(builtIn)};+ }++ async replaceBuiltInBadgeImage(kind: BuiltInBadgeKind, image: string): Promise<AdminCustomBadgeListResponse> {+ const {instanceConfigRepository, snowflakeService} = this.deps;+ const previous = (await instanceConfigRepository.getBuiltInBadgeImages())[kind];+ const prepared = await this.uploadImage(+ await snowflakeService.generate(),+ image,+ previous ? assetReferenceHash(previous) : null,+ );+ const replaced: {asset?: string} = {};+ try {+ await instanceConfigRepository.updateBuiltInBadgeImages((current) => {+ replaced.asset = current[kind];+ return {...current, [kind]: this.storedReference(prepared)};+ });+ } catch (error) {+ await this.deps.entityAssetService.rollbackAssetUpload(prepared);+ throw error;+ }+ if (replaced.asset) {+ await this.releaseAsset(replaced.asset);+ }+ return this.listBadges();+ }++ async resetBuiltInBadgeImage(kind: BuiltInBadgeKind): Promise<AdminCustomBadgeListResponse> {+ const removed: {asset?: string} = {};+ await this.deps.instanceConfigRepository.updateBuiltInBadgeImages((current) => {+ removed.asset = current[kind];+ const {[kind]: _, ...rest} = current;+ return rest;+ });+ if (removed.asset) {+ await this.releaseAsset(removed.asset);+ }+ return this.listBadges();}async createBadge(data: CreateCustomBadgeRequest): Promise<AdminCustomBadgeResponse> {@@ -151,7 +218,10 @@ export class AdminBadgeService {}return reordered;});- return {badges: badges.map(mapCustomBadgeToAdminResponse)};+ return {+ badges: badges.map(mapCustomBadgeToAdminResponse),+ built_in: mapBuiltInBadgeImages(await this.deps.instanceConfigRepository.getBuiltInBadgeImages()),+ };}async updateUserBadges(params: {diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.tsindex 72cd178bb..8eca85c49 100644--- a/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts+++ b/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts@@ -55,6 +55,36 @@ export const BadgeAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [};},},+ {+ method: 'PUT',+ route: '/admin/badges/built-in/:kind',+ async prepare() {+ return {+ request: {path: '/admin/badges/built-in/staff', body: {image: getPngDataUrl()}},+ expected: {+ action: 'replace_built_in_badge_image',+ targetType: 'badge',+ targetId: '0',+ metadata: {kind: 'staff'},+ },+ };+ },+ },+ {+ method: 'DELETE',+ route: '/admin/badges/built-in/:kind',+ async prepare() {+ return {+ request: {path: '/admin/badges/built-in/guild_verified'},+ expected: {+ action: 'reset_built_in_badge_image',+ targetType: 'badge',+ targetId: '0',+ metadata: {kind: 'guild_verified'},+ },+ };+ },+ },{method: 'PATCH',route: '/admin/badges/:badge_id',diff --git a/fluxer_api/src/api/channel/services/message/CrosspostSourceService.ts b/fluxer_api/src/api/channel/services/message/CrosspostSourceService.tsindex 0c8bb8957..98a764234 100644--- a/fluxer_api/src/api/channel/services/message/CrosspostSourceService.ts+++ b/fluxer_api/src/api/channel/services/message/CrosspostSourceService.ts@@ -73,6 +73,7 @@ export class CrosspostSourceService {icon: partial.icon ?? null,banner: partial.banner ?? null,features: partial.features.filter((feature) => CROSSPOST_SOURCE_PUBLIC_FEATURES.has(feature)),+ badge_ids: partial.badge_ids,approximate_member_count: counts?.memberCount ?? null,approximate_presence_count: counts?.presenceCount ?? null,description,diff --git a/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts b/fluxer_api/src/api/channel/tests/CrosspostSource.test.tsindex 3a3ffdd4e..df434a095 100644--- a/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts+++ b/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts@@ -84,6 +84,7 @@ describe('Crosspost source', () => {banner: null,description: null,features: [],+ badge_ids: [],approximate_member_count: 5,approximate_presence_count: 0,discoverable: false,diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.tsindex 9e93ab1c1..811b8740f 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.ts@@ -95,7 +95,7 @@ import {} from '@fluxer/constants/src/AccountIdentityConstants';import {resolveIdentifierFirst, resolveInstantAccountAvailability} from '@fluxer/constants/src/AccountTierRules';import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {CustomBadgeTypes} from '@fluxer/constants/src/BadgeConstants';+import {BUILT_IN_BADGE_KINDS, type BuiltInBadgeKind, CustomBadgeTypes} from '@fluxer/constants/src/BadgeConstants';import {resolveSmtpTlsMode, type SmtpTlsMode} from '@fluxer/constants/src/SmtpConstants';import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';@@ -923,14 +923,23 @@ const StoredCustomBadgeSchema = z.object({href: z.string().nullable(),});+const StoredBuiltInBadgeImagesSchema = z+ .partialRecord(z.enum(BUILT_IN_BADGE_KINDS), z.string().refine(isCustomBadgeAssetReference))+ .default({});+const StoredCustomBadgesSchema = z.object({badges: z.array(StoredCustomBadgeSchema).default([]),+ built_in: StoredBuiltInBadgeImagesSchema,});export type CustomBadgeDefinition = z.infer<typeof StoredCustomBadgeSchema>;-function parseStoredCustomBadges(raw: string | null): Array<CustomBadgeDefinition> {- return parseStoredConfigOrDefault(StoredCustomBadgesSchema, raw, 'custom badges').badges;+export type BuiltInBadgeImages = Readonly<Partial<Record<BuiltInBadgeKind, string>>>;++type StoredCustomBadges = z.infer<typeof StoredCustomBadgesSchema>;++function parseStoredCustomBadges(raw: string | null): StoredCustomBadges {+ return parseStoredConfigOrDefault(StoredCustomBadgesSchema, raw, 'custom badges');}function validateStoredCollection<T>(schema: z.ZodType<T>, value: unknown, section: StoredConfigSection): Array<T> {@@ -1620,7 +1629,7 @@ export class InstanceConfigRepository {private configCache: InstanceConfigCache;private effectiveBlueskyConfig: BlueskyOAuthConfig | null = null;private effectiveBlueskyConfigSource: string | null = null;- private parsedCustomBadges: {raw: string | null; badges: ReadonlyArray<CustomBadgeDefinition>} | null = null;+ private parsedCustomBadges: {raw: string | null; stored: StoredCustomBadges} | null = null;constructor(kvClient: IKVProvider | null = null) {this.kvClient = kvClient;@@ -2153,34 +2162,56 @@ export class InstanceConfigRepository {);}- async getCustomBadges(): Promise<ReadonlyArray<CustomBadgeDefinition>> {+ private async getStoredCustomBadges(): Promise<StoredCustomBadges> {const raw = await this.getConfig(CUSTOM_BADGES_CONFIG_KEY);if (this.parsedCustomBadges?.raw !== raw) {- this.parsedCustomBadges = {raw, badges: parseStoredCustomBadges(raw)};+ this.parsedCustomBadges = {raw, stored: parseStoredCustomBadges(raw)};}- return this.parsedCustomBadges.badges;+ return this.parsedCustomBadges.stored;}- async updateCustomBadges(- update: (current: ReadonlyArray<CustomBadgeDefinition>) => Array<CustomBadgeDefinition>,- ): Promise<ReadonlyArray<CustomBadgeDefinition>> {- const config = await this.updateStoredConfig(CUSTOM_BADGES_CONFIG_KEY, (raw) =>+ async getCustomBadges(): Promise<ReadonlyArray<CustomBadgeDefinition>> {+ return (await this.getStoredCustomBadges()).badges;+ }++ async getBuiltInBadgeImages(): Promise<BuiltInBadgeImages> {+ return (await this.getStoredCustomBadges()).built_in;+ }++ private updateStoredCustomBadges(update: (current: StoredCustomBadges) => StoredCustomBadges) {+ return this.updateStoredConfig(CUSTOM_BADGES_CONFIG_KEY, (raw) =>validateStoredConfig(StoredCustomBadgesSchema,- {badges: update(parseStoredConfig(StoredCustomBadgesSchema, raw, 'custom badges').badges)},+ update(parseStoredConfig(StoredCustomBadgesSchema, raw, 'custom badges')),'custom badges',),);+ }++ async updateCustomBadges(+ update: (current: ReadonlyArray<CustomBadgeDefinition>) => Array<CustomBadgeDefinition>,+ ): Promise<ReadonlyArray<CustomBadgeDefinition>> {+ const config = await this.updateStoredCustomBadges((current) => ({...current, badges: update(current.badges)}));return config.badges;}+ async updateBuiltInBadgeImages(+ update: (current: BuiltInBadgeImages) => BuiltInBadgeImages,+ ): Promise<BuiltInBadgeImages> {+ const config = await this.updateStoredCustomBadges((current) => ({+ ...current,+ built_in: {...update(current.built_in)},+ }));+ return config.built_in;+ }+async readStoredCustomBadgeAssetKeys(): Promise<Set<string>> {const cache = this.configCache;cache.assertActive();const raw = await this.fetchConfigFromDatabase(CUSTOM_BADGES_CONFIG_KEY);cache.assertActive();- const {badges} = parseStoredConfig(StoredCustomBadgesSchema, raw, 'custom badges');- return new Set(badges.map((badge) => assetStorageKey(badge.asset)));+ const {badges, built_in: builtIn} = parseStoredConfig(StoredCustomBadgesSchema, raw, 'custom badges');+ return new Set([...badges.map((badge) => badge.asset), ...Object.values(builtIn)].map(assetStorageKey));}async getCaptchaConfig(): Promise<CaptchaConfig> {diff --git a/fluxer_api/src/api/instance/InstanceController.ts b/fluxer_api/src/api/instance/InstanceController.tsindex 1caa2f2a1..96fb2afcc 100644--- a/fluxer_api/src/api/instance/InstanceController.ts+++ b/fluxer_api/src/api/instance/InstanceController.ts@@ -9,7 +9,7 @@ import {nextDiscoveryValidators,} from '@app/api/instance/DiscoveryValidators';import {customBadgeImageUrl} from '@app/api/instance/InstanceAssetReferences';-import type {CustomBadgeDefinition} from '@app/api/instance/InstanceConfigRepository';+import type {BuiltInBadgeImages, CustomBadgeDefinition} from '@app/api/instance/InstanceConfigRepository';import {assertSetupToken} from '@app/api/instance/SetupToken';import {getStatusPageDetector} from '@app/api/instance/StatusPageDetector';import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';@@ -45,6 +45,7 @@ import {toDomainMigrationDiscovery} from '@fluxer/schema/src/domains/admin/Domaiimport {InstanceAccountIdentityResponse,InstanceAccountIdentityUpdateRequest,+ type InstanceBuiltInGuildBadgeImages,type InstanceGuildBadge,InstanceSetupTokenCheckRequest,WellKnownFluxerResponse,@@ -154,6 +155,15 @@ function listVoiceOrigins(): Array<string> {return Array.from(origins).sort();}+function mapBuiltInGuildBadgeImagesForDiscovery(images: BuiltInBadgeImages): InstanceBuiltInGuildBadgeImages {+ const url = (asset: string | undefined) => (asset ? customBadgeImageUrl(asset, Config.endpoints.media) : null);+ return {+ verified: url(images.guild_verified),+ partnered: url(images.guild_partnered),+ discoverable: url(images.guild_discoverable),+ };+}+function mapGuildBadgesForDiscovery(badges: ReadonlyArray<CustomBadgeDefinition>): Array<InstanceGuildBadge> {return badges.filter((badge) => badge.type === 'guild')@@ -200,6 +210,7 @@ export function InstanceController(app: Hono<HonoEnv>) {instantAccountAvailability,notice,customBadges,+ builtInBadgeImages,] = await Promise.all([instanceConfigRepository.getRegistrationPublicConfig(),instanceConfigRepository.getInstanceCommunityPublicConfig(),@@ -214,6 +225,7 @@ export function InstanceController(app: Hono<HonoEnv>) {instanceConfigRepository.getInstantAccountAvailability(),instanceConfigRepository.getActiveInstanceNotice(),instanceConfigRepository.getCustomBadges(),+ instanceConfigRepository.getBuiltInBadgeImages(),]);const statusPageInstatus = await getStatusPageDetector().isInstatus(appPublicConfig.branding.status_page_url);const lockReason =@@ -262,6 +274,7 @@ export function InstanceController(app: Hono<HonoEnv>) {notice,domain_migration: toDomainMigrationDiscovery(domainMigration),guild_badges: mapGuildBadgesForDiscovery(customBadges),+ built_in_guild_badge_images: mapBuiltInGuildBadgeImagesForDiscovery(builtInBadgeImages),voice_origins: listVoiceOrigins(),};discoveryValidators = nextDiscoveryValidators(response, discoveryValidators);diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.jsonindex 0d509fbf2..083a0ecaa 100644--- a/fluxer_api/src/api/openapi/openapi.json+++ b/fluxer_api/src/api/openapi/openapi.json@@ -35734,6 +35734,10 @@"items": {"$ref": "#/components/schemas/GuildFeatureSchema"},"description": "The public badge features of the source community: VERIFIED, PARTNERED and DISCOVERABLE only"},+ "badge_ids": {+ "description": "IDs of the custom badges assigned to the source community. Look them up in guild_badges of the instance discovery document",+ "$ref": "#/components/schemas/CustomBadgeIdListResponse"+ },"approximate_member_count": {"anyOf": [{"$ref": "#/components/schemas/Int32Type"}, {"type": "null"}],"description": "Approximate number of members in the source community, or null when unavailable"@@ -37854,6 +37858,10 @@"type": "array","items": {"$ref": "#/components/schemas/InstanceGuildBadgeSchema"}},+ "built_in_guild_badge_images": {+ "description": "Images this instance shows in place of the built-in verified, partnered and discoverable community badges",+ "$ref": "#/components/schemas/InstanceBuiltInGuildBadgeImagesSchema"+ },"voice_origins": {"description": "Origins of every voice server endpoint, such as wss://voice.example.com, for content security policies","maxItems": 1000,@@ -37877,6 +37885,25 @@],"additionalProperties": false},+ "InstanceBuiltInGuildBadgeImagesSchema": {+ "type": "object",+ "properties": {+ "verified": {+ "description": "URL of the image this instance shows for the badge, or null to use the built-in artwork",+ "type": ["string", "null"]+ },+ "partnered": {+ "description": "URL of the image this instance shows for the badge, or null to use the built-in artwork",+ "type": ["string", "null"]+ },+ "discoverable": {+ "description": "URL of the image this instance shows for the badge, or null to use the built-in artwork",+ "type": ["string", "null"]+ }+ },+ "required": ["verified", "partnered", "discoverable"],+ "additionalProperties": false+ },"InstanceGuildBadgeSchema": {"type": "object","properties": {@@ -40616,6 +40643,10 @@"items": {"$ref": "#/components/schemas/GuildFeatureSchema"},"description": "The public badge features of the source community: VERIFIED, PARTNERED and DISCOVERABLE only"},+ "badge_ids": {+ "description": "IDs of the custom badges assigned to the source community. Look them up in guild_badges of the instance discovery document",+ "$ref": "#/components/schemas/CustomBadgeIdListResponse"+ },"approximate_member_count": {"anyOf": [{"$ref": "#/components/schemas/Int32Type"}, {"type": "null"}],"description": "Approximate number of members in the source community, or null when unavailable"@@ -40634,6 +40665,7 @@"name","description","features",+ "badge_ids","approximate_member_count","approximate_presence_count","discoverable"diff --git a/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.test.ts b/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.test.tsindex b86555168..085b65df0 100644--- a/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.test.ts+++ b/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.test.ts@@ -21,6 +21,7 @@ const HOSTED: ProfileBadgeEnvironment = {marketingUrl: 'https://fluxer.example',mediaUrl: 'https://media.fluxer.example',customBadges: [],+ builtInImages: {},};const OCTOBER = new Date('2026-10-15T12:00:00Z');diff --git a/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.ts b/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.tsindex 7df7dfea2..bf2ba1919 100644--- a/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.ts+++ b/fluxer_api/src/api/user/profile_badges/ProfileBadgeBuilder.ts@@ -15,7 +15,12 @@ import {type ProfileBadgeView,type VisibleOperatorPass,} from '@app/api/user/profile_badges/ProfileBadgeRegistry';-import {customProfileBadgeKey, type ProfileBadgeKey, type ProfileBadgeKind} from '@fluxer/constants/src/BadgeConstants';+import {+ customProfileBadgeKey,+ isReplaceableProfileBadgeKind,+ type ProfileBadgeKey,+ type ProfileBadgeKind,+} from '@fluxer/constants/src/BadgeConstants';import {PremiumFlags, stripHiddenProfileBadgeFlags} from '@fluxer/constants/src/UserConstants';import type {AdminProfileBadgeResponse,@@ -108,14 +113,21 @@ function render(source: ViewSource | null): Array<KeyedProfileBadge> {const content = definition.qualify({...source, shown});if (!content) continue;shown.add(definition.kind);+ const replacement = isReplaceableProfileBadgeKind(definition.kind)+ ? source.environment.builtInImages[definition.kind]+ : undefined;badges.push({key: definition.kind,kind: definition.kind,label: content.label,- asset: content.asset ?? definition.asset,- asset_url: null,- ...(content.smallAsset ? {small_asset: content.smallAsset} : {}),- aspect_ratio: content.aspectRatio ?? null,+ ...(replacement+ ? {asset: null, asset_url: customBadgeImageUrl(replacement, source.environment.mediaUrl), aspect_ratio: null}+ : {+ asset: content.asset ?? definition.asset,+ asset_url: null,+ ...(content.smallAsset ? {small_asset: content.smallAsset} : {}),+ aspect_ratio: content.aspectRatio ?? null,+ }),caption: content.caption ?? null,href: definition.href(source.environment),...(content.count !== undefined ? {count: content.count} : {}),diff --git a/fluxer_api/src/api/user/profile_badges/ProfileBadgeEnvironment.ts b/fluxer_api/src/api/user/profile_badges/ProfileBadgeEnvironment.tsindex 05cc43276..6de793689 100644--- a/fluxer_api/src/api/user/profile_badges/ProfileBadgeEnvironment.ts+++ b/fluxer_api/src/api/user/profile_badges/ProfileBadgeEnvironment.ts@@ -10,12 +10,13 @@ import {CustomBadgeTypes} from '@fluxer/constants/src/BadgeConstants';export async function loadProfileBadgeEnvironment(): Promise<ProfileBadgeEnvironment> {const selfHosted = Config.instance.selfHosted;const instanceConfigRepository = getInstanceConfigRepository();- const [branding, premiumInfoUrl, customBadges] = await Promise.all([+ const [branding, premiumInfoUrl, customBadges, builtInImages] = await Promise.all([getBillingBranding(),selfHosted? instanceConfigRepository.getAppPublicConfig().then((config) => config.branding.premium_info_url): Promise.resolve(null),instanceConfigRepository.getCustomBadges(),+ instanceConfigRepository.getBuiltInBadgeImages(),]);return {selfHosted,@@ -26,5 +27,6 @@ export async function loadProfileBadgeEnvironment(): Promise<ProfileBadgeEnvironmarketingUrl: Config.endpoints.marketing,mediaUrl: Config.endpoints.media,customBadges: customBadges.filter((badge) => badge.type === CustomBadgeTypes.USER),+ builtInImages,};}diff --git a/fluxer_api/src/api/user/profile_badges/ProfileBadgeRegistry.ts b/fluxer_api/src/api/user/profile_badges/ProfileBadgeRegistry.tsindex 54a2cda54..7ffe70d56 100644--- a/fluxer_api/src/api/user/profile_badges/ProfileBadgeRegistry.ts+++ b/fluxer_api/src/api/user/profile_badges/ProfileBadgeRegistry.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {getContentMessage} from '@app/api/content_i18n/ContentI18n';-import type {CustomBadgeDefinition} from '@app/api/instance/InstanceConfigRepository';+import type {BuiltInBadgeImages, CustomBadgeDefinition} from '@app/api/instance/InstanceConfigRepository';import {Logger} from '@app/api/Logger';import type {VisiblePremiumBadge} from '@app/api/user/profile_badges/PremiumBadgeMasking';import {@@ -23,6 +23,7 @@ export interface ProfileBadgeEnvironment {marketingUrl: string;mediaUrl: string;customBadges: ReadonlyArray<CustomBadgeDefinition>;+ builtInImages: BuiltInBadgeImages;}export interface VisibleOperatorPass {diff --git a/fluxer_app/src/features/app/state/InstanceSnapshotStore.ts b/fluxer_app/src/features/app/state/InstanceSnapshotStore.tsindex 733550169..aeb44593b 100644--- a/fluxer_app/src/features/app/state/InstanceSnapshotStore.ts+++ b/fluxer_app/src/features/app/state/InstanceSnapshotStore.ts@@ -121,6 +121,7 @@ export function runtimeSnapshotFromDiscovery(document: InstanceDiscoveryDocumentdomainMigration: discovery.domainMigration,notice: discovery.notice ?? null,guildBadges: discovery.guildBadges,+ builtInGuildBadgeImages: discovery.builtInGuildBadgeImages,});}diff --git a/fluxer_app/src/features/app/state/RuntimeConfig.ts b/fluxer_app/src/features/app/state/RuntimeConfig.tsindex 0f86b245e..9641c6047 100644--- a/fluxer_app/src/features/app/state/RuntimeConfig.ts+++ b/fluxer_app/src/features/app/state/RuntimeConfig.ts@@ -48,11 +48,13 @@ import {} from '@fluxer/constants/src/AccountIdentityConstants';import {resolveEffectiveVerificationBasis, resolveEmailCodeAvailability} from '@fluxer/constants/src/AccountTierRules';import {API_CODE_VERSION} from '@fluxer/constants/src/AppConstants';+import {NO_BUILT_IN_GUILD_BADGE_IMAGES} from '@fluxer/instance_bootstrap/src/ClientRuntimeDiscovery';import {InstanceDiscoveryUnreachableError} from '@fluxer/instance_bootstrap/src/Discovery';import {InstanceEndpointKind, normalizeInstanceEndpoint} from '@fluxer/instance_bootstrap/src/EndpointNormalization';import {isOfficialInstanceHost, OFFICIAL_INSTANCE_DISPLAY_HOST} from '@fluxer/instance_bootstrap/src/OfficialInstance';import type {InstanceAppPublic,+ InstanceBuiltInGuildBadgeImages,InstanceCommunity,InstanceFeatures,InstanceGuildBadge,@@ -684,6 +686,7 @@ class RuntimeConfig {appPublic: resolution.snapshot.appPublic,notice: resolution.snapshot.notice,guildBadges: resolution.snapshot.guildBadges,+ builtInGuildBadgeImages: resolution.snapshot.builtInGuildBadgeImages,limits: resolution.snapshot.limits,});this.activeRuntime = {...runtime, snapshot: usable};@@ -921,6 +924,10 @@ class RuntimeConfig {return this.activeRuntime?.snapshot.guildBadges ?? [];}+ get builtInGuildBadgeImages(): InstanceBuiltInGuildBadgeImages {+ return this.activeRuntime?.snapshot.builtInGuildBadgeImages ?? NO_BUILT_IN_GUILD_BADGE_IMAGES;+ }+get gifEnabled(): boolean {return this.services.gif_enabled;}diff --git a/fluxer_app/src/features/app/state/RuntimeConfigSnapshot.ts b/fluxer_app/src/features/app/state/RuntimeConfigSnapshot.tsindex 40ce32a2a..064b4fc47 100644--- a/fluxer_app/src/features/app/state/RuntimeConfigSnapshot.ts+++ b/fluxer_app/src/features/app/state/RuntimeConfigSnapshot.ts@@ -15,6 +15,7 @@ import {TagStyles,} from '@fluxer/constants/src/AccountIdentityConstants';import {LIMIT_KEYS, type LimitKey} from '@fluxer/constants/src/LimitConfigMetadata';+import {NO_BUILT_IN_GUILD_BADGE_IMAGES} from '@fluxer/instance_bootstrap/src/ClientRuntimeDiscovery';import {ACCOUNT_DELETION_GRACE_PERIOD_HOURS_MAX,ACCOUNT_DELETION_GRACE_PERIOD_HOURS_MIN,@@ -30,6 +31,7 @@ import {type InstanceAgePolicy,type InstanceAgePolicyGeo,type InstanceAppPublic,+ type InstanceBuiltInGuildBadgeImages,type InstanceCommunity,type InstanceDomainMigration,type InstanceFeatures,@@ -76,6 +78,7 @@ export interface RuntimeConfigSnapshot extends RuntimeConfigIdentity {readonly domainMigration: InstanceDomainMigration | null;readonly notice: InstanceNotice | null;readonly guildBadges: ReadonlyArray<InstanceGuildBadge>;+ readonly builtInGuildBadgeImages: InstanceBuiltInGuildBadgeImages;}export class InvalidRuntimeConfigSnapshotError extends Error {@@ -587,6 +590,16 @@ function readGuildBadges(value: unknown): Array<InstanceGuildBadge> {});}+function readBuiltInGuildBadgeImages(value: unknown): InstanceBuiltInGuildBadgeImages {+ if (value === undefined) {+ return NO_BUILT_IN_GUILD_BADGE_IMAGES;+ }+ const source = readRecord(value, 'builtInGuildBadgeImages');+ const read = (key: keyof InstanceBuiltInGuildBadgeImages) =>+ source[key] === undefined ? null : readNullableNonEmptyString(source, key, `builtInGuildBadgeImages.${key}`);+ return {verified: read('verified'), partnered: read('partnered'), discoverable: read('discoverable')};+}+export function requireRuntimeConfigSnapshot(value: unknown): RuntimeConfigSnapshot {const source = readRecord(value, 'root');return {@@ -617,5 +630,6 @@ export function requireRuntimeConfigSnapshot(value: unknown): RuntimeConfigSnapsdomainMigration: parseInstanceDomainMigration(source.domainMigration),notice: readNotice(source.notice),guildBadges: readGuildBadges(source.guildBadges),+ builtInGuildBadgeImages: readBuiltInGuildBadgeImages(source.builtInGuildBadgeImages),};}diff --git a/fluxer_app/src/features/channel/components/CrosspostCommunityCard.tsx b/fluxer_app/src/features/channel/components/CrosspostCommunityCard.tsxindex 6b529ad1e..09db50c0c 100644--- a/fluxer_app/src/features/channel/components/CrosspostCommunityCard.tsx+++ b/fluxer_app/src/features/channel/components/CrosspostCommunityCard.tsx@@ -54,6 +54,7 @@ interface CommunityCardData {banner: string | null;description: string | null;features: ReadonlySet<string> | ReadonlyArray<string>;+ badgeIds: ReadonlyArray<string>;onlineCount: number | null;memberCount: number | null;isMember: boolean;@@ -90,6 +91,7 @@ function useCommunityCardView(message: Message, sourceGuildId: string | null): Cbanner: localGuild.banner,description: fetched?.description ?? null,features: localGuild.features,+ badgeIds: localGuild.badgeIds,onlineCount: counts?.onlineCount ?? null,memberCount: counts?.memberCount ?? null,isMember: true,@@ -116,6 +118,7 @@ function useCommunityCardView(message: Message, sourceGuildId: string | null): Cbanner: card.banner ?? null,description: card.description ?? null,features: card.features,+ badgeIds: card.badge_ids,onlineCount: card.approximate_presence_count,memberCount: card.approximate_member_count,isMember: false,@@ -199,6 +202,7 @@ export const CrosspostCommunityCard = observer(function CrosspostCommunityCard({{data != null && (<GuildBadgefeatures={data.features}+ badgeIds={data.badgeIds}tooltipPosition="bottom"data-flx="channel.crosspost-community-card.guild-badge"/>diff --git a/fluxer_app/src/features/guild/components/GuildBadge.tsx b/fluxer_app/src/features/guild/components/GuildBadge.tsxindex a84f94e50..3f0e333bd 100644--- a/fluxer_app/src/features/guild/components/GuildBadge.tsx+++ b/fluxer_app/src/features/guild/components/GuildBadge.tsx@@ -9,6 +9,7 @@ import {VerifiedBadgeIcon} from '@app/features/ui/components/icons/VerifiedBadgeimport {Tooltip} from '@app/features/ui/tooltip/Tooltip';import {handleExternalLinkClick} from '@app/features/ui/utils/NativeUtils';import {customBadgeImageUrl} from '@app/features/user/utils/ProfileUtils';+import type {BuiltInGuildBadgeKind} from '@fluxer/constants/src/BadgeConstants';import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';import type {InstanceGuildBadge} from '@fluxer/instance_bootstrap/src/Types';import {msg} from '@lingui/core/macro';@@ -161,14 +162,17 @@ const BuiltInGuildBadge = observer(function BuiltInGuildBadge({} else {badgeClassName = onLightSurface ? styles.badgeOnLightSurface : styles.badge;}+ let kind: BuiltInGuildBadgeKind = 'discoverable';let tooltipText: string;let icon: React.JSX.Element;if (isPartnered) {+ kind = 'partnered';tooltipText = isVerified ? i18n._(VERIFIED_PARTNERED_COMMUNITY_DESCRIPTOR) : i18n._(PARTNERED_COMMUNITY_DESCRIPTOR);icon = (<PartneredBadgeIcon size={size} className={badgeClassName} data-flx="guild.guild-badge.partnered-badge-icon" />);} else if (isVerified) {+ kind = 'verified';tooltipText = i18n._(VERIFIED_COMMUNITY_DESCRIPTOR);icon = (<VerifiedBadgeIcon size={size} className={badgeClassName} data-flx="guild.guild-badge.verified-badge-icon" />@@ -183,6 +187,19 @@ const BuiltInGuildBadge = observer(function BuiltInGuildBadge({/>);}+ const replacement = RuntimeConfig.builtInGuildBadgeImages[kind];+ if (replacement !== null) {+ icon = (+ <img+ src={customBadgeImageUrl(replacement)}+ alt={tooltipText}+ width={size}+ height={size}+ className={styles.customBadge}+ data-flx="guild.guild-badge.replaced-badge-image"+ />+ );+ }if (!showTooltip) {return icon;}@@ -207,26 +224,28 @@ export const GuildBadge = observer(function GuildBadge({onLightSurface = false,}: GuildBadgeProps) {const size = variant === 'large' ? 24 : 20;+ const builtIn = (+ <BuiltInGuildBadge+ features={features}+ variant={variant}+ size={size}+ tooltipPosition={tooltipPosition}+ showTooltip={showTooltip}+ forceDarkTheme={forceDarkTheme}+ onLightSurface={onLightSurface}+ data-flx="guild.guild-badge.built-in-guild-badge"+ />+ );useEffect(() => {if (badgeIds.length > 0) revalidateUnknownBadges(badgeIds);}, [badgeIds]);const customBadges = assignedCustomBadges(badgeIds).slice(0, customBadgeLimit);if (customBadges.length === 0) {- return (- <BuiltInGuildBadge- features={features}- variant={variant}- size={size}- tooltipPosition={tooltipPosition}- showTooltip={showTooltip}- forceDarkTheme={forceDarkTheme}- onLightSurface={onLightSurface}- data-flx="guild.guild-badge.built-in-guild-badge"- />- );+ return builtIn;}return (<span className={styles.badgeRow} data-flx="guild.guild-badge.badge-row">+ {builtIn}{customBadges.map((badge) => (<CustomGuildBadgekey={badge.id}diff --git a/fluxer_docs/src/content/docs/admin-api/badges.mdx b/fluxer_docs/src/content/docs/admin-api/badges.mdxindex de62e5cab..58bdc56e0 100644--- a/fluxer_docs/src/content/docs/admin-api/badges.mdx+++ b/fluxer_docs/src/content/docs/admin-api/badges.mdx@@ -6,7 +6,9 @@ description: Admin API routes for making custom badges and giving them to usersimport RouteHeader from '@/components/RouteHeader.astro';-A custom badge is an image that instance admins make and give out. A user badge shows on the [profile](/http-api/users/#profile-badge-object) of each account it's given to, after the built-in badges. A guild badge shows next to the guild name in place of its verified, partnered or discoverable badge, and [instance discovery](/http-api/instance/#guild-badge-object) lists every guild badge for clients.+A custom badge is an image that instance admins make and give out. A user badge shows on the [profile](/http-api/users/#profile-badge-object) of each account it's given to, after the built-in badges. A guild badge shows next to the guild name, after its verified, partnered or discoverable badge, and [instance discovery](/http-api/instance/#guild-badge-object) lists every guild badge for clients.++Admins can also replace the image of a built-in badge: staff or premium on profiles, and verified, partnered or discoverable on guilds. The badge keeps its name, tooltip and meaning, and everyone sees the new image in its place. See [Replace built-in badge image](#replace-built-in-badge-image).You can make up to 100 badges of each type, and an account or guild can have up to 10. Give badges with [Update user badges](/admin-api/users/#update-user-badges) and the `badge_ids` field of [Update guild](/admin-api/guilds/#update-guild). Deleting a badge takes it off everyone who had it. You can change the display order with [Reorder badges](#reorder-badges) or the Move up and Move down buttons on the Badges page of the admin panel.@@ -36,6 +38,18 @@ You can make up to 100 badges of each type, and an account or guild can have up}```+## Built-in badge image object++### Structure++| Field | Type | Description |+| --- | --- | --- |+| kind | string | The built-in badge<sup>1</sup> |+| asset_url | ?string | The replacement image as WebP from the media proxy, or null when the built-in image is used |+| built_in_asset | ?string | The hash of the built-in image at `{static_cdn}/badges/{hash}.webp`, or null for a guild badge, which clients draw themselves |++<sup>1</sup> One of the profile badges `staff` and `premium`, or one of the guild badges `guild_verified`, `guild_partnered` and `guild_discoverable`+## List badges<RouteHeader method="GET" path="/v1/admin/badges" auditReason />@@ -47,6 +61,7 @@ Returns every custom badge in display order. A new badge goes to the end. You ne| Field | Type | Description || --- | --- | --- || badges | array[[Admin custom badge](#admin-custom-badge-object) object] | The badges of both types |+| built_in | array[[Built-in badge image](#built-in-badge-image-object) object] | Every built-in badge and the image the instance shows for it |### Response@@ -144,6 +159,7 @@ Sets the display order of the custom badges and returns them in the new order. S| Field | Type | Description || --- | --- | --- || badges | array[[Admin custom badge](#admin-custom-badge-object) object] | The badges of both types in the new order |+| built_in | array[[Built-in badge image](#built-in-badge-image-object) object] | Every built-in badge and the image the instance shows for it |### Response@@ -154,3 +170,42 @@ Sets the display order of the custom badges and returns them in the new order. S| 404 | [error response](/admin-api/#error-response) | `UNKNOWN_BADGE` when an ID isn't a badge on the instance |The rate limit is 100 requests per minute, on the `admin:user:modify` bucket.++## Replace built-in badge image++<RouteHeader method="PUT" path="/v1/admin/badges/built-in/{kind}" auditReason />++Uploads an image and shows it everywhere the built-in badge appears, then returns the same body as [List badges](#list-badges). Profiles and guilds keep the badge, its tooltip and its link. You need `badge:update`.++### JSON body++| Field | Type | Description |+| --- | --- | --- |+| image<sup>1</sup> | string | The image as a base64 data URI (up to 16000000 characters) |++<sup>1</sup> The same formats and limits as [Create badge](#create-badge)++### Response++| Status | Body | Condition |+| --- | --- | --- |+| 200 | [List badges](#list-badges) response body | The image was replaced |+| 400 | [error response](/admin-api/#error-response) | `INVALID_FORM_BODY` for an unknown `kind` |+| 400 | [error response](/admin-api/#error-response) | `IMAGE_SIZE_EXCEEDS_LIMIT`, `INVALID_IMAGE_FORMAT` or `FAILED_TO_UPLOAD_IMAGE` for a bad image |++The rate limit is 100 requests per minute, on the `admin:user:modify` bucket.++## Use built-in badge image++<RouteHeader method="DELETE" path="/v1/admin/badges/built-in/{kind}" auditReason />++Goes back to the built-in image for a badge, deletes the uploaded one and returns the same body as [List badges](#list-badges). You need `badge:update`.++### Response++| Status | Body | Condition |+| --- | --- | --- |+| 200 | [List badges](#list-badges) response body | The built-in image is used again |+| 400 | [error response](/admin-api/#error-response) | `INVALID_FORM_BODY` for an unknown `kind` |++The rate limit is 100 requests per minute, on the `admin:user:modify` bucket.diff --git a/fluxer_docs/src/content/docs/http-api/instance.mdx b/fluxer_docs/src/content/docs/http-api/instance.mdxindex 66d247aca..b8acb6ab2 100644--- a/fluxer_docs/src/content/docs/http-api/instance.mdx+++ b/fluxer_docs/src/content/docs/http-api/instance.mdx@@ -32,6 +32,7 @@ The public description of one instance.| age_policy? | [age policy](#age-policy-object) object | Regional age policy || notice? | ?[instance notice](#instance-notice-object) object | The current notice from the instance admins, or null || guild_badges? | array[[guild badge](#guild-badge-object) object] | The custom badges that guilds can show next to their name, in display order (at most 10) |+| built_in_guild_badge_images? | [built-in guild badge images](#built-in-guild-badge-images-object) object | The images the instance shows in place of the built-in guild badges || voice_origins? | array[string] | The origin of every voice server endpoint, such as `wss://voice.example.com`, for content security policies (at most 1000) |## Guild badge object@@ -48,6 +49,18 @@ A custom badge that instance admins give to guilds. A guild lists the badges it| asset_url | string | The badge image as WebP from the media proxy. Add a `size` query parameter to get it at the size you draw it || href | ?string | The `https` URL a click opens, or null |+## Built-in guild badge images object++Instance admins can replace the artwork of the built-in guild badges. When a field has a URL, draw that image wherever the badge appears and keep the badge's usual tooltip. When it's null, draw the built-in artwork.++### Structure++| Field | Type | Description |+| --- | --- | --- |+| verified | ?string | The image for the verified badge, as WebP from the media proxy, or null |+| partnered | ?string | The image for the partnered badge, or null |+| discoverable | ?string | The image for the discoverable badge, or null |+## Instance notice objectA short message from the instance admins, such as planned maintenance, that people can dismiss.diff --git a/fluxer_docs/src/content/docs/http-api/messages.mdx b/fluxer_docs/src/content/docs/http-api/messages.mdxindex c3b8ca79c..124e6613e 100644--- a/fluxer_docs/src/content/docs/http-api/messages.mdx+++ b/fluxer_docs/src/content/docs/http-api/messages.mdx@@ -709,6 +709,7 @@ To get the next page, set `before` to the `pinned_at` of the last item. Skip mes| banner | ?string | The guild banner hash || description | ?string | The discovery description, or null when the guild isn't in discovery || features | array of strings | `VERIFIED`, `PARTNERED` and `DISCOVERABLE` from [guild features](/http-api/guilds/#guild-features) |+| badge_ids | array[snowflake] | The [custom badges](/http-api/instance/#guild-badge-object) of the guild || approximate_member_count | ?integer | About how many members the guild has || approximate_presence_count | ?integer | About how many members are online || discoverable | boolean | Whether you can join through [Join discovery guild](/http-api/discovery/#join-discovery-guild) |diff --git a/fluxer_docs/src/content/docs/http-api/users.mdx b/fluxer_docs/src/content/docs/http-api/users.mdxindex f2bb570a1..dc402e774 100644--- a/fluxer_docs/src/content/docs/http-api/users.mdx+++ b/fluxer_docs/src/content/docs/http-api/users.mdx@@ -519,8 +519,8 @@ One badge on a [full user profile](#full-user-profile-object). The API picks the| key | string | The badge's identity, equal to `kind` for built-in badges and `custom:{id}` for a custom badge. Use it as the list key || kind<sup>1</sup> | string | The badge type || label | string | The badge description in your locale, for the tooltip and alt text. A custom badge uses its name |-| asset<sup>2</sup> | ?string | The 16-character hex hash of the badge image, or null for a text badge or a custom badge |-| asset_url<sup>3</sup> | ?string | The image URL of a custom badge, or null for other badges |+| asset<sup>2</sup> | ?string | The 16-character hex hash of the badge image, or null for a text badge, a custom badge or a built-in badge with a replaced image |+| asset_url<sup>3</sup> | ?string | The image URL of a custom badge or of a built-in badge whose image the instance admins replaced, or null for other badges || aspect_ratio | ?number | Image width divided by height, or null for a square badge || caption | ?string | Short text the badge stands for, shown in place of the image when `asset` is null || href | ?string | The URL a click opens, or null |diff --git a/fluxer_docs/src/content/docs/http-api/users/current-user.mdx b/fluxer_docs/src/content/docs/http-api/users/current-user.mdxindex e6c707f4e..fb786ea47 100644--- a/fluxer_docs/src/content/docs/http-api/users/current-user.mdx+++ b/fluxer_docs/src/content/docs/http-api/users/current-user.mdx@@ -398,8 +398,8 @@ A [profile badge](/http-api/users/#profile-badge-object) with a `hidden` field.| key | string | The badge's identity, and the value to put in `hidden_profile_badges` || kind | string | The badge type || label | string | The badge description in your locale |-| asset | ?string | The badge image hash, or null for a text badge or a custom badge |-| asset_url | ?string | The image URL of a custom badge |+| asset | ?string | The badge image hash, or null for a text badge, a custom badge or a built-in badge with a replaced image |+| asset_url | ?string | The image URL of a custom badge or of a built-in badge with a replaced image || aspect_ratio | ?number | The image width divided by its height || caption | ?string | The short badge text, such as `#42` || href | ?string | The URL a click opens |diff --git a/packages/constants/src/BadgeConstants.ts b/packages/constants/src/BadgeConstants.tsindex 6448ce865..4d768bfab 100644--- a/packages/constants/src/BadgeConstants.ts+++ b/packages/constants/src/BadgeConstants.ts@@ -30,6 +30,27 @@ export type ProfileBadgeKey = ProfileBadgeKind | `custom:${string}`;export const MAX_HIDDEN_PROFILE_BADGES = PROFILE_BADGE_KINDS.length + MAX_CUSTOM_BADGES_PER_ENTITY;+const BUILT_IN_GUILD_BADGE_KINDS = ['verified', 'partnered', 'discoverable'] as const;++export type BuiltInGuildBadgeKind = (typeof BUILT_IN_GUILD_BADGE_KINDS)[number];++const REPLACEABLE_PROFILE_BADGE_KINDS = ['staff', 'premium'] as const satisfies ReadonlyArray<ProfileBadgeKind>;++export type ReplaceableProfileBadgeKind = (typeof REPLACEABLE_PROFILE_BADGE_KINDS)[number];++export type BuiltInBadgeKind = ReplaceableProfileBadgeKind | `guild_${BuiltInGuildBadgeKind}`;++export const BUILT_IN_BADGE_KINDS = [+ ...REPLACEABLE_PROFILE_BADGE_KINDS,+ 'guild_verified',+ 'guild_partnered',+ 'guild_discoverable',+] as const satisfies ReadonlyArray<BuiltInBadgeKind>;++export function isReplaceableProfileBadgeKind(kind: ProfileBadgeKind): kind is ReplaceableProfileBadgeKind {+ return (REPLACEABLE_PROFILE_BADGE_KINDS as ReadonlyArray<string>).includes(kind);+}+export const PREMIUM_PROFILE_BADGE_KINDS: ReadonlyArray<ProfileBadgeKind> = ['plutonium', 'visionary', 'premium'];const CUSTOM_PROFILE_BADGE_KEY_PREFIX = 'custom:';diff --git a/packages/instance_bootstrap/src/ClientRuntimeDiscovery.ts b/packages/instance_bootstrap/src/ClientRuntimeDiscovery.tsindex 42ebcbbc8..e15aecb88 100644--- a/packages/instance_bootstrap/src/ClientRuntimeDiscovery.ts+++ b/packages/instance_bootstrap/src/ClientRuntimeDiscovery.ts@@ -8,6 +8,7 @@ import {import type {InstanceAgePolicy,InstanceAppPublic,+ InstanceBuiltInGuildBadgeImages,InstanceCommunity,InstanceDomainMigration,InstanceFeatures,@@ -23,6 +24,12 @@ import type {LimitConfigSnapshot, LimitConfigWireFormat} from '@fluxer/limits/srconst DEFAULT_PREMIUM_PRODUCT_NAME = 'Plutonium';+export const NO_BUILT_IN_GUILD_BADGE_IMAGES: InstanceBuiltInGuildBadgeImages = {+ verified: null,+ partnered: null,+ discoverable: null,+};+export interface ClientRuntimeDiscoveryEndpoints {readonly discoveryApiEndpoint: string;readonly apiEndpoint: string;@@ -56,6 +63,7 @@ export interface ClientRuntimeDiscovery {readonly domainMigration: InstanceDomainMigration | null;readonly notice?: InstanceNotice | null;readonly guildBadges: ReadonlyArray<InstanceGuildBadge>;+ readonly builtInGuildBadgeImages: InstanceBuiltInGuildBadgeImages;}export function projectClientRuntimeDiscovery(document: InstanceDiscoveryDocument): ClientRuntimeDiscovery {@@ -76,6 +84,7 @@ export function projectClientRuntimeDiscovery(document: InstanceDiscoveryDocumendomainMigration: document.domainMigration,notice: document.notice ?? null,guildBadges: document.guildBadges ?? [],+ builtInGuildBadgeImages: document.builtInGuildBadgeImages ?? NO_BUILT_IN_GUILD_BADGE_IMAGES,};}diff --git a/packages/instance_bootstrap/src/Discovery.ts b/packages/instance_bootstrap/src/Discovery.tsindex 4b0ea6e26..a2872724e 100644--- a/packages/instance_bootstrap/src/Discovery.ts+++ b/packages/instance_bootstrap/src/Discovery.ts@@ -24,6 +24,7 @@ import {type InstanceAgePolicyGeo,type InstanceAppRegistration,type InstanceBranding,+ type InstanceBuiltInGuildBadgeImages,type InstanceCommunity,type InstanceDomainMigration,type InstanceFeatures,@@ -145,6 +146,7 @@ export interface InstanceDiscoveryDocument {readonly domainMigration: InstanceDomainMigration | null;readonly notice?: InstanceNotice | null;readonly guildBadges?: ReadonlyArray<InstanceGuildBadge>;+ readonly builtInGuildBadgeImages?: InstanceBuiltInGuildBadgeImages;}interface InstanceDiscoveryAttempt {@@ -308,6 +310,7 @@ export function parseInstanceDiscoveryDocument(payload: unknown): InstanceDiscovdomainMigration: parseInstanceDomainMigration(source.domain_migration),notice: parseNotice(source.notice),guildBadges: parseGuildBadges(source.guild_badges),+ builtInGuildBadgeImages: parseBuiltInGuildBadgeImages(source.built_in_guild_badge_images),};}@@ -697,6 +700,15 @@ function parseNotice(value: unknown): InstanceNotice | null {};}+function parseBuiltInGuildBadgeImages(value: unknown): InstanceBuiltInGuildBadgeImages {+ const source = asRecord(value) ?? {};+ return {+ verified: readNonEmptyString(source, 'verified'),+ partnered: readNonEmptyString(source, 'partnered'),+ discoverable: readNonEmptyString(source, 'discoverable'),+ };+}+function parseGuildBadges(value: unknown): Array<InstanceGuildBadge> {if (!Array.isArray(value)) {return [];diff --git a/packages/instance_bootstrap/src/Types.ts b/packages/instance_bootstrap/src/Types.tsindex b5669c913..c82dbf4bd 100644--- a/packages/instance_bootstrap/src/Types.ts+++ b/packages/instance_bootstrap/src/Types.ts@@ -20,6 +20,7 @@ export type {InstanceAgePolicyGeo,InstanceAppPublic,InstanceBranding,+ InstanceBuiltInGuildBadgeImages,InstanceCaptcha,InstanceCommunity,InstanceEndpoints,diff --git a/packages/schema/src/domains/admin/AdminBadgeSchemas.ts b/packages/schema/src/domains/admin/AdminBadgeSchemas.tsindex a00955488..d139a5ef5 100644--- a/packages/schema/src/domains/admin/AdminBadgeSchemas.ts+++ b/packages/schema/src/domains/admin/AdminBadgeSchemas.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {+ BUILT_IN_BADGE_KINDS,CUSTOM_BADGE_DESCRIPTION_MAX_LENGTH,CUSTOM_BADGE_NAME_MAX_LENGTH,CustomBadgeTypes,@@ -50,8 +51,37 @@ export const AdminCustomBadgeResponse = z.object({export type AdminCustomBadgeResponse = z.infer<typeof AdminCustomBadgeResponse>;+export const BuiltInBadgeKindSchema = withOpenApiType(+ z+ .enum(BUILT_IN_BADGE_KINDS)+ .describe(+ 'A built-in badge whose image can be replaced: the staff or premium profile badge, or a community badge starting with guild_',+ ),+ 'BuiltInBadgeKind',+);++export const AdminBuiltInBadgeImageResponse = z.object({+ kind: BuiltInBadgeKindSchema,+ asset_url: z+ .string()+ .nullable()+ .describe('URL of the image shown in place of the built-in artwork, or null when the built-in artwork is used'),+ built_in_asset: z+ .string()+ .nullable()+ .describe(+ 'Hash of the built-in artwork at {static_cdn}/badges/{hash}.webp, or null for a guild badge, which clients draw themselves',+ ),+});++export type AdminBuiltInBadgeImageResponse = z.infer<typeof AdminBuiltInBadgeImageResponse>;+export const AdminCustomBadgeListResponse = z.object({badges: z.array(AdminCustomBadgeResponse).describe('Badges defined on this instance, in display order'),+ built_in: z+ .array(AdminBuiltInBadgeImageResponse)+ .max(BUILT_IN_BADGE_KINDS.length)+ .describe('Every built-in badge and the image this instance shows for it'),});export type AdminCustomBadgeListResponse = z.infer<typeof AdminCustomBadgeListResponse>;@@ -109,3 +139,13 @@ export const CustomBadgeIdListResponse = z.array(SnowflakeStringType).max(MAX_CUSTOM_BADGES_PER_ENTITY).describe('IDs of the custom badges assigned to it');++export const BuiltInBadgeKindParam = z.object({+ kind: BuiltInBadgeKindSchema,+});++export const ReplaceBuiltInBadgeImageRequest = z.object({+ image: CustomBadgeImageType,+});++export type ReplaceBuiltInBadgeImageRequest = z.infer<typeof ReplaceBuiltInBadgeImageRequest>;diff --git a/packages/schema/src/domains/instance/InstanceSchemas.ts b/packages/schema/src/domains/instance/InstanceSchemas.tsindex a2f136157..14007190f 100644--- a/packages/schema/src/domains/instance/InstanceSchemas.ts+++ b/packages/schema/src/domains/instance/InstanceSchemas.ts@@ -399,6 +399,19 @@ export const InstanceGuildBadgeSchema = z.object({export type InstanceGuildBadge = z.infer<typeof InstanceGuildBadgeSchema>;+const BuiltInGuildBadgeImageType = z+ .string()+ .nullable()+ .describe('URL of the image this instance shows for the badge, or null to use the built-in artwork');++export const InstanceBuiltInGuildBadgeImagesSchema = z.object({+ verified: BuiltInGuildBadgeImageType,+ partnered: BuiltInGuildBadgeImageType,+ discoverable: BuiltInGuildBadgeImageType,+});++export type InstanceBuiltInGuildBadgeImages = z.infer<typeof InstanceBuiltInGuildBadgeImagesSchema>;+export const WellKnownFluxerResponse = z.object({codename: z.string().optional().describe('Protocol generation spoken by this instance'),api_code_version: z.number().int().describe('Version of the API server code'),@@ -425,6 +438,9 @@ export const WellKnownFluxerResponse = z.object({.max(MAX_CUSTOM_BADGES_PER_TYPE).optional().describe('Custom badges that communities on this instance can show next to their name, in display order'),+ built_in_guild_badge_images: InstanceBuiltInGuildBadgeImagesSchema.optional().describe(+ 'Images this instance shows in place of the built-in verified, partnered and discoverable community badges',+ ),voice_origins: z.array(z.string()).max(1000)diff --git a/packages/schema/src/domains/message/CrosspostSourceSchemas.ts b/packages/schema/src/domains/message/CrosspostSourceSchemas.tsindex f977d0f43..d555a72cf 100644--- a/packages/schema/src/domains/message/CrosspostSourceSchemas.ts+++ b/packages/schema/src/domains/message/CrosspostSourceSchemas.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {CustomBadgeIdListResponse} from '@fluxer/schema/src/domains/admin/AdminBadgeSchemas';import {GuildFeatureSchema} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';import {Int32Type, SnowflakeStringType} from '@fluxer/schema/src/primitives/SchemaPrimitives';import {z} from 'zod';@@ -16,6 +17,9 @@ export const CrosspostSourceGuildResponse = z.object({features: z.array(GuildFeatureSchema).describe('The public badge features of the source community: VERIFIED, PARTNERED and DISCOVERABLE only'),+ badge_ids: CustomBadgeIdListResponse.describe(+ 'IDs of the custom badges assigned to the source community. Look them up in guild_badges of the instance discovery document',+ ),approximate_member_count: Int32Type.nullable().describe('Approximate number of members in the source community, or null when unavailable',),