Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat: add social links management to app settings

Ahmet Ömerf8b728d46490
diff --git a/apps/self-hosted/server/services/settings/contants.ts b/apps/self-hosted/server/services/settings/contants.ts
index ba190119..119855d7 100644
--- a/apps/self-hosted/server/services/settings/contants.ts
+++ b/apps/self-hosted/server/services/settings/contants.ts
@@ -89,6 +89,13 @@ export const DEFAULT_SETTINGS = [
description: 'settings.app.homeView.description',
isPublic: true,
},
+ {
+ namespace: 'app',
+ key: 'socialLinks',
+ type: 'json',
+ defaultValue: { links: [] },
+ isPublic: true,
+ },
{
namespace: 'app',
key: 'appearance.theme',
diff --git a/packages/console/app/composables/useSettingsForm.ts b/packages/console/app/composables/useSettingsForm.ts
index ad29c4b1..77785d31 100644
--- a/packages/console/app/composables/useSettingsForm.ts
+++ b/packages/console/app/composables/useSettingsForm.ts
@@ -84,10 +84,19 @@ export function useSettingsForm(namespace: string) {
value,
}))
- await consoleApi('/api/system/settings/batch', {
+ const result = await consoleApi<{
+ success: boolean
+ errors?: Array<{ error: string }>
+ }>('/api/system/settings/batch', {
method: 'PUT',
body: { updates },
})
+ if (!result.success) {
+ throw new Error(
+ result.errors?.map((item) => item.error).join('; ') ||
+ t('settings.form.saveFailed'),
+ )
+ }
// 刷新全局设置状态,确保所有使用 getSetting() 的地方都能获取到最新值
await refreshSettings()
diff --git a/packages/console/app/pages/dashboard/settings/general.vue b/packages/console/app/pages/dashboard/settings/general.vue
index db76c6f9..259c3169 100644
--- a/packages/console/app/pages/dashboard/settings/general.vue
+++ b/packages/console/app/pages/dashboard/settings/general.vue
@@ -1,5 +1,12 @@
<script lang="ts" setup>
import { settingsFieldCommitKey } from '#console/composables/useSettingsForm'
+import {
+ MAX_SOCIAL_LINKS,
+ parseSocialLink,
+ parseSocialLinks,
+ resolveSocialPlatform,
+ SocialLinkError,
+} from '@chronoframe/contracts/social-links'
definePageMeta({
layout: 'dashboard',
@@ -12,17 +19,92 @@ useHead({
const colorMode = useColorMode()
const { fields, state, submit, loading, commitField } = useSettingsForm('app')
+const { t } = useI18n()
provide(settingsFieldCommitKey, commitField)
const appFields = computed(() =>
- fields.value.filter((f) => !f.key.startsWith('appearance.')),
+ fields.value.filter(
+ (f) => !f.key.startsWith('appearance.') && f.key !== 'socialLinks',
+ ),
)
const appearanceFields = computed(() =>
fields.value.filter((f) => f.key.startsWith('appearance.')),
)
+const socialField = computed(() =>
+ fields.value.find((field) => field.key === 'socialLinks'),
+)
+const socialDraft = ref<string[]>(Array(MAX_SOCIAL_LINKS).fill(''))
+const socialInitialized = ref(false)
+const savedSocialLinks = computed(() => {
+ try {
+ return parseSocialLinks(socialField.value?.value ?? { links: [] })
+ } catch {
+ return []
+ }
+})
+
+watch(socialField, (field) => {
+ if (!field || socialInitialized.value) return
+ socialDraft.value = Array.from(
+ { length: MAX_SOCIAL_LINKS },
+ (_, index) => savedSocialLinks.value[index] ?? '',
+ )
+ socialInitialized.value = true
+})
+
+const socialErrors = computed(() => {
+ const seen = new Set<string>()
+ return socialDraft.value.map((value) => {
+ if (!value.trim()) return ''
+ try {
+ const url = parseSocialLink(value.trim())
+ const identity = `${url.origin}${url.pathname.replace(/\/+$/, '')}`
+ if (seen.has(identity)) return t('settings.app.socialLinks.duplicate')
+ seen.add(identity)
+ return ''
+ } catch {
+ return t('settings.app.socialLinks.invalid')
+ }
+ })
+})
+
+const isSocialDirty = computed(
+ () =>
+ socialInitialized.value &&
+ socialDraft.value.some(
+ (value, index) => value !== (savedSocialLinks.value[index] ?? ''),
+ ),
+)
+
+const resetSocialLinks = () => {
+ socialDraft.value = Array.from(
+ { length: MAX_SOCIAL_LINKS },
+ (_, index) => savedSocialLinks.value[index] ?? '',
+ )
+}
+
+const socialSubmitError = ref('')
+const handleSocialLinksSubmit = async () => {
+ socialSubmitError.value = ''
+ const links = socialDraft.value.map((link) => link.trim()).filter(Boolean)
+ try {
+ parseSocialLinks({ links })
+ await submit({ socialLinks: { links } })
+ socialDraft.value = Array.from(
+ { length: MAX_SOCIAL_LINKS },
+ (_, index) => links[index] ?? '',
+ )
+ } catch (error) {
+ socialSubmitError.value =
+ error instanceof SocialLinkError
+ ? t(`settings.app.socialLinks.${error.code}`)
+ : t('settings.form.saveFailed')
+ }
+}
+
const sameValue = (left: any, right: any) =>
JSON.stringify(left ?? null) === JSON.stringify(right ?? null)
@@ -239,6 +321,121 @@ const handleAppearanceSettingsSubmit = async () => {
</div>
</footer>
</section>
+ <section
+ class="rounded-md border border-neutral-200 bg-white dark:border-neutral-800 dark:bg-neutral-950"
+ >
+ <header
+ class="border-b border-neutral-200 px-5 py-4 dark:border-neutral-800"
+ >
+ <h3
+ class="text-base font-semibold text-neutral-900 dark:text-neutral-100"
+ >
+ {{ $t('settings.app.socialLinks.title') }}
+ </h3>
+ <p class="mt-1 text-sm text-neutral-600 dark:text-neutral-400">
+ {{ $t('settings.app.socialLinks.description') }}
+ </p>
+ </header>
+
+ <div
+ v-if="loading && !socialInitialized"
+ class="space-y-3 px-5 py-5"
+ >
+ <USkeleton
+ v-for="index in MAX_SOCIAL_LINKS"
+ :key="index"
+ class="h-10 w-full"
+ />
+ </div>
+ <form
+ v-else
+ class="space-y-4 px-5 py-5"
+ @submit.prevent="handleSocialLinksSubmit"
+ >
+ <div
+ v-for="(_, index) in socialDraft"
+ :key="index"
+ class="flex items-start gap-3"
+ >
+ <Icon
+ :name="resolveSocialPlatform(socialDraft[index] || '').icon"
+ class="mt-2.5 shrink-0 text-xl text-neutral-500 dark:text-neutral-400"
+ aria-hidden="true"
+ />
+ <div class="min-w-0 flex-1">
+ <label
+ :for="`social-link-${index}`"
+ class="mb-1 block text-sm font-medium text-neutral-900 dark:text-neutral-100"
+ >
+ {{
+ $t('settings.app.socialLinks.slot', { number: index + 1 })
+ }}
+ </label>
+ <UInput
+ :id="`social-link-${index}`"
+ v-model="socialDraft[index]"
+ type="url"
+ class="w-full"
+ :placeholder="$t('settings.app.socialLinks.placeholder')"
+ :aria-invalid="Boolean(socialErrors[index])"
+ :aria-describedby="
+ socialErrors[index]
+ ? `social-link-error-${index}`
+ : undefined
+ "
+ />
+ <p
+ v-if="socialErrors[index]"
+ :id="`social-link-error-${index}`"
+ class="mt-1 text-sm text-error-600 dark:text-error-400"
+ >
+ {{ socialErrors[index] }}
+ </p>
+ </div>
+ <UButton
+ v-if="socialDraft[index]"
+ type="button"
+ color="neutral"
+ variant="ghost"
+ icon="tabler:x"
+ :aria-label="
+ $t('settings.app.socialLinks.clear', { number: index + 1 })
+ "
+ class="mt-6"
+ @click="socialDraft[index] = ''"
+ />
+ </div>
+
+ <p
+ v-if="socialSubmitError"
+ role="alert"
+ class="text-sm text-error-600 dark:text-error-400"
+ >
+ {{ socialSubmitError }}
+ </p>
+ <div
+ class="flex items-center justify-end gap-2 border-t border-neutral-200 pt-4 dark:border-neutral-800"
+ >
+ <UButton
+ type="button"
+ color="neutral"
+ variant="outline"
+ :disabled="!isSocialDirty || loading"
+ @click="resetSocialLinks"
+ >
+ {{ $t('common.actions.reset') }}
+ </UButton>
+ <UButton
+ type="submit"
+ icon="tabler:device-floppy"
+ :loading="loading"
+ :disabled="!isSocialDirty || socialErrors.some(Boolean)"
+ >
+ {{ $t('common.actions.saveSettings') }}
+ </UButton>
+ </div>
+ </form>
+ </section>
</div>
</template>
</UDashboardPanel>
diff --git a/packages/contracts/package.json b/packages/contracts/package.json
index 3b581997..0068bf64 100644
--- a/packages/contracts/package.json
+++ b/packages/contracts/package.json
@@ -11,6 +11,7 @@
"./location": "./src/location.ts",
"./resources": "./src/resources.ts",
"./settings": "./src/settings.ts",
+ "./social-links": "./src/social-links.ts",
"./queue": "./src/queue.ts"
},
"scripts": {
diff --git a/packages/contracts/src/social-links.ts b/packages/contracts/src/social-links.ts
new file mode 100644
index 00000000..0e51ef1d
--- /dev/null
+++ b/packages/contracts/src/social-links.ts
@@ -0,0 +1,179 @@
+/// <reference lib="dom" />
+
+export const MAX_SOCIAL_LINKS = 4
+
+export type SocialLinkErrorCode = 'shape' | 'limit' | 'invalid' | 'duplicate'
+
+export class SocialLinkError extends Error {
+ readonly code: SocialLinkErrorCode
+
+ constructor(code: SocialLinkErrorCode, message: string) {
+ super(message)
+ this.name = 'SocialLinkError'
+ this.code = code
+ }
+}
+
+/** Validate public profile URLs without requesting or resolving their hosts. */
+export function parseSocialLink(value: unknown): URL {
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length > 2048 ||
+ value !== value.trim() ||
+ [...value].some((character) => {
+ const code = character.charCodeAt(0)
+ return code <= 31 || code === 127
+ })
+ ) {
+ throw new SocialLinkError('invalid', 'Enter a valid HTTPS URL')
+ }
+
+ let url: URL
+ try {
+ url = new URL(value)
+ } catch {
+ throw new SocialLinkError('invalid', 'Enter a valid HTTPS URL')
+ }
+
+ const labels = url.hostname.split('.')
+ const validHostname =
+ labels.length >= 2 &&
+ labels.every(
+ (label) =>
+ label.length > 0 &&
+ label.length <= 63 &&
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label),
+ ) &&
+ /[a-z]/i.test(labels.at(-1) ?? '') &&
+ !['local', 'localhost', 'internal', 'invalid'].includes(labels.at(-1) ?? '')
+
+ if (
+ url.protocol !== 'https:' ||
+ url.username ||
+ url.password ||
+ !validHostname
+ ) {
+ throw new SocialLinkError('invalid', 'Enter a valid HTTPS URL')
+ }
+ return url
+}
+
+export function parseSocialLinks(value: unknown): string[] {
+ if (
+ !value ||
+ typeof value !== 'object' ||
+ Array.isArray(value) ||
+ Object.keys(value).length !== 1 ||
+ !Object.hasOwn(value, 'links') ||
+ !Array.isArray((value as { links: unknown }).links)
+ ) {
+ throw new SocialLinkError('shape', 'Invalid social links shape')
+ }
+
+ const links = (value as { links: unknown[] }).links
+ if (links.length > MAX_SOCIAL_LINKS)
+ throw new SocialLinkError('limit', 'Use at most four social links')
+
+ const seen = new Set<string>()
+ return links.map((link) => {
+ const url = parseSocialLink(link)
+ const path = url.pathname.replace(/\/+$/, '')
+ const identity = `${url.origin}${path}`
+ if (seen.has(identity))
+ throw new SocialLinkError('duplicate', 'Duplicate social link')
+ seen.add(identity)
+ return link as string
+ })
+}
+
+const platforms = [
+ {
+ domains: ['instagram.com'],
+ label: 'Instagram',
+ icon: 'tabler:brand-instagram',
+ },
+ {
+ domains: ['facebook.com', 'fb.com'],
+ label: 'Facebook',
+ icon: 'tabler:brand-facebook',
+ },
+ { domains: ['github.com'], label: 'GitHub', icon: 'tabler:brand-github' },
+ { domains: ['x.com', 'twitter.com'], label: 'X', icon: 'tabler:brand-x' },
+ {
+ domains: ['youtube.com', 'youtu.be'],
+ label: 'YouTube',
+ icon: 'tabler:brand-youtube',
+ },
+ {
+ domains: ['linkedin.com'],
+ label: 'LinkedIn',
+ icon: 'tabler:brand-linkedin',
+ },
+ { domains: ['tiktok.com'], label: 'TikTok', icon: 'tabler:brand-tiktok' },
+ { domains: ['threads.net'], label: 'Threads', icon: 'tabler:brand-threads' },
+ { domains: ['bsky.app'], label: 'Bluesky', icon: 'tabler:brand-bluesky' },
+ {
+ domains: ['mastodon.social'],
+ label: 'Mastodon',
+ icon: 'tabler:brand-mastodon',
+ },
+ {
+ domains: ['pinterest.com'],
+ label: 'Pinterest',
+ icon: 'tabler:brand-pinterest',
+ },
+ { domains: ['reddit.com'], label: 'Reddit', icon: 'tabler:brand-reddit' },
+ { domains: ['twitch.tv'], label: 'Twitch', icon: 'tabler:brand-twitch' },
+ { domains: ['flickr.com'], label: 'Flickr', icon: 'tabler:brand-flickr' },
+ { domains: ['vimeo.com'], label: 'Vimeo', icon: 'tabler:brand-vimeo' },
+ { domains: ['behance.net'], label: 'Behance', icon: 'tabler:brand-behance' },
+ {
+ domains: ['dribbble.com'],
+ label: 'Dribbble',
+ icon: 'tabler:brand-dribbble',
+ },
+ { domains: ['tumblr.com'], label: 'Tumblr', icon: 'tabler:brand-tumblr' },
+ {
+ domains: ['snapchat.com'],
+ label: 'Snapchat',
+ icon: 'tabler:brand-snapchat',
+ },
+ { domains: ['medium.com'], label: 'Medium', icon: 'tabler:brand-medium' },
+ { domains: ['weibo.com'], label: 'Weibo', icon: 'tabler:brand-weibo' },
+ {
+ domains: ['discord.com', 'discord.gg'],
+ label: 'Discord',
+ icon: 'tabler:brand-discord',
+ },
+ {
+ domains: ['t.me', 'telegram.me'],
+ label: 'Telegram',
+ icon: 'tabler:brand-telegram',
+ },
+ {
+ domains: ['wa.me', 'whatsapp.com'],
+ label: 'WhatsApp',
+ icon: 'tabler:brand-whatsapp',
+ },
+] as const
+
+export function resolveSocialPlatform(value: string): {
+ label: string
+ icon: string
+} {
+ let hostname: string
+ try {
+ hostname = parseSocialLink(value).hostname
+ } catch {
+ return { label: 'Link', icon: 'tabler:link' }
+ }
+ const platform = platforms.find(({ domains }) =>
+ domains.some(
+ (domain) => hostname === domain || hostname.endsWith(`.${domain}`),
+ ),
+ )
+ return platform
+ ? { label: platform.label, icon: platform.icon }
+ : { label: hostname.replace(/^www\./, ''), icon: 'tabler:link' }
+}
diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts
index 9b2a3812..72a4ddf9 100644
--- a/packages/core/src/settings.ts
+++ b/packages/core/src/settings.ts
@@ -1,4 +1,5 @@
import type { SettingValue } from '@chronoframe/contracts/settings'
+import { parseSocialLinks } from '@chronoframe/contracts/social-links'
export const DEFAULT_QUEUE_WORKER_COUNT = 5
@@ -55,6 +56,7 @@ export function validateSettingWrite(input: {
}
if (namespace === 'system' && key === 'queue.workerCount')
validateQueueWorkerCount(value)
+ if (namespace === 'app' && key === 'socialLinks') parseSocialLinks(value)
}
/** Resolve the configured connection through an injected persistence boundary. */
diff --git a/packages/gallery/app/components/masonry/item/Header.vue b/packages/gallery/app/components/masonry/item/Header.vue
index e4216e40..5f29b8af 100644
--- a/packages/gallery/app/components/masonry/item/Header.vue
+++ b/packages/gallery/app/components/masonry/item/Header.vue
@@ -41,6 +41,7 @@ defineProps<{
/>
</template>
</AuthState>
+ <MasonryItemHeaderSocialLinks />
<MasonryItemHeaderFooter variant="embedded" />
</div>
</div>
diff --git a/packages/gallery/app/components/masonry/item/HeaderFixed.vue b/packages/gallery/app/components/masonry/item/HeaderFixed.vue
index 46c113a1..621bbee1 100644
--- a/packages/gallery/app/components/masonry/item/HeaderFixed.vue
+++ b/packages/gallery/app/components/masonry/item/HeaderFixed.vue
@@ -32,6 +32,7 @@ defineProps<{
:total="stats?.total"
:date-range-text="dateRangeText"
/>
+ <MasonryItemHeaderSocialLinks variant="fixedDesktop" />
<MasonryItemActions
:logged-in="loggedIn"
:clear="clear"
@@ -53,6 +54,10 @@ defineProps<{
</MasonryItemActions>
<MasonryItemHeaderFooter variant="fixed" />
</div>
+ <MasonryItemHeaderSocialLinks
+ variant="fixedMobile"
+ class="border-t border-neutral-200 px-2 dark:border-neutral-800"
+ />
</template>
</AuthState>
</header>
diff --git a/packages/gallery/app/components/masonry/item/HeaderSocialLinks.vue b/packages/gallery/app/components/masonry/item/HeaderSocialLinks.vue
new file mode 100644
index 00000000..8038f8c0
--- /dev/null
+++ b/packages/gallery/app/components/masonry/item/HeaderSocialLinks.vue
@@ -0,0 +1,56 @@
+<script lang="ts" setup>
+import {
+ parseSocialLinks,
+ resolveSocialPlatform,
+} from '@chronoframe/contracts/social-links'
+
+const props = withDefaults(
+ defineProps<{ variant?: 'embedded' | 'fixedDesktop' | 'fixedMobile' }>(),
+ { variant: 'embedded' },
+)
+
+const setting = useSettingRef('app:socialLinks')
+const links = computed(() => {
+ try {
+ return parseSocialLinks(setting.value).map((href) => ({
+ href,
+ ...resolveSocialPlatform(href),
+ }))
+ } catch {
+ return []
+ }
+})
+</script>
+
+<template>
+ <nav
+ v-if="links.length"
+ :aria-label="$t('settings.app.socialLinks.title')"
+ class="flex-wrap items-center justify-center gap-1"
+ :class="{
+ flex: props.variant === 'embedded',
+ 'hidden lg:flex': props.variant === 'fixedDesktop',
+ 'flex lg:hidden': props.variant === 'fixedMobile',
+ }"
+ >
+ <a
+ v-for="link in links"
+ :key="link.href"
+ :href="link.href"
+ :aria-label="
+ $t('settings.app.socialLinks.visit', { platform: link.label })
+ "
+ :title="link.label"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="inline-flex size-10 items-center justify-center rounded-full text-neutral-600 transition-colors hover:bg-neutral-200/70 hover:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-500 dark:text-neutral-300 dark:hover:bg-neutral-700/70 dark:hover:text-white"
+ >
+ <Icon
+ :name="link.icon"
+ mode="svg"
+ class="text-xl"
+ aria-hidden="true"
+ />
+ </a>
+ </nav>
+</template>
diff --git a/packages/gallery/i18n/locales/en.json b/packages/gallery/i18n/locales/en.json
index e0d4d422..5b273342 100644
--- a/packages/gallery/i18n/locales/en.json
+++ b/packages/gallery/i18n/locales/en.json
@@ -1218,6 +1218,18 @@
},
"settings": {
"app": {
+ "socialLinks": {
+ "title": "Social accounts",
+ "description": "Add up to four HTTPS links to show in the home page header.",
+ "slot": "Social link {number}",
+ "placeholder": "https://example.com/your-profile",
+ "clear": "Clear social link {number}",
+ "visit": "Visit {platform}",
+ "shape": "Invalid social links data",
+ "limit": "Add no more than four links",
+ "invalid": "Enter a valid HTTPS link to a public website",
+ "duplicate": "This link is already listed"
+ },
"title": {
"label": "Instance Name",
"description": "The title of the instance"
diff --git a/packages/gallery/i18n/locales/ja.json b/packages/gallery/i18n/locales/ja.json
index b2e78e5b..b8d33c93 100644
--- a/packages/gallery/i18n/locales/ja.json
+++ b/packages/gallery/i18n/locales/ja.json
@@ -1140,6 +1140,18 @@
},
"settings": {
"app": {
+ "socialLinks": {
+ "title": "ソーシャルアカウント",
+ "description": "ホームページのヘッダーに表示する HTTPS リンクを最大4件追加できます。",
+ "slot": "ソーシャルリンク {number}",
+ "placeholder": "https://example.com/your-profile",
+ "clear": "ソーシャルリンク {number} を消去",
+ "visit": "{platform} を開く",
+ "shape": "ソーシャルリンクのデータが無効です",
+ "limit": "リンクは最大4件までです",
+ "invalid": "公開サイトの有効な HTTPS リンクを入力してください",
+ "duplicate": "このリンクは既に追加されています"
+ },
"title": {
"label": "インスタンス名",
"description": "インスタンスのタイトル"
diff --git a/packages/gallery/i18n/locales/ru.json b/packages/gallery/i18n/locales/ru.json
index 41880b18..88896fad 100644
--- a/packages/gallery/i18n/locales/ru.json
+++ b/packages/gallery/i18n/locales/ru.json
@@ -1218,6 +1218,18 @@
},
"settings": {
"app": {
+ "socialLinks": {
+ "title": "Социальные сети",
+ "description": "Добавьте до четырёх ссылок HTTPS для отображения в шапке главной страницы.",
+ "slot": "Ссылка {number}",
+ "placeholder": "https://example.com/your-profile",
+ "clear": "Очистить ссылку {number}",
+ "visit": "Открыть {platform}",
+ "shape": "Неверные данные социальных ссылок",
+ "limit": "Можно добавить не более четырёх ссылок",
+ "invalid": "Введите действительную ссылку HTTPS на общедоступный сайт",
+ "duplicate": "Эта ссылка уже добавлена"
+ },
"title": {
"label": "Название приложения",
"description": "Название этого инстанса приложения"
diff --git a/packages/gallery/i18n/locales/zh-Hans.json b/packages/gallery/i18n/locales/zh-Hans.json
index b26e254e..ea8229e4 100644
--- a/packages/gallery/i18n/locales/zh-Hans.json
+++ b/packages/gallery/i18n/locales/zh-Hans.json
@@ -1218,6 +1218,18 @@
},
"settings": {
"app": {
+ "socialLinks": {
+ "title": "社交账号",
+ "description": "最多添加四个 HTTPS 链接,显示在首页页眉。",
+ "slot": "社交链接 {number}",
+ "placeholder": "https://example.com/your-profile",
+ "clear": "清除社交链接 {number}",
+ "visit": "访问 {platform}",
+ "shape": "社交链接数据无效",
+ "limit": "最多添加四个链接",
+ "invalid": "请输入指向公开网站的有效 HTTPS 链接",
+ "duplicate": "此链接已添加"
+ },
"title": {
"label": "实例名称",
"description": "实例的标题"
diff --git a/packages/gallery/i18n/locales/zh-Hant-HK.json b/packages/gallery/i18n/locales/zh-Hant-HK.json
index a0a3ba1a..5508994e 100644
--- a/packages/gallery/i18n/locales/zh-Hant-HK.json
+++ b/packages/gallery/i18n/locales/zh-Hant-HK.json
@@ -1140,6 +1140,18 @@
},
"settings": {
"app": {
+ "socialLinks": {
+ "title": "社交帳戶",
+ "description": "最多加入四個 HTTPS 連結,顯示於首頁頁首。",
+ "slot": "社交連結 {number}",
+ "placeholder": "https://example.com/your-profile",
+ "clear": "清除社交連結 {number}",
+ "visit": "瀏覽 {platform}",
+ "shape": "社交連結資料無效",
+ "limit": "最多只能加入四個連結",
+ "invalid": "請輸入指向公開網站的有效 HTTPS 連結",
+ "duplicate": "此連結已加入"
+ },
"title": {
"label": "實例名稱",
"description": "實例的標題"
diff --git a/packages/gallery/i18n/locales/zh-Hant-TW.json b/packages/gallery/i18n/locales/zh-Hant-TW.json
index 6d82c8de..46956a40 100644
--- a/packages/gallery/i18n/locales/zh-Hant-TW.json
+++ b/packages/gallery/i18n/locales/zh-Hant-TW.json
@@ -1140,6 +1140,18 @@
},
"settings": {
"app": {
+ "socialLinks": {
+ "title": "社群帳號",
+ "description": "最多新增四個 HTTPS 連結,顯示在首頁頁首。",
+ "slot": "社群連結 {number}",
+ "placeholder": "https://example.com/your-profile",
+ "clear": "清除社群連結 {number}",
+ "visit": "前往 {platform}",
+ "shape": "社群連結資料無效",
+ "limit": "最多只能新增四個連結",
+ "invalid": "請輸入指向公開網站的有效 HTTPS 連結",
+ "duplicate": "此連結已新增"
+ },
"title": {
"label": "實例名稱",
"description": "實例的標題"
diff --git a/tests/social-links-persistence.test.ts b/tests/social-links-persistence.test.ts
new file mode 100644
index 00000000..ae9a278b
--- /dev/null
+++ b/tests/social-links-persistence.test.ts
@@ -0,0 +1,72 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import { and, eq } from 'drizzle-orm'
+import * as tables from '../apps/self-hosted/server/database/schema.ts'
+
+test('social links survive settings manager reads and invalid updates leave the row unchanged', async () => {
+ const sqlite = new Database(':memory:')
+ const db = drizzle(sqlite, { schema: tables })
+ migrate(db, {
+ migrationsFolder: './apps/self-hosted/server/database/migrations',
+ })
+ const fakeLogger = { info() {}, warn() {}, error() {}, debug() {} }
+ const globals = globalThis as unknown as Record<string, unknown>
+ const overrides = {
+ logger: { dynamic: () => fakeLogger },
+ useDB: () => db,
+ tables,
+ and,
+ eq,
+ }
+ const previous = Object.fromEntries(
+ Object.keys(overrides).map((key) => [key, globals[key]]),
+ )
+ Object.assign(globals, overrides)
+ try {
+ const { settingsManager } =
+ await import('../apps/self-hosted/server/services/settings/settingsManager.ts')
+ await settingsManager.init([
+ {
+ namespace: 'app',
+ key: 'socialLinks',
+ type: 'json',
+ defaultValue: { links: [] },
+ isPublic: true,
+ },
+ ])
+ const links = [
+ 'https://github.com/example',
+ 'https://instagram.com/example',
+ ]
+ await settingsManager.set('app', 'socialLinks', { links })
+ assert.deepEqual(await settingsManager.get('app', 'socialLinks'), { links })
+
+ await assert.rejects(
+ settingsManager.set('app', 'socialLinks', {
+ links: ['http://instagram.com/example'],
+ }),
+ /HTTPS/i,
+ )
+ const row = db
+ .select()
+ .from(tables.settings)
+ .where(
+ and(
+ eq(tables.settings.namespace, 'app'),
+ eq(tables.settings.key, 'socialLinks'),
+ ),
+ )
+ .get()!
+ assert.equal(row.isPublic, true)
+ assert.deepEqual(JSON.parse(row.value!), { links })
+ } finally {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete globals[key]
+ else globals[key] = value
+ }
+ sqlite.close()
+ }
+})
diff --git a/tests/social-links.test.ts b/tests/social-links.test.ts
new file mode 100644
index 00000000..f07001a6
--- /dev/null
+++ b/tests/social-links.test.ts
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ parseSocialLinks,
+ resolveSocialPlatform,
+} from '@chronoframe/contracts/social-links'
+import { validateSettingWrite } from '@chronoframe/core'
+
+test('accepts an ordered list of at most four HTTPS profile links', () => {
+ const links = [
+ 'https://instagram.com/example',
+ 'https://github.com/example',
+ 'https://www.youtube.com/@example',
+ 'https://example.org/profile',
+ ]
+ assert.deepEqual(parseSocialLinks({ links }), links)
+ assert.deepEqual(parseSocialLinks({ links: [] }), [])
+ assert.throws(
+ () => parseSocialLinks({ links: [...links, 'https://x.com/example'] }),
+ /four/i,
+ )
+})
+
+test('rejects unsafe, malformed and duplicate social links', () => {
+ for (const link of [
+ 'http://instagram.com/example',
+ 'javascript:alert(1)',
+ 'https://user:[email protected]/example',
+ 'https://localhost/example',
+ 'https://profile.local/example',
+ 'https://127.0.0.1/example',
+ 'https://instagram.com.evil.test/example\n',
+ ' https://instagram.com/example ',
+ ]) {
+ assert.throws(() => parseSocialLinks({ links: [link] }), undefined, link)
+ }
+ assert.throws(
+ () =>
+ parseSocialLinks({
+ links: ['https://Instagram.com/me', 'https://instagram.com/me/'],
+ }),
+ /duplicate/i,
+ )
+ assert.throws(
+ () => parseSocialLinks({ links: ['https://example.com'], extra: true }),
+ /shape/i,
+ )
+})
+
+test('settings write validation enforces the social-link contract', () => {
+ const input = {
+ namespace: 'app',
+ key: 'socialLinks',
+ value: { links: ['https://github.com/example'] },
+ readonly: false,
+ enumValues: null,
+ sudo: false,
+ }
+ validateSettingWrite(input)
+ assert.throws(
+ () =>
+ validateSettingWrite({ ...input, value: { links: ['http://bad.test'] } }),
+ /HTTPS/i,
+ )
+})
+
+test('resolves known platforms by exact host or subdomain only', () => {
+ assert.equal(
+ resolveSocialPlatform('https://www.instagram.com/me').icon,
+ 'tabler:brand-instagram',
+ )
+ assert.equal(resolveSocialPlatform('https://x.com/me').label, 'X')
+ assert.equal(
+ resolveSocialPlatform('https://www.flickr.com/photos/me').label,
+ 'Flickr',
+ )
+ assert.equal(
+ resolveSocialPlatform('https://instagram.com.evil.test/me').icon,
+ 'tabler:link',
+ )
+ assert.equal(
+ resolveSocialPlatform('https://example.org/me').label,
+ 'example.org',
+ )
+})