@luckylillia-dev/plugin-aiimgdetector 0.0.0-placeholder → 1.0.4

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.
Files changed (99) hide show
  1. package/README.md +2 -2
  2. package/assets/demo.png +0 -0
  3. package/assets/icon.svg +15 -0
  4. package/assets/synthid-login-check.jpg +0 -0
  5. package/docs/details.md +45 -0
  6. package/docs/publishing.md +66 -0
  7. package/docs/synthid.md +80 -0
  8. package/lib/image.js +90 -0
  9. package/lib/index.js +207 -0
  10. package/lib/provenance.js +21 -0
  11. package/lib/synthid-auth.js +100 -0
  12. package/lib/synthid-browser.js +451 -0
  13. package/lib/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
  14. package/lib/synthid-http-runtime/complete-protocol.mjs +88 -0
  15. package/lib/synthid-http-runtime/entry.d.mts +41 -0
  16. package/lib/synthid-http-runtime/entry.mjs +6 -0
  17. package/lib/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
  18. package/lib/synthid-http-runtime/independent-request-reference.mjs +49 -0
  19. package/lib/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
  20. package/lib/synthid-http-runtime/lifecycle-client.mjs +165 -0
  21. package/lib/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
  22. package/lib/synthid-http-runtime/lifecycle-worker.mjs +363 -0
  23. package/lib/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
  24. package/lib/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
  25. package/lib/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
  26. package/lib/synthid-http-runtime/realm-init.js +34 -0
  27. package/lib/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
  28. package/lib/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
  29. package/lib/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
  30. package/lib/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
  31. package/lib/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
  32. package/lib/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
  33. package/lib/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
  34. package/lib/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
  35. package/lib/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
  36. package/lib/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
  37. package/lib/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
  38. package/lib/synthid-http-runtime/runtime-web-compat.mjs +639 -0
  39. package/lib/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
  40. package/lib/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
  41. package/lib/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
  42. package/lib/synthid-http-runtime/scripting-parser.mjs +13 -0
  43. package/lib/synthid-http-runtime/web-session.mjs +64 -0
  44. package/lib/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
  45. package/lib/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
  46. package/lib/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
  47. package/lib/synthid-http.js +314 -0
  48. package/lib/synthid-manual.js +365 -0
  49. package/lib/synthid-page.js +101 -0
  50. package/lib/synthid-result.js +189 -0
  51. package/lib/synthid.js +540 -0
  52. package/lib/vision.js +41 -0
  53. package/package.json +77 -4
  54. package/src/image.ts +74 -0
  55. package/src/index.ts +203 -0
  56. package/src/provenance.ts +40 -0
  57. package/src/synthid-auth.ts +83 -0
  58. package/src/synthid-browser.ts +426 -0
  59. package/src/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
  60. package/src/synthid-http-runtime/complete-protocol.mjs +88 -0
  61. package/src/synthid-http-runtime/entry.d.mts +41 -0
  62. package/src/synthid-http-runtime/entry.mjs +6 -0
  63. package/src/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
  64. package/src/synthid-http-runtime/independent-request-reference.mjs +49 -0
  65. package/src/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
  66. package/src/synthid-http-runtime/lifecycle-client.mjs +165 -0
  67. package/src/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
  68. package/src/synthid-http-runtime/lifecycle-worker.mjs +363 -0
  69. package/src/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
  70. package/src/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
  71. package/src/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
  72. package/src/synthid-http-runtime/realm-init.js +34 -0
  73. package/src/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
  74. package/src/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
  75. package/src/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
  76. package/src/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
  77. package/src/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
  78. package/src/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
  79. package/src/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
  80. package/src/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
  81. package/src/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
  82. package/src/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
  83. package/src/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
  84. package/src/synthid-http-runtime/runtime-web-compat.mjs +639 -0
  85. package/src/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
  86. package/src/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
  87. package/src/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
  88. package/src/synthid-http-runtime/scripting-parser.mjs +13 -0
  89. package/src/synthid-http-runtime/web-session.mjs +64 -0
  90. package/src/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
  91. package/src/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
  92. package/src/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
  93. package/src/synthid-http.ts +290 -0
  94. package/src/synthid-manual.ts +388 -0
  95. package/src/synthid-page.ts +103 -0
  96. package/src/synthid-result.ts +177 -0
  97. package/src/synthid.ts +514 -0
  98. package/src/vision.ts +57 -0
  99. package/webui/index.js +279 -0
