@luckylillia-dev/plugin-aiimgdetector 1.0.5 → 1.1.1

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@luckylillia-dev/plugin-aiimgdetector",
3
- "version": "1.0.5",
4
- "description": "Checks AI image provenance through OpenAI, optional SynthID detection, and a vision model",
3
+ "version": "1.1.1",
4
+ "description": "Checks AI image and video provenance through OpenAI, optional SynthID detection, and a vision model",
5
5
  "author": "linyuchen",
6
6
  "repository": {
7
7
  "type": "git",
@@ -66,7 +66,7 @@
66
66
  "en": "aiimgdetector"
67
67
  },
68
68
  "category": "chat",
69
- "description": "对着图片回复「ai吗」(或者「ai吗」后面直接带图),通过 OpenAI 水印检测、可选的 SynthID 检测和看图模型判断是否由 AI 生成。",
69
+ "description": "对着图片或视频回复「ai吗」(或者「ai吗」后面直接带图或视频),通过 OpenAI 水印检测、可选的 SynthID 检测和看图模型判断是否由 AI 生成。视频整段送 OpenAI 和 SynthID 检测,不走看图模型。",
70
70
  "icon": "assets/icon.svg",
71
71
  "screenshots": [
72
72
  "assets/demo.png"
package/src/image.ts CHANGED
@@ -1,17 +1,21 @@
1
1
  import type { Context } from '@luckylillia-dev/plugin-sdk'
2
2
 
3
- /** Downloaded once, for every check */
3
+ /** Downloaded once, for every check: an image, or a video (`type` starting with `video/`) */
4
4
  export interface Image {
5
5
  data: ArrayBuffer
6
6
  type: string
7
7
  }
8
8
 
9
- const MAX_SIZE = 20 * 1024 * 1024
9
+ export type MediaKind = 'image' | 'video'
10
+
11
+ export const MAX_SIZE: Record<MediaKind, number> = { image: 20 * 1024 * 1024, video: 100 * 1024 * 1024 }
12
+
13
+ export const isVideo = (media: Image) => media.type.startsWith('video/')
10
14
  // Exact QQ media hosts only. Message senders cannot introduce a domain they
11
15
  // control, a local address, a different port, or a redirect destination.
12
16
  const IMAGE_HOSTS = new Set(['gchat.qpic.cn', 'c2cpicdw.qpic.cn', 'multimedia.nt.qq.com.cn'])
13
17
 
14
- function imageUrl(input: string): URL {
18
+ function mediaUrl(input: string): URL {
15
19
  if (typeof input !== 'string' || input.length > 16 * 1024 || /[\x00-\x20\x7f\\]/.test(input)) throw new Error('unsupported image URL')
16
20
  let url: URL
17
21
  try { url = new URL(input) } catch { throw new Error('unsupported image URL') }
@@ -41,15 +45,36 @@ function imageType(bytes: Uint8Array): string | undefined {
41
45
  }
42
46
  }
43
47
 
44
- export async function download(ctx: Context, url: string): Promise<Image> {
45
- const target = imageUrl(url)
48
+ function videoType(bytes: Uint8Array): string | undefined {
49
+ const text = (start: number, end: number) => String.fromCharCode(...bytes.subarray(start, end))
50
+ // ISO media (MP4, MOV) that is not an image: the image brands are taken above
51
+ if (text(4, 8) === 'ftyp') return text(8, 12) === 'qt ' ? 'video/quicktime' : 'video/mp4'
52
+ if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3) return 'video/webm'
53
+ }
54
+
55
+ /** A file's address as the bot's own API gave it, not one from a message: QQ's file servers have no fixed hosts */
56
+ function fileUrl(input: string): URL {
57
+ let url: URL
58
+ try { url = new URL(input) } catch { throw new Error('unsupported file URL') }
59
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('unsupported file URL')
60
+ return url
61
+ }
62
+
63
+ /**
64
+ * An image, or with `kind` video a video, from a QQ media host. `fromApi`: the address came from the bot's API (a
65
+ * file's), so any http(s) host will do and redirects are followed.
66
+ */
67
+ export async function download(ctx: Context, url: string, kind: MediaKind = 'image', fromApi = false): Promise<Image> {
68
+ const max = MAX_SIZE[kind]
69
+ const target = fromApi ? fileUrl(url) : mediaUrl(url)
70
+ const timeout = kind === 'video' ? 120_000 : 30_000
46
71
  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: '' })
72
+ redirect: fromApi ? 'follow' : 'error', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(timeout),
73
+ }, { timeout, proxyAgent: '' })
49
74
  const length = response.headers.get('content-length')
