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