fix:图片访问
fix:权限修改
This commit is contained in:
1 parent
653b4688cd
commit
3ea7c4e872
6 files changed
+526
No files matched your search
@@ -0,0 +1,126 @@
|
||||
import * as CryptoJS from 'crypto-js'
|
||||
|
||||
export const FILE_ACCESS_FIELDS = ['appId', 'kid', 'ts', 'sign']
|
||||
const FILE_PATHS = ['/sys-file/oss/file', '/admin/sys-file/oss/file', '/api/admin/sys-file/oss/file']
|
||||
export interface FileAccessOptions {
|
||||
appId: string; kid: string; key: string; baseUrl: () => string
|
||||
allowedOrigins?: string[]; now?: () => number
|
||||
}
|
||||
const decode = (s: string) => decodeURIComponent(s.replace(/\+/g, ' '))
|
||||
const encode = (s: string) => encodeURIComponent(s).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
|
||||
const origin = (s: string) => {
|
||||
const match = /^(https?):\/\/([^/?#]+)/i.exec(s)
|
||||
if (!match || match[2].includes('@')) return ''
|
||||
return (match[1] + '://' + match[2]).toLowerCase().replace(match[1].toLowerCase() === 'https' ? /:443$/ : /:80$/, '')
|
||||
}
|
||||
export function fileAccessCanonical(file: string, app: string, kid: string, ts: number): string {
|
||||
const name = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(file)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
return ['v1', 'oss-file-read', app, kid, String(ts), name].join('\n')
|
||||
}
|
||||
export function fileAccessSignature(file: string, app: string, kid: string, ts: number, key: string): string {
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(key) || CryptoJS.enc.Base64.parse(key).sigBytes < 32) throw new Error('Invalid file access key')
|
||||
return CryptoJS.HmacSHA256(fileAccessCanonical(file, app, kid, ts), CryptoJS.enc.Base64.parse(key)).toString(CryptoJS.enc.Hex)
|
||||
}
|
||||
export function createFileAccess(options: FileAccessOptions) {
|
||||
const now = options.now || Date.now
|
||||
let offset = 0, ttl = 1800
|
||||
const cache = new Map<string, { url: string; ts: number }>()
|
||||
const base = () => (options.baseUrl() || '').replace(/\/+$/, '')
|
||||
const allowed = () => [origin(base()), ...(options.allowedOrigins || []).map(origin)].filter(Boolean)
|
||||
function resolve(source?: string | null): string {
|
||||
const raw = typeof source === 'string' ? source.trim() : ''
|
||||
if (!raw || /^(?:data:|blob:|file:|wxfile:|content:|\/static\/|static\/|\/assets\/|\/src\/|@\/|#)/i.test(raw)) return raw
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) return raw
|
||||
if (raw.startsWith('//')) return (base().startsWith('http:') ? 'http:' : 'https:') + raw
|
||||
const root = base()
|
||||
if (/^[^/?#:\\]+\.[a-z0-9]{1,10}$/i.test(raw)) return root + '/admin/sys-file/oss/file?fileName=' + encode(raw)
|
||||
const path = raw.startsWith('/') ? raw : '/' + raw
|
||||
if (/^(?:\/api)?\/admin\/sys-file\/oss\/(?:file|access-info)(?:[?#]|$)/.test(path)) return root + path.replace(/^\/api\//, '/')
|
||||
const prefix = root.replace(/^https?:\/\/[^/?#]+/i, '')
|
||||
if ((prefix && path.startsWith(prefix + '/')) || path.startsWith('/api/')) return (origin(root) || '') + path
|
||||
if (path.startsWith('/sys-file/oss/')) return root + '/admin' + path
|
||||
if (raw.startsWith('?')) return root + '/admin/sys-file/oss/file' + raw
|
||||
return root + path
|
||||
}
|
||||
function parse(source?: string | null) {
|
||||
const resolved = resolve(source)
|
||||
const ownOrigin = origin(resolved)
|
||||
if (ownOrigin && !allowed().includes(ownOrigin)) return null
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(resolved) && !ownOrigin) return null
|
||||
const relative = ownOrigin ? resolved.replace(/^https?:\/\/[^/?#]+/i, '') : resolved
|
||||
const path = relative.split(/[?#]/)[0]
|
||||
const prefix = base().replace(/^https?:\/\/[^/?#]+/i, '')
|
||||
if (!FILE_PATHS.includes(path) && path !== prefix + '/admin/sys-file/oss/file') return null
|
||||
const hashAt = resolved.indexOf('#'), head = hashAt < 0 ? resolved : resolved.slice(0, hashAt)
|
||||
const hash = hashAt < 0 ? '' : resolved.slice(hashAt)
|
||||
const question = head.indexOf('?')
|
||||
const endpoint = question < 0 ? head : head.slice(0, question)
|
||||
const pairs = (question < 0 ? '' : head.slice(question + 1)).split('&').filter(Boolean).map(pair => {
|
||||
const at = pair.indexOf('='); return [decode(at < 0 ? pair : pair.slice(0, at)), decode(at < 0 ? '' : pair.slice(at + 1))]
|
||||
})
|
||||
const names = pairs.filter(([key]) => key === 'fileName')
|
||||
if (names.length !== 1 || !names[0][1] || /[\r\n]/.test(names[0][1])) throw new Error('Invalid file-center URL')
|
||||
const extras = pairs.filter(([key]) => key !== 'fileName' && !FILE_ACCESS_FIELDS.includes(key))
|
||||
const unsigned = endpoint + '?' + [...extras, ['fileName', names[0][1]]].map(([k, v]) => encode(k) + '=' + encode(v)).join('&') + hash
|
||||
return { endpoint, file: names[0][1], extras, hash, unsigned }
|
||||
}
|
||||
function url(source?: string | null, force = false): string {
|
||||
const parsed = parse(source)
|
||||
if (!parsed) return resolve(source)
|
||||
const seconds = Math.floor((now() + offset) / 1000), cached = cache.get(parsed.unsigned)
|
||||
if (!force && cached && seconds >= cached.ts - 300 && seconds < cached.ts + ttl - Math.min(300, ttl / 6)) return cached.url
|
||||
if (!options.appId || !options.kid) throw new Error('Missing file access configuration')
|
||||
const sign = fileAccessSignature(parsed.file, options.appId, options.kid, seconds, options.key)
|
||||
const pairs = [...parsed.extras, ['appId', options.appId], ['kid', options.kid], ['ts', String(seconds)], ['sign', sign], ['fileName', parsed.file]]
|
||||
const result = parsed.endpoint + '?' + pairs.map(([k, v]) => encode(k) + '=' + encode(v)).join('&') + parsed.hash
|
||||
if (cache.size >= 2048) cache.delete(cache.keys().next().value as string)
|
||||
cache.set(parsed.unsigned, { url: result, ts: seconds })
|
||||
return result
|
||||
}
|
||||
function strip(source?: string | null): string {
|
||||
if (!source) return source || ''
|
||||
const parsed = parse(source)
|
||||
if (!parsed) return source
|
||||
// Preserve the original origin/path form in persisted values.
|
||||
const hashAt = source.indexOf('#'), hash = hashAt < 0 ? '' : source.slice(hashAt)
|
||||
const head = hashAt < 0 ? source : source.slice(0, hashAt), at = head.indexOf('?')
|
||||
if (at < 0) return source
|
||||
const query = head.slice(at + 1).split('&').filter(p => !FILE_ACCESS_FIELDS.includes(decode(p.split('=')[0])))
|
||||
return head.slice(0, at) + (query.length ? '?' + query.join('&') : '') + hash
|
||||
}
|
||||
function synchronize(serverTime: number, ttlSeconds = ttl, roundTripMs = 0) {
|
||||
if (!Number.isFinite(serverTime) || serverTime <= 0) return
|
||||
offset = serverTime + roundTripMs / 2 - now()
|
||||
if (Number.isFinite(ttlSeconds) && ttlSeconds > 300 && ttlSeconds <= 86400) ttl = ttlSeconds
|
||||
cache.clear()
|
||||
}
|
||||
return { url, resolve, strip, protected: (s?: string | null) => !!parse(s), synchronize, clear: () => cache.clear(), ttl: () => ttl }
|
||||
}
|
||||
|
||||
const unescapeAttribute = (s: string) => s.replace(/&/gi, '&').replace(/"/gi, '"').replace(/&#(?:39|x27);/gi, "'").replace(/&#(x[0-9a-f]+|\d+);/gi, (_, n) => { const code = n[0].toLowerCase() === 'x' ? parseInt(n.slice(1), 16) : Number(n); return code <= 0x10ffff ? String.fromCodePoint(code) : ''; })
|
||||
const escapeAttribute = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''')
|
||||
/** Rewrite only resource attributes; no DOM/window dependency (also used by mini programs). */
|
||||
export function rewriteFileHtml(html: string, transform: (url: string) => string): string {
|
||||
if (typeof html !== 'string' || !html) return html
|
||||
return html.replace(/<[a-z][^>]*>/gi, tag => tag.replace(/\b(src|href|poster|srcset)\s*=\s*(["'])([\s\S]*?)\2/gi, (attribute, name, quote, raw) => {
|
||||
const value = unescapeAttribute(raw)
|
||||
const next = name.toLowerCase() === 'srcset' && !value.startsWith('data:')
|
||||
? value.split(',').map(item => item.trim().replace(/^\S+/, transform)).join(', ')
|
||||
: transform(value)
|
||||
return next === value ? attribute : name + '=' + quote + escapeAttribute(next) + quote
|
||||
}).replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi, (all, quote, value) => {
|
||||
const next = transform(unescapeAttribute(value)); return next === value ? all : 'url(' + quote + escapeAttribute(next) + quote + ')'
|
||||
}))
|
||||
}
|
||||
export function rewriteFileNodes(nodes: any, transform: (url: string) => string): any {
|
||||
if (typeof nodes === 'string') return rewriteFileHtml(nodes, transform)
|
||||
if (Array.isArray(nodes)) return nodes.map(node => rewriteFileNodes(node, transform))
|
||||
if (!nodes || typeof nodes !== 'object') return nodes
|
||||
const copy = { ...nodes }
|
||||
if (copy.attrs) {
|
||||
copy.attrs = { ...copy.attrs }
|
||||
for (const key of ['src', 'href', 'poster']) if (typeof copy.attrs[key] === 'string') copy.attrs[key] = transform(copy.attrs[key])
|
||||
}
|
||||
if (copy.children) copy.children = rewriteFileNodes(copy.children, transform)
|
||||
return copy
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { ref } from 'vue'
|
||||
import { createFileAccess, rewriteFileHtml, rewriteFileNodes } from './file-access-core'
|
||||
import { isDevEnv } from './app'
|
||||
|
||||
export const fileAccessRevision = ref(0)
|
||||
const client = createFileAccess({
|
||||
appId: import.meta.env.VITE_FILE_ACCESS_APP_ID,
|
||||
kid: import.meta.env.VITE_FILE_ACCESS_KEY_ID,
|
||||
key: import.meta.env.VITE_FILE_ACCESS_KEY,
|
||||
baseUrl: () => isDevEnv() ? (import.meta.env.VITE_IMAGE_DEV_PATH || import.meta.env.VITE_APP_DEV_SERVICE) : import.meta.env.VITE_APP_PROD_IMAGE,
|
||||
allowedOrigins: [import.meta.env.VITE_IMAGE_DEV_PATH, import.meta.env.VITE_APP_DEV_SERVICE, import.meta.env.VITE_APP_PROD_IMAGE, import.meta.env.VITE_APP_PROD_SERVICE, ...(import.meta.env.VITE_FILE_ACCESS_ALLOWED_ORIGINS || '').split(',')],
|
||||
})
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
let pending: Promise<void> | undefined
|
||||
let lastSync = 0
|
||||
const retried = new Map<string, number>()
|
||||
export function fileUrl(source?: string | null): string {
|
||||
void fileAccessRevision.value
|
||||
try { return client.url(source) } catch { return '' }
|
||||
}
|
||||
export const accessFileUrl = (source?: string | null) => isProtectedFile(source) ? fileUrl(source) : (source || '')
|
||||
export const fileUrls = (sources: any) => Array.isArray(sources) ? sources.map(accessFileUrl) : []
|
||||
export const originalFileUrl = (source?: string | null) => client.strip(source)
|
||||
export const resolveFileUrl = (source?: string | null) => client.resolve(source)
|
||||
export const fileHtml = (html: string) => rewriteFileHtml(html, accessFileUrl)
|
||||
export const stripFileHtml = (html: string) => rewriteFileHtml(html, originalFileUrl)
|
||||
export const fileNodes = (nodes: any) => rewriteFileNodes(nodes, accessFileUrl)
|
||||
export const isProtectedFile = (source?: string | null) => { try { return client.protected(source) } catch { return false } }
|
||||
export async function refreshFileAccess(force = false): Promise<void> {
|
||||
if (pending) return pending
|
||||
if (!force && Date.now() - lastSync < 60000) return
|
||||
pending = (async () => {
|
||||
const started = Date.now()
|
||||
try {
|
||||
const result: any = await readAccessInfo()
|
||||
const info = result?.data || result
|
||||
if (info?.serverTime) client.synchronize(Number(info.serverTime), Number(info.ttlSeconds), Date.now() - started)
|
||||
lastSync = Date.now()
|
||||
} catch { /* Retain the last clock offset and signed access; never fall back to a bare URL. */ }
|
||||
finally { fileAccessRevision.value++; pending = undefined }
|
||||
})()
|
||||
return pending
|
||||
}
|
||||
export function startFileAccess() {
|
||||
if (!timer) timer = setInterval(() => { fileAccessRevision.value++ }, 60000)
|
||||
void refreshFileAccess()
|
||||
}
|
||||
export function stopFileAccess() { if (timer) clearInterval(timer); timer = undefined }
|
||||
export async function retryFileAccess(source?: string | null) {
|
||||
if (!isProtectedFile(source)) return false
|
||||
const raw = originalFileUrl(source), previous = retried.get(raw) || 0
|
||||
if (Date.now() - previous < 30 * 60 * 1000) return false
|
||||
if (retried.size >= 2048) retried.clear()
|
||||
retried.set(raw, Date.now())
|
||||
const previousUrl = fileUrl(source)
|
||||
await refreshFileAccess(true)
|
||||
client.clear()
|
||||
if (fileUrl(source) === previousUrl) {
|
||||
await new Promise(resolve => setTimeout(resolve, 1100))
|
||||
client.clear()
|
||||
}
|
||||
fileAccessRevision.value++
|
||||
return true
|
||||
}
|
||||
export function installFileAccess(app: any) {
|
||||
Object.assign(app.config.globalProperties, {
|
||||
$fileUrl: accessFileUrl, $fileUrls: fileUrls, $fileHtml: fileHtml, $fileNodes: fileNodes, $fileRetry: retryFileAccess,
|
||||
})
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('click', event => {
|
||||
const anchor = (event.target as Element | null)?.closest?.('a[href]')
|
||||
const href = anchor?.getAttribute('href')
|
||||
if (event.defaultPrevented || !href || !isProtectedFile(href)) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
openFileLink(href)
|
||||
}, true)
|
||||
}
|
||||
app.mixin({
|
||||
onShow() { startFileAccess() },
|
||||
})
|
||||
uni.onNetworkStatusChange(({ isConnected }: any) => {
|
||||
if (isConnected) { retried.clear(); void refreshFileAccess(true) }
|
||||
})
|
||||
}
|
||||
|
||||
function readAccessInfo(): Promise<any> {
|
||||
return new Promise((resolve, reject) => uni.request({
|
||||
url: client.resolve('/admin/sys-file/oss/access-info'), method: 'GET', timeout: 5000,
|
||||
success: (response: any) => response.statusCode === 200 ? resolve(response.data) : reject(new Error('File clock unavailable')),
|
||||
fail: reject,
|
||||
}))
|
||||
}
|
||||
/** All preview entrypoints sign at the moment of opening, including already-open pages. */
|
||||
export function previewFiles(options: any) {
|
||||
const values = { ...options, urls: fileUrls(options.urls) }
|
||||
if (typeof options.current === 'string') values.current = fileUrl(options.current)
|
||||
return uni.previewImage(values)
|
||||
}
|
||||
/** One clock/signature retry. Only successful downloads are delivered to the caller. */
|
||||
export function downloadFile(options: any) {
|
||||
const run = (retry: boolean) => uni.downloadFile({
|
||||
...options, url: fileUrl(options.url),
|
||||
success: async (response: any) => {
|
||||
if (response.statusCode === 200) { options.success?.(response); options.complete?.(response); return }
|
||||
if (retry && response.statusCode === 403 && isProtectedFile(options.url)) {
|
||||
await refreshFileAccess(true); client.clear(); run(false); return
|
||||
}
|
||||
const error = { errMsg: '文件下载失败', statusCode: response.statusCode }
|
||||
options.fail?.(error); options.complete?.(error)
|
||||
if (!options.fail) uni.showToast({ title: error.errMsg, icon: 'none' })
|
||||
},
|
||||
complete: undefined,
|
||||
fail: (error: any) => { options.fail?.(error); options.complete?.(error) },
|
||||
})
|
||||
return run(true)
|
||||
}
|
||||
|
||||
/** Open owned rich-text file links without navigating the browser to the file endpoint. */
|
||||
export function openFileLink(source: string) {
|
||||
const match = /[?&]fileName=([^&#]*)/.exec(resolveFileUrl(source))
|
||||
const filename = match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : '文件'
|
||||
if (/\.(?:jpe?g|png|gif|webp|bmp|svg|ico)$/i.test(filename)) {
|
||||
return previewFiles({ urls: [source] })
|
||||
}
|
||||
return downloadFile({
|
||||
url: source,
|
||||
success: (response: any) => {
|
||||
if (typeof document !== 'undefined') {
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = response.tempFilePath
|
||||
anchor.download = filename
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
} else {
|
||||
uni.openDocument({
|
||||
filePath: response.tempFilePath, showMenu: true,
|
||||
fail: () => uni.showToast({ title: '无法打开此文件', icon: 'none' }),
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
import 'vue'
|
||||
declare module '@vue/runtime-core' {
|
||||
interface ComponentCustomProperties {
|
||||
$fileUrl: (source?: string | null) => string
|
||||
$fileUrls: (sources: any) => string[]
|
||||
$fileHtml: (html: string) => string
|
||||
$fileNodes: (nodes: any) => any
|
||||
$fileRetry: (source?: string | null) => Promise<boolean>
|
||||
}
|
||||
}
|
||||
export {}
|
||||
Reference in new issue
Block a user