1 Commits
Author SHA1 Message Date
O96u 4ed4692f5e release: v1.4.2
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Fix batch tagging and upload token auth; single API token and tagNames-only upload; tag management sort and responsive layout.
2026-09-23 15:38:46 +08:00
24 changed files with 828 additions and 370 deletions

No files matched your search

+14
View File
@@ -4,6 +4,20 @@
## [Unreleased] ## [Unreleased]
## [1.4.2] - 2026-09-23
### 修复
- 图库批量打标:管理员/跨归属场景下标签解析与失败提示
- 上传鉴权:`Auth-Token` 与表单 `token` 优先于会话;兼容全局 `API_UPLOAD_TOKEN`(上传归属首位管理员)
### 改进
- **API 页**:每账号单一 API Token,界面与文档统一
- **上传 API**:仅支持 `tagNames`(按名创建或复用标签);Twikoo 兼容路由同步
- **标签管理**:按图片数/最近使用排序;桌面列布局;窄屏卡片列表
- **API 文档**:参数表列宽,避免 form-data 列异常换行
## [1.4.1] - 2026-09-16 ## [1.4.1] - 2026-09-16
### 新增 ### 新增
File diff suppressed because it is too large. Load diff
+16 -9
View File
@@ -38,19 +38,26 @@ const { t } = useI18n()
</h3> </h3>
</div> </div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="w-full min-w-[32rem] text-left text-sm"> <table class="w-full min-w-[36rem] table-fixed text-left text-sm">
<colgroup>
<col class="w-[5.5rem]">
<col class="w-[3.5rem]">
<col class="w-[5.75rem]">
<col class="w-[3.25rem]">
<col>
</colgroup>
<thead> <thead>
<tr class="border-b border-default text-xs text-muted"> <tr class="border-b border-default text-xs text-muted">
<th class="px-4 py-2.5 font-medium"> <th class="px-4 py-2.5 font-medium">
{{ t('api.paramName') }} {{ t('api.paramName') }}
</th> </th>
<th class="px-4 py-2.5 font-medium"> <th class="whitespace-nowrap px-4 py-2.5 font-medium">
{{ t('api.paramType') }} {{ t('api.paramType') }}
</th> </th>
<th class="px-4 py-2.5 font-medium"> <th class="whitespace-nowrap px-4 py-2.5 font-medium">
{{ t('api.paramLocation') }} {{ t('api.paramLocation') }}
</th> </th>
<th class="px-4 py-2.5 font-medium"> <th class="whitespace-nowrap px-4 py-2.5 font-medium">
{{ t('api.paramRequired') }} {{ t('api.paramRequired') }}
</th> </th>
<th class="px-4 py-2.5 font-medium"> <th class="px-4 py-2.5 font-medium">
@@ -64,20 +71,20 @@ const { t } = useI18n()
:key="param.name" :key="param.name"
class="border-b border-default last:border-b-0" class="border-b border-default last:border-b-0"
> >
<td class="px-4 py-2.5 font-mono text-xs"> <td class="whitespace-nowrap px-4 py-2.5 font-mono text-xs">
{{ param.name }} {{ param.name }}
<span <span
v-if="param.required" v-if="param.required"
class="text-error" class="text-error"
>*</span> >*</span>
</td> </td>
<td class="px-4 py-2.5 text-muted"> <td class="whitespace-nowrap px-4 py-2.5 text-muted">
{{ param.type }} {{ param.type }}
</td> </td>
<td class="px-4 py-2.5 text-muted"> <td class="whitespace-nowrap px-4 py-2.5 text-muted">
{{ param.location }} {{ param.location }}
</td> </td>
<td class="px-4 py-2.5"> <td class="whitespace-nowrap px-4 py-2.5">
<UBadge <UBadge
:color="param.required ? 'primary' : 'neutral'" :color="param.required ? 'primary' : 'neutral'"
variant="subtle" variant="subtle"
@@ -86,7 +93,7 @@ const { t } = useI18n()
{{ param.required ? t('api.required') : t('api.optional') }} {{ param.required ? t('api.required') : t('api.optional') }}
</UBadge> </UBadge>
</td> </td>
<td class="px-4 py-2.5 text-muted"> <td class="px-4 py-2.5 leading-relaxed text-muted break-words">
{{ t(param.descriptionKey) }} {{ t(param.descriptionKey) }}
</td> </td>
</tr> </tr>
-9
View File
@@ -75,15 +75,6 @@ async function copyToken() {
:description="t('api.envOverrideDesc')" :description="t('api.envOverrideDesc')"
/> />
<UAlert
v-else-if="!isAdmin"
color="info"
variant="subtle"
icon="i-lucide-info"
:title="t('api.personalTitle')"
:description="t('api.personalDesc')"
/>
<UAlert <UAlert
v-else-if="!token && !loading" v-else-if="!token && !loading"
color="info" color="info"
-7
View File
@@ -74,13 +74,6 @@ export function buildApiDocs(ctx: ApiDocsContext): ApiDocEndpoint[] {
required: false, required: false,
descriptionKey: 'api.params.upload.token' descriptionKey: 'api.params.upload.token'
}, },
{
name: 'tagIds',
type: 'string',
location: 'form-data',
required: false,
descriptionKey: 'api.params.upload.tagIds'
},
{ {
name: 'tagNames', name: 'tagNames',
type: 'string', type: 'string',
+7 -1
View File
@@ -11,6 +11,7 @@ export function useImageUpload() {
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
const { compressEnabled, clientWebpQuality, lastTagIds } = useUploadPreferences() const { compressEnabled, clientWebpQuality, lastTagIds } = useUploadPreferences()
const { items: tagItems } = useTags()
const uploading = ref(false) const uploading = ref(false)
const progressItems = ref<UploadProgressItem[]>([]) const progressItems = ref<UploadProgressItem[]>([])
const lastUploadResult = ref<UploadResponse | null>(null) const lastUploadResult = ref<UploadResponse | null>(null)
@@ -60,7 +61,12 @@ export function useImageUpload() {
const tagIds = options?.tagIds ?? lastTagIds.value const tagIds = options?.tagIds ?? lastTagIds.value
if (tagIds.length) { if (tagIds.length) {
formData.append('tagIds', JSON.stringify(tagIds)) const names = tagIds
.map(id => tagItems.value.find(tag => tag.id === id)?.name)
.filter((name): name is string => Boolean(name))
if (names.length) {
formData.append('tagNames', JSON.stringify(names))
}
lastTagIds.value = tagIds lastTagIds.value = tagIds
} }
+16 -32
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
interface SettingsResponse { interface UserTokenResponse {
apiUploadToken: string apiUploadToken: string
tokenSource: 'env' | 'db' | 'none' tokenSource: 'env' | 'db' | 'none'
envTokenOverride: boolean envTokenOverride: boolean
@@ -16,7 +16,7 @@ const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus,
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
const settings = ref<SettingsResponse | null>(null) const tokenSettings = ref<UserTokenResponse | null>(null)
const loading = ref(false) const loading = ref(false)
const regenerating = ref(false) const regenerating = ref(false)
const confirmRegenerateOpen = ref(false) const confirmRegenerateOpen = ref(false)
@@ -25,19 +25,17 @@ const newToken = ref('')
const activeEndpointId = ref('upload') const activeEndpointId = ref('upload')
const baseUrl = computed(() => { const baseUrl = computed(() => {
const configured = settings.value?.env.siteBaseUrl const configured = tokenSettings.value?.env.siteBaseUrl
if (configured) return configured if (configured) return configured
if (import.meta.client) { if (import.meta.client) {
return window.location.origin return window.location.origin
} }
return settings.value?.env.imageBaseUrl ?? '' return tokenSettings.value?.env.imageBaseUrl ?? ''
}) })
const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '') const tokenDisplay = computed(() => tokenSettings.value?.apiUploadToken ?? '')
const hasToken = computed(() => tokenDisplay.value.length > 0) const hasToken = computed(() => tokenDisplay.value.length > 0)
const canRegenerate = computed(() => const canRegenerate = computed(() => !loading.value)
!settings.value?.envTokenOverride && !loading.value
)
const authHeader = computed(() => const authHeader = computed(() =>
hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN' hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN'
@@ -54,11 +52,10 @@ const activeEndpoint = computed(() =>
apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0] apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0]
) )
async function loadSettings() { async function loadTokenSettings() {
loading.value = true loading.value = true
try { try {
const endpoint = isAdmin.value ? '/api/settings' : '/api/user/api-token' tokenSettings.value = await $fetch<UserTokenResponse>('/api/user/api-token', {
settings.value = await $fetch<SettingsResponse>(endpoint, {
credentials: 'include' credentials: 'include'
}) })
} catch (error: unknown) { } catch (error: unknown) {
@@ -66,6 +63,7 @@ async function loadSettings() {
if (isAuthenticated.value) { if (isAuthenticated.value) {
toast.add({ title: t('api.loadFailed'), color: 'error' }) toast.add({ title: t('api.loadFailed'), color: 'error' })
} }
tokenSettings.value = null
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -80,30 +78,17 @@ async function confirmRegenerate() {
confirmRegenerateOpen.value = false confirmRegenerateOpen.value = false
regenerating.value = true regenerating.value = true
try { try {
const endpoint = isAdmin.value
? '/api/settings/api-token/regenerate'
: '/api/user/api-token/regenerate'
const response = await $fetch<{ apiUploadToken: string }>( const response = await $fetch<{ apiUploadToken: string }>(
endpoint, '/api/user/api-token/regenerate',
{ method: 'POST', credentials: 'include' } { method: 'POST', credentials: 'include' }
) )
newToken.value = response.apiUploadToken newToken.value = response.apiUploadToken
regenerateResultOpen.value = true regenerateResultOpen.value = true
await loadSettings() await loadTokenSettings()
} catch (error: unknown) { } catch (error: unknown) {
handleAuthError(error) handleAuthError(error)
if (isAuthenticated.value) { if (isAuthenticated.value) {
const status = typeof error === 'object' && error !== null && 'statusCode' in error toast.add({ title: t('api.regenerateFailed'), color: 'error' })
? (error as { statusCode: number }).statusCode
: 0
if (status === 409) {
toast.add({
title: t('api.regenerateEnvBlocked'),
color: 'warning'
})
} else {
toast.add({ title: t('api.regenerateFailed'), color: 'error' })
}
} }
} finally { } finally {
regenerating.value = false regenerating.value = false
@@ -126,16 +111,16 @@ onMounted(async () => {
} }
await checkSession() await checkSession()
if (isAuthenticated.value) { if (isAuthenticated.value) {
await loadSettings() await loadTokenSettings()
} }
}) })
watch(isAuthenticated, async (authed, prev) => { watch(isAuthenticated, async (authed, prev) => {
if (authed && prev === false) { if (authed && prev === false) {
await nextTick() await nextTick()
await loadSettings() await loadTokenSettings()
} else { } else {
settings.value = null tokenSettings.value = null
} }
}) })
</script> </script>
@@ -174,8 +159,7 @@ watch(isAuthenticated, async (authed, prev) => {
:loading="loading" :loading="loading"
:regenerating="regenerating" :regenerating="regenerating"
:can-regenerate="canRegenerate" :can-regenerate="canRegenerate"
:token-source="settings?.tokenSource" token-source="db"
:env-token-override="settings?.envTokenOverride"
:is-admin="isAdmin" :is-admin="isAdmin"
@regenerate="requestRegenerate" @regenerate="requestRegenerate"
/> />
+5 -2
View File
@@ -57,7 +57,7 @@ const {
const { items: tagItems, fetchTags, batchUpdateTags } = useTags() const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth() const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, getFetchErrorMessage } = useAuth()
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
@@ -256,7 +256,10 @@ async function confirmBatchTags(tagIds: number[], action: 'add' | 'remove') {
await Promise.all([reloadGallery(), fetchStats(), fetchTags(true)]) await Promise.all([reloadGallery(), fetchStats(), fetchTags(true)])
} catch (error: unknown) { } catch (error: unknown) {
handleAuthError(error) handleAuthError(error)
toast.add({ title: t('tags.batchFailed'), color: 'error' }) toast.add({
title: getFetchErrorMessage(error, t('tags.batchFailed')),
color: 'error'
})
} }
} }
+6 -6
View File
@@ -12,10 +12,10 @@ All REST calls use:
Auth-Token: YOUR_TOKEN Auth-Token: YOUR_TOKEN
``` ```
| Token type | How to obtain | Notes | | Token | How to obtain | Notes |
| ---------- | ------------- | ----- | | ----- | ------------- | ----- |
| **Global** | Admin **API** page or `API_UPLOAD_TOKEN` env | Env wins and blocks UI regenerate | | **API token** | **API** page after sign-in (one per account, auto-created) | `Auth-Token` header; uploads and tagNames belong to that account |
| **Personal** | Each user’s **API** page | Uploads belong to that user | | **Legacy site token** | `API_UPLOAD_TOKEN` env or old admin setting | Still accepted; uploads belong to the **first admin**. Twikoo form `token` also accepts each user’s API token |
Form uploads may use field `token` (Twikoo protocol). Form uploads may use field `token` (Twikoo protocol).
@@ -31,10 +31,10 @@ Upload one or more images via `image`; also accepts `file`, `files`. Stored unde
curl -X POST "https://admin.example.com/api/images/upload" \ curl -X POST "https://admin.example.com/api/images/upload" \
-H "Auth-Token: YOUR_TOKEN" \ -H "Auth-Token: YOUR_TOKEN" \
-F "image=@./demo.png" \ -F "image=@./demo.png" \
-F 'tagIds=[1,2]' -F 'tagNames=["blog","screenshot"]'
``` ```
Optional form field `tagIds`: JSON array string or repeated fields. Tags do **not** change storage paths under `images/`. Optional form field `tagNames`: JSON array or comma-separated names. Tags apply to the user bound to the token (**global token cannot tag**). Tags do **not** change storage paths under `images/`.
### 2. List images ### 2. List images
+10
View File
@@ -4,6 +4,16 @@ Version history and notable changes. The full log is also in the repo root [CHAN
--- ---
## [1.4.2] — 2026-09-23
### Fixed
- Gallery batch tagging and upload token auth (incl. legacy `API_UPLOAD_TOKEN`)
### Improved
- Single API token per account; upload `tagNames` only; tag management sort/mobile layout; API doc table layout
## [1.4.1] — 2026-09-16 ## [1.4.1] — 2026-09-16
### Added ### Added
+6 -6
View File
@@ -12,10 +12,10 @@ PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API*
Auth-Token: YOUR_TOKEN Auth-Token: YOUR_TOKEN
``` ```
| Token 类型 | 获取方式 | 说明 | | Token | 获取方式 | 说明 |
| ---------- | -------- | ---- | | ----- | -------- | ---- |
| **全局 Token** | 管理员 **API** 页生成;或 `API_UPLOAD_TOKEN` 环境变量 | 环境变量优先且锁定后台重新生成 | | **API Token** | 登录后 **API** 页(每账号一个,自动生成) | 请求头 `Auth-Token`;上传与 tagNames 归属该账号 |
| **个人 Token** | 各用户 **API** 页 | 仅用于该用户脚本,上传归属本人 | | **遗留全站 Token** | 环境变量 `API_UPLOAD_TOKEN` 或旧版后台配置 | 仍可用;上传归属**首个管理员**账号。Twikoo 表单 `token` 亦支持各账号 API Token |
表单上传仍可使用字段 `token`(Twikoo 协议)。 表单上传仍可使用字段 `token`(Twikoo 协议)。
@@ -31,10 +31,10 @@ Auth-Token: YOUR_TOKEN
curl -X POST "https://admin.example.com/api/images/upload" \ curl -X POST "https://admin.example.com/api/images/upload" \
-H "Auth-Token: YOUR_TOKEN" \ -H "Auth-Token: YOUR_TOKEN" \
-F "image=@./demo.png" \ -F "image=@./demo.png" \
-F 'tagIds=[1,2]' -F 'tagNames=["博客","截图"]'
``` ```
可选表单字段 `tagIds`:JSON 数组字符串(如 `[1,2]`)或重复字段,上传成功后自动打标。存储路径仍为 `images/年/月/id.webp`,**不会**因标签创建子目录。 可选表单字段 `tagNames`:JSON 数组或逗号分隔名称;上传成功后自动打标。存储路径仍为 `images/年/月/id.webp`,**不会**因标签创建子目录。
### 2. 获取图片列表 ### 2. 获取图片列表
+10
View File
@@ -4,6 +4,16 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
--- ---
## [1.4.2] — 2026-09-23
### 修复
- 图库批量打标与上传 Token 鉴权(含 `API_UPLOAD_TOKEN` 兼容)
### 改进
- API 页单 Token;上传 `tagNames`;标签管理排序与移动端布局;API 文档表格式
## [1.4.1] — 2026-09-16 ## [1.4.1] — 2026-09-16
### 新增 ### 新增
+7 -12
View File
@@ -13,8 +13,7 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 系统设置(`/settings`) | ✓ | — | | 系统设置(`/settings`) | ✓ | — |
| 开放注册开关 | ✓ | — | | 开放注册开关 | ✓ | — |
| 登录人机验证方式(滑块 / Turnstile / Cap) | ✓ | — | | 登录人机验证方式(滑块 / Turnstile / Cap) | ✓ | — |
| 全局 API Token 管理 | ✓ | — | | API Token(每账号一个) | ✓ | ✓ |
| 个人 API Token | ✓ | ✓ |
| 图库统计概览(含注册用户数) | ✓ | 部分 | | 图库统计概览(含注册用户数) | ✓ | 部分 |
| 标签管理(设置 → 标签管理) | ✓ | — | | 标签管理(设置 → 标签管理) | ✓ | — |
| 操作日志(设置 → 操作日志) | ✓ | — | | 操作日志(设置 → 操作日志) | ✓ | — |
@@ -26,9 +25,8 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 场景 | 鉴权方式 | 图片归属 / 可见范围 | | 场景 | 鉴权方式 | 图片归属 / 可见范围 |
| ---- | -------- | ------------------- | | ---- | -------- | ------------------- |
| 网页上传 | Session Cookie | 当前登录用户 | | 网页上传 | Session Cookie | 当前登录用户 |
| API 上传 + **个人 Token** | `Auth-Token` 头 | Token 所属用户 | | API 上传 | `Auth-Token` 或表单 `token` | Token 对应账号(遗留 `API_UPLOAD_TOKEN` 归属首个管理员) |
| API 上传 + **全局 Token** | `Auth-Token` 头 | 管理员(`userId` 为空) | | Twikoo `POST /api/index.php` | 表单 `token` | 同上 |
| Twikoo `POST /api/index.php` | 表单 `token` | 与全局 Token 相同 |
| 图库列表 / 搜索 / 删除 | Session 或 Token | 普通用户仅自己;管理员全部 | | 图库列表 / 搜索 / 删除 | Session 或 Token | 普通用户仅自己;管理员全部 |
| 图片直链 `GET /images/...` | 无(Referer 防盗链) | 知道 URL 即可访问 | | 图片直链 `GET /images/...` | 无(Referer 防盗链) | 知道 URL 即可访问 |
@@ -59,14 +57,11 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
- **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好 - **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好
- **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片 - **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片
## API Token 说明 ## API Token
| 类型 | 谁管理 | 上传归属 | 典型用途 | - **每个账号一个 Token**(含管理员),在 **API** 页查看或重新生成;首次打开会自动创建
| ---- | ------ | -------- | -------- | - 上传、`tagNames` 打标、图库接口均归属 **该 Token 所属账号**
| **全局 Token** | 管理员(API 页) | 管理员账号 | Twikoo、站点级脚本 | - 环境变量 **`API_UPLOAD_TOKEN`**(旧部署)仍可作为鉴权密钥,上传归属 **首个管理员**,见 [环境变量](./configuration.md)
| **个人 Token** | 各用户(API 页) | 该用户 | 个人博客、私有脚本 |
若设置了环境变量 `API_UPLOAD_TOKEN`,则全局 Token 被锁定,见 [环境变量](./configuration.md)。
## 相关 ## 相关
+4 -4
View File
@@ -196,6 +196,7 @@
"colName": "Tag name", "colName": "Tag name",
"colImageCount": "Images", "colImageCount": "Images",
"colLastUsed": "Last used", "colLastUsed": "Last used",
"colCreatedAt": "Created",
"neverUsed": "Never used", "neverUsed": "Never used",
"colActions": "Actions", "colActions": "Actions",
"mergeIntoAction": "Merge into…", "mergeIntoAction": "Merge into…",
@@ -824,13 +825,13 @@
"pagePlaceholder": "Page" "pagePlaceholder": "Page"
}, },
"api": { "api": {
"tokenTitle": "API Token", "tokenTitle": "API token",
"envOverrideTitle": "Token overridden by environment", "envOverrideTitle": "Token overridden by environment",
"envOverrideDesc": "Restart after changing API_UPLOAD_TOKEN; cannot regenerate in UI.", "envOverrideDesc": "Restart after changing API_UPLOAD_TOKEN; cannot regenerate in UI.",
"personalTitle": "Personal API token", "personalTitle": "Personal API token",
"personalDesc": "For your scripts only; uploads belong to your account.", "personalDesc": "For your scripts only; uploads belong to your account.",
"notConfiguredTitle": "No token configured", "notConfiguredTitle": "No token configured",
"notConfiguredDesc": "Click Regenerate to create a token for Auth-Token on all endpoints below.", "notConfiguredDesc": "A token is created automatically on first visit, or click Regenerate.",
"regenerate": "Regenerate", "regenerate": "Regenerate",
"tokenSourceEnv": "Source: API_UPLOAD_TOKEN environment variable", "tokenSourceEnv": "Source: API_UPLOAD_TOKEN environment variable",
"tokenSourceDb": "Source: generated in app (can regenerate)", "tokenSourceDb": "Source: generated in app (can regenerate)",
@@ -879,8 +880,7 @@
"file": "Compatibility field, single file", "file": "Compatibility field, single file",
"files": "Compatibility field, multiple files", "files": "Compatibility field, multiple files",
"token": "Twikoo protocol form token", "token": "Twikoo protocol form token",
"tagIds": "Optional JSON array or repeated fields; tag images by ID after upload", "tagNames": "Optional JSON array or comma-separated names; creates or reuses tags"
"tagNames": "Optional JSON array or comma-separated names; creates missing tags, reuses existing"
}, },
"list": { "list": {
"limit": "Page size, default 20, max 100", "limit": "Page size, default 20, max 100",
+3 -3
View File
@@ -196,6 +196,7 @@
"colName": "标签名称", "colName": "标签名称",
"colImageCount": "图片数", "colImageCount": "图片数",
"colLastUsed": "最近使用", "colLastUsed": "最近使用",
"colCreatedAt": "创建时间",
"neverUsed": "从未使用", "neverUsed": "从未使用",
"colActions": "操作", "colActions": "操作",
"mergeIntoAction": "合并到…", "mergeIntoAction": "合并到…",
@@ -830,7 +831,7 @@
"personalTitle": "个人 API Token", "personalTitle": "个人 API Token",
"personalDesc": "此 Token 仅用于您自己的脚本上传,上传的图片归属您的账号。", "personalDesc": "此 Token 仅用于您自己的脚本上传,上传的图片归属您的账号。",
"notConfiguredTitle": "尚未配置 Token", "notConfiguredTitle": "尚未配置 Token",
"notConfiguredDesc": "点击「重新生成」创建 Token,用于下方所有接口的 Auth-Token 鉴权。", "notConfiguredDesc": "首次打开会自动创建 Token,或点击「重新生成」。",
"regenerate": "重新生成", "regenerate": "重新生成",
"tokenSourceEnv": "来源:环境变量 API_UPLOAD_TOKEN", "tokenSourceEnv": "来源:环境变量 API_UPLOAD_TOKEN",
"tokenSourceDb": "来源:后台生成(可重新生成)", "tokenSourceDb": "来源:后台生成(可重新生成)",
@@ -879,8 +880,7 @@
"file": "兼容字段,单图上传", "file": "兼容字段,单图上传",
"files": "兼容字段,多图上传", "files": "兼容字段,多图上传",
"token": "Twikoo 协议兼容,表单 token", "token": "Twikoo 协议兼容,表单 token",
"tagIds": "可选,JSON 数组或重复字段,上传后按 ID 打标", "tagNames": "可选,JSON 数组或逗号分隔;名称不存在则创建,存在则复用"
"tagNames": "可选,JSON 数组或逗号分隔;名称不存在则自动创建,存在则复用"
}, },
"list": { "list": {
"limit": "每页条数,默认 20,最大 100", "limit": "每页条数,默认 20,最大 100",
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "pichost", "name": "pichost",
"version": "1.4.1", "version": "1.4.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "pichost", "name": "pichost",
"version": "1.4.1", "version": "1.4.2",
"hasInstallScript": true, "hasInstallScript": true,
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"dependencies": { "dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "pichost", "name": "pichost",
"version": "1.4.1", "version": "1.4.2",
"description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk or S3-compatible storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.", "description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk or S3-compatible storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.",
"homepage": "https://github.com/O96u/PicHost#readme", "homepage": "https://github.com/O96u/PicHost#readme",
"repository": { "repository": {
+6 -3
View File
@@ -32,6 +32,9 @@ function validateKeys(keys: string[]): void {
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
await requireApiOrAdminAuth(event) await requireApiOrAdminAuth(event)
const user = await getCurrentUser(event) const user = await getCurrentUser(event)
if (!user) {
createApiError(event, 'UNAUTHORIZED', '批量打标需要登录', 401)
}
const body = await readBody<BatchTagsBody>(event) const body = await readBody<BatchTagsBody>(event)
const keys = Array.isArray(body?.keys) const keys = Array.isArray(body?.keys)
@@ -70,10 +73,10 @@ export default defineEventHandler(async (event) => {
try { try {
for (const key of keys) { for (const key of keys) {
if (action === 'add') { if (action === 'add') {
addTagsToImage(key, tagIds, user!.id, user!.role === 'admin') addTagsToImage(key, tagIds, user.id, user.role === 'admin')
} else { } else {
for (const tagId of tagIds) { for (const tagId of tagIds) {
removeTagFromImage(key, tagId, user!.id, user!.role === 'admin') removeTagFromImage(key, tagId, user.id, user.role === 'admin')
} }
} }
updated++ updated++
@@ -88,7 +91,7 @@ export default defineEventHandler(async (event) => {
originalName: action === 'add' originalName: action === 'add'
? `批量打标(${keys.length} 张)` ? `批量打标(${keys.length} 张)`
: `批量移除标签(${keys.length} 张)`, : `批量移除标签(${keys.length} 张)`,
userId: user!.id userId: user.id
}) })
return { success: true, updated } return { success: true, updated }
+2 -5
View File
@@ -14,7 +14,6 @@ import { createApiError } from '../../utils/api-error'
import { checkUploadRateLimit } from '../../utils/rate-limit' import { checkUploadRateLimit } from '../../utils/rate-limit'
import { readMultipartFormFieldValues } from '../../utils/multipart-form' import { readMultipartFormFieldValues } from '../../utils/multipart-form'
import { import {
parseTagIdsParam,
parseTagNamesParam, parseTagNamesParam,
resolveUploadTagIds resolveUploadTagIds
} from '../../utils/tags' } from '../../utils/tags'
@@ -34,13 +33,11 @@ export default defineEventHandler(async (event) => {
checkUploadRateLimit(event, formToken) checkUploadRateLimit(event, formToken)
const source = verifyApiUploadToken(event) ? 'api' : 'web' const source = verifyApiUploadToken(event) ? 'api' : 'web'
const uploadUserId = await getUploadUserId(event) const uploadUserId = await getUploadUserId(event, formToken)
const tagIdsRaw = readMultipartFormFieldValues(formData, 'tagIds')
const tagNamesRaw = readMultipartFormFieldValues(formData, 'tagNames') const tagNamesRaw = readMultipartFormFieldValues(formData, 'tagNames')
const uploadTagIdsInput = parseTagIdsParam(tagIdsRaw.length === 1 ? tagIdsRaw[0] : tagIdsRaw)
const uploadTagNames = parseTagNamesParam(tagNamesRaw.length === 1 ? tagNamesRaw[0] : tagNamesRaw) const uploadTagNames = parseTagNamesParam(tagNamesRaw.length === 1 ? tagNamesRaw[0] : tagNamesRaw)
const resolvedTags = resolveUploadTagIds(uploadUserId, uploadTagIdsInput, uploadTagNames) const resolvedTags = resolveUploadTagIds(uploadUserId, uploadTagNames)
if ('message' in resolvedTags) { if ('message' in resolvedTags) {
createApiError(event, 'INVALID_REQUEST', resolvedTags.message, 400) createApiError(event, 'INVALID_REQUEST', resolvedTags.message, 400)
} }
+6 -7
View File
@@ -1,5 +1,5 @@
import { readMultipartFormData } from 'h3' import { readMultipartFormData } from 'h3'
import { verifyUploadTokenValue } from '../../utils/access' import { verifyUploadTokenValue, getUploadUserId } from '../../utils/access'
import { checkUploadRateLimit } from '../../utils/rate-limit' import { checkUploadRateLimit } from '../../utils/rate-limit'
import { import {
detectMimeFromSignature, detectMimeFromSignature,
@@ -9,7 +9,6 @@ import {
mimeMatchesDeclared, mimeMatchesDeclared,
processSingleImageUpload processSingleImageUpload
} from '../../utils/process-image-upload' } from '../../utils/process-image-upload'
import { getApiUploadToken } from '../../utils/env'
/** EasyImages 2.0 兼容上传(Twikoo IMAGE_CDN=easyimage) */ /** EasyImages 2.0 兼容上传(Twikoo IMAGE_CDN=easyimage) */
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
@@ -29,15 +28,14 @@ export default defineEventHandler(async (event) => {
: '' : ''
if (!devBypass) { if (!devBypass) {
if (!getApiUploadToken(event)) { if (!token || !verifyUploadTokenValue(event, token)) {
return easyImageError(500, '服务端未配置 API_UPLOAD_TOKEN')
}
if (!verifyUploadTokenValue(event, token)) {
return easyImageError(401, 'token 错误或无效') return easyImageError(401, 'token 错误或无效')
} }
checkUploadRateLimit(event, token) checkUploadRateLimit(event, token)
} }
const uploadUserId = await getUploadUserId(event, token)
const imagePart = formData.find( const imagePart = formData.find(
part => part.name === 'image' && part.data?.length part => part.name === 'image' && part.data?.length
) )
@@ -60,7 +58,8 @@ export default defineEventHandler(async (event) => {
const result = await processSingleImageUpload(event, { const result = await processSingleImageUpload(event, {
bytes, bytes,
filename: imagePart.filename, filename: imagePart.filename,
source: 'api' source: 'api',
userId: uploadUserId
}) })
if ('error' in result) { if ('error' in result) {
+58 -11
View File
@@ -1,5 +1,5 @@
import type { H3Event } from 'h3' import type { H3Event } from 'h3'
import { findUserByApiToken } from './db' import { findUserByApiToken, getPrimaryAdminUserId } from './db'
import { getAdminSecret, getApiUploadToken } from './env' import { getAdminSecret, getApiUploadToken } from './env'
import { createApiError } from './api-error' import { createApiError } from './api-error'
import { import {
@@ -85,10 +85,29 @@ export function verifyGlobalApiUploadToken(event: H3Event): boolean {
return timingSafeEqual(token, expected) return timingSafeEqual(token, expected)
} }
export function resolveUserIdFromApiToken(event: H3Event): number | null { function resolveUserIdFromTokenValue(token: string): number | null {
const token = extractApiToken(event) const trimmed = token.trim()
if (!token) return null if (!trimmed) return null
return findUserByApiToken(token)?.id ?? null return findUserByApiToken(trimmed)?.id ?? null
}
/** 从 Auth-Token 请求头或表单 token 解析个人 API Token 对应用户(非全站 Token) */
export function resolveUserIdFromApiToken(
event: H3Event,
extraToken?: string
): number | null {
const headerToken = extractApiToken(event)
if (headerToken) {
const fromHeader = resolveUserIdFromTokenValue(headerToken)
if (fromHeader !== null) return fromHeader
}
if (extraToken) {
const fromForm = resolveUserIdFromTokenValue(extraToken)
if (fromForm !== null) return fromForm
}
return null
} }
export function verifyApiUploadToken(event: H3Event): boolean { export function verifyApiUploadToken(event: H3Event): boolean {
@@ -222,20 +241,48 @@ export function resolveActivitySource(event: H3Event): 'api' | 'web' {
return verifyApiUploadToken(event) ? 'api' : 'web' return verifyApiUploadToken(event) ? 'api' : 'web'
} }
export async function getUploadUserId(event: H3Event): Promise<number | null> { function resolveUploadOwnerFromGlobalToken(
event: H3Event,
formToken?: string
): number | null {
const expected = getApiUploadToken(event)
if (!expected) return null
const headerToken = extractApiToken(event)
if (headerToken && timingSafeEqual(headerToken, expected)) {
return getPrimaryAdminUserId()
}
const trimmedForm = formToken?.trim()
if (trimmedForm && timingSafeEqual(trimmedForm, expected)) {
return getPrimaryAdminUserId()
}
return null
}
export async function getUploadUserId(
event: H3Event,
formToken?: string
): Promise<number | null> {
if (devBypass(event)) { if (devBypass(event)) {
return null return null
} }
const userIdFromToken = resolveUserIdFromApiToken(event) const userIdFromToken = resolveUserIdFromApiToken(event, formToken)
if (userIdFromToken !== null) { if (userIdFromToken !== null) {
return userIdFromToken return userIdFromToken
} }
if (verifyGlobalApiUploadToken(event)) { const user = await getCurrentUser(event)
return null if (user) {
return user.id
} }
const user = await getCurrentUser(event) const globalOwnerId = resolveUploadOwnerFromGlobalToken(event, formToken)
return user?.id ?? null if (globalOwnerId !== null) {
return globalOwnerId
}
return null
} }
+8
View File
@@ -414,6 +414,14 @@ export function listAdminUserIds(): Set<number> {
return new Set(rows.map(row => row.id)) return new Set(rows.map(row => row.id))
} }
/** 首个管理员(按 id),用于遗留全站 Token 上传归属 */
export function getPrimaryAdminUserId(): number | null {
const row = getDb().prepare(`
SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1
`).get() as { id: number } | undefined
return row?.id ?? null
}
export function setUserAutoDeleteDays(userId: number, days: number): void { export function setUserAutoDeleteDays(userId: number, days: number): void {
setUserAutoDeletePolicy(userId, days) setUserAutoDeletePolicy(userId, days)
} }
+3 -6
View File
@@ -67,14 +67,11 @@ describe('parseTagNamesParam', () => {
describe('resolveUploadTagIds', () => { describe('resolveUploadTagIds', () => {
it('returns empty when no tags requested', () => { it('returns empty when no tags requested', () => {
expect(resolveUploadTagIds(1, [], [])).toEqual({ tagIds: [] }) expect(resolveUploadTagIds(1, [])).toEqual({ tagIds: [] })
}) })
it('requires user when tags are requested', () => { it('requires user when tag names are requested', () => {
expect(resolveUploadTagIds(null, [1], [])).toMatchObject({ expect(resolveUploadTagIds(null, ['博客'])).toMatchObject({
message: expect.stringContaining('API Token')
})
expect(resolveUploadTagIds(null, [], ['博客'])).toMatchObject({
message: expect.stringContaining('API Token') message: expect.stringContaining('API Token')
}) })
}) })
+104 -29
View File
@@ -1,5 +1,6 @@
import { getDb } from './db' import { getDb } from './db'
import { getImageIndexRow } from './image-index' import { getImageIndexRow } from './image-index'
import { toCanonicalImageKey } from './image-key'
export const TAG_COLOR_PRESETS = [ export const TAG_COLOR_PRESETS = [
'#22c55e', '#22c55e',
@@ -310,17 +311,65 @@ function assertTagsOwnedByUser(userId: number, tagIds: number[]): void {
} }
} }
function resolveImageOwnerUserId(key: string): number | null { function resolveIndexedImageKey(key: string): string | null {
const row = getImageIndexRow(key) if (getImageIndexRow(key)) return key
return row?.user_id ?? null const canonical = toCanonicalImageKey(key)
if (canonical && getImageIndexRow(canonical)) return canonical
return null
}
/** 打标时标签归属的用户:无上传者的索引图用操作者自己的标签 */
function resolveTagOwnerUserId(
imageOwnerUserId: number | null,
actorUserId: number
): number {
return imageOwnerUserId ?? actorUserId
}
/**
* 管理员给他人图片打标时,将操作者选中的 tagId 按名称映射到图片所有者的标签。
*/
export function resolveTagIdsForImageTagging(
actorUserId: number,
tagIds: number[],
imageOwnerUserId: number | null,
isAdmin: boolean
): number[] {
const tagOwnerUserId = resolveTagOwnerUserId(imageOwnerUserId, actorUserId)
const unique = [...new Set(tagIds)]
if (!unique.length) return []
if (tagOwnerUserId === actorUserId || !isAdmin) {
assertTagsOwnedByUser(tagOwnerUserId, unique)
return unique
}
const resolved: number[] = []
for (const tagId of unique) {
const row = getTagById(tagId)
if (!row) {
throw new Error('TAG_NOT_FOUND')
}
if (row.user_id === tagOwnerUserId) {
resolved.push(tagId)
continue
}
if (row.user_id === actorUserId) {
resolved.push(findOrCreateTagByName(tagOwnerUserId, row.name).id)
continue
}
throw new Error('TAG_NOT_FOUND')
}
return [...new Set(resolved)]
} }
export function assertCanTagImage(key: string, actorUserId: number, isAdmin: boolean): void { export function assertCanTagImage(key: string, actorUserId: number, isAdmin: boolean): void {
const ownerId = resolveImageOwnerUserId(key) const indexedKey = resolveIndexedImageKey(key)
if (ownerId == null) { if (!indexedKey) {
throw new Error('IMAGE_NOT_FOUND') throw new Error('IMAGE_NOT_FOUND')
} }
if (!isAdmin && ownerId !== actorUserId) { const ownerId = getImageIndexRow(indexedKey)!.user_id
if (!isAdmin && (ownerId === null || ownerId !== actorUserId)) {
throw new Error('FORBIDDEN') throw new Error('FORBIDDEN')
} }
} }
@@ -332,19 +381,27 @@ export function addTagsToImage(
isAdmin: boolean isAdmin: boolean
): TagItem[] { ): TagItem[] {
ensureTagSchema() ensureTagSchema()
assertCanTagImage(key, actorUserId, isAdmin) const indexedKey = resolveIndexedImageKey(key)
const ownerId = resolveImageOwnerUserId(key)! if (!indexedKey) {
const uniqueTagIds = [...new Set(tagIds)] throw new Error('IMAGE_NOT_FOUND')
assertTagsOwnedByUser(ownerId, uniqueTagIds) }
assertCanTagImage(indexedKey, actorUserId, isAdmin)
const imageOwnerUserId = getImageIndexRow(indexedKey)!.user_id
const uniqueTagIds = resolveTagIdsForImageTagging(
actorUserId,
tagIds,
imageOwnerUserId,
isAdmin
)
const insert = getDb().prepare(` const insert = getDb().prepare(`
INSERT OR IGNORE INTO image_tags (image_key, tag_id) VALUES (?, ?) INSERT OR IGNORE INTO image_tags (image_key, tag_id) VALUES (?, ?)
`) `)
for (const tagId of uniqueTagIds) { for (const tagId of uniqueTagIds) {
insert.run(key, tagId) insert.run(indexedKey, tagId)
} }
return getTagsForImageKeys([key]).get(key) ?? [] return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
} }
export function removeTagFromImage( export function removeTagFromImage(
@@ -354,15 +411,27 @@ export function removeTagFromImage(
isAdmin: boolean isAdmin: boolean
): TagItem[] { ): TagItem[] {
ensureTagSchema() ensureTagSchema()
assertCanTagImage(key, actorUserId, isAdmin) const indexedKey = resolveIndexedImageKey(key)
const ownerId = resolveImageOwnerUserId(key)! if (!indexedKey) {
assertTagsOwnedByUser(ownerId, [tagId]) throw new Error('IMAGE_NOT_FOUND')
}
assertCanTagImage(indexedKey, actorUserId, isAdmin)
const imageOwnerUserId = getImageIndexRow(indexedKey)!.user_id
const [resolvedTagId] = resolveTagIdsForImageTagging(
actorUserId,
[tagId],
imageOwnerUserId,
isAdmin
)
if (resolvedTagId == null) {
return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
}
getDb().prepare(` getDb().prepare(`
DELETE FROM image_tags WHERE image_key = ? AND tag_id = ? DELETE FROM image_tags WHERE image_key = ? AND tag_id = ?
`).run(key, tagId) `).run(indexedKey, resolvedTagId)
return getTagsForImageKeys([key]).get(key) ?? [] return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
} }
export function setImageTags( export function setImageTags(
@@ -372,20 +441,28 @@ export function setImageTags(
isAdmin: boolean isAdmin: boolean
): TagItem[] { ): TagItem[] {
ensureTagSchema() ensureTagSchema()
assertCanTagImage(key, actorUserId, isAdmin) const indexedKey = resolveIndexedImageKey(key)
const ownerId = resolveImageOwnerUserId(key)! if (!indexedKey) {
const uniqueTagIds = [...new Set(tagIds)] throw new Error('IMAGE_NOT_FOUND')
assertTagsOwnedByUser(ownerId, uniqueTagIds) }
assertCanTagImage(indexedKey, actorUserId, isAdmin)
const imageOwnerUserId = getImageIndexRow(indexedKey)!.user_id
const uniqueTagIds = resolveTagIdsForImageTagging(
actorUserId,
tagIds,
imageOwnerUserId,
isAdmin
)
const db = getDb() const db = getDb()
db.exec('BEGIN') db.exec('BEGIN')
try { try {
db.prepare('DELETE FROM image_tags WHERE image_key = ?').run(key) db.prepare('DELETE FROM image_tags WHERE image_key = ?').run(indexedKey)
const insert = db.prepare(` const insert = db.prepare(`
INSERT INTO image_tags (image_key, tag_id) VALUES (?, ?) INSERT INTO image_tags (image_key, tag_id) VALUES (?, ?)
`) `)
for (const tagId of uniqueTagIds) { for (const tagId of uniqueTagIds) {
insert.run(key, tagId) insert.run(indexedKey, tagId)
} }
db.exec('COMMIT') db.exec('COMMIT')
} catch (error) { } catch (error) {
@@ -393,7 +470,7 @@ export function setImageTags(
throw error throw error
} }
return getTagsForImageKeys([key]).get(key) ?? [] return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
} }
export function attachTagsAfterUpload( export function attachTagsAfterUpload(
@@ -529,22 +606,20 @@ export function resolveTagIdsFromNames(userId: number, names: readonly string[])
export function resolveUploadTagIds( export function resolveUploadTagIds(
userId: number | null, userId: number | null,
tagIds: number[],
tagNames: string[] tagNames: string[]
): { tagIds: number[] } | { message: string } { ): { tagIds: number[] } | { message: string } {
if (!tagIds.length && !tagNames.length) { if (!tagNames.length) {
return { tagIds: [] } return { tagIds: [] }
} }
if (userId == null) { if (userId == null) {
return { return {
message: '打标签需要登录或使用绑定用户的 API Token' message: '使用 tagNames 时请登录或通过 Auth-Token / 表单 token 提供有效 API Token'
} }
} }
try { try {
const fromNames = tagNames.length ? resolveTagIdsFromNames(userId, tagNames) : [] return { tagIds: resolveTagIdsFromNames(userId, tagNames) }
return { tagIds: [...new Set([...tagIds, ...fromNames])] }
} catch (error) { } catch (error) {
if (error instanceof Error) { if (error instanceof Error) {
switch (error.message) { switch (error.message) {