50
- if (!response.ok || response.redirected || length !== null && Number(length) > MAX_SIZE || !response.body) {
75
+ if (!response.ok || response.redirected && !fromApi || length !== null && Number(length) > max || !response.body) {
51
76
  await response.body?.cancel()
52
- throw new Error('image download was refused or exceeds 20 MB')
77
+ throw new Error(`${kind} download was refused or exceeds ${max / 1024 / 1024} MB`)
53
78
  }
54
79
  const reader = response.body.getReader(), chunks: Uint8Array[] = []
55
80
  let size = 0
@@ -58,7 +83,7 @@ export async function download(ctx: Context, url: string): Promise<Image> {
58
83
  const { done, value } = await reader.read()
59
84
  if (done) break
60
85
  size += value.byteLength
61
- if (size > MAX_SIZE) throw new Error('the image is over 20 MB')
86
+ if (size > max) throw new Error(`the ${kind} is over ${max / 1024 / 1024} MB`)
62
87
  chunks.push(value)
63
88
  }
64
89
  } catch (error) {
@@ -68,7 +93,7 @@ export async function download(ctx: Context, url: string): Promise<Image> {
68
93
  const data = new Uint8Array(size)
69
94
  let offset = 0
70
95
  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')
96
+ const type = kind === 'video' ? videoType(data) : imageType(data)
97
+ if (!type) throw new Error(`the response is not a supported ${kind}`)
73
98
  return { data: data.buffer, type }
74
99
  }
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Context, h, Schema, Session } from '@luckylillia-dev/plugin-sdk'
2
2
  import type { AiError } from '@luckylillia-dev/plugin-aiprovider'
3
- import { download, Image } from './image.js'
3
+ import { download, Image, isVideo, MAX_SIZE, type MediaKind } from './image.js'
4
4
  import { checkProvenance, provenanceService } from './provenance.js'
5
5
  import { SynthIdClient, handleSynthId, type SynthIdConfig } from './synthid.js'
6
6
  import { describeSynthIdFailure, formatSynthId, SynthIdError } from './synthid-result.js'
@@ -19,7 +19,7 @@ export interface Config {
19
19
  }
20
20
 
