@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/docs/details.md +5 -1
- package/lib/image.js +40 -12
- package/lib/index.js +70 -24
- package/lib/provenance.js +1 -1
- package/lib/synthid-http.js +52 -16
- package/lib/synthid-manual.js +5 -4
- package/lib/synthid-result.js +46 -16
- package/lib/synthid.js +6 -4
- package/package.json +3 -3
- package/src/image.ts +37 -12
- package/src/index.ts +74 -25
- package/src/provenance.ts +1 -1
- package/src/synthid-http.ts +49 -18
- package/src/synthid-manual.ts +4 -3
- package/src/synthid-result.ts +48 -17
- package/src/synthid.ts +6 -5
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
|
|
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
|
-
|
|
51
|
-
const
|
|
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(
|
|
54
|
-
}, { timeout
|
|
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) >
|
|
84
|
+
if (!response.ok || response.redirected && !fromApi || length !== null && Number(length) > max || !response.body) {
|
|
57
85
|
await response.body?.cancel();
|
|
58
|
-
throw new Error(
|
|
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 >
|
|
69
|
-
throw new Error(
|
|
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(
|
|
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
|
|
100
|
+
return `${noun}由 OpenAI 制作。`;
|
|
99
101
|
checked = true;
|
|
100
102
|
}
|
|
101
103
|
catch (e) {
|
|
102
|
-
failure
|
|
103
|
-
|
|
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
|
-
|
|
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, '
|
|
152
|
-
const picked =
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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 {
|
|
226
|
+
return { ...own, messageId: session.messageId };
|
|
181
227
|
const quote = session.elements.find(element => element.type === 'quote');
|
|
182
|
-
const quoted = quote &&
|
|
228
|
+
const quoted = quote && firstMedia(quote.children);
|
|
183
229
|
if (quoted)
|
|
184
|
-
return {
|
|
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
|
}
|
package/lib/synthid-http.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { MAX_SIZE } from './image.js';
|
|
2
3
|
import { SynthIdTokenStore } from './synthid-auth.js';
|
|
3
|
-
import {
|
|
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';
|
|
7
|
+
const RPC_ID = 'vZ4jac';
|
|
8
|
+
const VIDEO_DEFAULT_FPS = 30;
|
|
5
9
|
const TOKEN = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyCjADz3UffE3DF5HZ--7MgVEXrbt6Bgcck';
|
|
6
10
|
const CREATE = 'https://waa-pa.clients6.google.com/$rpc/google.internal.waa.v1.Waa/Create';
|
|
7
11
|
const UPLOAD = 'https://content-push.googleapis.com/upload/';
|
|
@@ -10,7 +14,12 @@ const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
|
|
|
10
14
|
const EXTENSIONS = {
|
|
11
15
|
'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif',
|
|
12
16
|
'image/bmp': 'bmp', 'image/avif': 'avif', 'image/heic': 'heic', 'image/heif': 'heif', 'image/tiff': 'tiff',
|
|
17
|
+
'video/mp4': 'mp4', 'video/quicktime': 'mov', 'video/webm': 'webm',
|
|
13
18
|
};
|
|
19
|
+
/** A video uploads tens of MB, often through a proxy: it gets at least this long whatever the setting */
|
|
20
|
+
export const VIDEO_TIMEOUT = 120_000;
|
|
21
|
+
/** Before the one retry after a connection failure */
|
|
22
|
+
const RETRY_DELAY = 1000;
|
|
14
23
|
const accounts = new Map();
|
|
15
24
|
const cancelled = () => new SynthIdError('cancelled', 'SynthID detection was cancelled');
|
|
16
25
|
function prune(key, account) {
|
|
@@ -78,8 +87,9 @@ export class HttpSynthIdClient {
|
|
|
78
87
|
const mime = image.type.split(';')[0].trim().toLowerCase();
|
|
79
88
|
if (signal.aborted)
|
|
80
89
|
return Promise.reject(cancelled());
|
|
81
|
-
|
|
82
|
-
|
|
90
|
+
const kind = mime.startsWith('video/') ? 'video' : 'image';
|
|
91
|
+
if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > MAX_SIZE[kind]) {
|
|
92
|
+
return Promise.reject(new SynthIdError('request', `SynthID needs a supported, non-empty ${kind} of at most ${MAX_SIZE[kind] / 1024 / 1024} MB`));
|
|
83
93
|
}
|
|
84
94
|
if (this.active.size >= 4)
|
|
85
95
|
return Promise.reject(new SynthIdError('busy', 'SynthID account queue is full'));
|
|
@@ -96,7 +106,15 @@ export class HttpSynthIdClient {
|
|
|
96
106
|
const entry = await this.runtime;
|
|
97
107
|
const reference = entry.createIndependentRequestReference({ userAgent: USER_AGENT });
|
|
98
108
|
const started = Date.now();
|
|
99
|
-
const
|
|
109
|
+
const timeout = mime.startsWith('video/') ? Math.max(this.options.timeout, VIDEO_TIMEOUT) : this.options.timeout;
|
|
110
|
+
const authOperation = { signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]), reference, timeout };
|
|
111
|
+
const tokens = await this.authenticate(authOperation).catch(async (error) => {
|
|
112
|
+
// A dropped connection is often a moment's: try once more while time is left
|
|
113
|
+
if (!(error instanceof SynthIdError) || error.kind !== 'network' || authOperation.signal.aborted)
|
|
114
|
+
throw error;
|
|
115
|
+
await sleep(RETRY_DELAY, undefined, { signal: authOperation.signal }).catch(() => { throw failure(undefined, authOperation.signal); });
|
|
116
|
+
return this.authenticate(authOperation);
|
|
117
|
+
});
|
|
100
118
|
signal.throwIfAborted();
|
|
101
119
|
const authElapsed = Date.now() - started;
|
|
102
120
|
for (const [key, account] of accounts)
|
|
@@ -112,17 +130,28 @@ export class HttpSynthIdClient {
|
|
|
112
130
|
signal.throwIfAborted();
|
|
113
131
|
if (account.retryAt > Date.now())
|
|
114
132
|
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,
|
|
116
|
-
const operation = { reference, signal: AbortSignal.any([signal, deadline]) };
|
|
133
|
+
const deadline = AbortSignal.timeout(Math.max(1, timeout - authElapsed));
|
|
134
|
+
const operation = { reference, signal: AbortSignal.any([signal, deadline]), timeout };
|
|
117
135
|
try {
|
|
118
|
-
|
|
136
|
+
let refreshed = false, retried = false;
|
|
137
|
+
for (let auth = tokens;;) {
|
|
119
138
|
try {
|
|
120
139
|
return await this.detectQueued(image, mime, auth, operation, entry);
|
|
121
140
|
}
|
|
122
141
|
catch (error) {
|
|
123
|
-
if (!(error instanceof SynthIdError)
|
|
142
|
+
if (!(error instanceof SynthIdError))
|
|
143
|
+
throw error;
|
|
144
|
+
if (error.code === 16 && !refreshed) {
|
|
145
|
+
refreshed = true;
|
|
146
|
+
auth = await this.authenticate(operation, true);
|
|
147
|
+
}
|
|
148
|
+
else if (error.kind === 'network' && !retried && !operation.signal.aborted) {
|
|
149
|
+
// The whole chain again: the verification token is bound to one upload path and used once
|
|
150
|
+
retried = true;
|
|
151
|
+
await sleep(RETRY_DELAY, undefined, { signal: operation.signal });
|
|
152
|
+
}
|
|
153
|
+
else
|
|
124
154
|
throw error;
|
|
125
|
-
auth = await this.authenticate(operation, true);
|
|
126
155
|
}
|
|
127
156
|
}
|
|
128
157
|
}
|
|
@@ -161,16 +190,19 @@ export class HttpSynthIdClient {
|
|
|
161
190
|
try {
|
|
162
191
|
response = await this.ctx.http.fetch(url, { ...init, headers, signal, redirect: 'error' });
|
|
163
192
|
}
|
|
164
|
-
catch {
|
|
193
|
+
catch (error) {
|
|
165
194
|
if (signal.aborted)
|
|
166
195
|
throw failure(undefined, signal);
|
|
167
|
-
|
|
196
|
+
// The code only: the message may name the proxy, credentials included
|
|
197
|
+
const code = connectionCode(error);
|
|
198
|
+
throw new SynthIdError('network', `SynthID ${stage} could not connect (${code ?? 'unknown'})`, undefined, undefined, networkCodeOf(code));
|
|
168
199
|
}
|
|
169
200
|
if (!response.ok) {
|
|
170
201
|
await response.body?.cancel();
|
|
171
202
|
const status = response.status;
|
|
172
203
|
const kind = status === 429 ? 'rate-limit' : status === 401 || stage === 'auth' && status === 400 ? 'auth'
|
|
173
|
-
: status === 403 ? 'permission' : status
|
|
204
|
+
: status === 403 ? 'permission' : status === 400 && stage === 'detect' ? 'response'
|
|
205
|
+
: status >= 500 ? 'server' : 'request';
|
|
174
206
|
throw new SynthIdError(kind, `SynthID ${stage} returned HTTP ${status}`, stage === 'detect' && status === 401 ? 16 : status, status === 429 ? retryAfter(response.headers.get('retry-after')) : undefined);
|
|
175
207
|
}
|
|
176
208
|
const limit = stage === 'page' || stage === 'challenge' ? 4 * 1024 * 1024 : 1024 * 1024;
|
|
@@ -252,7 +284,7 @@ export class HttpSynthIdClient {
|
|
|
252
284
|
}
|
|
253
285
|
lifecycle = entry.createLifecycleClient({ signal: operation.signal,
|
|
254
286
|
webidlBrandErrors: true,
|
|
255
|
-
timeouts: { init: Math.min(
|
|
287
|
+
timeouts: { init: Math.min(operation.timeout, 25_000), snapshot: Math.min(operation.timeout, 15_000) }, maxLifetimeMs: Math.max(100, operation.timeout) });
|
|
256
288
|
const initialized = await lifecycle.initialize({ ...await session.environment(),
|
|
257
289
|
program: challenge.program, globalName: challenge.globalName, rawExperiments: challenge.clientExperimentsStateBlob ?? '',
|
|
258
290
|
experiments: entry.normalizeOfficialExperimentState(challenge.clientExperimentsStateBlob),
|
|
@@ -274,7 +306,7 @@ export class HttpSynthIdClient {
|
|
|
274
306
|
throw new SynthIdError('response', 'SynthID verification token generation failed');
|
|
275
307
|
const headers = { Authorization: 'Basic amI5dChNbS0qNjFlczJJVzpyZyRHNUp1QENpV29OJVNS', 'Push-ID': 'feeds/szvztmw263lqqp',
|
|
276
308
|
'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]}`,
|
|
309
|
+
const start = await request(UPLOAD, { method: 'POST', body: `file_name ${mime.startsWith('video/') ? 'video' : 'image'}.${EXTENSIONS[mime]}`,
|
|
278
310
|
headers: { ...headers, 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': String(image.data.byteLength) } }, 'start');
|
|
279
311
|
let uploadUrl;
|
|
280
312
|
try {
|
|
@@ -290,12 +322,16 @@ export class HttpSynthIdClient {
|
|
|
290
322
|
headers: { ...headers, 'X-Goog-Upload-Command': 'upload, finalize', 'X-Goog-Upload-Offset': '0' } }, 'upload, finalize');
|
|
291
323
|
if (uploaded.headers.get('x-goog-upload-status') !== 'final' || (await uploaded.text()).trim() !== blobref)
|
|
292
324
|
throw new SynthIdError('response', 'SynthID upload did not finalize at the generated path');
|
|
325
|
+
const video = mime.startsWith('video/');
|
|
293
326
|
const endpoint = new URL('/_/WatermarkApp/data/batchexecute', ORIGIN);
|
|
294
327
|
if (typeof session.config.cfb2h !== 'string' || !session.config.cfb2h || typeof session.config.FdrFJe !== 'string' || !session.config.FdrFJe)
|
|
295
328
|
throw new SynthIdError('response', 'SynthID page metadata is incomplete');
|
|
296
|
-
endpoint.search = new URLSearchParams({ rpcids:
|
|
329
|
+
endpoint.search = new URLSearchParams({ rpcids: RPC_ID, 'source-path': video ? '/video-detection' : '/image-detection', bl: session.config.cfb2h,
|
|
297
330
|
'f.sid': session.config.FdrFJe, hl: session.config.hl || 'en-US', _reqid: session.nextRequestId(), rt: 'c' }).toString();
|
|
298
|
-
const
|
|
331
|
+
const requestPayload = video
|
|
332
|
+
? [[null, [[[mime, null, null, null, null, null, blobref]]], 0, null, null, null, VIDEO_DEFAULT_FPS]]
|
|
333
|
+
: [[null, [[[mime, null, null, null, null, null, blobref]]], 0]];
|
|
334
|
+
const form = entry.attachWebXsrf(new URLSearchParams({ 'f.req': JSON.stringify([[[RPC_ID, JSON.stringify(requestPayload), null, 'generic']]]) }), session.config);
|
|
299
335
|
const response = await session.request(endpoint.href, { method: 'POST', body: form.toString() + '&', headers: {
|
|
300
336
|
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'X-Same-Domain': '1',
|
|
301
337
|
'X-Goog-Ext-525006476-Jspb': JSON.stringify([auth.idToken, null, null, null, null, generated.bgToken]),
|
package/lib/synthid-manual.js
CHANGED
|
@@ -24,7 +24,7 @@ function manualError(error) {
|
|
|
24
24
|
const ORIGIN = 'https://synthid.com';
|
|
25
25
|
const UPLOAD = 'https://content-push.googleapis.com/upload/';
|
|
26
26
|
const TOKEN = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyCjADz3UffE3DF5HZ--7MgVEXrbt6Bgcck';
|
|
27
|
-
const DETECT = ORIGIN + '/_/WatermarkApp/data/batchexecute?rpcids=
|
|
27
|
+
const DETECT = ORIGIN + '/_/WatermarkApp/data/batchexecute?rpcids=vZ4jac&source-path=%2Fimage-detection&hl=en-US&rt=c';
|
|
28
28
|
const DROPZONE = '/synthid-demo-drop-zone/ttl_1d/';
|
|
29
29
|
const WEB_HEADERS = {
|
|
30
30
|
Origin: ORIGIN,
|
|
@@ -207,9 +207,9 @@ export class ManualSynthIdClient {
|
|
|
207
207
|
const blob = await this.upload(image, mime, auth);
|
|
208
208
|
try {
|
|
209
209
|
const media = [mime, null, null, null, null, null, blob];
|
|
210
|
-
const request = JSON.stringify([null, [[media]], 0]);
|
|
210
|
+
const request = JSON.stringify([[null, [[media]], 0]]);
|
|
211
211
|
const result = await this.post(DETECT, {
|
|
212
|
-
body: new URLSearchParams({ 'f.req': JSON.stringify([[['
|
|
212
|
+
body: new URLSearchParams({ 'f.req': JSON.stringify([[['vZ4jac', request, null, 'generic']]]) }),
|
|
213
213
|
headers: {
|
|
214
214
|
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
|
|
215
215
|
'X-Same-Domain': '1',
|
|
@@ -271,7 +271,8 @@ export class ManualSynthIdClient {
|
|
|
271
271
|
const kind = status === 429 ? 'rate-limit'
|
|
272
272
|
: status === 403 ? 'permission'
|
|
273
273
|
: status === 401 || status === 400 && stage === 'auth' ? 'auth'
|
|
274
|
-
: status
|
|
274
|
+
: status === 400 && stage === 'detect' ? 'response'
|
|
275
|
+
: status >= 500 ? 'server' : 'request';
|
|
275
276
|
throw new ManualSynthIdError(kind, `SynthID ${stage} returned HTTP ${status}`, stage === 'detect' && status === 401 ? 16 : status, status === 429 ? retryAfter(response.headers.get('retry-after')) : undefined);
|
|
276
277
|
}
|
|
277
278
|
return { headers: response.headers, text: await response.text() };
|
package/lib/synthid-result.js
CHANGED
|
@@ -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;
|
|
@@ -91,7 +106,7 @@ export function parseSynthIdResponse(text) {
|
|
|
91
106
|
// after our complete RPC frame so a footer cannot mask a real auth result.
|
|
92
107
|
let frame;
|
|
93
108
|
for (const value of frames(text)) {
|
|
94
|
-
if (Array.isArray(value) && value[0] === 'wrb.fr' && value[1] === '
|
|
109
|
+
if (Array.isArray(value) && value[0] === 'wrb.fr' && value[1] === 'vZ4jac') {
|
|
95
110
|
frame = value;
|
|
96
111
|
break;
|
|
97
112
|
}
|
|
@@ -109,7 +124,10 @@ export function parseSynthIdResponse(text) {
|
|
|
109
124
|
}
|
|
110
125
|
if (typeof frame[2] !== 'string')
|
|
111
126
|
return invalid();
|
|
112
|
-
const
|
|
127
|
+
const outer = json(frame[2]);
|
|
128
|
+
if (!Array.isArray(outer))
|
|
129
|
+
return invalid();
|
|
130
|
+
const payload = outer[0];
|
|
113
131
|
if (!Array.isArray(payload))
|
|
114
132
|
return invalid();
|
|
115
133
|
if (Array.isArray(payload[6]) && payload[6].length) {
|
|
@@ -140,24 +158,28 @@ export function parseSynthIdResponse(text) {
|
|
|
140
158
|
default: return invalid();
|
|
141
159
|
}
|
|
142
160
|
}
|
|
143
|
-
|
|
161
|
+
/** `noun`: what was checked, 图片 or 视频 */
|
|
162
|
+
export function formatSynthId(result, noun = '图片') {
|
|
144
163
|
if (result.status === 'not_detected')
|
|
145
164
|
return '没有找到 AI 特征,但不能完全确认不是 AI。';
|
|
146
165
|
if (result.status === 'uncertain') {
|
|
147
166
|
const reasons = {
|
|
148
|
-
1:
|
|
149
|
-
2:
|
|
150
|
-
3:
|
|
151
|
-
|
|
152
|
-
|
|
167
|
+
1: `${noun}为空`,
|
|
168
|
+
2: `${noun}分辨率过低`,
|
|
169
|
+
3: `${noun}细节不足`,
|
|
170
|
+
4: `${noun}帧率过低`,
|
|
171
|
+
5: `${noun}质量过低`,
|
|
172
|
+
6: `${noun}可能经过修改,或只在局部使用了 AI`,
|
|
173
|
+
7: `${noun}时长过长`,
|
|
153
174
|
};
|
|
154
175
|
return `无法判断是否为 AI 生成:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`;
|
|
155
176
|
}
|
|
156
|
-
const sources = { google: 'Google',
|
|
177
|
+
const sources = { apple: 'Apple', google: 'Google', heygen: 'HeyGen', kakao: 'Kakao', nvidia: 'NVIDIA', openai: 'OpenAI' };
|
|
157
178
|
const source = result.source && (Object.hasOwn(sources, result.source.toLowerCase()) ? sources[result.source.toLowerCase()] : result.source);
|
|
158
|
-
return
|
|
179
|
+
return `${noun}是 ${source || 'AI'} 生成`;
|
|
159
180
|
}
|
|
160
|
-
|
|
181
|
+
/** `during`: login, from the WebUI's login window, or a detection */
|
|
182
|
+
export function describeSynthIdFailure(error, noun = '图片', during = 'detect') {
|
|
161
183
|
switch (error.kind) {
|
|
162
184
|
case 'runtime': return '检测运行环境不可用,当前需要 Node.js 24 或以上版本。';
|
|
163
185
|
case 'config':
|
|
@@ -176,12 +198,20 @@ export function describeSynthIdFailure(error) {
|
|
|
176
198
|
ECONNRESET: '连接被重置(ECONNRESET)', ECONNREFUSED: '连接被拒绝(ECONNREFUSED)',
|
|
177
199
|
ENOTFOUND: '域名解析失败(ENOTFOUND)', EAI_AGAIN: '域名解析暂时失败(EAI_AGAIN)', ETIMEDOUT: '连接超时(ETIMEDOUT)',
|
|
178
200
|
};
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
201
|
+
const reason = error.networkCode && reasons[error.networkCode];
|
|
202
|
+
if (during === 'login') {
|
|
203
|
+
return reason
|
|
204
|
+
? `登录页加载失败:${reason}。请检查 Bot「代理」插件设置,确认当前代理可正常连接检测服务后重试。`
|
|
205
|
+
: '连不上检测服务,请检查网络或代理设置。';
|
|
206
|
+
}
|
|
207
|
+
return reason
|
|
208
|
+
? `连不上检测服务:${reason},已重试一次。请检查网络或 Bot「代理」插件设置。`
|
|
209
|
+
: '连不上检测服务,已重试一次。请检查网络或代理设置。';
|
|
182
210
|
}
|
|
183
|
-
case 'timeout': return '
|
|
184
|
-
|
|
211
|
+
case 'timeout': return during === 'login'
|
|
212
|
+
? '连不上检测服务,请检查网络或代理设置。'
|
|
213
|
+
: `${noun}检测超时:网络或代理较慢时,可在插件设置里调大「检测超时」。`;
|
|
214
|
+
case 'request': return noun === '视频' ? '无法处理这个视频:只支持 MP4、MOV、WebM,且不超过 100 MB。' : '无法处理这张图片,请尝试发送原图。';
|
|
185
215
|
case 'response': return '检测服务返回了无法识别的结果,检测接口可能已变更。';
|
|
186
216
|
case 'cancelled': return '检测已取消。';
|
|
187
217
|
default: return '检测失败,请稍后再试。';
|
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
|
-
|
|
442
|
-
|
|
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')
|