@luckylillia-dev/plugin-aiimgdetector 0.0.0-stage → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/assets/demo.png +0 -0
- package/assets/icon.svg +15 -0
- package/assets/synthid-login-check.jpg +0 -0
- package/docs/details.md +45 -0
- package/docs/publishing.md +66 -0
- package/docs/synthid.md +80 -0
- package/lib/image.js +90 -0
- package/lib/index.js +207 -0
- package/lib/provenance.js +21 -0
- package/lib/synthid-auth.js +100 -0
- package/lib/synthid-browser.js +451 -0
- package/lib/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
- package/lib/synthid-http-runtime/complete-protocol.mjs +88 -0
- package/lib/synthid-http-runtime/entry.d.mts +41 -0
- package/lib/synthid-http-runtime/entry.mjs +6 -0
- package/lib/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
- package/lib/synthid-http-runtime/independent-request-reference.mjs +49 -0
- package/lib/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
- package/lib/synthid-http-runtime/lifecycle-client.mjs +165 -0
- package/lib/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
- package/lib/synthid-http-runtime/lifecycle-worker.mjs +363 -0
- package/lib/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
- package/lib/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
- package/lib/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
- package/lib/synthid-http-runtime/realm-init.js +34 -0
- package/lib/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
- package/lib/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
- package/lib/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
- package/lib/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
- package/lib/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
- package/lib/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
- package/lib/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
- package/lib/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
- package/lib/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
- package/lib/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
- package/lib/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
- package/lib/synthid-http-runtime/runtime-web-compat.mjs +639 -0
- package/lib/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
- package/lib/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
- package/lib/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
- package/lib/synthid-http-runtime/scripting-parser.mjs +13 -0
- package/lib/synthid-http-runtime/web-session.mjs +64 -0
- package/lib/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
- package/lib/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
- package/lib/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
- package/lib/synthid-http.js +314 -0
- package/lib/synthid-manual.js +365 -0
- package/lib/synthid-page.js +101 -0
- package/lib/synthid-result.js +189 -0
- package/lib/synthid.js +540 -0
- package/lib/vision.js +41 -0
- package/package.json +84 -4
- package/src/image.ts +74 -0
- package/src/index.ts +203 -0
- package/src/provenance.ts +40 -0
- package/src/synthid-auth.ts +83 -0
- package/src/synthid-browser.ts +426 -0
- package/src/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
- package/src/synthid-http-runtime/complete-protocol.mjs +88 -0
- package/src/synthid-http-runtime/entry.d.mts +41 -0
- package/src/synthid-http-runtime/entry.mjs +6 -0
- package/src/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
- package/src/synthid-http-runtime/independent-request-reference.mjs +49 -0
- package/src/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
- package/src/synthid-http-runtime/lifecycle-client.mjs +165 -0
- package/src/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
- package/src/synthid-http-runtime/lifecycle-worker.mjs +363 -0
- package/src/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
- package/src/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
- package/src/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
- package/src/synthid-http-runtime/realm-init.js +34 -0
- package/src/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
- package/src/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
- package/src/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
- package/src/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
- package/src/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
- package/src/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
- package/src/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
- package/src/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
- package/src/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
- package/src/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
- package/src/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
- package/src/synthid-http-runtime/runtime-web-compat.mjs +639 -0
- package/src/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
- package/src/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
- package/src/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
- package/src/synthid-http-runtime/scripting-parser.mjs +13 -0
- package/src/synthid-http-runtime/web-session.mjs +64 -0
- package/src/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
- package/src/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
- package/src/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
- package/src/synthid-http.ts +290 -0
- package/src/synthid-manual.ts +388 -0
- package/src/synthid-page.ts +103 -0
- package/src/synthid-result.ts +177 -0
- package/src/synthid.ts +514 -0
- package/src/vision.ts +57 -0
- package/webui/index.js +279 -0
package/src/image.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Context } from '@luckylillia-dev/plugin-sdk'
|
|
2
|
+
|
|
3
|
+
/** Downloaded once, for every check */
|
|
4
|
+
export interface Image {
|
|
5
|
+
data: ArrayBuffer
|
|
6
|
+
type: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const MAX_SIZE = 20 * 1024 * 1024
|
|
10
|
+
// Exact QQ media hosts only. Message senders cannot introduce a domain they
|
|
11
|
+
// control, a local address, a different port, or a redirect destination.
|
|
12
|
+
const IMAGE_HOSTS = new Set(['gchat.qpic.cn', 'c2cpicdw.qpic.cn', 'multimedia.nt.qq.com.cn'])
|
|
13
|
+
|
|
14
|
+
function imageUrl(input: string): URL {
|
|
15
|
+
if (typeof input !== 'string' || input.length > 16 * 1024 || /[\x00-\x20\x7f\\]/.test(input)) throw new Error('unsupported image URL')
|
|
16
|
+
let url: URL
|
|
17
|
+
try { url = new URL(input) } catch { throw new Error('unsupported image URL') }
|
|
18
|
+
if (!['http:', 'https:'].includes(url.protocol) || !IMAGE_HOSTS.has(url.hostname)
|
|
19
|
+
|| url.port || url.username || url.password) throw new Error('unsupported image URL')
|
|
20
|
+
// Older QQ adapters return http: URLs for the same CDN. Always use TLS.
|
|
21
|
+
url.protocol = 'https:'
|
|
22
|
+
url.hash = ''
|
|
23
|
+
return url
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function imageType(bytes: Uint8Array): string | undefined {
|
|
27
|
+
const starts = (...signature: number[]) => signature.every((byte, index) => bytes[index] === byte)
|
|
28
|
+
const text = (start: number, end: number) => String.fromCharCode(...bytes.subarray(start, end))
|
|
29
|
+
if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return 'image/png'
|
|
30
|
+
if (starts(0xff, 0xd8, 0xff)) return 'image/jpeg'
|
|
31
|
+
if (['GIF87a', 'GIF89a'].includes(text(0, 6))) return 'image/gif'
|
|
32
|
+
if (text(0, 4) === 'RIFF' && text(8, 12) === 'WEBP') return 'image/webp'
|
|
33
|
+
if (starts(0x42, 0x4d)) return 'image/bmp'
|
|
34
|
+
if (starts(0x49, 0x49, 0x2a, 0) || starts(0x4d, 0x4d, 0, 0x2a)) return 'image/tiff'
|
|
35
|
+
if (text(4, 8) === 'ftyp' && bytes.length >= 16) {
|
|
36
|
+
const brands = [text(8, 12)]
|
|
37
|
+
for (let offset = 16; offset + 4 <= Math.min(bytes.length, 64); offset += 4) brands.push(text(offset, offset + 4))
|
|
38
|
+
if (brands.some(brand => ['avif', 'avis'].includes(brand))) return 'image/avif'
|
|
39
|
+
if (brands.some(brand => ['heic', 'heix', 'hevc', 'hevx'].includes(brand))) return 'image/heic'
|
|
40
|
+
if (brands.some(brand => ['mif1', 'msf1'].includes(brand))) return 'image/heif'
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function download(ctx: Context, url: string): Promise<Image> {
|
|
45
|
+
const target = imageUrl(url)
|
|
46
|
+
const response = await ctx.http.fetch(target.href, {
|
|
47
|
+
redirect: 'error', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(30_000),
|
|
48
|
+
}, { timeout: 30_000, proxyAgent: '' })
|
|
49
|
+
const length = response.headers.get('content-length')
|
|
50
|
+
if (!response.ok || response.redirected || length !== null && Number(length) > MAX_SIZE || !response.body) {
|
|
51
|
+
await response.body?.cancel()
|
|
52
|
+
throw new Error('image download was refused or exceeds 20 MB')
|
|
53
|
+
}
|
|
54
|
+
const reader = response.body.getReader(), chunks: Uint8Array[] = []
|
|
55
|
+
let size = 0
|
|
56
|
+
try {
|
|
57
|
+
while (true) {
|
|
58
|
+
const { done, value } = await reader.read()
|
|
59
|
+
if (done) break
|
|
60
|
+
size += value.byteLength
|
|
61
|
+
if (size > MAX_SIZE) throw new Error('the image is over 20 MB')
|
|
62
|
+
chunks.push(value)
|
|
63
|
+
}
|
|
64
|
+
} catch (error) {
|
|
65
|
+
await reader.cancel().catch(() => {})
|
|
66
|
+
throw error
|
|
67
|
+
} finally { reader.releaseLock() }
|
|
68
|
+
const data = new Uint8Array(size)
|
|
69
|
+
let offset = 0
|
|
70
|
+
for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.byteLength }
|
|
71
|
+
const type = imageType(data)
|
|
72
|
+
if (!type) throw new Error('the response is not a supported image')
|
|
73
|
+
return { data: data.buffer, type }
|
|
74
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { Context, h, Schema, Session } from '@luckylillia-dev/plugin-sdk'
|
|
2
|
+
import type { AiError } from '@luckylillia-dev/plugin-aiprovider'
|
|
3
|
+
import { download, Image } from './image.js'
|
|
4
|
+
import { checkProvenance, provenanceService } from './provenance.js'
|
|
5
|
+
import { SynthIdClient, handleSynthId, type SynthIdConfig } from './synthid.js'
|
|
6
|
+
import { describeSynthIdFailure, formatSynthId, SynthIdError } from './synthid-result.js'
|
|
7
|
+
import { describeManualSynthIdFailure, ManualSynthIdError } from './synthid-manual.js'
|
|
8
|
+
import { judgeByVision, VisionResult } from './vision.js'
|
|
9
|
+
|
|
10
|
+
export const name = 'aiimgdetector'
|
|
11
|
+
export const inject = ['bots', 'ai', 'http', 'commands']
|
|
12
|
+
|
|
13
|
+
export interface Config {
|
|
14
|
+
trigger: string
|
|
15
|
+
cooldown: number
|
|
16
|
+
provenance: false | { ai: string }
|
|
17
|
+
synthid: false | SynthIdConfig
|
|
18
|
+
vision: false | { ai: string; model: string }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const Config: Schema<Config> = Schema.object({
|
|
22
|
+
trigger: Schema.string().pattern(/^\s*\S*\s*$/).default('ai吗').description('触发词,不分大小写:对着图片回复它,或者它后面直接带图'),
|
|
23
|
+
cooldown: Schema.natural().role('ms').default(10_000).description('同一个群(或私聊)两次检测至少隔多久'),
|
|
24
|
+
provenance: Schema.union([
|
|
25
|
+
Schema.const(false),
|
|
26
|
+
Schema.object({
|
|
27
|
+
ai: Schema.string().role('ai').extra('extra', {
|
|
28
|
+
provider: 'openai',
|
|
29
|
+
emptyHint: 'OpenAI 水印检测免费,但有调用频率限制;请求过于频繁时请稍后再试。',
|
|
30
|
+
}).default('').description('服务'),
|
|
31
|
+
}),
|
|
32
|
+
]).default({ ai: '' }).description('OpenAI 官方 API,检测 ChatGPT 等 OpenAI 工具生成的图片'),
|
|
33
|
+
synthid: Schema.union([
|
|
34
|
+
Schema.const(false).description('不用'),
|
|
35
|
+
Schema.object({
|
|
36
|
+
// Mask credentials from the previous version if an old saved config still contains them.
|
|
37
|
+
// They are ignored by the browser login and are never displayed as form fields.
|
|
38
|
+
refreshToken: Schema.string().role('secret').hidden(),
|
|
39
|
+
bgToken: Schema.string().role('secret').hidden(),
|
|
40
|
+
pushFilename: Schema.string().role('secret').hidden(),
|
|
41
|
+
timeout: Schema.natural().min(1000).max(120_000).role('ms').default(30_000).description('检测超时'),
|
|
42
|
+
credentials: Schema.union([
|
|
43
|
+
Schema.object({
|
|
44
|
+
refreshToken: Schema.string().role('secret').default('').description('登录凭据(refresh_token)'),
|
|
45
|
+
pushFilename: Schema.string().role('secret').default('').hidden(),
|
|
46
|
+
bgToken: Schema.string().role('secret').default('').hidden(),
|
|
47
|
+
}),
|
|
48
|
+
// Migrate the previous browser/manual switch without losing saved secrets.
|
|
49
|
+
Schema.transform(Schema.const(false).hidden(), () => ({ refreshToken: '', pushFilename: '', bgToken: '' })),
|
|
50
|
+
]).default({ refreshToken: '', pushFilename: '', bgToken: '' }).description('登录凭证'),
|
|
51
|
+
}).description('用'),
|
|
52
|
+
]).default(false).description('SynthID 检测,支持 Google、OpenAI、NVIDIA、Kakao 生成的图片'),
|
|
53
|
+
vision: Schema.union([
|
|
54
|
+
Schema.const(false).description('不用'),
|
|
55
|
+
Schema.object({
|
|
56
|
+
ai: Schema.string().default('').description('服务'),
|
|
57
|
+
model: Schema.string().default('').description('模型:请选择支持图片输入的模型'),
|
|
58
|
+
}).role('ai-model').description('用'),
|
|
59
|
+
]).default({ ai: '', model: '' }).description('多模态模型判断:让能看图的 AI 从画面里找 AI 生成的破绽。只是推测,按图片计费'),
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
interface Picked {
|
|
63
|
+
url: string
|
|
64
|
+
/** The message the image is in, which the answer quotes */
|
|
65
|
+
messageId?: string
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const VERDICT_TEXT: Record<VisionResult['verdict'], string> = {
|
|
69
|
+
ai: '疑似 AI 生成',
|
|
70
|
+
real: '更像人工创作',
|
|
71
|
+
unsure: '看不出来',
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function apply(ctx: Context, config: Config) {
|
|
75
|
+
const logger = ctx.logger('aiimgdetector')
|
|
76
|
+
const trigger = config.trigger.trim()
|
|
77
|
+
const lastCheck = new Map<string, number>()
|
|
78
|
+
// Login is available before enabling detection; saving a config must not lose the browser session.
|
|
79
|
+
const synthid = new SynthIdClient(ctx, config.synthid || { timeout: 30_000 })
|
|
80
|
+
ctx.inject(['webuiServer'], (ctx) => {
|
|
81
|
+
// SDK contract: private /api routes run after the host's WebUI password
|
|
82
|
+
// authentication. This is management access, not a QQ message role check.
|
|
83
|
+
ctx.webuiServer.route('/api/aiimgdetector/synthid', { fetch: request => handleSynthId(synthid, request) }, { public: false })
|
|
84
|
+
})
|
|
85
|
+
let active = true
|
|
86
|
+
ctx.effect(() => () => { active = false })
|
|
87
|
+
ctx.on('internal/update', (next: Config, restart) => {
|
|
88
|
+
if (next.trigger.trim() !== trigger) return restart()
|
|
89
|
+
synthid.update(next.synthid || { timeout: 30_000 })
|
|
90
|
+
config = next
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
function cooling(key: string): boolean {
|
|
94
|
+
if (!config.cooldown) return false
|
|
95
|
+
const now = Date.now()
|
|
96
|
+
const last = lastCheck.get(key)
|
|
97
|
+
if (last !== undefined && now - last < config.cooldown) return true
|
|
98
|
+
lastCheck.set(key, now)
|
|
99
|
+
for (const [other, at] of lastCheck) if (now - at >= config.cooldown) lastCheck.delete(other)
|
|
100
|
+
return false
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function verdict(image: Image): Promise<string> {
|
|
104
|
+
// Whether a check ran to the end without finding anything, and what failed on the way
|
|
105
|
+
let checked = false
|
|
106
|
+
let failure: unknown
|
|
107
|
+
let inconclusive: string | undefined
|
|
108
|
+
const watermarkAi = config.provenance
|
|
109
|
+
? provenanceService(ctx.ai, config.provenance.ai) : undefined
|
|
110
|
+
if (watermarkAi) {
|
|
111
|
+
try {
|
|
112
|
+
const answer = await checkProvenance(ctx.ai, watermarkAi, image)
|
|
113
|
+
if (answer.results?.some(result => result.outcome === 'detected')) return '图片由 OpenAI 制作。'
|
|
114
|
+
checked = true
|
|
115
|
+
} catch (e) {
|
|
116
|
+
failure = e
|
|
117
|
+
logger.warn('watermark check failed:', (e as Error).message)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (config.synthid && active) {
|
|
121
|
+
try {
|
|
122
|
+
const result = await synthid.detect(image)
|
|
123
|
+
if (result.status === 'detected') return formatSynthId(result)
|
|
124
|
+
if (result.status === 'not_detected') checked = true
|
|
125
|
+
else if (result.status === 'uncertain') inconclusive = formatSynthId(result)
|
|
126
|
+
else if (result.status === 'quota_exceeded') {
|
|
127
|
+
failure ??= new SynthIdError('rate-limit', 'SynthID account quota exceeded', undefined, result.retryAfterSeconds)
|
|
128
|
+
}
|
|
129
|
+
} catch (e) {
|
|
130
|
+
failure ??= e
|
|
131
|
+
if (active) logger.warn('SynthID check failed:', (e as Error).message)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (config.vision && active) {
|
|
135
|
+
try {
|
|
136
|
+
const result = await judgeByVision(ctx.ai, config.vision, image)
|
|
137
|
+
if (result) return formatVision(result)
|
|
138
|
+
inconclusive ??= '看图模型没有返回检测结果,暂时无法判断。'
|
|
139
|
+
} catch (e) {
|
|
140
|
+
failure ??= e
|
|
141
|
+
logger.warn('vision check failed:', (e as Error).message)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (failure) return describeFailure(failure)
|
|
145
|
+
if (inconclusive) return inconclusive
|
|
146
|
+
if (checked) return formatSynthId({ status: 'not_detected' })
|
|
147
|
+
if (config.provenance) return config.provenance.ai
|
|
148
|
+
? '所选服务无法用于水印检测,请重新选择 OpenAI 官方服务,或打开看图判断。'
|
|
149
|
+
: '没有可用于水印检测的 OpenAI 官方服务,请在 AI 服务中添加,或打开看图判断。'
|
|
150
|
+
return '还没有打开任何检测,请在 aiimgdetector 插件的设置里打开。'
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (!trigger) return
|
|
154
|
+
ctx.command(trigger, '检测图片是否由 AI 生成').action(async ({ session, next }) => {
|
|
155
|
+
const picked = pickImage(session)
|
|
156
|
+
// A message starting with the word is not always meant for this plugin
|
|
157
|
+
if (!picked) return next()
|
|
158
|
+
if (cooling(`${session.platform}:${session.channelId}`)) return next()
|
|
159
|
+
// Quote the message the image is in: with several images in a busy group, that says which one it was about
|
|
160
|
+
const reply = (text: string) => session.send(picked.messageId ? [h('quote', { id: picked.messageId }), h.text(text)] : h.text(text))
|
|
161
|
+
let image: Image
|
|
162
|
+
try {
|
|
163
|
+
image = await download(ctx, picked.url)
|
|
164
|
+
} catch (e) {
|
|
165
|
+
logger.warn('cannot download the image:', (e as Error).message)
|
|
166
|
+
await reply('图片下载失败,请稍后再试。')
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
if (!active) return
|
|
170
|
+
const answer = await verdict(image)
|
|
171
|
+
if (active) await reply(answer)
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** An image of the message itself first, then one of the message it quotes */
|
|
176
|
+
function pickImage(session: Session): Picked | undefined {
|
|
177
|
+
const own = h.select(session.elements.filter(element => element.type !== 'quote'), 'img')[0]
|
|
178
|
+
if (own) return { url: String(own.attrs.src ?? own.attrs.url), messageId: session.messageId }
|
|
179
|
+
const quote = session.elements.find(element => element.type === 'quote')
|
|
180
|
+
const quoted = quote && h.select(quote.children, 'img')[0]
|
|
181
|
+
if (quoted) return { url: String(quoted.attrs.src ?? quoted.attrs.url), messageId: quote.attrs.id || session.messageId }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function formatVision(result: VisionResult): string {
|
|
185
|
+
if (result.raw) return `${result.model} 判断:${result.raw}`
|
|
186
|
+
const head = result.confidence ? `${VERDICT_TEXT[result.verdict]}(置信度 ${result.confidence}%)` : VERDICT_TEXT[result.verdict]
|
|
187
|
+
return [`${result.model} 判断:${head}`, ...result.reasons.map(reason => `- ${reason}`)].join('\n')
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** What group members can act on; the details go to the log */
|
|
191
|
+
function describeFailure(error: unknown): string {
|
|
192
|
+
if (error instanceof ManualSynthIdError) return describeManualSynthIdFailure(error)
|
|
193
|
+
if (error instanceof SynthIdError) return describeSynthIdFailure(error)
|
|
194
|
+
switch ((error as Partial<AiError>)?.kind) {
|
|
195
|
+
case 'rate-limit': return '检测请求过于频繁,请稍后再试。'
|
|
196
|
+
case 'quota': return 'AI 服务的余额或额度用完了。'
|
|
197
|
+
case 'auth': return 'API Key 无效或没有权限。'
|
|
198
|
+
case 'network':
|
|
199
|
+
case 'timeout': return '连不上检测服务,请检查网络或代理设置。'
|
|
200
|
+
case 'config': return 'AI 服务或模型尚未配置好。'
|
|
201
|
+
default: return '检测失败,请稍后再试。'
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { AiProvider } from '@luckylillia-dev/plugin-aiprovider'
|
|
2
|
+
import type { Image } from './image.js'
|
|
3
|
+
|
|
4
|
+
// The answer of OpenAI's content_provenance_checks
|
|
5
|
+
export interface ProvenanceResult {
|
|
6
|
+
type: 'c2pa' | 'synthid'
|
|
7
|
+
outcome: 'detected' | 'not_detected'
|
|
8
|
+
validation_state?: 'trusted' | 'valid' | 'invalid' | 'not_present'
|
|
9
|
+
issuer?: string | null
|
|
10
|
+
model?: string | null
|
|
11
|
+
generated_at?: string | null
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ProvenanceResponse {
|
|
15
|
+
object: string
|
|
16
|
+
created_at: number
|
|
17
|
+
results: ProvenanceResult[]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Keep implicit selection in sync with the filtered service selector: official default, then list order. */
|
|
21
|
+
export function provenanceService(ai: AiProvider, name?: string): string | undefined {
|
|
22
|
+
if (name) {
|
|
23
|
+
const explicit = ai.get(name)
|
|
24
|
+
return explicit?.provider === 'openai' ? explicit.name : undefined
|
|
25
|
+
}
|
|
26
|
+
const fallback = ai.get()
|
|
27
|
+
if (fallback?.provider === 'openai') return fallback.name
|
|
28
|
+
return ai.list().find(service => service.provider === 'openai')?.name
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether OpenAI's own marks are in the image: its C2PA credentials and SynthID watermark. It knows nothing of other
|
|
33
|
+
* makers' images, and only OpenAI's own API has the endpoint (relays answer 404).
|
|
34
|
+
*/
|
|
35
|
+
export async function checkProvenance(ai: AiProvider, name: string, image: Image): Promise<ProvenanceResponse> {
|
|
36
|
+
const form = new FormData()
|
|
37
|
+
form.append('file', new Blob([image.data], { type: image.type }), 'image')
|
|
38
|
+
const response = await ai.request(name, '/content_provenance_checks', { method: 'POST', body: form })
|
|
39
|
+
return await response.json() as ProvenanceResponse
|
|
40
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import type { Context } from '@luckylillia-dev/plugin-sdk'
|
|
5
|
+
import { SynthIdError } from './synthid-result.js'
|
|
6
|
+
|
|
7
|
+
export interface SynthIdTokens { refreshToken: string; idToken: string; userId: string }
|
|
8
|
+
const locks = new Map<string, Promise<void>>()
|
|
9
|
+
export function tokenClaims(token: string): Record<string, unknown> {
|
|
10
|
+
try {
|
|
11
|
+
const value = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'))
|
|
12
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
13
|
+
} catch { return {} }
|
|
14
|
+
}
|
|
15
|
+
const validSecret = (value: unknown): value is string => typeof value === 'string' && /^[\x21-\x7e]+$/.test(value)
|
|
16
|
+
function waitForLock(lock: Promise<void>, signal?: AbortSignal): Promise<void> {
|
|
17
|
+
if (!signal) return lock
|
|
18
|
+
signal.throwIfAborted()
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
const abort = () => reject(signal.reason)
|
|
21
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
22
|
+
void lock.then(() => { signal.removeEventListener('abort', abort); resolve() }, reject)
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Trust account identity only after the HTTPS refresh endpoint responds.
|
|
27
|
+
* Persist rotated refresh tokens atomically; a disk JWT is never authority. */
|
|
28
|
+
export class SynthIdTokenStore {
|
|
29
|
+
private tokens?: SynthIdTokens
|
|
30
|
+
private file?: string
|
|
31
|
+
private updatedAt = 0
|
|
32
|
+
constructor(private readonly ctx: Context, private readonly initial: string) {}
|
|
33
|
+
|
|
34
|
+
async get(refresh: (token: string) => Promise<Record<string, unknown>>, force = false, signal?: AbortSignal): Promise<SynthIdTokens> {
|
|
35
|
+
signal?.throwIfAborted()
|
|
36
|
+
if (!force && this.tokens && Number(tokenClaims(this.tokens.idToken).exp) > Date.now() / 1000 + 180) return { ...this.tokens }
|
|
37
|
+
const directory = join(await this.ctx.storage.dir(), 'synthid-http')
|
|
38
|
+
const file = this.file ??= join(directory, createHash('sha256').update(this.initial).digest('hex') + '.json')
|
|
39
|
+
const previous = locks.get(file) ?? Promise.resolve()
|
|
40
|
+
let release!: () => void
|
|
41
|
+
const gate = new Promise<void>(resolve => { release = resolve })
|
|
42
|
+
const tail = previous.then(() => gate)
|
|
43
|
+
locks.set(file, tail)
|
|
44
|
+
try {
|
|
45
|
+
await waitForLock(previous, signal)
|
|
46
|
+
signal?.throwIfAborted()
|
|
47
|
+
if (!force && this.tokens && Number(tokenClaims(this.tokens.idToken).exp) > Date.now() / 1000 + 180) return { ...this.tokens }
|
|
48
|
+
let refreshToken = this.tokens?.refreshToken ?? this.initial
|
|
49
|
+
try {
|
|
50
|
+
const saved = JSON.parse(await readFile(file, 'utf8'))
|
|
51
|
+
if (validSecret(saved?.refreshToken) && (!this.tokens || saved.updatedAt >= this.updatedAt)) refreshToken = saved.refreshToken
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') this.ctx.logger('aiimgdetector').warn('Could not load SynthID login cache')
|
|
54
|
+
}
|
|
55
|
+
const value = await refresh(refreshToken)
|
|
56
|
+
if (!validSecret(value.id_token)) throw new SynthIdError('response', 'SynthID token refresh returned an invalid token')
|
|
57
|
+
const claims = tokenClaims(value.id_token)
|
|
58
|
+
const userId = claims.user_id ?? claims.sub
|
|
59
|
+
if (typeof userId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(userId)
|
|
60
|
+
|| claims.sub !== undefined && claims.sub !== userId || claims.user_id !== undefined && claims.user_id !== userId
|
|
61
|
+
|| value.user_id !== undefined && value.user_id !== userId || this.tokens && this.tokens.userId !== userId) {
|
|
62
|
+
throw new SynthIdError('auth', 'SynthID token refresh returned inconsistent account information')
|
|
63
|
+
}
|
|
64
|
+
if (typeof claims.exp !== 'number' || !Number.isFinite(claims.exp) || claims.exp <= Date.now() / 1000) {
|
|
65
|
+
throw new SynthIdError('response', 'SynthID token refresh returned an invalid expiry')
|
|
66
|
+
}
|
|
67
|
+
this.tokens = { userId, idToken: value.id_token, refreshToken: validSecret(value.refresh_token) ? value.refresh_token : refreshToken }
|
|
68
|
+
this.updatedAt = Math.max(Date.now(), this.updatedAt + 1)
|
|
69
|
+
const temporary = file + '.' + randomUUID() + '.tmp'
|
|
70
|
+
try {
|
|
71
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
72
|
+
// Only the rotating secret is needed after a restart.
|
|
73
|
+
await writeFile(temporary, JSON.stringify({ refreshToken: this.tokens.refreshToken, updatedAt: this.updatedAt }), { mode: 0o600, flag: 'wx' })
|
|
74
|
+
await rename(temporary, file)
|
|
75
|
+
} catch { this.ctx.logger('aiimgdetector').warn('Could not save SynthID login cache; login may need renewing after restart') }
|
|
76
|
+
finally { await unlink(temporary).catch(() => {}) }
|
|
77
|
+
return { ...this.tokens }
|
|
78
|
+
} finally {
|
|
79
|
+
release()
|
|
80
|
+
void tail.then(() => { if (locks.get(file) === tail) locks.delete(file) })
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|