@luckylillia-dev/plugin-aiimgdetector 1.0.4 → 1.1.0

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/docs/details.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  在群里或私聊里**对着一张图片回复「/ai吗」**,或者发「/ai吗」时**直接带上图片**,Bot 会引用那张图,回复检测结果。默认也支持不带斜杠的「ai吗」,文字和图片之间不用加空格。
4
4
 
5
+ 视频也一样:对着视频回复「/ai吗」,或者「/ai吗」直接带视频。视频整段上传给 OpenAI 水印检测和 SynthID 检测(支持 MP4、MOV、WebM,最大 100 MB),看图判断只看图片,不检测视频。OpenAI 不接受视频时会跳过这一项,不算检测失败。
6
+
7
+ 以文件发送的图片和视频也能检测(目前只支持 NTQQ 账号):按文件名后缀判断是图片还是视频,检测时才向 QQ 获取下载地址。其他类型的文件会回复「只能检测图片或视频文件」。
8
+
5
9
  - 不分大小写,支持前面 @ 机器人
6
10
  - 前缀、是否允许省略前缀统一在「指令」页设置
7
11
  - 同一个群(或私聊)两次检测之间有冷却,默认 10 秒
@@ -36,7 +40,7 @@
36
40
 
37
41
  新安装的插件默认停用,需要分别启用。批准 AI 服务插件的界面后,aiimgdetector 配置中会显示服务和模型下拉框。
38
42
 
39
- 要使用 SynthID,批准本插件界面,在设置里打开「SynthID 检测,支持 Google、OpenAI、NVIDIA、Kakao 生成的图片」,点击组内的「登录 SynthID」,在 Bot 所在电脑弹出的浏览器窗口中完成 Google 登录和首次使用提示。插件会在当前已登录页面自动选择内置测试图片取得凭证,无需自行选图。取得凭证后自动填入下面的三项输入框,再点击弹窗底部「保存」。之后使用保存的浏览器会话,由网站为每张图片生成新的网页校验。登录和检测自动沿用 Bot「代理」插件的网络设置。
43
+ 要使用 SynthID,批准本插件界面,在设置里打开「SynthID 检测,支持 Google、OpenAI、NVIDIA、Kakao 生成的图片」,点击组内的「登录 SynthID」,在 Bot 所在电脑弹出的浏览器窗口中完成 Google 登录和首次使用提示。插件会在当前已登录页面自动选择内置测试图片取得凭证,无需自行选图。取得凭证后自动填入下面的三项输入框,再点击弹窗底部「保存」。之后使用保存的浏览器会话,由网站为每张图片生成新的网页校验。登录和检测自动沿用 Bot「代理」插件的网络设置。连接失败(如连接被重置)时会自动重新检测一次;超时不重试,视频的检测时限至少 120 秒。
40
44
 
41
45
  三项凭证始终显示,也可直接从自己浏览器中获取登录凭据、网站上传标识和网页校验凭据并填写,无需切换模式。设置中有可展开的获取步骤,完整操作路径见 [SynthID 接入说明](synthid.md)。手动获取不要求 Bot 安装浏览器;网页校验被拒绝不代表登录失效,可改用插件浏览器登录,或重新从同一次网页检测获取上传标识和网页校验凭据。上传标识是网站请求里的值,不是本机文件夹。
42
46
 
package/lib/image.js CHANGED
@@ -1,8 +1,9 @@
1
- const MAX_SIZE = 20 * 1024 * 1024;
1
+ export const MAX_SIZE = { image: 20 * 1024 * 1024, video: 100 * 1024 * 1024 };
2
+ export const isVideo = (media) => media.type.startsWith('video/');
2
3
  // Exact QQ media hosts only. Message senders cannot introduce a domain they
3
4
  // control, a local address, a different port, or a redirect destination.
4
5
  const IMAGE_HOSTS = new Set(['gchat.qpic.cn', 'c2cpicdw.qpic.cn', 'multimedia.nt.qq.com.cn']);
5
- function imageUrl(input) {
6
+ function mediaUrl(input) {
6
7
  if (typeof input !== 'string' || input.length > 16 * 1024 || /[\x00-\x20\x7f\\]/.test(input))
7
8
  throw new Error('unsupported image URL');
8
9
  let url;
@@ -47,15 +48,42 @@ function imageType(bytes) {
47
48
  return 'image/heif';
48
49
  }
49
50
  }
50
- export async function download(ctx, url) {
51
- const target = imageUrl(url);
51
+ function videoType(bytes) {
52
+ const text = (start, end) => String.fromCharCode(...bytes.subarray(start, end));
53
+ // ISO media (MP4, MOV) that is not an image: the image brands are taken above
54
+ if (text(4, 8) === 'ftyp')
55
+ return text(8, 12) === 'qt ' ? 'video/quicktime' : 'video/mp4';
56
+ if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3)
57
+ return 'video/webm';
58
+ }
59
+ /** 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 */
60
+ function fileUrl(input) {
61
+ let url;
62
+ try {
63
+ url = new URL(input);
64
+ }
65
+ catch {
66
+ throw new Error('unsupported file URL');
67
+ }
68
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
69
+ throw new Error('unsupported file URL');
70
+ return url;
71
+ }
72
+ /**
73
+ * An image, or with `kind` video a video, from a QQ media host. `fromApi`: the address came from the bot's API (a
74
+ * file's), so any http(s) host will do and redirects are followed.
75
+ */
76
+ export async function download(ctx, url, kind = 'image', fromApi = false) {
77
+ const max = MAX_SIZE[kind];
78
+ const target = fromApi ? fileUrl(url) : mediaUrl(url);
79
+ const timeout = kind === 'video' ? 120_000 : 30_000;
52
80
  const response = await ctx.http.fetch(target.href, {
53
- redirect: 'error', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(30_000),
54
- }, { timeout: 30_000, proxyAgent: '' });
81
+ redirect: fromApi ? 'follow' : 'error', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(timeout),
82
+ }, { timeout, proxyAgent: '' });
55
83
  const length = response.headers.get('content-length');
56
- if (!response.ok || response.redirected || length !== null && Number(length) > MAX_SIZE || !response.body) {
84
+ if (!response.ok || response.redirected && !fromApi || length !== null && Number(length) > max || !response.body) {
57
85
  await response.body?.cancel();
58
- throw new Error('image download was refused or exceeds 20 MB');
86
+ throw new Error(`${kind} download was refused or exceeds ${max / 1024 / 1024} MB`);
59
87
  }
60
88
  const reader = response.body.getReader(), chunks = [];
61
89
  let size = 0;
@@ -65,8 +93,8 @@ export async function download(ctx, url) {
65
93
  if (done)
66
94
  break;
67
95
  size += value.byteLength;
68
- if (size > MAX_SIZE)
69
- throw new Error('the image is over 20 MB');
96
+ if (size > max)
97
+ throw new Error(`the ${kind} is over ${max / 1024 / 1024} MB`);
70
98
  chunks.push(value);
71
99
  }
72
100
  }
@@ -83,8 +111,8 @@ export async function download(ctx, url) {
83
111
  data.set(chunk, offset);
84
112
  offset += chunk.byteLength;
85
113
  }
86
- const type = imageType(data);
114
+ const type = kind === 'video' ? videoType(data) : imageType(data);
87
115
  if (!type)
88
- throw new Error('the response is not a supported image');
116
+ throw new Error(`the response is not a supported ${kind}`);
89
117
  return { data: data.buffer, type };