package/lib/synthid.js ADDED
@@ -0,0 +1,540 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { launchSynthIdBrowser } from './synthid-browser.js';
6
+ import { HttpSynthIdClient } from './synthid-http.js';
7
+ import { describeSynthIdFailure, SynthIdError } from './synthid-result.js';
8
+ // All entries in one instance share a profile and queue. The last owner closes
9
+ // the browser and removes this entry, including during plugin reload.
10
+ const sessions = new Map();
11
+ const supported = /^image\/(?:jpeg|png|webp|gif|bmp|avif|heic|heif|tiff)$/;
12
+ const cancelled = () => new SynthIdError('cancelled', 'SynthID operation was cancelled');
13
+ class ManagedSession {
14
+ root;
15
+ owners = new Set();
16
+ ready;
17
+ profile;
18
+ stateFile;
19
+ state = { state: 'logged-out' };
20
+ captured;
21
+ // A failed initialization is not evidence that the recognized account logged out.
22
+ // Keep only a sanitized, transient error; never persist it or return failed credentials.
23
+ initializationFailure;
24
+ browser;
25
+ browserProxy;
26
+ launch;
27
+ browserAbort;
28
+ loginTask;
29
+ loginAbort;
30
+ tail = Promise.resolve();
31
+ controls = Promise.resolve();
32
+ pending = 0;
33
+ retryAt = 0;
34
+ epoch = 0;
35
+ closing;
36
+ constructor(root) {
37
+ this.root = root;
38
+ this.profile = join(root, 'browser');
39
+ this.stateFile = join(root, 'account.json');
40
+ this.ready = this.restore();
41
+ }
42
+ async restore() {
43
+ await mkdir(this.root, { recursive: true, mode: 0o700 });
44
+ try {
45
+ const saved = JSON.parse(await readFile(this.stateFile, 'utf8'));
46
+ if (saved?.loggedIn === true && typeof saved.account === 'string') {
47
+ this.state = { state: 'ready', account: saved.account, message: '已保存登录状态' };
48
+ if (typeof saved.captured?.revision === 'string' && validCredentials(saved.captured.credentials)) {
49
+ this.captured = saved.captured;
50
+ this.state.credentialRevision = this.captured.revision;
51
+ }
52
+ }
53
+ }
54
+ catch {
55
+ this.state = { state: 'logged-out' };
56
+ }
57
+ }
58
+ status() { return { ...this.state }; }
59
+ credentials(revision) {
60
+ if (this.state.state !== 'ready' || !this.captured || this.captured.revision !== revision) {
61
+ throw new SynthIdError('auth', 'SynthID captured credentials are no longer available');
62
+ }
63
+ return { revision, credentials: { ...this.captured.credentials } };
64
+ }
65
+ control(action) {
66
+ const task = this.controls.then(() => {
67
+ if (this.closing)
68
+ throw cancelled();
69
+ return action();
70
+ });
71
+ this.controls = task.then(() => { }, () => { });
72
+ return task;
73
+ }
74
+ async save(account, captured) {
75
+ await this.writeState({ loggedIn: true, account, captured });
76
+ }
77
+ async writeState(value) {
78
+ const temporary = this.stateFile + '.' + randomUUID() + '.tmp';
79
+ try {
80
+ // Keep the captured form values private, alongside our isolated browser profile.
81
+ await writeFile(temporary, JSON.stringify(value), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
82
+ await rename(temporary, this.stateFile);
83
+ }
84
+ finally {
85
+ await unlink(temporary).catch(() => { });
86
+ }
87
+ }
88
+ async forget() {
89
+ this.state = { state: 'logged-out' };
90
+ this.captured = undefined;
91
+ this.initializationFailure = undefined;
92
+ await unlink(this.stateFile).catch(error => { if (error.code !== 'ENOENT')
93
+ throw error; });
94
+ }
95
+ async open(headed, timeout) {
96
+ const owner = [...this.owners].find(owner => !owner.disposed);
97
+ if (!owner)
98
+ throw cancelled();
99
+ let proxy;
100
+ try {
101
+ proxy = typeof owner.http.proxy === 'function' ? owner.http.proxy('https://synthid.com') : undefined;
102
+ }
103
+ catch {
104
+ throw new SynthIdError('proxy', 'SynthID proxy settings could not be resolved');
105
+ }
106
+ if (this.browser && !this.browser.isClosed()) {
107
+ if (proxy === this.browserProxy)
108
+ return this.browser;
109
+ await this.closeBrowser();
110
+ }
111
+ if (!this.launch) {
112
+ // Use a live owner for every request even if the first entry was disposed.
113
+ const http = { fetch: (...args) => {
114
+ const owner = [...this.owners].find(owner => !owner.disposed);
115
+ if (!owner)
116
+ return Promise.reject(cancelled());
117
+ return owner.http.fetch(...args);
118
+ }, ...(proxy === undefined ? {} : { proxy: () => proxy }) };
119
+ this.browserProxy = proxy;
120
+ this.browserAbort = new AbortController();
121
+ this.launch = launchSynthIdBrowser({ profileDir: this.profile, headed, timeout, http, signal: this.browserAbort.signal })
122
+ .then(browser => { this.browser = browser; return browser; })
123
+ .finally(() => { this.launch = undefined; });
124
+ }
125
+ return this.launch;
126
+ }
127
+ async closeBrowser(expected) {
128
+ if (expected && expected !== this.browser) {
129
+ await expected.close();
130
+ return;
131
+ }
132
+ this.browserAbort?.abort();
133
+ const browser = this.browser ?? await this.launch?.catch(() => undefined);
134
+ this.browser = undefined;
135
+ if (browser)
136
+ await browser.close();
137
+ }
138
+ async login(timeout) {
139
+ await this.ready;
140
+ if (this.closing)
141
+ throw cancelled();
142
+ if (this.pending)
143
+ throw new SynthIdError('busy', 'SynthID is currently detecting an image');
144
+ if (this.loginTask) {
145
+ await this.browser?.bringToFront();
146
+ return this.status();
147
+ }
148
+ const epoch = ++this.epoch;
149
+ const controller = this.loginAbort = new AbortController();
150
+ let keepBrowser = false;
151
+ this.initializationFailure = undefined;
152
+ this.state = { state: 'opening', message: '正在 Bot 所在电脑打开登录窗口…' };
153
+ this.loginTask = (async () => {
154
+ await this.closeBrowser();
155
+ if (controller.signal.aborted)
156
+ return;
157
+ const browser = await this.open(true, timeout);
158
+ if (controller.signal.aborted)
159
+ return;
160
+ this.state = { state: 'awaiting-login', message: '请在打开的窗口中登录 Google,并完成 SynthID 页面上的首次使用提示。' };
161
+ const deadline = Date.now() + 10 * 60_000;
162
+ while (!controller.signal.aborted && Date.now() < deadline) {
163
+ if (browser.isClosed()) {
164
+ await this.forget();
165
+ return;
166
+ }
167
+ const info = await browser.account();
168
+ if (controller.signal.aborted || epoch !== this.epoch)
169
+ return;
170
+ if (info.loggedIn && info.accepted) {
171
+ const account = info.email || 'Google 账号';
172
+ this.state = { state: 'capturing', account, message: '已登录,正在保存登录凭据…' };
173
+ const credentials = await browser.captureCredentials(Math.max(timeout, 60_000));
174
+ if (controller.signal.aborted || epoch !== this.epoch)
175
+ return;
176
+ if (!validCredentials(credentials))
177
+ throw new SynthIdError('response', 'SynthID returned incomplete credentials');
178
+ const captured = { revision: randomUUID(), credentials };
179
+ await this.save(account, captured);
180
+ if (controller.signal.aborted || epoch !== this.epoch) {
181
+ await this.forget();
182
+ return;
183
+ }
184
+ this.captured = captured;
185
+ this.initializationFailure = undefined;
186
+ this.state = { state: 'ready', account, credentialRevision: captured.revision, message: '登录成功,已获取检测凭证。' };
187
+ return;
188
+ }
189
+ await delay(1000, undefined, { signal: controller.signal });
190
+ }
191
+ if (!controller.signal.aborted) {
192
+ this.initializationFailure = new SynthIdError('timeout', 'SynthID login initialization timed out');
193
+ this.state = { state: 'error', message: '登录等待已超时,请重新点击登录。' };
194
+ }
195
+ })().catch(error => {
196
+ if (!controller.signal.aborted && epoch === this.epoch) {
197
+ const failure = safeInitializationError(error);
198
+ this.initializationFailure = failure?.kind === 'cancelled' ? undefined : failure;
199
+ const account = this.state.state === 'capturing' ? this.state.account : undefined;
200
+ // Preserve the signed-in window for inspection. A retry is explicit and
201
+ // starts a fresh browser operation; never ask the user to supply a test image.
202
+ keepBrowser = !!account && !!this.browser && !this.browser.isClosed();
203
+ const message = account && error instanceof SynthIdError && error.kind === 'verification'
204
+ ? '网站校验未通过,稍后可点击「重新获取凭证」。'
205
+ : account && error instanceof SynthIdError && error.kind === 'timeout'
206
+ ? '自动获取超时,可点击「重新获取凭证」再试。'
207
+ : account && error instanceof SynthIdError && error.kind === 'cancelled'
208
+ ? '浏览器已关闭,可点击「重新获取凭证」再试。' : safeError(failure ?? error);
209
+ this.state = { state: 'error', ...(account ? { account } : {}),
210
+ message: (account ? '已登录,但自动获取检测凭证失败。' : '') + message };
211
+ }
212
+ }).finally(async () => {
213
+ if (!keepBrowser || controller.signal.aborted)
214
+ await this.closeBrowser().catch(() => { });
215
+ if (epoch === this.epoch) {
216
+ this.loginTask = undefined;
217
+ this.loginAbort = undefined;
218
+ }
219
+ });
220
+ return this.status();
221
+ }
222
+ async cancel() {
223
+ this.initializationFailure = undefined;
224
+ if (this.loginTask) {
225
+ this.epoch++;
226
+ this.loginAbort?.abort();
227
+ await this.closeBrowser();
228
+ await this.loginTask;
229
+ this.loginTask = undefined;
230
+ this.loginAbort = undefined;
231
+ await this.forget();
232
+ }
233
+ else if (this.state.state === 'error') {
234
+ await this.closeBrowser();
235
+ await this.forget();
236
+ }
237
+ return this.status();
238
+ }
239
+ async logout() {
240
+ if (this.pending)
241
+ throw new SynthIdError('busy', 'SynthID is currently detecting an image');
242
+ await this.cancel();
243
+ await this.closeBrowser();
244
+ // Resolve and check our own profile before recursive deletion.
245
+ const root = await realpath(this.root);
246
+ const profile = await realpath(this.profile).catch(error => {
247
+ if (error.code === 'ENOENT')
248
+ return undefined;
249
+ throw error;
250
+ });
251
+ if (profile) {
252
+ if (dirname(resolve(profile)) !== resolve(root) || resolve(profile) !== resolve(root, 'browser')) {
253
+ throw new SynthIdError('config', 'SynthID profile is outside its storage directory');
254
+ }
255
+ await rm(profile, { recursive: true, force: true });
256
+ }
257
+ await this.forget();
258
+ this.retryAt = 0;
259
+ return this.status();
260
+ }
261
+ async detect(image, signal, resolveClient) {
262
+ await this.ready;
263
+ await this.controls;
264
+ if (signal.aborted || this.closing)
265
+ throw cancelled();
266
+ // Detection is browser-free: a fresh challenge, an in-process interpreter
267
+ // run and a per-request verification token, all over plain HTTP.
268
+ if (this.loginTask)
269
+ throw new SynthIdError('busy', 'SynthID login is in progress');
270
+ const http = await resolveClient(this.captured?.credentials);
271
+ if (this.pending >= 4)
272
+ throw new SynthIdError('busy', 'SynthID account queue is full');
273
+ this.pending++;
274
+ let started = false;
275
+ let released = false;
276
+ const release = () => {
277
+ if (!released) {
278
+ released = true;
279
+ this.pending--;
280
+ }
281
+ };
282
+ let queuedImage = image;
283
+ const task = this.tail.then(async () => {
284
+ if (signal.aborted || this.closing)
285
+ throw cancelled();
286
+ started = true;
287
+ const input = queuedImage;
288
+ queuedImage = undefined;
289
+ if (this.retryAt > Date.now())
290
+ throw new SynthIdError('rate-limit', 'SynthID account is cooling down', undefined, Math.ceil((this.retryAt - Date.now()) / 1000));
291
+ const result = await http.detect(input, signal);
292
+ if (signal.aborted)
293
+ throw cancelled();
294
+ if (result.status === 'quota_exceeded')
295
+ this.retryAt = Date.now() + (result.retryAfterSeconds || 60) * 1000;
296
+ return result;
297
+ });
298
+ this.tail = task.then(release, release);
299
+ let onCancel;
300
+ const cancellation = new Promise((_, reject) => {
301
+ onCancel = () => { queuedImage = undefined; reject(cancelled()); };
302
+ signal.addEventListener('abort', onCancel, { once: true });
303
+ if (signal.aborted)
304
+ onCancel();
305
+ });
306
+ try {
307
+ return await Promise.race([task, cancellation]);
308
+ }
309
+ finally {
310
+ signal.removeEventListener('abort', onCancel);
311
+ queuedImage = undefined;
312
+ if (!started)
313
+ release();
314
+ }
315
+ }
316
+ close() {
317
+ this.closing ??= (async () => {
318
+ this.initializationFailure = undefined;
319
+ this.epoch++;
320
+ this.loginAbort?.abort();
321
+ await this.closeBrowser();
322
+ await this.controls;
323
+ await this.loginTask;
324
+ await this.tail;
325
+ })();
326
+ return this.closing;
327
+ }
328
+ }
329
+ export class SynthIdClient {
330
+ ctx;
331
+ http;
332
+ abort = new AbortController();
333
+ current;
334
+ configurations = new Set();
335
+ loadRuntime;
336
+ manager;
337
+ closing;
338
+ get disposed() { return this.abort.signal.aborted; }
339
+ constructor(ctx, config, options = {}) {
340
+ this.ctx = ctx;
341
+ this.http = ctx.http;
342
+ this.loadRuntime = options.loadRuntime;
343
+ this.update(config);
344
+ ctx.effect(() => () => this.dispose());
345
+ }
346
+ update(config) {
347
+ if (this.disposed)
348
+ throw cancelled();
349
+ const previous = this.current;
350
+ // Only the login credential drives detection; a refresh token alone is enough.
351
+ const refreshToken = config.credentials && typeof config.credentials.refreshToken === 'string' && config.credentials.refreshToken.trim()
352
+ ? config.credentials.refreshToken.trim() : '';
353
+ if (previous && previous.timeout === config.timeout && previous.credentials?.refreshToken?.trim() === refreshToken)
354
+ return;
355
+ const credentials = refreshToken ? { refreshToken } : undefined;
356
+ const next = { timeout: config.timeout, credentials, users: 0 };
357
+ if (refreshToken) {
358
+ // Each generation owns its effects; disposing it also disposes the
359
+ // browser-free HTTP client and its in-flight generation workers.
360
+ this.createHttp(next, refreshToken);
361
+ }
362
+ this.current = next;
363
+ this.configurations.add(next);
364
+ if (previous)
365
+ void this.retire(previous);
366
+ }
367
+ createHttp(settings, refreshToken) {
368
+ settings.scope = this.ctx.plugin({ inject: ['http'], apply: (ctx) => {
369
+ settings.http = new HttpSynthIdClient(ctx, { refreshToken, timeout: settings.timeout, ...(this.loadRuntime ? { loadRuntime: this.loadRuntime } : {}) });
370
+ } });
371
+ }
372
+ retire(settings) {
373
+ if (!this.disposed && (settings === this.current || settings.users))
374
+ return Promise.resolve();
375
+ settings.closing ??= (async () => {
376
+ try {
377
+ await settings.scope?.dispose();
378
+ }
379
+ catch {
380
+ this.ctx.logger('aiimgdetector').warn('Could not dispose retired SynthID credential resources');
381
+ }
382
+ finally {
383
+ this.configurations.delete(settings);
384
+ settings.credentials = undefined;
385
+ settings.http = undefined;
386
+ settings.scope = undefined;
387
+ }
388
+ })();
389
+ return settings.closing;
390
+ }
391
+ async session() {
392
+ if (this.disposed)
393
+ throw cancelled();
394
+ this.manager ??= (async () => {
395
+ const root = resolve(await this.ctx.storage.dir(), 'synthid-session');
396
+ let session = sessions.get(root);
397
+ while (session?.closing) {
398
+ await session.closing;
399
+ if (sessions.get(root) === session)
400
+ sessions.delete(root);
401
+ session = sessions.get(root);
402
+ }
403
+ if (this.disposed)
404
+ throw cancelled();
405
+ if (!session) {
406
+ session = new ManagedSession(root);
407
+ sessions.set(root, session);
408
+ }
409
+ session.owners.add(this);
410
+ try {
411
+ await session.ready;
412
+ }
413
+ catch (error) {
414
+ session.owners.delete(this);
415
+ if (!session.owners.size && sessions.get(root) === session)
416
+ sessions.delete(root);
417
+ throw error;
418
+ }
419
+ return session;
420
+ })();
421
+ return this.manager;
422
+ }
423
+ async status() { return (await this.session()).status(); }
424
+ async credentials(revision) { return (await this.session()).credentials(revision); }
425
+ async login() { return this.control('login'); }
426
+ async cancel() { return this.control('cancel'); }
427
+ async logout() { return this.control('logout'); }
428
+ async control(action) {
429
+ const timeout = this.current.timeout;
430
+ const session = await this.session();
431
+ return session.control(() => {
432
+ if (this.disposed)
433
+ throw cancelled();
434
+ return action === 'login' ? session.login(timeout) : session[action]();
435
+ });
436
+ }
437
+ async detect(image) {
438
+ if (this.disposed)
439
+ throw cancelled();
440
+ 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');
443
+ }
444
+ // Snapshot before either context initialization or the shared queue waits.
445
+ // An update affects only subsequent requests, including credential identity.
446
+ const settings = this.current;
447
+ let fallback;
448
+ settings.users++;
449
+ try {
450
+ await settings.scope;
451
+ if (this.disposed)
452
+ throw cancelled();
453
+ return await (await this.session()).detect({ ...image, type: mime }, this.abort.signal, async (saved) => {
454
+ if (!settings.http) {
455
+ if (!saved?.refreshToken)
456
+ throw new SynthIdError('auth', 'SynthID needs a login credential (refresh_token)');
457
+ fallback = { timeout: settings.timeout, users: 1 };
458
+ this.configurations.add(fallback);
459
+ this.createHttp(fallback, saved.refreshToken);
460
+ await fallback.scope;
461
+ return fallback.http;
462
+ }
463
+ return settings.http;
464
+ });
465
+ }
466
+ finally {
467
+ if (fallback) {
468
+ fallback.users--;
469
+ await this.retire(fallback);
470
+ }
471
+ settings.users--;
472
+ await this.retire(settings);
473
+ }
474
+ }
475
+ dispose() {
476
+ this.abort.abort();
477
+ this.closing ??= (async () => {
478
+ await Promise.all([...this.configurations].map(settings => this.retire(settings)));
479
+ const session = await this.manager?.catch(() => undefined);
480
+ if (!session)
481
+ return;
482
+ session.owners.delete(this);
483
+ if (!session.owners.size) {
484
+ try {
485
+ await session.close();
486
+ }
487
+ finally {
488
+ if (sessions.get(session.root) === session)
489
+ sessions.delete(session.root);
490
+ }
491
+ }
492
+ })();
493
+ return this.closing;
494
+ }
495
+ }
496
+ function safeInitializationError(error) {
497
+ if (!(error instanceof SynthIdError))
498
+ return;
499
+ return new SynthIdError(error.kind, 'SynthID login initialization failed', typeof error.code === 'number' && Number.isFinite(error.code) ? error.code : undefined, typeof error.retryAfterSeconds === 'number' && Number.isFinite(error.retryAfterSeconds) && error.retryAfterSeconds >= 0
500
+ ? error.retryAfterSeconds : undefined, error.networkCode && ['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT'].includes(error.networkCode)
501
+ ? error.networkCode : undefined);
502
+ }
503
+ function safeError(error) {
504
+ return error instanceof SynthIdError ? describeSynthIdFailure(error) : '无法启动或保存 SynthID 登录,请检查浏览器、网络和插件数据目录。';
505
+ }
506
+ function validCredentials(value) {
507
+ if (!value || typeof value !== 'object')
508
+ return false;
509
+ const fields = value;
510
+ return typeof fields.refreshToken === 'string' && /^[\x21-\x7e]+$/.test(fields.refreshToken.trim());
511
+ }
512
+ /** Protected by host WebUI authentication. Status never includes credentials. */
513
+ export async function handleSynthId(client, request) {
514
+ const path = new URL(request.url).pathname;
515
+ const action = path.slice('/api/aiimgdetector/synthid/'.length);
516
+ if (path !== '/api/aiimgdetector/synthid/' + action || !['status', 'login', 'cancel', 'logout', 'credentials'].includes(action)) {
517
+ return Response.json({ success: false, message: 'not found' }, { status: 404 });
518
+ }
519
+ if (request.method !== (action === 'status' ? 'GET' : 'POST')) {
520
+ return Response.json({ success: false, message: 'method not allowed' }, { status: 405 });
521
+ }
522
+ try {
523
+ if (action === 'credentials') {
524
+ const body = await request.json().catch(() => null);
525
+ if (typeof body?.revision !== 'string' || !/^[a-f0-9-]{36}$/.test(body.revision)) {
526
+ return Response.json({ success: false, message: '凭证版本无效,请重新获取登录状态。' }, { status: 400, headers: { 'Cache-Control': 'no-store' } });
527
+ }
528
+ const data = await client.credentials(body.revision);
529
+ return Response.json({ success: true, data }, { headers: { 'Cache-Control': 'no-store' } });
530
+ }
531
+ const data = action === 'status' ? await client.status() : action === 'login' ? await client.login()
532
+ : action === 'cancel' ? await client.cancel() : await client.logout();
533
+ return Response.json({ success: true, data }, { headers: { 'Cache-Control': 'no-store' } });
534
+ }
535
+ catch (error) {
536
+ return Response.json({ success: false, message: safeError(error) }, {
537
+ status: error instanceof SynthIdError && error.kind === 'busy' ? 409 : 503, headers: { 'Cache-Control': 'no-store' },
538
+ });
539
+ }
540
+ }
package/lib/vision.js ADDED
@@ -0,0 +1,41 @@
1
+ const SYSTEM = '你是数字图像取证专家,只输出 JSON,不写任何解释性前后缀。';
2
+ const PROMPT = `判断这张图片是否由 AI 生成(含 AI 绘画和 AI 大幅修图)。
3
+
4
+ 依次检查:手指数量与关节走向;画面内文字 / 招牌 / logo 是否可读;物体边缘与背景的衔接是否有融化或糊成一团;
5
+ 光影方向和反射是否自洽;皮肤 / 材质是否过度平滑或出现重复纹理;透视与结构是否成立;细小配件(首饰 / 眼镜腿 / 栏杆)有没有断续。
6
+
7
+ 只输出如下 JSON:
8
+ {"verdict":"ai|real|unsure","confidence":0-100,"reasons":["中文短句,指出具体位置和现象","最多 3 条"]}
9
+
10
+ 判不准就给 unsure,不要硬猜。`;
11
+ /** Models like to wrap the JSON in a code fence or a greeting: take the first object */
12
+ function parse(text) {
13
+ const match = text.match(/\{[\s\S]*\}/);
14
+ if (!match)
15
+ return;
16
+ try {
17
+ const value = JSON.parse(match[0]);
18
+ const verdict = value.verdict === 'ai' || value.verdict === 'real' ? value.verdict : 'unsure';
19
+ const confidence = Math.max(0, Math.min(100, Number(value.confidence) || 0));
20
+ const reasons = (Array.isArray(value.reasons) ? value.reasons : [])
21
+ .map((reason) => String(reason).trim())
22
+ .filter(Boolean)
23
+ .slice(0, 3);
24
+ return { verdict, confidence, reasons };
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /** A guess from the picture itself, for what carries no watermark; undefined when the model says nothing */
31
+ export async function judgeByVision(ai, options, image) {
32
+ const result = await ai.chat([
33
+ { role: 'system', content: SYSTEM },
34
+ // The image goes as data: QQ image links expire and refuse other sites, so the model could not fetch them
35
+ { role: 'user', content: [{ type: 'text', text: PROMPT }, { type: 'image', data: image.data, mime: image.type }] },
36
+ ], { ai: options.ai, model: options.model || undefined, temperature: 0 });
37
+ const text = result.text.trim();
38
+ if (!text)
39
+ return;
40
+ return { ...parse(text) ?? { verdict: 'unsure', confidence: 0, reasons: [], raw: text.slice(0, 200) }, model: result.model };
41
+ }
package/package.json CHANGED
@@ -1,13 +1,86 @@
1
1
  {
2
2
  "name": "@luckylillia-dev/plugin-aiimgdetector",
3
- "version": "0.0.0-placeholder",
4
- "description": "Placeholder reserving this name for LuckyLillia; real releases are published from GitHub Actions.",
5
- "license": "MIT",
3
+ "version": "1.0.4",
4
+ "description": "Checks AI image provenance through OpenAI, optional SynthID detection, and a vision model",
5
+ "author": "linyuchen",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/linyuchen/lucky-lillia-plugin-aiimgdetector.git"
9
9
  },
10
10
  "publishConfig": {
11
- "access": "public"
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org/"
13
+ },
14
+ "type": "module",
15
+ "main": "lib/index.js",
16
+ "exports": {
17
+ ".": {
18
+ "development": "./src/index.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "lib",
25
+ "webui",
26
+ "src",
27
+ "assets",
28
+ "docs"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc -p . && node scripts/copy-synthid-http-runtime-lib.mjs",
32
+ "dev": "tsc -p . --watch",
33
+ "test": "vitest run",
34
+ "test:runtime": "node scripts/smoke-synthid-runtime.mjs",
35
+ "test:browser": "node test/synthid-browser.mjs && node test/synthid-native-proxy.mjs",
36
+ "prepack": "npm run build"
37
+ },
38
+ "keywords": [
39
+ "luckylillia-plugin"
40
+ ],
41
+ "dependencies": {
42
+ "@contentauth/toolkit": "0.13.14",
43
+ "acorn": "8.15.0",
44
+ "cssstyle": "4.6.0",
45
+ "jsdom": "26.1.0",
46
+ "parse5": "7.3.0",
47
+ "playwright-core": "^1.65.0",
48
+ "tough-cookie": "5.1.2",
49
+ "whatwg-url": "14.2.0"
50
+ },
51
+ "peerDependencies": {
52
+ "@luckylillia-dev/plugin-aiprovider": "^1.0.0",
53
+ "@luckylillia-dev/plugin-sdk": "^1.0.1"
54
+ },
55
+ "devDependencies": {
56
+ "@luckylillia-dev/plugin-aiprovider": "npm:@luckylillia/plugin-aiprovider@^1.0.0",
57
+ "@luckylillia-dev/plugin-sdk": "npm:@luckylillia/plugin-sdk@^1.0.1",
58
+ "@types/node": "^24.12.4",
59
+ "typescript": "^7.0.2",
60
+ "vitest": "^4.1.11"
61
+ },
62
+ "llbot": {
63
+ "webui": "webui/index.js",
64
+ "title": {
65
+ "zh": "AI 图片检测",
66
+ "en": "aiimgdetector"
67
+ },
68
+ "category": "chat",
69
+ "description": "对着图片回复「ai吗」(或者「ai吗」后面直接带图),通过 OpenAI 水印检测、可选的 SynthID 检测和看图模型判断是否由 AI 生成。",
70
+ "icon": "assets/icon.svg",
71
+ "screenshots": [
72
+ "assets/demo.png"
73
+ ],
74
+ "dependencies": {
75
+ "@luckylillia-dev/plugin-aiprovider": "^1.0.0"
76
+ },
77
+ "service": {
78
+ "required": [
79
+ "bots",
80
+ "ai",
81
+ "http",
82
+ "commands"
83
+ ]
84
+ }
12
85
  }
13
86
  }