21
21
  export const Config: Schema<Config> = Schema.object({
22
- trigger: Schema.string().pattern(/^\s*\S*\s*$/).default('ai吗').description('触发词,不分大小写:对着图片回复它,或者它后面直接带图'),
22
+ trigger: Schema.string().pattern(/^\s*\S*\s*$/).default('ai吗').description('触发词,不分大小写:对着图片或视频回复它,或者它后面直接带图或视频'),
23
23
  cooldown: Schema.natural().role('ms').default(10_000).description('同一个群(或私聊)两次检测至少隔多久'),
24
24
  provenance: Schema.union([
25
25
  Schema.const(false),
@@ -38,7 +38,7 @@ export const Config: Schema<Config> = Schema.object({
38
38
  refreshToken: Schema.string().role('secret').hidden(),
39
39
  bgToken: Schema.string().role('secret').hidden(),
40
40
  pushFilename: Schema.string().role('secret').hidden(),
41
- timeout: Schema.natural().min(1000).max(120_000).role('ms').default(30_000).description('检测超时'),
41
+ timeout: Schema.natural().min(1000).max(120_000).role('ms').default(30_000).description('检测超时:视频至少 120 秒。连接失败会自动重试一次'),
42
42
  credentials: Schema.union([
43
43
  Schema.object({
44
44
  refreshToken: Schema.string().role('secret').default('').description('登录凭据(refresh_token)'),
@@ -60,7 +60,13 @@ export const Config: Schema<Config> = Schema.object({
60
60
  })
61
61
 
62
62
  interface Picked {
63
- url: string
63
+ /** For a file: none, its address comes from the bot's API by `fileId` */
64
+ url?: string
65
+ /** Undefined for a file that is neither an image nor a video by its name */
66
+ kind?: MediaKind
67
+ fileId?: string
68
+ /** A file's size as the message gives it */
69
+ size?: number
64
70
  /** The message the image is in, which the answer quotes */
65
71
  messageId?: string
66
72
  }
@@ -101,6 +107,8 @@ export function apply(ctx: Context, config: Config) {
101
107
  }
102
108
 
103
109
  async function verdict(image: Image): Promise<string> {
110
+ const video = isVideo(image)
111
+ const noun = video ? '视频' : '图片'
104
112
  // Whether a check ran to the end without finding anything, and what failed on the way
105
113
  let checked = false
106
114
  let failure: unknown
@@ -110,19 +118,23 @@ export function apply(ctx: Context, config: Config) {
110
118
  if (watermarkAi) {
111
119
  try {
112
120
  const answer = await checkProvenance(ctx.ai, watermarkAi, image)
113
- if (answer.results?.some(result => result.outcome === 'detected')) return '图片由 OpenAI 制作。'
121
+ if (answer.results?.some(result => result.outcome === 'detected')) return `${noun}由 OpenAI 制作。`
114
122
  checked = true
115
123
  } catch (e) {
116
- failure = e
117
- logger.warn('watermark check failed:', (e as Error).message)
124
+ // OpenAI may not take videos: a refused video is not a failure worth reporting over the other checks
125
+ if (video && (e as Partial<AiError>)?.kind === 'request') logger.info('watermark check refused the video:', (e as Error).message)
126
+ else {
127
+ failure = e
128
+ logger.warn('watermark check failed:', (e as Error).message)
129
+ }
118
130
  }
119
131
  }
120
132
  if (config.synthid && active) {
121
133
  try {
122
134
  const result = await synthid.detect(image)
123
- if (result.status === 'detected') return formatSynthId(result)
135
+ if (result.status === 'detected') return formatSynthId(result, noun)
124
136
  if (result.status === 'not_detected') checked = true
125
- else if (result.status === 'uncertain') inconclusive = formatSynthId(result)
137
+ else if (result.status === 'uncertain') inconclusive = formatSynthId(result, noun)
126
138
  else if (result.status === 'quota_exceeded') {
127
139
  failure ??= new SynthIdError('rate-limit', 'SynthID account quota exceeded', undefined, result.retryAfterSeconds)
128
140
  }
@@ -131,7 +143,8 @@ export function apply(ctx: Context, config: Config) {
131
143
  if (active) logger.warn('SynthID check failed:', (e as Error).message)
132
144
  }
133
145
  }
134
- if (config.vision && active) {
146
+ // The models take images only
147
+ if (config.vision && active && !video) {
135
148
  try {
136
149
  const result = await judgeByVision(ctx.ai, config.vision, image)
137
150
  if (result) return formatVision(result)
@@ -141,9 +154,10 @@ export function apply(ctx: Context, config: Config) {
141
154
  logger.warn('vision check failed:', (e as Error).message)
142
155
  }
143
156
  }
144
- if (failure) return describeFailure(failure)
157
+ if (failure) return describeFailure(failure, noun)
145
158
  if (inconclusive) return inconclusive
146
- if (checked) return formatSynthId({ status: 'not_detected' })
159
+ if (checked) return formatSynthId({ status: 'not_detected' }, noun)
160
+ if (video && !config.synthid && !watermarkAi) return '视频只能用 OpenAI 水印检测或 SynthID 检测,请在 aiimgdetector 插件的设置里打开。'
147
161
  if (config.provenance) return config.provenance.ai
148
162
  ? '所选服务无法用于水印检测,请重新选择 OpenAI 官方服务,或打开看图判断。'
149
163
  : '没有可用于水印检测的 OpenAI 官方服务,请在 AI 服务中添加,或打开看图判断。'
@@ -151,19 +165,29 @@ export function apply(ctx: Context, config: Config) {
151
165
  }
152
166
 
153
167
  if (!trigger) return
154
- ctx.command(trigger, '检测图片是否由 AI 生成').action(async ({ session, next }) => {
155
- const picked = pickImage(session)
168
+ ctx.command(trigger, '检测图片或视频是否由 AI 生成').action(async ({ session, next }) => {
169
+ const picked = pickMedia(session)
156
170
  // A message starting with the word is not always meant for this plugin
157
171
  if (!picked) return next()
158
172
  if (cooling(`${session.platform}:${session.channelId}`)) return next()
159
173
  // Quote the message the image is in: with several images in a busy group, that says which one it was about
160
174
  const reply = (text: string) => session.send(picked.messageId ? [h('quote', { id: picked.messageId }), h.text(text)] : h.text(text))
175
+ const { kind } = picked
176
+ if (!kind) {
177
+ await reply('只能检测图片或视频文件。')
178
+ return
179
+ }
180
+ if (picked.size !== undefined && picked.size > MAX_SIZE[kind]) {
181
+ await reply(kind === 'video' ? '视频超过 100 MB,无法检测。' : '图片超过 20 MB,无法检测。')
182
+ return
183
+ }
161
184
  let image: Image
162
185
  try {
163
- image = await download(ctx, picked.url)
186
+ const url = picked.fileId === undefined ? picked.url! : await fileAddress(session, picked.fileId)
187
+ image = await download(ctx, url, kind, picked.fileId !== undefined)
164
188
  } catch (e) {
165
- logger.warn('cannot download the image:', (e as Error).message)
166
- await reply('图片下载失败,请稍后再试。')
189
+ logger.warn(`cannot download the ${kind}:`, (e as Error).message)
190
+ await reply(kind === 'video' ? '视频下载失败(最大 100 MB),请稍后再试。' : '图片下载失败,请稍后再试。')
167
191
  return
168
192
  }
169
193
  if (!active) return
@@ -172,13 +196,38 @@ export function apply(ctx: Context, config: Config) {
172
196
  })
173
197
  }
174
198
 
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 }
199
+ const IMAGE_FILE = /\.(?:png|jpe?g|gif|webp|bmp|avif|heic|heif|tiff?)$/i
200
+ const VIDEO_FILE = /\.(?:mp4|m4v|mov|webm)$/i
201
+
202
+ function firstMedia(elements: h[]): Omit<Picked, 'messageId'> | undefined {
203
+ const found = h.select(elements, 'img, video, file')[0]
204
+ if (!found) return
205
+ if (found.type !== 'file') return { url: String(found.attrs.src ?? found.attrs.url), kind: found.type === 'video' ? 'video' : 'image' }
206
+ // NTQQ gives a file no address, only its id: the address is asked for when it is checked
207
+ const name = String(found.attrs.title ?? found.attrs.name ?? '')
208
+ const kind = IMAGE_FILE.test(name) ? 'image' : VIDEO_FILE.test(name) ? 'video' : undefined
209
+ const size = Number(found.attrs.size)
210
+ return { kind, fileId: String(found.attrs.id ?? ''), size: Number.isFinite(size) && size > 0 ? size : undefined }
211
+ }
212
+
213
+ /** A file's download address, from the NTQQ account's API; it expires, so it is asked for just before downloading. */
214
+ async function fileAddress(session: Session, fileId: string): Promise<string> {
215
+ const api = session.bot.platform === 'ntqq' ? session.bot.internal : undefined
216
+ if (!fileId || !api) throw new Error('files can only be fetched on the NTQQ account')
217
+ const result = session.isDirect
218
+ ? await api.getPrivateFileUrl?.({ file_id: fileId })
219
+ : await api.getGroupFileUrl?.({ group_id: session.guildId, file_id: fileId })
220
+ if (typeof result?.url !== 'string' || !result.url) throw new Error('no download address for the file')
221
+ return result.url
222
+ }
223
+
224
+ /** An image, video or file of the message itself first, then one of the message it quotes */
225
+ function pickMedia(session: Session): Picked | undefined {
226
+ const own = firstMedia(session.elements.filter(element => element.type !== 'quote'))
227
+ if (own) return { ...own, messageId: session.messageId }
179
228
  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 }
229
+ const quoted = quote && firstMedia(quote.children)
230
+ if (quoted) return { ...quoted, messageId: quote.attrs.id || session.messageId }
182
231
  }
183
232
 
184
233
  function formatVision(result: VisionResult): string {
@@ -188,9 +237,9 @@ function formatVision(result: VisionResult): string {
188
237
  }
189
238
 
190
239
  /** What group members can act on; the details go to the log */
191
- function describeFailure(error: unknown): string {
240
+ function describeFailure(error: unknown, noun: string): string {
192
241
  if (error instanceof ManualSynthIdError) return describeManualSynthIdFailure(error)
193
- if (error instanceof SynthIdError) return describeSynthIdFailure(error)
242
+ if (error instanceof SynthIdError) return describeSynthIdFailure(error, noun)
194
243
  switch ((error as Partial<AiError>)?.kind) {
195
244
  case 'rate-limit': return '检测请求过于频繁,请稍后再试。'
196
245
  case 'quota': return 'AI 服务的余额或额度用完了。'
package/src/provenance.ts CHANGED
@@ -34,7 +34,7 @@ export function provenanceService(ai: AiProvider, name?: string): string | undef
34
34
  */
35
35
  export async function checkProvenance(ai: AiProvider, name: string, image: Image): Promise<ProvenanceResponse> {
36
36
  const form = new FormData()
37
- form.append('file', new Blob([image.data], { type: image.type }), 'image')
37
+ form.append('file', new Blob([image.data], { type: image.type }), image.type.startsWith('video/') ? 'video' : 'image')
38
38
  const response = await ai.request(name, '/content_provenance_checks', { method: 'POST', body: form })
39
39
  return await response.json() as ProvenanceResponse
40
40
  }
@@ -1,11 +1,14 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import type { Context } from '@luckylillia-dev/plugin-sdk'
3
- import type { Image } from './image.js'
3
+ import { MAX_SIZE, type Image } from './image.js'
4
4
  import { SynthIdTokenStore, type SynthIdTokens } from './synthid-auth.js'
5
- import { parseSynthIdResponse, SynthIdError, type SynthIdResult } from './synthid-result.js'
5
+ import { setTimeout as sleep } from 'node:timers/promises'
6
+ import { connectionCode, networkCodeOf, parseSynthIdResponse, SynthIdError, type SynthIdResult } from './synthid-result.js'
6
7
  import type { LifecycleClient, RequestReference } from './synthid-http-runtime/entry.mjs'
7
8
 
8
9
  const ORIGIN = 'https://synthid.com'
10
+ const RPC_ID = 'vZ4jac'
11
+ const VIDEO_DEFAULT_FPS = 30
9
12
  const TOKEN = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyCjADz3UffE3DF5HZ--7MgVEXrbt6Bgcck'
10
13
  const CREATE = 'https://waa-pa.clients6.google.com/$rpc/google.internal.waa.v1.Waa/Create'
11
14
  const UPLOAD = 'https://content-push.googleapis.com/upload/'
@@ -14,6 +17,7 @@ const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
14
17
  const EXTENSIONS: Record<string, string> = {
15
18
  'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif',
16
19
  'image/bmp': 'bmp', 'image/avif': 'avif', 'image/heic': 'heic', 'image/heif': 'heif', 'image/tiff': 'tiff',
20
+ 'video/mp4': 'mp4', 'video/quicktime': 'mov', 'video/webm': 'webm',
17
21
  }
18
22
  export interface HttpSynthIdOptions {
19
23
  refreshToken: string
@@ -21,7 +25,11 @@ export interface HttpSynthIdOptions {
21
25
  /** Replace the interpreter process in isolated wire tests. */
22
26
  loadRuntime?: () => Promise<typeof import('./synthid-http-runtime/entry.mjs')>
23
27
  }
24
- interface Operation { signal: AbortSignal; reference: RequestReference }
28
+ /** A video uploads tens of MB, often through a proxy: it gets at least this long whatever the setting */
29
+ export const VIDEO_TIMEOUT = 120_000
30
+ /** Before the one retry after a connection failure */
31
+ const RETRY_DELAY = 1000
32
+ interface Operation { signal: AbortSignal; reference: RequestReference; timeout: number }
25
33
  interface Job {
26
34
  run?: () => Promise<SynthIdResult>
27
35
  resolve: (result: SynthIdResult) => void
@@ -88,8 +96,9 @@ export class HttpSynthIdClient {
88
96
  const signal = external ? AbortSignal.any([this.abort.signal, external]) : this.abort.signal
89
97
  const mime = image.type.split(';')[0].trim().toLowerCase()
90
98
  if (signal.aborted) return Promise.reject(cancelled())
91
- if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > 20 * 1024 * 1024) {
92
- return Promise.reject(new SynthIdError('request', 'SynthID needs a supported, non-empty image of at most 20 MB'))
99
+ const kind = mime.startsWith('video/') ? 'video' : 'image'
100
+ if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > MAX_SIZE[kind]) {
101
+ return Promise.reject(new SynthIdError('request', `SynthID needs a supported, non-empty ${kind} of at most ${MAX_SIZE[kind] / 1024 / 1024} MB`))
93
102
  }
94
103
  if (this.active.size >= 4) return Promise.reject(new SynthIdError('busy', 'SynthID account queue is full'))
95
104
  const task = this.prepare(image, mime, signal).catch(error => { throw failure(error, signal) })
@@ -106,7 +115,14 @@ export class HttpSynthIdClient {
106
115
  const entry = await this.runtime
107
116
  const reference = entry.createIndependentRequestReference({ userAgent: USER_AGENT })
108
117
  const started = Date.now()
109
- const tokens = await this.authenticate({ signal: AbortSignal.any([signal, AbortSignal.timeout(this.options.timeout)]), reference })
118
+ const timeout = mime.startsWith('video/') ? Math.max(this.options.timeout, VIDEO_TIMEOUT) : this.options.timeout
119
+ const authOperation = { signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]), reference, timeout }
120
+ const tokens = await this.authenticate(authOperation).catch(async error => {
121
+ // A dropped connection is often a moment's: try once more while time is left
122
+ if (!(error instanceof SynthIdError) || error.kind !== 'network' || authOperation.signal.aborted) throw error
123
+ await sleep(RETRY_DELAY, undefined, { signal: authOperation.signal }).catch(() => { throw failure(undefined, authOperation.signal) })
124
+ return this.authenticate(authOperation)
125
+ })
110
126
  signal.throwIfAborted()
111
127
  const authElapsed = Date.now() - started
112
128
  for (const [key, account] of accounts) prune(key, account)
@@ -119,14 +135,22 @@ export class HttpSynthIdClient {
119
135
  run: async () => {
120
136
  signal.throwIfAborted()
121
137
  if (account.retryAt > Date.now()) throw new SynthIdError('rate-limit', 'SynthID account is cooling down', undefined, Math.ceil((account.retryAt - Date.now()) / 1000))
122
- const deadline = AbortSignal.timeout(Math.max(1, this.options.timeout - authElapsed))
123
- const operation = { reference, signal: AbortSignal.any([signal, deadline]) }
138
+ const deadline = AbortSignal.timeout(Math.max(1, timeout - authElapsed))
139
+ const operation = { reference, signal: AbortSignal.any([signal, deadline]), timeout }
124
140
  try {
125
- for (let attempt = 0, auth = tokens; ; attempt++) {
141
+ let refreshed = false, retried = false
142
+ for (let auth = tokens; ;) {
126
143
  try { return await this.detectQueued(image, mime, auth, operation, entry) }
127
144
  catch (error) {
128
- if (!(error instanceof SynthIdError) || error.code !== 16 || attempt) throw error
129
- auth = await this.authenticate(operation, true)
145
+ if (!(error instanceof SynthIdError)) throw error
146
+ if (error.code === 16 && !refreshed) {
147
+ refreshed = true
148
+ auth = await this.authenticate(operation, true)
149
+ } else if (error.kind === 'network' && !retried && !operation.signal.aborted) {
150
+ // The whole chain again: the verification token is bound to one upload path and used once
151
+ retried = true
152
+ await sleep(RETRY_DELAY, undefined, { signal: operation.signal })
153
+ } else throw error
130
154
  }
131
155
  }
132
156
  } catch (error) { throw failure(error, operation.signal) }
@@ -158,15 +182,18 @@ export class HttpSynthIdClient {
158
182
  headers.delete('content-length')
159
183
  let response: Response
160
184
  try { response = await this.ctx.http.fetch(url, { ...init, headers, signal, redirect: 'error' }) }
161
- catch {
185
+ catch (error) {
162
186
  if (signal.aborted) throw failure(undefined, signal)
163
- throw new SynthIdError('network', `SynthID ${stage} could not connect`)
187
+ // The code only: the message may name the proxy, credentials included
188
+ const code = connectionCode(error)
189
+ throw new SynthIdError('network', `SynthID ${stage} could not connect (${code ?? 'unknown'})`, undefined, undefined, networkCodeOf(code))
164
190
  }
165
191
  if (!response.ok) {
166
192
  await response.body?.cancel()
167
193
  const status = response.status
168
194
  const kind = status === 429 ? 'rate-limit' : status === 401 || stage === 'auth' && status === 400 ? 'auth'
169
- : status === 403 ? 'permission' : status >= 500 ? 'server' : 'request'
195
+ : status === 403 ? 'permission' : status === 400 && stage === 'detect' ? 'response'
196
+ : status >= 500 ? 'server' : 'request'
170
197
  throw new SynthIdError(kind, `SynthID ${stage} returned HTTP ${status}`, stage === 'detect' && status === 401 ? 16 : status,
171
198
  status === 429 ? retryAfter(response.headers.get('retry-after')) : undefined)
172
199
  }
@@ -238,7 +265,7 @@ export class HttpSynthIdClient {
238
265
  }
239
266
  lifecycle = entry.createLifecycleClient({ signal: operation.signal,
240
267
  webidlBrandErrors: true,
241
- timeouts: { init: Math.min(this.options.timeout, 25_000), snapshot: Math.min(this.options.timeout, 15_000) }, maxLifetimeMs: Math.max(100, this.options.timeout) })
268
+ timeouts: { init: Math.min(operation.timeout, 25_000), snapshot: Math.min(operation.timeout, 15_000) }, maxLifetimeMs: Math.max(100, operation.timeout) })
242
269
  const initialized = await lifecycle.initialize({ ...await session.environment(),
243
270
  program: challenge.program, globalName: challenge.globalName, rawExperiments: challenge.clientExperimentsStateBlob ?? '',
244
271
  experiments: entry.normalizeOfficialExperimentState(challenge.clientExperimentsStateBlob),
@@ -258,7 +285,7 @@ export class HttpSynthIdClient {
258
285
  if (!generated.success || typeof generated.bgToken !== 'string' || !/^![\x21-\x7e]+$/.test(generated.bgToken)) throw new SynthIdError('response', 'SynthID verification token generation failed')
259
286
  const headers = { Authorization: 'Basic amI5dChNbS0qNjFlczJJVzpyZyRHNUp1QENpV29OJVNS', 'Push-ID': 'feeds/szvztmw263lqqp',
260
287
  'Push-Filename': path, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
261
- const start = await request(UPLOAD, { method: 'POST', body: `file_name image.${EXTENSIONS[mime]}`,
288
+ const start = await request(UPLOAD, { method: 'POST', body: `file_name ${mime.startsWith('video/') ? 'video' : 'image'}.${EXTENSIONS[mime]}`,
262
289
  headers: { ...headers, 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': String(image.data.byteLength) } }, 'start')
263
290
  let uploadUrl: URL
264
291
  try {
@@ -269,11 +296,15 @@ export class HttpSynthIdClient {
269
296
  const uploaded = await request(uploadUrl.href, { method: 'POST', body: image.data,
270
297
  headers: { ...headers, 'X-Goog-Upload-Command': 'upload, finalize', 'X-Goog-Upload-Offset': '0' } }, 'upload, finalize')
271
298
  if (uploaded.headers.get('x-goog-upload-status') !== 'final' || (await uploaded.text()).trim() !== blobref) throw new SynthIdError('response', 'SynthID upload did not finalize at the generated path')
299
+ const video = mime.startsWith('video/')
272
300
  const endpoint = new URL('/_/WatermarkApp/data/batchexecute', ORIGIN)
273
301
  if (typeof session.config.cfb2h !== 'string' || !session.config.cfb2h || typeof session.config.FdrFJe !== 'string' || !session.config.FdrFJe) throw new SynthIdError('response', 'SynthID page metadata is incomplete')
274
- endpoint.search = new URLSearchParams({ rpcids: 'TZRKo', 'source-path': '/image-detection', bl: session.config.cfb2h,
302
+ endpoint.search = new URLSearchParams({ rpcids: RPC_ID, 'source-path': video ? '/video-detection' : '/image-detection', bl: session.config.cfb2h,
275
303
  'f.sid': session.config.FdrFJe, hl: session.config.hl || 'en-US', _reqid: session.nextRequestId(), rt: 'c' }).toString()
276
- const form = entry.attachWebXsrf(new URLSearchParams({ 'f.req': JSON.stringify([[['TZRKo', JSON.stringify([null, [[[mime, null, null, null, null, null, blobref]]], 0]), null, 'generic']]]) }), session.config)
304
+ const requestPayload = video
305
+ ? [[null, [[[mime, null, null, null, null, null, blobref]]], 0, null, null, null, VIDEO_DEFAULT_FPS]]
306
+ : [[null, [[[mime, null, null, null, null, null, blobref]]], 0]]
307
+ const form = entry.attachWebXsrf(new URLSearchParams({ 'f.req': JSON.stringify([[[RPC_ID, JSON.stringify(requestPayload), null, 'generic']]]) }), session.config)
277
308
  const response = await session.request(endpoint.href, { method: 'POST', body: form.toString() + '&', headers: {
278
309
  'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'X-Same-Domain': '1',
279
310
  'X-Goog-Ext-525006476-Jspb': JSON.stringify([auth.idToken, null, null, null, null, generated.bgToken]),
@@ -38,7 +38,7 @@ function manualError(error: unknown): ManualSynthIdError {
38
38
  const ORIGIN = 'https://synthid.com'
39
39
  const UPLOAD = 'https://content-push.googleapis.com/upload/'
40
40
  const TOKEN = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyCjADz3UffE3DF5HZ--7MgVEXrbt6Bgcck'
41
- const DETECT = ORIGIN + '/_/WatermarkApp/data/batchexecute?rpcids=TZRKo&source-path=%2Fimage-detection&hl=en-US&rt=c'
41
+ const DETECT = ORIGIN + '/_/WatermarkApp/data/batchexecute?rpcids=vZ4jac&source-path=%2Fimage-detection&hl=en-US&rt=c'
42
42
  const DROPZONE = '/synthid-demo-drop-zone/ttl_1d/'
43
43
  const WEB_HEADERS = {
44
44
  Origin: ORIGIN,
@@ -242,9 +242,9 @@ export class ManualSynthIdClient {
242
242
  const blob = await this.upload(image, mime, auth)
243
243
  try {
244
244
  const media = [mime, null, null, null, null, null, blob]
245
- const request = JSON.stringify([null, [[media]], 0])
245
+ const request = JSON.stringify([[null, [[media]], 0]])
246
246
  const result = await this.post(DETECT, {
247
- body: new URLSearchParams({ 'f.req': JSON.stringify([[['TZRKo', request, null, 'generic']]]) }),
247
+ body: new URLSearchParams({ 'f.req': JSON.stringify([[['vZ4jac', request, null, 'generic']]]) }),
248
248
  headers: {
249
249
  'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
250
250
  'X-Same-Domain': '1',
@@ -304,6 +304,7 @@ export class ManualSynthIdClient {
304
304
  const kind = status === 429 ? 'rate-limit'
305
305
  : status === 403 ? 'permission'
306
306
  : status === 401 || status === 400 && stage === 'auth' ? 'auth'
307
+ : status === 400 && stage === 'detect' ? 'response'
307
308
  : status >= 500 ? 'server' : 'request'
308
309
  throw new ManualSynthIdError(kind, `SynthID ${stage} returned HTTP ${status}`, stage === 'detect' && status === 401 ? 16 : status,
309
310
  status === 429 ? retryAfter(response.headers.get('retry-after')) : undefined)
@@ -1,4 +1,4 @@
1
- /** Image-only decoding of synthid.com's TZRKo response. Protocol reference: docs/synthid.md. */
1
+ /** Image and video decoding of synthid.com's vZ4jac response. Protocol reference: docs/synthid.md. */
2
2
  export type SynthIdResult =
3
3
  | { status: 'detected'; source?: string; confidence?: 'very-high' | 'high' | 'medium' }
4
4
  | { status: 'not_detected' }
@@ -10,6 +10,23 @@ export type SynthIdErrorKind = 'config' | 'runtime' | 'browser' | 'proxy' | 'ter
10
10
 
11
11
  export type SynthIdNetworkCode = 'ECONNRESET' | 'ECONNREFUSED' | 'ENOTFOUND' | 'EAI_AGAIN' | 'ETIMEDOUT'
12
12
 
13
+ const NETWORK_CODES: Record<string, SynthIdNetworkCode> = {
14
+ ECONNRESET: 'ECONNRESET', EPIPE: 'ECONNRESET', UND_ERR_SOCKET: 'ECONNRESET',
15
+ ECONNREFUSED: 'ECONNREFUSED', ENOTFOUND: 'ENOTFOUND', EAI_AGAIN: 'EAI_AGAIN',
16
+ ETIMEDOUT: 'ETIMEDOUT', UND_ERR_CONNECT_TIMEOUT: 'ETIMEDOUT', UND_ERR_HEADERS_TIMEOUT: 'ETIMEDOUT', UND_ERR_BODY_TIMEOUT: 'ETIMEDOUT',
17
+ }
18
+
19
+ /** The connection error's code, as `ctx.http` reports it (`code`, or down the cause chain); only the code, never the message */
20
+ export function connectionCode(error: unknown): string | undefined {
21
+ for (let cause = error as { code?: unknown, cause?: unknown } | undefined, depth = 0; cause && depth < 8; cause = cause.cause as typeof cause, depth++) {
22
+ if (typeof cause.code === 'string' && /^[A-Z][A-Z0-9_]{1,40}$/.test(cause.code)) return cause.code
23
+ }
24
+ }
25
+
26
+ export function networkCodeOf(code: string | undefined): SynthIdNetworkCode | undefined {
27
+ return code && Object.hasOwn(NETWORK_CODES, code) ? NETWORK_CODES[code] : undefined
28
+ }
29
+
13
30
  /** Messages contain no response bodies, tokens, or upload paths: they are safe to log. */
14
31
  export class SynthIdError extends Error {
15
32
  readonly name = 'SynthIdError'
@@ -87,7 +104,7 @@ export function parseSynthIdResponse(text: string): SynthIdResult {
87
104
  // after our complete RPC frame so a footer cannot mask a real auth result.
88
105
  let frame: unknown[] | undefined
89
106
  for (const value of frames(text)) {
90
- if (Array.isArray(value) && value[0] === 'wrb.fr' && value[1] === 'TZRKo') { frame = value; break }
107
+ if (Array.isArray(value) && value[0] === 'wrb.fr' && value[1] === 'vZ4jac') { frame = value; break }
91
108
  }
92
109
  if (!frame) return invalid()
93
110
  if (frame[2] === null) {
@@ -100,7 +117,9 @@ export function parseSynthIdResponse(text: string): SynthIdResult {
100
117
  throw new SynthIdError(kind, `SynthID RPC failed (${code ?? 'unknown'})`, code, retryAfterSeconds)
101
118
  }
102
119
  if (typeof frame[2] !== 'string') return invalid()
103
- const payload = json(frame[2])
120
+ const outer = json(frame[2])
121
+ if (!Array.isArray(outer)) return invalid()
122
+ const payload = outer[0]
104
123
  if (!Array.isArray(payload)) return invalid()
105
124
  if (Array.isArray(payload[6]) && payload[6].length) {
106
125
  const quota = payload[6][0]
@@ -128,24 +147,28 @@ export function parseSynthIdResponse(text: string): SynthIdResult {
128
147
  }
129
148
  }
130
149
 
131
- export function formatSynthId(result: Exclude<SynthIdResult, { status: 'quota_exceeded' }>): string {
150
+ /** `noun`: what was checked, 图片 or 视频 */
151
+ export function formatSynthId(result: Exclude<SynthIdResult, { status: 'quota_exceeded' }>, noun = '图片'): string {
132
152
  if (result.status === 'not_detected') return '没有找到 AI 特征,但不能完全确认不是 AI。'
133
153
  if (result.status === 'uncertain') {
134
154
  const reasons: Record<number, string> = {
135
- 1: '图片为空',
136
- 2: '图片分辨率过低',
137
- 3: '图片细节不足',
138
- 5: '图片质量过低',
139
- 6: '图片可能经过修改,或只在局部使用了 AI',
155
+ 1: `${noun}为空`,
156
+ 2: `${noun}分辨率过低`,
157
+ 3: `${noun}细节不足`,
158
+ 4: `${noun}帧率过低`,
159
+ 5: `${noun}质量过低`,
160
+ 6: `${noun}可能经过修改,或只在局部使用了 AI`,
161
+ 7: `${noun}时长过长`,
140
162
  }
141
163
  return `无法判断是否为 AI 生成:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`
142
164
  }
143
- const sources: Record<string, string> = { google: 'Google', openai: 'OpenAI', nvidia: 'NVIDIA', kakao: 'Kakao' }
165
+ const sources: Record<string, string> = { apple: 'Apple', google: 'Google', heygen: 'HeyGen', kakao: 'Kakao', nvidia: 'NVIDIA', openai: 'OpenAI' }
144
166
  const source = result.source && (Object.hasOwn(sources, result.source.toLowerCase()) ? sources[result.source.toLowerCase()] : result.source)
145
- return `图片是 ${source || 'AI'} 生成`
167
+ return `${noun}是 ${source || 'AI'} 生成`
146
168
  }
147
169
 
148
- export function describeSynthIdFailure(error: SynthIdError): string {
170
+ /** `during`: login, from the WebUI's login window, or a detection */
171
+ export function describeSynthIdFailure(error: SynthIdError, noun = '图片', during: 'detect' | 'login' = 'detect'): string {
149
172
  switch (error.kind) {
150
173
  case 'runtime': return '检测运行环境不可用,当前需要 Node.js 24 或以上版本。'
151
174
  case 'config':
@@ -164,12 +187,20 @@ export function describeSynthIdFailure(error: SynthIdError): string {
164
187
  ECONNRESET: '连接被重置(ECONNRESET)', ECONNREFUSED: '连接被拒绝(ECONNREFUSED)',
165
188
  ENOTFOUND: '域名解析失败(ENOTFOUND)', EAI_AGAIN: '域名解析暂时失败(EAI_AGAIN)', ETIMEDOUT: '连接超时(ETIMEDOUT)',
166
189
  }
167
- return error.networkCode && reasons[error.networkCode]
168
- ? `登录页加载失败:${reasons[error.networkCode]}。请检查 Bot「代理」插件设置,确认当前代理可正常连接检测服务后重试。`
169
- : '连不上检测服务,请检查网络或代理设置。'
190
+ const reason = error.networkCode && reasons[error.networkCode]
191
+ if (during === 'login') {
192
+ return reason
193
+ ? `登录页加载失败:${reason}。请检查 Bot「代理」插件设置,确认当前代理可正常连接检测服务后重试。`
194
+ : '连不上检测服务,请检查网络或代理设置。'
195
+ }
196
+ return reason
197
+ ? `连不上检测服务:${reason},已重试一次。请检查网络或 Bot「代理」插件设置。`
198
+ : '连不上检测服务,已重试一次。请检查网络或代理设置。'
170
199
  }
171
- case 'timeout': return '连不上检测服务,请检查网络或代理设置。'
172
- case 'request': return '无法处理这张图片,请尝试发送原图。'
200
+ case 'timeout': return during === 'login'
201
+ ? '连不上检测服务,请检查网络或代理设置。'
202
+ : `${noun}检测超时:网络或代理较慢时,可在插件设置里调大「检测超时」。`
203
+ case 'request': return noun === '视频' ? '无法处理这个视频:只支持 MP4、MOV、WebM,且不超过 100 MB。' : '无法处理这张图片,请尝试发送原图。'
173
204
  case 'response': return '检测服务返回了无法识别的结果,检测接口可能已变更。'
174
205
  case 'cancelled': return '检测已取消。'
175
206
  default: return '检测失败,请稍后再试。'