90
118
  }
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { h, Schema } from '@luckylillia-dev/plugin-sdk';
2
- import { download } from './image.js';
2
+ import { download, isVideo, MAX_SIZE } from './image.js';
3
3
  import { checkProvenance, provenanceService } from './provenance.js';
4
4
  import { SynthIdClient, handleSynthId } from './synthid.js';
5
5
  import { describeSynthIdFailure, formatSynthId, SynthIdError } from './synthid-result.js';
@@ -8,7 +8,7 @@ import { judgeByVision } from './vision.js';
8
8
  export const name = 'aiimgdetector';
9
9
  export const inject = ['bots', 'ai', 'http', 'commands'];
10
10
  export const Config = Schema.object({
11
- trigger: Schema.string().pattern(/^\s*\S*\s*$/).default('ai吗').description('触发词,不分大小写:对着图片回复它,或者它后面直接带图'),
11
+ trigger: Schema.string().pattern(/^\s*\S*\s*$/).default('ai吗').description('触发词,不分大小写:对着图片或视频回复它,或者它后面直接带图或视频'),
12
12
  cooldown: Schema.natural().role('ms').default(10_000).description('同一个群(或私聊)两次检测至少隔多久'),
13
13
  provenance: Schema.union([
14
14
  Schema.const(false),
@@ -27,7 +27,7 @@ export const Config = Schema.object({
27
27
  refreshToken: Schema.string().role('secret').hidden(),
28
28
  bgToken: Schema.string().role('secret').hidden(),
29
29
  pushFilename: Schema.string().role('secret').hidden(),
30
- timeout: Schema.natural().min(1000).max(120_000).role('ms').default(30_000).description('检测超时'),
30
+ timeout: Schema.natural().min(1000).max(120_000).role('ms').default(30_000).description('检测超时:视频至少 120 秒。连接失败会自动重试一次'),
31
31
  credentials: Schema.union([
32
32
  Schema.object({
33
33
  refreshToken: Schema.string().role('secret').default('').description('登录凭据(refresh_token)'),
@@ -85,6 +85,8 @@ export function apply(ctx, config) {
85
85
  return false;
86
86
  }
87
87
  async function verdict(image) {
88
+ const video = isVideo(image);
89
+ const noun = video ? '视频' : '图片';
88
90
  // Whether a check ran to the end without finding anything, and what failed on the way
89
91
  let checked = false;
90
92
  let failure;
@@ -95,23 +97,28 @@ export function apply(ctx, config) {
95
97
  try {
96
98
  const answer = await checkProvenance(ctx.ai, watermarkAi, image);
97
99
  if (answer.results?.some(result => result.outcome === 'detected'))
98
- return '图片由 OpenAI 制作。';
100
+ return `${noun}由 OpenAI 制作。`;
99
101
  checked = true;
100
102
  }
101
103
  catch (e) {
102
- failure = e;
103
- logger.warn('watermark check failed:', e.message);
104
+ // OpenAI may not take videos: a refused video is not a failure worth reporting over the other checks
105
+ if (video && e?.kind === 'request')
106
+ logger.info('watermark check refused the video:', e.message);
107
+ else {
108
+ failure = e;
109
+ logger.warn('watermark check failed:', e.message);
110
+ }
104
111
  }
105
112
  }
106
113
  if (config.synthid && active) {
107
114
  try {
108
115
  const result = await synthid.detect(image);
109
116
  if (result.status === 'detected')
110
- return formatSynthId(result);
117
+ return formatSynthId(result, noun);
111
118
  if (result.status === 'not_detected')
112
119
  checked = true;
113
120
  else if (result.status === 'uncertain')
114
- inconclusive = formatSynthId(result);
121
+ inconclusive = formatSynthId(result, noun);
115
122
  else if (result.status === 'quota_exceeded') {
116
123
  failure ??= new SynthIdError('rate-limit', 'SynthID account quota exceeded', undefined, result.retryAfterSeconds);
117
124
  }
@@ -122,7 +129,8 @@ export function apply(ctx, config) {
122
129
  logger.warn('SynthID check failed:', e.message);
123
130
  }
124
131
  }
125
- if (config.vision && active) {
132
+ // The models take images only
133
+ if (config.vision && active && !video) {
126
134
  try {
127
135
  const result = await judgeByVision(ctx.ai, config.vision, image);
128
136
  if (result)
@@ -135,11 +143,13 @@ export function apply(ctx, config) {
135
143
  }
136
144
  }
137
145
  if (failure)
138
- return describeFailure(failure);
146
+ return describeFailure(failure, noun);
139
147
  if (inconclusive)
140
148
  return inconclusive;
141
149
  if (checked)
142
- return formatSynthId({ status: 'not_detected' });
150
+ return formatSynthId({ status: 'not_detected' }, noun);
151
+ if (video && !config.synthid && !watermarkAi)
152
+ return '视频只能用 OpenAI 水印检测或 SynthID 检测,请在 aiimgdetector 插件的设置里打开。';
143
153
  if (config.provenance)
144
154
  return config.provenance.ai
145
155
  ? '所选服务无法用于水印检测,请重新选择 OpenAI 官方服务,或打开看图判断。'
@@ -148,8 +158,8 @@ export function apply(ctx, config) {
148
158
  }
149
159
  if (!trigger)
150
160
  return;
151
- ctx.command(trigger, '检测图片是否由 AI 生成').action(async ({ session, next }) => {
152
- const picked = pickImage(session);
161
+ ctx.command(trigger, '检测图片或视频是否由 AI 生成').action(async ({ session, next }) => {
162
+ const picked = pickMedia(session);
153
163
  // A message starting with the word is not always meant for this plugin
154
164
  if (!picked)
155
165
  return next();
@@ -157,13 +167,23 @@ export function apply(ctx, config) {
157
167
  return next();
158
168
  // Quote the message the image is in: with several images in a busy group, that says which one it was about
159
169
  const reply = (text) => session.send(picked.messageId ? [h('quote', { id: picked.messageId }), h.text(text)] : h.text(text));
170
+ const { kind } = picked;
171
+ if (!kind) {
172
+ await reply('只能检测图片或视频文件。');
173
+ return;
174
+ }
175
+ if (picked.size !== undefined && picked.size > MAX_SIZE[kind]) {
176
+ await reply(kind === 'video' ? '视频超过 100 MB,无法检测。' : '图片超过 20 MB,无法检测。');
177
+ return;
178
+ }
160
179
  let image;
161
180
  try {
162
- image = await download(ctx, picked.url);
181
+ const url = picked.fileId === undefined ? picked.url : await fileAddress(session, picked.fileId);
182
+ image = await download(ctx, url, kind, picked.fileId !== undefined);
163
183
  }
164
184
  catch (e) {
165
- logger.warn('cannot download the image:', e.message);
166
- await reply('图片下载失败,请稍后再试。');
185
+ logger.warn(`cannot download the ${kind}:`, e.message);
186
+ await reply(kind === 'video' ? '视频下载失败(最大 100 MB),请稍后再试。' : '图片下载失败,请稍后再试。');
167
187
  return;
168
188
  }
169
189
  if (!active)
@@ -173,15 +193,41 @@ export function apply(ctx, config) {
173
193
  await reply(answer);
174
194
  });
175
195
  }
176
- /** An image of the message itself first, then one of the message it quotes */
177
- function pickImage(session) {
178
- const own = h.select(session.elements.filter(element => element.type !== 'quote'), 'img')[0];
196
+ const IMAGE_FILE = /\.(?:png|jpe?g|gif|webp|bmp|avif|heic|heif|tiff?)$/i;
197
+ const VIDEO_FILE = /\.(?:mp4|m4v|mov|webm)$/i;
198
+ function firstMedia(elements) {
199
+ const found = h.select(elements, 'img, video, file')[0];
200
+ if (!found)
201
+ return;
202
+ if (found.type !== 'file')
203
+ return { url: String(found.attrs.src ?? found.attrs.url), kind: found.type === 'video' ? 'video' : 'image' };
204
+ // NTQQ gives a file no address, only its id: the address is asked for when it is checked
205
+ const name = String(found.attrs.title ?? found.attrs.name ?? '');
206
+ const kind = IMAGE_FILE.test(name) ? 'image' : VIDEO_FILE.test(name) ? 'video' : undefined;
207
+ const size = Number(found.attrs.size);
208
+ return { kind, fileId: String(found.attrs.id ?? ''), size: Number.isFinite(size) && size > 0 ? size : undefined };
209
+ }
210
+ /** A file's download address, from the NTQQ account's API; it expires, so it is asked for just before downloading. */
211
+ async function fileAddress(session, fileId) {
212
+ const api = session.bot.platform === 'ntqq' ? session.bot.internal : undefined;
213
+ if (!fileId || !api)
214
+ throw new Error('files can only be fetched on the NTQQ account');
215
+ const result = session.isDirect
216
+ ? await api.getPrivateFileUrl?.({ file_id: fileId })
217
+ : await api.getGroupFileUrl?.({ group_id: session.guildId, file_id: fileId });
218
+ if (typeof result?.url !== 'string' || !result.url)
219
+ throw new Error('no download address for the file');
220
+ return result.url;
221
+ }
222
+ /** An image, video or file of the message itself first, then one of the message it quotes */
223
+ function pickMedia(session) {
224
+ const own = firstMedia(session.elements.filter(element => element.type !== 'quote'));
179
225
  if (own)
180
- return { url: String(own.attrs.src ?? own.attrs.url), messageId: session.messageId };
226
+ return { ...own, messageId: session.messageId };
181
227
  const quote = session.elements.find(element => element.type === 'quote');
182
- const quoted = quote && h.select(quote.children, 'img')[0];
228
+ const quoted = quote && firstMedia(quote.children);
183
229
  if (quoted)
184
- return { url: String(quoted.attrs.src ?? quoted.attrs.url), messageId: quote.attrs.id || session.messageId };
230
+ return { ...quoted, messageId: quote.attrs.id || session.messageId };
185
231
  }
186
232
  function formatVision(result) {
187
233
  if (result.raw)
@@ -190,11 +236,11 @@ function formatVision(result) {
190
236
  return [`${result.model} 判断:${head}`, ...result.reasons.map(reason => `- ${reason}`)].join('\n');
191
237
  }
192
238
  /** What group members can act on; the details go to the log */
193
- function describeFailure(error) {
239
+ function describeFailure(error, noun) {
194
240
  if (error instanceof ManualSynthIdError)
195
241
  return describeManualSynthIdFailure(error);
196
242
  if (error instanceof SynthIdError)
197
- return describeSynthIdFailure(error);
243
+ return describeSynthIdFailure(error, noun);
198
244
  switch (error?.kind) {
199
245
  case 'rate-limit': return '检测请求过于频繁,请稍后再试。';
200
246
  case 'quota': return 'AI 服务的余额或额度用完了。';
package/lib/provenance.js CHANGED
@@ -15,7 +15,7 @@ export function provenanceService(ai, name) {
15
15
  */
16
16
  export async function checkProvenance(ai, name, image) {
17
17
  const form = new FormData();
18
- form.append('file', new Blob([image.data], { type: image.type }), 'image');
18
+ form.append('file', new Blob([image.data], { type: image.type }), image.type.startsWith('video/') ? 'video' : 'image');
19
19
  const response = await ai.request(name, '/content_provenance_checks', { method: 'POST', body: form });
20
20
  return await response.json();
21
21
  }
@@ -1,6 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { MAX_SIZE } from './image.js';
2
3
  import { SynthIdTokenStore } from './synthid-auth.js';
3
- import { parseSynthIdResponse, SynthIdError } from './synthid-result.js';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
5
+ import { connectionCode, networkCodeOf, parseSynthIdResponse, SynthIdError } from './synthid-result.js';
4
6
  const ORIGIN = 'https://synthid.com';
5
7
  const TOKEN = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyCjADz3UffE3DF5HZ--7MgVEXrbt6Bgcck';
6
8
  const CREATE = 'https://waa-pa.clients6.google.com/$rpc/google.internal.waa.v1.Waa/Create';
@@ -10,7 +12,12 @@ const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
10
12
  const EXTENSIONS = {
11
13
  'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif',
12
14
  'image/bmp': 'bmp', 'image/avif': 'avif', 'image/heic': 'heic', 'image/heif': 'heif', 'image/tiff': 'tiff',
15
+ 'video/mp4': 'mp4', 'video/quicktime': 'mov', 'video/webm': 'webm',
13
16
  };
17
+ /** A video uploads tens of MB, often through a proxy: it gets at least this long whatever the setting */
18
+ export const VIDEO_TIMEOUT = 120_000;
19
+ /** Before the one retry after a connection failure */
20
+ const RETRY_DELAY = 1000;
14
21
  const accounts = new Map();
15
22
  const cancelled = () => new SynthIdError('cancelled', 'SynthID detection was cancelled');
16
23
  function prune(key, account) {
@@ -78,8 +85,9 @@ export class HttpSynthIdClient {
78
85
  const mime = image.type.split(';')[0].trim().toLowerCase();
79
86
  if (signal.aborted)
80
87
  return Promise.reject(cancelled());
81
- if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > 20 * 1024 * 1024) {
82
- return Promise.reject(new SynthIdError('request', 'SynthID needs a supported, non-empty image of at most 20 MB'));
88
+ const kind = mime.startsWith('video/') ? 'video' : 'image';
89
+ if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > MAX_SIZE[kind]) {
90
+ return Promise.reject(new SynthIdError('request', `SynthID needs a supported, non-empty ${kind} of at most ${MAX_SIZE[kind] / 1024 / 1024} MB`));
83
91
  }
84
92
  if (this.active.size >= 4)
85
93
  return Promise.reject(new SynthIdError('busy', 'SynthID account queue is full'));
@@ -96,7 +104,15 @@ export class HttpSynthIdClient {
96
104
  const entry = await this.runtime;
97
105
  const reference = entry.createIndependentRequestReference({ userAgent: USER_AGENT });
98
106
  const started = Date.now();
99
- const tokens = await this.authenticate({ signal: AbortSignal.any([signal, AbortSignal.timeout(this.options.timeout)]), reference });
107
+ const timeout = mime.startsWith('video/') ? Math.max(this.options.timeout, VIDEO_TIMEOUT) : this.options.timeout;
108
+ const authOperation = { signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]), reference, timeout };
109
+ const tokens = await this.authenticate(authOperation).catch(async (error) => {
110
+ // A dropped connection is often a moment's: try once more while time is left
111
+ if (!(error instanceof SynthIdError) || error.kind !== 'network' || authOperation.signal.aborted)
112
+ throw error;
113
+ await sleep(RETRY_DELAY, undefined, { signal: authOperation.signal }).catch(() => { throw failure(undefined, authOperation.signal); });
114
+ return this.authenticate(authOperation);
115
+ });
100
116
  signal.throwIfAborted();
101
117
  const authElapsed = Date.now() - started;
102
118
  for (const [key, account] of accounts)
@@ -112,17 +128,28 @@ export class HttpSynthIdClient {
112
128
  signal.throwIfAborted();
113
129
  if (account.retryAt > Date.now())
114
130
  throw new SynthIdError('rate-limit', 'SynthID account is cooling down', undefined, Math.ceil((account.retryAt - Date.now()) / 1000));
115
- const deadline = AbortSignal.timeout(Math.max(1, this.options.timeout - authElapsed));
116
- const operation = { reference, signal: AbortSignal.any([signal, deadline]) };
131
+ const deadline = AbortSignal.timeout(Math.max(1, timeout - authElapsed));
132
+ const operation = { reference, signal: AbortSignal.any([signal, deadline]), timeout };
117
133
  try {
118
- for (let attempt = 0, auth = tokens;; attempt++) {
134
+ let refreshed = false, retried = false;
135
+ for (let auth = tokens;;) {
119
136
  try {
120
137
  return await this.detectQueued(image, mime, auth, operation, entry);
121
138
  }
122
139
  catch (error) {
123
- if (!(error instanceof SynthIdError) || error.code !== 16 || attempt)
140
+ if (!(error instanceof SynthIdError))
141
+ throw error;
142
+ if (error.code === 16 && !refreshed) {
143
+ refreshed = true;
144
+ auth = await this.authenticate(operation, true);
145
+ }
146
+ else if (error.kind === 'network' && !retried && !operation.signal.aborted) {
147
+ // The whole chain again: the verification token is bound to one upload path and used once
148
+ retried = true;
149
+ await sleep(RETRY_DELAY, undefined, { signal: operation.signal });
150
+ }
151
+ else
124
152
  throw error;
125
- auth = await this.authenticate(operation, true);
126
153
  }
127
154
  }
128
155
  }
@@ -161,10 +188,12 @@ export class HttpSynthIdClient {
161
188
  try {
162
189
  response = await this.ctx.http.fetch(url, { ...init, headers, signal, redirect: 'error' });
163
190
  }
164
- catch {
191
+ catch (error) {
165
192
  if (signal.aborted)
166
193
  throw failure(undefined, signal);
167
- throw new SynthIdError('network', `SynthID ${stage} could not connect`);
194
+ // The code only: the message may name the proxy, credentials included
195
+ const code = connectionCode(error);
196
+ throw new SynthIdError('network', `SynthID ${stage} could not connect (${code ?? 'unknown'})`, undefined, undefined, networkCodeOf(code));
168
197
  }
169
198
  if (!response.ok) {
170
199
  await response.body?.cancel();
@@ -252,7 +281,7 @@ export class HttpSynthIdClient {
252
281
  }
253
282
  lifecycle = entry.createLifecycleClient({ signal: operation.signal,
254
283
  webidlBrandErrors: true,
255
- timeouts: { init: Math.min(this.options.timeout, 25_000), snapshot: Math.min(this.options.timeout, 15_000) }, maxLifetimeMs: Math.max(100, this.options.timeout) });
284
+ timeouts: { init: Math.min(operation.timeout, 25_000), snapshot: Math.min(operation.timeout, 15_000) }, maxLifetimeMs: Math.max(100, operation.timeout) });
256
285
  const initialized = await lifecycle.initialize({ ...await session.environment(),
257
286
  program: challenge.program, globalName: challenge.globalName, rawExperiments: challenge.clientExperimentsStateBlob ?? '',
258
287
  experiments: entry.normalizeOfficialExperimentState(challenge.clientExperimentsStateBlob),
@@ -274,7 +303,7 @@ export class HttpSynthIdClient {
274
303
  throw new SynthIdError('response', 'SynthID verification token generation failed');
275
304
  const headers = { Authorization: 'Basic amI5dChNbS0qNjFlczJJVzpyZyRHNUp1QENpV29OJVNS', 'Push-ID': 'feeds/szvztmw263lqqp',
276
305
  'Push-Filename': path, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' };
277
- const start = await request(UPLOAD, { method: 'POST', body: `file_name image.${EXTENSIONS[mime]}`,
306
+ const start = await request(UPLOAD, { method: 'POST', body: `file_name ${mime.startsWith('video/') ? 'video' : 'image'}.${EXTENSIONS[mime]}`,
278
307
  headers: { ...headers, 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': String(image.data.byteLength) } }, 'start');
279
308
  let uploadUrl;
280
309
  try {
@@ -293,7 +322,7 @@ export class HttpSynthIdClient {
293
322
  const endpoint = new URL('/_/WatermarkApp/data/batchexecute', ORIGIN);
294
323
  if (typeof session.config.cfb2h !== 'string' || !session.config.cfb2h || typeof session.config.FdrFJe !== 'string' || !session.config.FdrFJe)
295
324
  throw new SynthIdError('response', 'SynthID page metadata is incomplete');
296
- endpoint.search = new URLSearchParams({ rpcids: 'TZRKo', 'source-path': '/image-detection', bl: session.config.cfb2h,
325
+ endpoint.search = new URLSearchParams({ rpcids: 'TZRKo', 'source-path': mime.startsWith('video/') ? '/video-detection' : '/image-detection', bl: session.config.cfb2h,
297
326
  'f.sid': session.config.FdrFJe, hl: session.config.hl || 'en-US', _reqid: session.nextRequestId(), rt: 'c' }).toString();
298
327
  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);
299
328
  const response = await session.request(endpoint.href, { method: 'POST', body: form.toString() + '&', headers: {
@@ -7,9 +7,9 @@ export class ManualSynthIdError extends SynthIdError {
7
7
  }
8
8
  export function describeManualSynthIdFailure(error) {
9
9
  switch (error.kind) {
10
- case 'config': return 'SynthID 凭证不完整、格式错误或账号不一致,请使用浏览器登录自动填写,或按插件设置中的获取说明重新填写。';
11
- case 'auth': return 'SynthID 登录凭证已失效,请重新登录自动填写,或重新获取登录凭据(refresh_token)。';
12
- case 'verification': return 'SynthID 未接受本次请求提供的网页校验凭据,请确认上传标识与网页校验凭据来自同一次检测,或在网页完成新检测后一起更新。';
10
+ case 'config': return '检测凭证不完整、格式错误或账号不一致,请在插件设置中重新登录自动填写,或按获取说明重新填写。';
11
+ case 'auth': return '检测登录凭证已失效,请在插件设置中重新登录自动填写,或重新获取登录凭据(refresh_token)。';
12
+ case 'verification': return '检测服务未接受本次请求提供的网页校验凭据,请确认上传标识与网页校验凭据来自同一次检测,或在网页完成新检测后一起更新。';
13
13
  default: return describeSynthIdFailure(error);
14
14
  }
15
15
  }
@@ -1,3 +1,18 @@
1
+ const NETWORK_CODES = {
2
+ ECONNRESET: 'ECONNRESET', EPIPE: 'ECONNRESET', UND_ERR_SOCKET: 'ECONNRESET',
3
+ ECONNREFUSED: 'ECONNREFUSED', ENOTFOUND: 'ENOTFOUND', EAI_AGAIN: 'EAI_AGAIN',
4
+ ETIMEDOUT: 'ETIMEDOUT', UND_ERR_CONNECT_TIMEOUT: 'ETIMEDOUT', UND_ERR_HEADERS_TIMEOUT: 'ETIMEDOUT', UND_ERR_BODY_TIMEOUT: 'ETIMEDOUT',
5
+ };
6
+ /** The connection error's code, as `ctx.http` reports it (`code`, or down the cause chain); only the code, never the message */
7
+ export function connectionCode(error) {
8
+ for (let cause = error, depth = 0; cause && depth < 8; cause = cause.cause, depth++) {
9
+ if (typeof cause.code === 'string' && /^[A-Z][A-Z0-9_]{1,40}$/.test(cause.code))
10
+ return cause.code;
11
+ }
12
+ }
13
+ export function networkCodeOf(code) {
14
+ return code && Object.hasOwn(NETWORK_CODES, code) ? NETWORK_CODES[code] : undefined;
15
+ }
1
16
  /** Messages contain no response bodies, tokens, or upload paths: they are safe to log. */
2
17
  export class SynthIdError extends Error {
3
18
  kind;
@@ -140,50 +155,60 @@ export function parseSynthIdResponse(text) {
140
155
  default: return invalid();
141
156
  }
142
157
  }
143
- export function formatSynthId(result) {
158
+ /** `noun`: what was checked, 图片 or 视频 */
159
+ export function formatSynthId(result, noun = '图片') {
144
160
  if (result.status === 'not_detected')
145
161
  return '没有找到 AI 特征,但不能完全确认不是 AI。';
146
162
  if (result.status === 'uncertain') {
147
163
  const reasons = {
148
- 1: '图片为空',
149
- 2: '图片分辨率过低',
150
- 3: '图片细节不足',
151
- 5: '图片质量过低',
152
- 6: '图片可能经过修改,或只在局部使用了 AI',
164
+ 1: `${noun}为空`,
165
+ 2: `${noun}分辨率过低`,
166
+ 3: `${noun}细节不足`,
167
+ 5: `${noun}质量过低`,
168
+ 6: `${noun}可能经过修改,或只在局部使用了 AI`,
153
169
  };
154
- return `SynthID 无法判断:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`;
170
+ return `无法判断是否为 AI 生成:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`;
155
171
  }
156
172
  const sources = { google: 'Google', openai: 'OpenAI', nvidia: 'NVIDIA', kakao: 'Kakao' };
157
173
  const source = result.source && (Object.hasOwn(sources, result.source.toLowerCase()) ? sources[result.source.toLowerCase()] : result.source);
158
- return `图片是 ${source || 'AI'} 生成`;
174
+ return `${noun}是 ${source || 'AI'} 生成`;
159
175
  }
160
- export function describeSynthIdFailure(error) {
176
+ /** `during`: login, from the WebUI's login window, or a detection */
177
+ export function describeSynthIdFailure(error, noun = '图片', during = 'detect') {
161
178
  switch (error.kind) {
162
- case 'runtime': return 'SynthID HTTP 运行环境不可用,当前需要 Node.js 24 或以上版本。';
179
+ case 'runtime': return '检测运行环境不可用,当前需要 Node.js 24 或以上版本。';
163
180
  case 'config':
164
- case 'browser': return 'SynthID 浏览器无法启动,请确认运行 Bot 的电脑已安装 Chrome 或 Edge,并且能打开桌面窗口。';
165
- case 'proxy': return 'SynthID 浏览器无法使用当前代理,请检查「代理」插件的地址与账号密码;浏览器不支持带账号密码的 SOCKS5 代理。';
166
- case 'terms': return '请在插件设置中点击「登录 SynthID」,完成登录窗口中的首次使用提示。';
167
- case 'auth': return 'SynthID 尚未登录或登录已失效,请在插件设置中点击「登录 SynthID」。';
168
- case 'permission': return 'SynthID 服务拒绝了本次检测请求。';
169
- case 'verification': return 'SynthID 本次请求未通过网页校验,请稍后再试。';
181
+ case 'browser': return '浏览器无法启动,请确认运行 Bot 的电脑已安装 Chrome 或 Edge,并且能打开桌面窗口。';
182
+ case 'proxy': return '浏览器无法使用当前代理,请检查「代理」插件的地址与账号密码;浏览器不支持带账号密码的 SOCKS5 代理。';
183
+ case 'terms': return '请在插件设置中打开检测登录窗口,完成首次使用提示。';
184
+ case 'auth': return '检测服务尚未登录或登录已失效,请在插件设置中完成登录。';
185
+ case 'permission': return '检测服务拒绝了本次检测请求。';
186
+ case 'verification': return '本次请求未通过网页校验,请稍后再试。';
170
187
  case 'rate-limit': return error.retryAfterSeconds
171
- ? `SynthID 检测额度暂时用完,请约 ${error.retryAfterSeconds} 秒后再试。`
172
- : 'SynthID 检测过于频繁或额度暂时用完,请稍后再试。';
173
- case 'busy': return 'SynthID 检测队列已满,请稍后再试。';
188
+ ? `检测额度暂时用完,请约 ${error.retryAfterSeconds} 秒后再试。`
189
+ : '检测请求过于频繁或额度暂时用完,请稍后再试。';
190
+ case 'busy': return '检测队列已满,请稍后再试。';
174
191
  case 'network': {
175
192
  const reasons = {
176
193
  ECONNRESET: '连接被重置(ECONNRESET)', ECONNREFUSED: '连接被拒绝(ECONNREFUSED)',
177
194
  ENOTFOUND: '域名解析失败(ENOTFOUND)', EAI_AGAIN: '域名解析暂时失败(EAI_AGAIN)', ETIMEDOUT: '连接超时(ETIMEDOUT)',
178
195
  };
179
- return error.networkCode && reasons[error.networkCode]
180
- ? `登录页加载失败:${reasons[error.networkCode]}。请在 Bot「代理」插件中测试 https://synthid.com/,确认该网站能通过当前代理访问后重试。`
181
- : '连不上 SynthID 检测服务,请检查网络或代理设置。';
196
+ const reason = error.networkCode && reasons[error.networkCode];
197
+ if (during === 'login') {
198
+ return reason
199
+ ? `登录页加载失败:${reason}。请检查 Bot「代理」插件设置,确认当前代理可正常连接检测服务后重试。`
200
+ : '连不上检测服务,请检查网络或代理设置。';
201
+ }
202
+ return reason
203
+ ? `连不上检测服务:${reason},已重试一次。请检查网络或 Bot「代理」插件设置。`
204
+ : '连不上检测服务,已重试一次。请检查网络或代理设置。';
182
205
  }
183
- case 'timeout': return '连不上 SynthID 检测服务,请检查网络或代理设置。';
184
- case 'request': return 'SynthID 无法处理这张图片,请尝试发送原图。';
185
- case 'response': return 'SynthID 返回了无法识别的结果,检测接口可能已变更。';
186
- case 'cancelled': return 'SynthID 检测已取消。';
187
- default: return 'SynthID 检测失败,请稍后再试。';
206
+ case 'timeout': return during === 'login'
207
+ ? '连不上检测服务,请检查网络或代理设置。'
208
+ : `${noun}检测超时:网络或代理较慢时,可在插件设置里调大「检测超时」。`;
209
+ case 'request': return noun === '视频' ? '无法处理这个视频:只支持 MP4、MOV、WebM,且不超过 100 MB。' : '无法处理这张图片,请尝试发送原图。';
210
+ case 'response': return '检测服务返回了无法识别的结果,检测接口可能已变更。';
211
+ case 'cancelled': return '检测已取消。';
212
+ default: return '检测失败,请稍后再试。';
188
213
  }
189
214
  }
package/lib/synthid.js CHANGED
@@ -2,13 +2,14 @@ import { randomUUID } from 'node:crypto';
2
2
  import { mkdir, readFile, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
+ import { MAX_SIZE } from './image.js';
5
6
  import { launchSynthIdBrowser } from './synthid-browser.js';
6
7
  import { HttpSynthIdClient } from './synthid-http.js';
7
8
  import { describeSynthIdFailure, SynthIdError } from './synthid-result.js';
8
9
  // All entries in one instance share a profile and queue. The last owner closes
9
10
  // the browser and removes this entry, including during plugin reload.
10
11
  const sessions = new Map();
11
- const supported = /^image\/(?:jpeg|png|webp|gif|bmp|avif|heic|heif|tiff)$/;
12
+ const supported = /^(?:image\/(?:jpeg|png|webp|gif|bmp|avif|heic|heif|tiff)|video\/(?:mp4|quicktime|webm))$/;
12
13
  const cancelled = () => new SynthIdError('cancelled', 'SynthID operation was cancelled');
13
14
  class ManagedSession {
14
15
  root;
@@ -438,8 +439,9 @@ export class SynthIdClient {
438
439
  if (this.disposed)
439
440
  throw cancelled();
440
441
  const mime = image.type.split(';')[0].trim().toLowerCase();
441
- if (!supported.test(mime) || !image.data.byteLength || image.data.byteLength > 20 * 1024 * 1024) {
442
- throw new SynthIdError('request', 'SynthID needs a supported image of at most 20 MB');
442
+ const kind = mime.startsWith('video/') ? 'video' : 'image';
443
+ if (!supported.test(mime) || !image.data.byteLength || image.data.byteLength > MAX_SIZE[kind]) {
444
+ throw new SynthIdError('request', `SynthID needs a supported ${kind} of at most ${MAX_SIZE[kind] / 1024 / 1024} MB`);
443
445
  }
444
446
  // Snapshot before either context initialization or the shared queue waits.
445
447
  // An update affects only subsequent requests, including credential identity.
@@ -501,7 +503,7 @@ function safeInitializationError(error) {
501
503
  ? error.networkCode : undefined);
502
504
  }
503
505
  function safeError(error) {
504
- return error instanceof SynthIdError ? describeSynthIdFailure(error) : '无法启动或保存 SynthID 登录,请检查浏览器、网络和插件数据目录。';
506
+ return error instanceof SynthIdError ? describeSynthIdFailure(error, '图片', 'login') : '无法启动或保存 SynthID 登录,请检查浏览器、网络和插件数据目录。';
505
507
  }
506
508
  function validCredentials(value) {
507
509
  if (!value || typeof value !== 'object')
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@luckylillia-dev/plugin-aiimgdetector",
3
- "version": "1.0.4",
4
- "description": "Checks AI image provenance through OpenAI, optional SynthID detection, and a vision model",
3
+ "version": "1.1.0",
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,8 +1,9 @@
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'
@@ -14,6 +15,7 @@ const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
14
15
  const EXTENSIONS: Record<string, string> = {
15
16
  'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif',
16
17
  'image/bmp': 'bmp', 'image/avif': 'avif', 'image/heic': 'heic', 'image/heif': 'heif', 'image/tiff': 'tiff',
18
+ 'video/mp4': 'mp4', 'video/quicktime': 'mov', 'video/webm': 'webm',
17
19
  }
18
20
  export interface HttpSynthIdOptions {
19
21
  refreshToken: string
@@ -21,7 +23,11 @@ export interface HttpSynthIdOptions {
21
23
  /** Replace the interpreter process in isolated wire tests. */
22
24
  loadRuntime?: () => Promise<typeof import('./synthid-http-runtime/entry.mjs')>
23
25
  }
24
- interface Operation { signal: AbortSignal; reference: RequestReference }
26
+ /** A video uploads tens of MB, often through a proxy: it gets at least this long whatever the setting */
27
+ export const VIDEO_TIMEOUT = 120_000
28
+ /** Before the one retry after a connection failure */
29
+ const RETRY_DELAY = 1000
30
+ interface Operation { signal: AbortSignal; reference: RequestReference; timeout: number }
25
31
  interface Job {
26
32
  run?: () => Promise<SynthIdResult>
27
33
  resolve: (result: SynthIdResult) => void
@@ -88,8 +94,9 @@ export class HttpSynthIdClient {
88
94
  const signal = external ? AbortSignal.any([this.abort.signal, external]) : this.abort.signal
89
95
  const mime = image.type.split(';')[0].trim().toLowerCase()
90
96
  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'))
97
+ const kind = mime.startsWith('video/') ? 'video' : 'image'
98
+ if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > MAX_SIZE[kind]) {
99
+ return Promise.reject(new SynthIdError('request', `SynthID needs a supported, non-empty ${kind} of at most ${MAX_SIZE[kind] / 1024 / 1024} MB`))
93
100
  }
94
101
  if (this.active.size >= 4) return Promise.reject(new SynthIdError('busy', 'SynthID account queue is full'))
95
102
  const task = this.prepare(image, mime, signal).catch(error => { throw failure(error, signal) })
@@ -106,7 +113,14 @@ export class HttpSynthIdClient {
106
113
  const entry = await this.runtime
107
114
  const reference = entry.createIndependentRequestReference({ userAgent: USER_AGENT })
108
115
  const started = Date.now()
109
- const tokens = await this.authenticate({ signal: AbortSignal.any([signal, AbortSignal.timeout(this.options.timeout)]), reference })
116
+ const timeout = mime.startsWith('video/') ? Math.max(this.options.timeout, VIDEO_TIMEOUT) : this.options.timeout
117
+ const authOperation = { signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]), reference, timeout }
118
+ const tokens = await this.authenticate(authOperation).catch(async error => {
119
+ // A dropped connection is often a moment's: try once more while time is left
120
+ if (!(error instanceof SynthIdError) || error.kind !== 'network' || authOperation.signal.aborted) throw error
121
+ await sleep(RETRY_DELAY, undefined, { signal: authOperation.signal }).catch(() => { throw failure(undefined, authOperation.signal) })
122
+ return this.authenticate(authOperation)
123
+ })
110
124
  signal.throwIfAborted()
111
125
  const authElapsed = Date.now() - started
112
126
  for (const [key, account] of accounts) prune(key, account)
@@ -119,14 +133,22 @@ export class HttpSynthIdClient {
119
133
  run: async () => {
120
134
  signal.throwIfAborted()
121
135
  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]) }
136
+ const deadline = AbortSignal.timeout(Math.max(1, timeout - authElapsed))
137
+ const operation = { reference, signal: AbortSignal.any([signal, deadline]), timeout }
124
138
  try {
125
- for (let attempt = 0, auth = tokens; ; attempt++) {
139
+ let refreshed = false, retried = false
140
+ for (let auth = tokens; ;) {
126
141
  try { return await this.detectQueued(image, mime, auth, operation, entry) }
127
142
  catch (error) {
128
- if (!(error instanceof SynthIdError) || error.code !== 16 || attempt) throw error
129
- auth = await this.authenticate(operation, true)
143
+ if (!(error instanceof SynthIdError)) throw error
144
+ if (error.code === 16 && !refreshed) {
145
+ refreshed = true
146
+ auth = await this.authenticate(operation, true)
147
+ } else if (error.kind === 'network' && !retried && !operation.signal.aborted) {
148
+ // The whole chain again: the verification token is bound to one upload path and used once
149
+ retried = true
150
+ await sleep(RETRY_DELAY, undefined, { signal: operation.signal })
151
+ } else throw error
130
152
  }
131
153
  }
132
154
  } catch (error) { throw failure(error, operation.signal) }
@@ -158,9 +180,11 @@ export class HttpSynthIdClient {
158
180
  headers.delete('content-length')
159
181
  let response: Response
160
182
  try { response = await this.ctx.http.fetch(url, { ...init, headers, signal, redirect: 'error' }) }
161
- catch {
183
+ catch (error) {
162
184
  if (signal.aborted) throw failure(undefined, signal)
163
- throw new SynthIdError('network', `SynthID ${stage} could not connect`)
185
+ // The code only: the message may name the proxy, credentials included
186
+ const code = connectionCode(error)
187
+ throw new SynthIdError('network', `SynthID ${stage} could not connect (${code ?? 'unknown'})`, undefined, undefined, networkCodeOf(code))
164
188
  }
165
189
  if (!response.ok) {
166
190
  await response.body?.cancel()
@@ -238,7 +262,7 @@ export class HttpSynthIdClient {
238
262
  }
239
263
  lifecycle = entry.createLifecycleClient({ signal: operation.signal,
240
264
  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) })
265
+ timeouts: { init: Math.min(operation.timeout, 25_000), snapshot: Math.min(operation.timeout, 15_000) }, maxLifetimeMs: Math.max(100, operation.timeout) })
242
266
  const initialized = await lifecycle.initialize({ ...await session.environment(),
243
267
  program: challenge.program, globalName: challenge.globalName, rawExperiments: challenge.clientExperimentsStateBlob ?? '',
244
268
  experiments: entry.normalizeOfficialExperimentState(challenge.clientExperimentsStateBlob),
@@ -258,7 +282,7 @@ export class HttpSynthIdClient {
258
282
  if (!generated.success || typeof generated.bgToken !== 'string' || !/^![\x21-\x7e]+$/.test(generated.bgToken)) throw new SynthIdError('response', 'SynthID verification token generation failed')
259
283
  const headers = { Authorization: 'Basic amI5dChNbS0qNjFlczJJVzpyZyRHNUp1QENpV29OJVNS', 'Push-ID': 'feeds/szvztmw263lqqp',
260
284
  '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]}`,
285
+ const start = await request(UPLOAD, { method: 'POST', body: `file_name ${mime.startsWith('video/') ? 'video' : 'image'}.${EXTENSIONS[mime]}`,
262
286
  headers: { ...headers, 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': String(image.data.byteLength) } }, 'start')
263
287
  let uploadUrl: URL
264
288
  try {
@@ -271,7 +295,7 @@ export class HttpSynthIdClient {
271
295
  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')
272
296
  const endpoint = new URL('/_/WatermarkApp/data/batchexecute', ORIGIN)
273
297
  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,
298
+ endpoint.search = new URLSearchParams({ rpcids: 'TZRKo', 'source-path': mime.startsWith('video/') ? '/video-detection' : '/image-detection', bl: session.config.cfb2h,
275
299
  'f.sid': session.config.FdrFJe, hl: session.config.hl || 'en-US', _reqid: session.nextRequestId(), rt: 'c' }).toString()
276
300
  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)
277
301
  const response = await session.request(endpoint.href, { method: 'POST', body: form.toString() + '&', headers: {
@@ -21,9 +21,9 @@ export class ManualSynthIdError extends SynthIdError {}
21
21
 
22
22
  export function describeManualSynthIdFailure(error: SynthIdError): string {
23
23
  switch (error.kind) {
24
- case 'config': return 'SynthID 凭证不完整、格式错误或账号不一致,请使用浏览器登录自动填写,或按插件设置中的获取说明重新填写。'
25
- case 'auth': return 'SynthID 登录凭证已失效,请重新登录自动填写,或重新获取登录凭据(refresh_token)。'
26
- case 'verification': return 'SynthID 未接受本次请求提供的网页校验凭据,请确认上传标识与网页校验凭据来自同一次检测,或在网页完成新检测后一起更新。'
24
+ case 'config': return '检测凭证不完整、格式错误或账号不一致,请在插件设置中重新登录自动填写,或按获取说明重新填写。'
25
+ case 'auth': return '检测登录凭证已失效,请在插件设置中重新登录自动填写,或重新获取登录凭据(refresh_token)。'
26
+ case 'verification': return '检测服务未接受本次请求提供的网页校验凭据,请确认上传标识与网页校验凭据来自同一次检测,或在网页完成新检测后一起更新。'
27
27
  default: return describeSynthIdFailure(error)
28
28
  }
29
29
  }
@@ -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'
@@ -128,50 +145,60 @@ export function parseSynthIdResponse(text: string): SynthIdResult {
128
145
  }
129
146
  }
130
147
 
131
- export function formatSynthId(result: Exclude<SynthIdResult, { status: 'quota_exceeded' }>): string {
148
+ /** `noun`: what was checked, 图片 or 视频 */
149
+ export function formatSynthId(result: Exclude<SynthIdResult, { status: 'quota_exceeded' }>, noun = '图片'): string {
132
150
  if (result.status === 'not_detected') return '没有找到 AI 特征,但不能完全确认不是 AI。'
133
151
  if (result.status === 'uncertain') {
134
152
  const reasons: Record<number, string> = {
135
- 1: '图片为空',
136
- 2: '图片分辨率过低',
137
- 3: '图片细节不足',
138
- 5: '图片质量过低',
139
- 6: '图片可能经过修改,或只在局部使用了 AI',
153
+ 1: `${noun}为空`,
154
+ 2: `${noun}分辨率过低`,
155
+ 3: `${noun}细节不足`,
156
+ 5: `${noun}质量过低`,
157
+ 6: `${noun}可能经过修改,或只在局部使用了 AI`,
140
158
  }
141
- return `SynthID 无法判断:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`
159
+ return `无法判断是否为 AI 生成:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`
142
160
  }
143
161
  const sources: Record<string, string> = { google: 'Google', openai: 'OpenAI', nvidia: 'NVIDIA', kakao: 'Kakao' }
144
162
  const source = result.source && (Object.hasOwn(sources, result.source.toLowerCase()) ? sources[result.source.toLowerCase()] : result.source)
145
- return `图片是 ${source || 'AI'} 生成`
163
+ return `${noun}是 ${source || 'AI'} 生成`
146
164
  }
147
165
 
148
- export function describeSynthIdFailure(error: SynthIdError): string {
166
+ /** `during`: login, from the WebUI's login window, or a detection */
167
+ export function describeSynthIdFailure(error: SynthIdError, noun = '图片', during: 'detect' | 'login' = 'detect'): string {
149
168
  switch (error.kind) {
150
- case 'runtime': return 'SynthID HTTP 运行环境不可用,当前需要 Node.js 24 或以上版本。'
169
+ case 'runtime': return '检测运行环境不可用,当前需要 Node.js 24 或以上版本。'
151
170
  case 'config':
152
- case 'browser': return 'SynthID 浏览器无法启动,请确认运行 Bot 的电脑已安装 Chrome 或 Edge,并且能打开桌面窗口。'
153
- case 'proxy': return 'SynthID 浏览器无法使用当前代理,请检查「代理」插件的地址与账号密码;浏览器不支持带账号密码的 SOCKS5 代理。'
154
- case 'terms': return '请在插件设置中点击「登录 SynthID」,完成登录窗口中的首次使用提示。'
155
- case 'auth': return 'SynthID 尚未登录或登录已失效,请在插件设置中点击「登录 SynthID」。'
156
- case 'permission': return 'SynthID 服务拒绝了本次检测请求。'
157
- case 'verification': return 'SynthID 本次请求未通过网页校验,请稍后再试。'
171
+ case 'browser': return '浏览器无法启动,请确认运行 Bot 的电脑已安装 Chrome 或 Edge,并且能打开桌面窗口。'
172
+ case 'proxy': return '浏览器无法使用当前代理,请检查「代理」插件的地址与账号密码;浏览器不支持带账号密码的 SOCKS5 代理。'
173
+ case 'terms': return '请在插件设置中打开检测登录窗口,完成首次使用提示。'
174
+ case 'auth': return '检测服务尚未登录或登录已失效,请在插件设置中完成登录。'
175
+ case 'permission': return '检测服务拒绝了本次检测请求。'
176
+ case 'verification': return '本次请求未通过网页校验,请稍后再试。'
158
177
  case 'rate-limit': return error.retryAfterSeconds
159
- ? `SynthID 检测额度暂时用完,请约 ${error.retryAfterSeconds} 秒后再试。`
160
- : 'SynthID 检测过于频繁或额度暂时用完,请稍后再试。'
161
- case 'busy': return 'SynthID 检测队列已满,请稍后再试。'
178
+ ? `检测额度暂时用完,请约 ${error.retryAfterSeconds} 秒后再试。`
179
+ : '检测请求过于频繁或额度暂时用完,请稍后再试。'
180
+ case 'busy': return '检测队列已满,请稍后再试。'
162
181
  case 'network': {
163
182
  const reasons: Record<SynthIdNetworkCode, string> = {
164
183
  ECONNRESET: '连接被重置(ECONNRESET)', ECONNREFUSED: '连接被拒绝(ECONNREFUSED)',
165
184
  ENOTFOUND: '域名解析失败(ENOTFOUND)', EAI_AGAIN: '域名解析暂时失败(EAI_AGAIN)', ETIMEDOUT: '连接超时(ETIMEDOUT)',
166
185
  }
167
- return error.networkCode && reasons[error.networkCode]
168
- ? `登录页加载失败:${reasons[error.networkCode]}。请在 Bot「代理」插件中测试 https://synthid.com/,确认该网站能通过当前代理访问后重试。`
169
- : '连不上 SynthID 检测服务,请检查网络或代理设置。'
186
+ const reason = error.networkCode && reasons[error.networkCode]
187
+ if (during === 'login') {
188
+ return reason
189
+ ? `登录页加载失败:${reason}。请检查 Bot「代理」插件设置,确认当前代理可正常连接检测服务后重试。`
190
+ : '连不上检测服务,请检查网络或代理设置。'
191
+ }
192
+ return reason
193
+ ? `连不上检测服务:${reason},已重试一次。请检查网络或 Bot「代理」插件设置。`
194
+ : '连不上检测服务,已重试一次。请检查网络或代理设置。'
170
195
  }
171
- case 'timeout': return '连不上 SynthID 检测服务,请检查网络或代理设置。'
172
- case 'request': return 'SynthID 无法处理这张图片,请尝试发送原图。'
173
- case 'response': return 'SynthID 返回了无法识别的结果,检测接口可能已变更。'
174
- case 'cancelled': return 'SynthID 检测已取消。'
175
- default: return 'SynthID 检测失败,请稍后再试。'
196
+ case 'timeout': return during === 'login'
197
+ ? '连不上检测服务,请检查网络或代理设置。'
198
+ : `${noun}检测超时:网络或代理较慢时,可在插件设置里调大「检测超时」。`
199
+ case 'request': return noun === '视频' ? '无法处理这个视频:只支持 MP4、MOV、WebM,且不超过 100 MB。' : '无法处理这张图片,请尝试发送原图。'
200
+ case 'response': return '检测服务返回了无法识别的结果,检测接口可能已变更。'
201
+ case 'cancelled': return '检测已取消。'
202
+ default: return '检测失败,请稍后再试。'
176
203
  }
177
204
  }
package/src/synthid.ts CHANGED
@@ -3,7 +3,7 @@ import { mkdir, readFile, realpath, rename, rm, unlink, writeFile } from 'node:f
3
3
  import { dirname, join, resolve } from 'node:path'
4
4
  import { setTimeout as delay } from 'node:timers/promises'
5
5
  import type { Context, Http } from '@luckylillia-dev/plugin-sdk'
6
- import type { Image } from './image.js'
6
+ import { MAX_SIZE, type Image } from './image.js'
7
7
  import { launchSynthIdBrowser, type SynthIdBrowserSession } from './synthid-browser.js'
8
8
  import { HttpSynthIdClient, type HttpSynthIdOptions } from './synthid-http.js'
9
9
  import { describeSynthIdFailure, SynthIdError, type SynthIdResult } from './synthid-result.js'
@@ -33,7 +33,7 @@ interface CapturedCredentials {
33
33
  // All entries in one instance share a profile and queue. The last owner closes
34
34
  // the browser and removes this entry, including during plugin reload.
35
35
  const sessions = new Map<string, ManagedSession>()
36
- const supported = /^image\/(?:jpeg|png|webp|gif|bmp|avif|heic|heif|tiff)$/
36
+ const supported = /^(?:image\/(?:jpeg|png|webp|gif|bmp|avif|heic|heif|tiff)|video\/(?:mp4|quicktime|webm))$/
37
37
  const cancelled = () => new SynthIdError('cancelled', 'SynthID operation was cancelled')
38
38
 
39
39
  class ManagedSession {
@@ -420,8 +420,9 @@ export class SynthIdClient {
420
420
  async detect(image: Image): Promise<SynthIdResult> {
421
421
  if (this.disposed) throw cancelled()
422
422
  const mime = image.type.split(';')[0].trim().toLowerCase()
423
- if (!supported.test(mime) || !image.data.byteLength || image.data.byteLength > 20 * 1024 * 1024) {
424
- throw new SynthIdError('request', 'SynthID needs a supported image of at most 20 MB')
423
+ const kind = mime.startsWith('video/') ? 'video' : 'image'
424
+ if (!supported.test(mime) || !image.data.byteLength || image.data.byteLength > MAX_SIZE[kind]) {
425
+ throw new SynthIdError('request', `SynthID needs a supported ${kind} of at most ${MAX_SIZE[kind] / 1024 / 1024} MB`)
425
426
  }
426
427
  // Snapshot before either context initialization or the shared queue waits.
427
428
  // An update affects only subsequent requests, including credential identity.
@@ -475,7 +476,7 @@ function safeInitializationError(error: unknown): SynthIdError | undefined {
475
476
  }
476
477
 
477
478
  function safeError(error: unknown): string {
478
- return error instanceof SynthIdError ? describeSynthIdFailure(error) : '无法启动或保存 SynthID 登录,请检查浏览器、网络和插件数据目录。'
479
+ return error instanceof SynthIdError ? describeSynthIdFailure(error, '图片', 'login') : '无法启动或保存 SynthID 登录,请检查浏览器、网络和插件数据目录。'
479
480
  }
480
481
 
481
482
  function validCredentials(value: unknown): value is SynthIdCredentials {