@luckylillia-dev/plugin-aiimgdetector 0.0.0-stage → 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.
- package/README.md +2 -2
- package/assets/demo.png +0 -0
- package/assets/icon.svg +15 -0
- package/assets/synthid-login-check.jpg +0 -0
- package/docs/details.md +45 -0
- package/docs/publishing.md +66 -0
- package/docs/synthid.md +80 -0
- package/lib/image.js +90 -0
- package/lib/index.js +207 -0
- package/lib/provenance.js +21 -0
- package/lib/synthid-auth.js +100 -0
- package/lib/synthid-browser.js +451 -0
- package/lib/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
- package/lib/synthid-http-runtime/complete-protocol.mjs +88 -0
- package/lib/synthid-http-runtime/entry.d.mts +41 -0
- package/lib/synthid-http-runtime/entry.mjs +6 -0
- package/lib/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
- package/lib/synthid-http-runtime/independent-request-reference.mjs +49 -0
- package/lib/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
- package/lib/synthid-http-runtime/lifecycle-client.mjs +165 -0
- package/lib/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
- package/lib/synthid-http-runtime/lifecycle-worker.mjs +363 -0
- package/lib/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
- package/lib/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
- package/lib/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
- package/lib/synthid-http-runtime/realm-init.js +34 -0
- package/lib/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
- package/lib/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
- package/lib/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
- package/lib/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
- package/lib/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
- package/lib/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
- package/lib/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
- package/lib/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
- package/lib/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
- package/lib/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
- package/lib/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
- package/lib/synthid-http-runtime/runtime-web-compat.mjs +639 -0
- package/lib/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
- package/lib/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
- package/lib/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
- package/lib/synthid-http-runtime/scripting-parser.mjs +13 -0
- package/lib/synthid-http-runtime/web-session.mjs +64 -0
- package/lib/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
- package/lib/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
- package/lib/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
- package/lib/synthid-http.js +314 -0
- package/lib/synthid-manual.js +365 -0
- package/lib/synthid-page.js +101 -0
- package/lib/synthid-result.js +189 -0
- package/lib/synthid.js +540 -0
- package/lib/vision.js +41 -0
- package/package.json +84 -4
- package/src/image.ts +74 -0
- package/src/index.ts +203 -0
- package/src/provenance.ts +40 -0
- package/src/synthid-auth.ts +83 -0
- package/src/synthid-browser.ts +426 -0
- package/src/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
- package/src/synthid-http-runtime/complete-protocol.mjs +88 -0
- package/src/synthid-http-runtime/entry.d.mts +41 -0
- package/src/synthid-http-runtime/entry.mjs +6 -0
- package/src/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
- package/src/synthid-http-runtime/independent-request-reference.mjs +49 -0
- package/src/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
- package/src/synthid-http-runtime/lifecycle-client.mjs +165 -0
- package/src/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
- package/src/synthid-http-runtime/lifecycle-worker.mjs +363 -0
- package/src/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
- package/src/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
- package/src/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
- package/src/synthid-http-runtime/realm-init.js +34 -0
- package/src/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
- package/src/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
- package/src/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
- package/src/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
- package/src/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
- package/src/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
- package/src/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
- package/src/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
- package/src/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
- package/src/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
- package/src/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
- package/src/synthid-http-runtime/runtime-web-compat.mjs +639 -0
- package/src/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
- package/src/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
- package/src/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
- package/src/synthid-http-runtime/scripting-parser.mjs +13 -0
- package/src/synthid-http-runtime/web-session.mjs +64 -0
- package/src/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
- package/src/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
- package/src/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
- package/src/synthid-http.ts +290 -0
- package/src/synthid-manual.ts +388 -0
- package/src/synthid-page.ts +103 -0
- package/src/synthid-result.ts +177 -0
- package/src/synthid.ts +514 -0
- package/src/vision.ts +57 -0
- package/webui/index.js +279 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import type { Context } from '@luckylillia-dev/plugin-sdk'
|
|
5
|
+
import type { Image } from './image.js'
|
|
6
|
+
import { describeSynthIdFailure, parseSynthIdResponse, SynthIdError, type SynthIdResult } from './synthid-result.js'
|
|
7
|
+
|
|
8
|
+
export interface ManualSynthIdCredentials {
|
|
9
|
+
refreshToken: string
|
|
10
|
+
pushFilename: string
|
|
11
|
+
bgToken: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SynthIdCredentialIdentity {
|
|
15
|
+
key: string
|
|
16
|
+
userId: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Credential recovery instructions, for typed and browser-filled credentials alike. */
|
|
20
|
+
export class ManualSynthIdError extends SynthIdError {}
|
|
21
|
+
|
|
22
|
+
export function describeManualSynthIdFailure(error: SynthIdError): string {
|
|
23
|
+
switch (error.kind) {
|
|
24
|
+
case 'config': return 'SynthID 凭证不完整、格式错误或账号不一致,请使用浏览器登录自动填写,或按插件设置中的获取说明重新填写。'
|
|
25
|
+
case 'auth': return 'SynthID 登录凭证已失效,请重新登录自动填写,或重新获取登录凭据(refresh_token)。'
|
|
26
|
+
case 'verification': return 'SynthID 未接受本次请求提供的网页校验凭据,请确认上传标识与网页校验凭据来自同一次检测,或在网页完成新检测后一起更新。'
|
|
27
|
+
default: return describeSynthIdFailure(error)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function manualError(error: unknown): ManualSynthIdError {
|
|
32
|
+
if (error instanceof ManualSynthIdError) return error
|
|
33
|
+
if (error instanceof SynthIdError) return new ManualSynthIdError(error.kind, error.message, error.code, error.retryAfterSeconds)
|
|
34
|
+
return new ManualSynthIdError('response', 'SynthID manual detection failed')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Public web-app protocol constants, not an account's credentials. See docs/synthid.md.
|
|
38
|
+
const ORIGIN = 'https://synthid.com'
|
|
39
|
+
const UPLOAD = 'https://content-push.googleapis.com/upload/'
|
|
40
|
+
const TOKEN = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyCjADz3UffE3DF5HZ--7MgVEXrbt6Bgcck'
|
|
41
|
+
const DETECT = ORIGIN + '/_/WatermarkApp/data/batchexecute?rpcids=TZRKo&source-path=%2Fimage-detection&hl=en-US&rt=c'
|
|
42
|
+
const DROPZONE = '/synthid-demo-drop-zone/ttl_1d/'
|
|
43
|
+
const WEB_HEADERS = {
|
|
44
|
+
Origin: ORIGIN,
|
|
45
|
+
Referer: ORIGIN + '/',
|
|
46
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
|
47
|
+
}
|
|
48
|
+
const EXTENSIONS: Record<string, string> = {
|
|
49
|
+
'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif',
|
|
50
|
+
'image/bmp': 'bmp', 'image/avif': 'avif', 'image/heic': 'heic', 'image/heif': 'heif', 'image/tiff': 'tiff',
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface Credentials {
|
|
54
|
+
refreshToken: string
|
|
55
|
+
pushFilename: string
|
|
56
|
+
bgToken: string
|
|
57
|
+
userId: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface Tokens {
|
|
61
|
+
refreshToken: string
|
|
62
|
+
idToken: string
|
|
63
|
+
updatedAt: number
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface Account {
|
|
67
|
+
queue: Job[]
|
|
68
|
+
running: boolean
|
|
69
|
+
retryAt: number
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface Job {
|
|
73
|
+
run?: () => Promise<SynthIdResult>
|
|
74
|
+
resolve: (value: SynthIdResult) => void
|
|
75
|
+
reject: (error: ManualSynthIdError) => void
|
|
76
|
+
detach: () => void
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Shared across plugin entries in this process, because a second upload can replace the first one's blob.
|
|
80
|
+
const accounts = new Map<string, Account>()
|
|
81
|
+
|
|
82
|
+
function credentials(config: ManualSynthIdCredentials): Credentials {
|
|
83
|
+
if (typeof config.refreshToken !== 'string' || typeof config.pushFilename !== 'string' || typeof config.bgToken !== 'string') {
|
|
84
|
+
throw new ManualSynthIdError('config', 'Missing or invalid SynthID manual credentials')
|
|
85
|
+
}
|
|
86
|
+
const refreshToken = config.refreshToken.trim()
|
|
87
|
+
const pushFilename = config.pushFilename.trim().replace(/^\/synthid-demo-drop-zone\/ttl_1d\//, '')
|
|
88
|
+
const userId = /^users\/([A-Za-z0-9_-]+)\/files\/[A-Za-z0-9_-]+$/.exec(pushFilename)?.[1]
|
|
89
|
+
let bgToken = config.bgToken.trim()
|
|
90
|
+
let idToken = ''
|
|
91
|
+
if (bgToken.startsWith('[')) {
|
|
92
|
+
try {
|
|
93
|
+
const header: unknown = JSON.parse(bgToken)
|
|
94
|
+
if (!Array.isArray(header) || typeof header[5] !== 'string' || (header[0] != null && typeof header[0] !== 'string')) throw new Error()
|
|
95
|
+
bgToken = header[5]
|
|
96
|
+
idToken = typeof header[0] === 'string' ? header[0] : ''
|
|
97
|
+
} catch {
|
|
98
|
+
throw new ManualSynthIdError('config', 'Invalid SynthID verification header')
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (!refreshToken || !/^[\x21-\x7e]+$/.test(refreshToken) || !userId || !/^![\x21-\x7e]+$/.test(bgToken)) {
|
|
102
|
+
throw new ManualSynthIdError('config', 'Missing or invalid SynthID manual credentials')
|
|
103
|
+
}
|
|
104
|
+
if (idToken) {
|
|
105
|
+
const value = claims(idToken)
|
|
106
|
+
if ((value.user_id ?? value.sub) !== userId || value.user_id && value.sub && value.user_id !== value.sub) {
|
|
107
|
+
throw new ManualSynthIdError('config', 'SynthID credentials belong to different accounts')
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// A captured JWT is unverified. Only a successful refresh or our own cache supplies the ID token.
|
|
111
|
+
return { refreshToken, pushFilename, bgToken, userId }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Internal source identity only; never include this key in status, logs or WebUI responses. */
|
|
115
|
+
export function synthIdCredentialIdentity(config: ManualSynthIdCredentials): SynthIdCredentialIdentity | undefined {
|
|
116
|
+
try {
|
|
117
|
+
const normalized = credentials(config)
|
|
118
|
+
const key = createHash('sha256').update(JSON.stringify([
|
|
119
|
+
normalized.refreshToken, normalized.pushFilename, normalized.bgToken,
|
|
120
|
+
])).digest('hex')
|
|
121
|
+
return { key, userId: normalized.userId }
|
|
122
|
+
} catch {
|
|
123
|
+
return undefined
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function claims(token: string): Record<string, unknown> {
|
|
128
|
+
try {
|
|
129
|
+
const value: unknown = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'))
|
|
130
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
|
|
131
|
+
} catch {
|
|
132
|
+
return {}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function retryAfter(value: string | null): number {
|
|
137
|
+
if (!value) return 60
|
|
138
|
+
const seconds = /^\d+(?:\.\d+)?$/.test(value) ? Number(value) : (Date.parse(value) - Date.now()) / 1000
|
|
139
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.ceil(seconds) : 60
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function pruneAccount(key: string, account: Account): void {
|
|
143
|
+
if (!account.running && !account.queue.length && account.retryAt <= Date.now() && accounts.get(key) === account) accounts.delete(key)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function drain(key: string, account: Account): void {
|
|
147
|
+
if (account.running) return
|
|
148
|
+
const job = account.queue.shift()
|
|
149
|
+
if (!job) return pruneAccount(key, account)
|
|
150
|
+
const run = job.run!
|
|
151
|
+
job.run = undefined
|
|
152
|
+
job.detach()
|
|
153
|
+
account.running = true
|
|
154
|
+
// Keep the account occupied until the active request has actually stopped, even on cancellation.
|
|
155
|
+
void Promise.resolve().then(run).then(result => {
|
|
156
|
+
if (result.status === 'quota_exceeded') account.retryAt = Date.now() + (result.retryAfterSeconds || 60) * 1000
|
|
157
|
+
job.resolve(result)
|
|
158
|
+
}, error => {
|
|
159
|
+
const failure = manualError(error)
|
|
160
|
+
if (failure.kind === 'rate-limit') account.retryAt = Date.now() + (failure.retryAfterSeconds || 60) * 1000
|
|
161
|
+
job.reject(failure)
|
|
162
|
+
}).finally(() => {
|
|
163
|
+
account.running = false
|
|
164
|
+
drain(key, account)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export class ManualSynthIdClient {
|
|
169
|
+
private readonly abort = new AbortController()
|
|
170
|
+
private readonly active = new Set<Promise<SynthIdResult>>()
|
|
171
|
+
private tokens?: Tokens
|
|
172
|
+
private cachePath?: string
|
|
173
|
+
private readonly logger
|
|
174
|
+
|
|
175
|
+
constructor(private readonly ctx: Context, private readonly config: ManualSynthIdCredentials & { timeout: number }) {
|
|
176
|
+
this.config = { ...config }
|
|
177
|
+
this.logger = ctx.logger('aiimgdetector')
|
|
178
|
+
ctx.effect(() => () => this.dispose())
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async dispose(): Promise<void> {
|
|
182
|
+
this.abort.abort()
|
|
183
|
+
await Promise.allSettled([...this.active])
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
detect(image: Image): Promise<SynthIdResult> {
|
|
187
|
+
try {
|
|
188
|
+
return this.enqueue(image)
|
|
189
|
+
} catch (error) {
|
|
190
|
+
return Promise.reject(manualError(error))
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private enqueue(image: Image): Promise<SynthIdResult> {
|
|
195
|
+
const auth = credentials(this.config)
|
|
196
|
+
const mime = image.type.split(';')[0].trim().toLowerCase()
|
|
197
|
+
if (!Object.hasOwn(EXTENSIONS, mime) || !image.data.byteLength || image.data.byteLength > 20 * 1024 * 1024) {
|
|
198
|
+
throw new ManualSynthIdError('request', 'SynthID needs a supported, non-empty image of at most 20 MB')
|
|
199
|
+
}
|
|
200
|
+
for (const [key, entry] of accounts) pruneAccount(key, entry)
|
|
201
|
+
const account = accounts.get(auth.userId) ?? { queue: [], running: false, retryAt: 0 }
|
|
202
|
+
accounts.set(auth.userId, account)
|
|
203
|
+
this.checkReady(account)
|
|
204
|
+
// Bound the number of images retained while a shared account is busy. Includes the running request.
|
|
205
|
+
if (account.queue.length + Number(account.running) >= 4) throw new ManualSynthIdError('busy', 'SynthID account queue is full')
|
|
206
|
+
const task = new Promise<SynthIdResult>((resolve, reject) => {
|
|
207
|
+
const job: Job = {
|
|
208
|
+
run: () => { this.checkReady(account); return this.detectQueued(image, mime, auth) },
|
|
209
|
+
resolve, reject,
|
|
210
|
+
detach: () => this.abort.signal.removeEventListener('abort', cancel),
|
|
211
|
+
}
|
|
212
|
+
const cancel = () => {
|
|
213
|
+
const index = account.queue.indexOf(job)
|
|
214
|
+
if (index < 0) return
|
|
215
|
+
account.queue.splice(index, 1)
|
|
216
|
+
// Release retained image bytes and the owning client immediately, without waiting for other clients.
|
|
217
|
+
job.run = undefined
|
|
218
|
+
job.detach()
|
|
219
|
+
reject(new ManualSynthIdError('cancelled', 'SynthID client was disposed'))
|
|
220
|
+
pruneAccount(auth.userId, account)
|
|
221
|
+
}
|
|
222
|
+
this.abort.signal.addEventListener('abort', cancel, { once: true })
|
|
223
|
+
account.queue.push(job)
|
|
224
|
+
drain(auth.userId, account)
|
|
225
|
+
})
|
|
226
|
+
this.active.add(task)
|
|
227
|
+
void task.then(() => this.active.delete(task), () => this.active.delete(task))
|
|
228
|
+
return task
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private checkReady(account: Account): void {
|
|
232
|
+
if (this.abort.signal.aborted) throw new ManualSynthIdError('cancelled', 'SynthID client was disposed')
|
|
233
|
+
if (account.retryAt > Date.now()) {
|
|
234
|
+
throw new ManualSynthIdError('rate-limit', 'SynthID account is cooling down', undefined, Math.ceil((account.retryAt - Date.now()) / 1000))
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
private async detectQueued(image: Image, mime: string, auth: Credentials): Promise<SynthIdResult> {
|
|
239
|
+
const tokens = await this.loadTokens(auth)
|
|
240
|
+
await this.refresh(auth, tokens)
|
|
241
|
+
for (let attempt = 0; ; attempt++) {
|
|
242
|
+
const blob = await this.upload(image, mime, auth)
|
|
243
|
+
try {
|
|
244
|
+
const media = [mime, null, null, null, null, null, blob]
|
|
245
|
+
const request = JSON.stringify([null, [[media]], 0])
|
|
246
|
+
const result = await this.post(DETECT, {
|
|
247
|
+
body: new URLSearchParams({ 'f.req': JSON.stringify([[['TZRKo', request, null, 'generic']]]) }),
|
|
248
|
+
headers: {
|
|
249
|
+
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
|
|
250
|
+
'X-Same-Domain': '1',
|
|
251
|
+
'X-Goog-Ext-525006476-Jspb': JSON.stringify([tokens.idToken, null, null, null, null, auth.bgToken]),
|
|
252
|
+
},
|
|
253
|
+
}, 'detect')
|
|
254
|
+
return parseSynthIdResponse(result.text)
|
|
255
|
+
} catch (error) {
|
|
256
|
+
if (!(error instanceof SynthIdError) || error.code !== 16 || attempt > 0) throw error
|
|
257
|
+
// Only retry a rejected login once. Re-upload: a blob may already have been consumed.
|
|
258
|
+
await this.refresh(auth, tokens, true)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private async upload(image: Image, mime: string, auth: Credentials): Promise<string> {
|
|
264
|
+
const headers = {
|
|
265
|
+
Authorization: 'Basic amI5dChNbS0qNjFlczJJVzpyZyRHNUp1QENpV29OJVNS',
|
|
266
|
+
'Push-ID': 'feeds/szvztmw263lqqp',
|
|
267
|
+
'Push-Filename': auth.pushFilename,
|
|
268
|
+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
|
269
|
+
}
|
|
270
|
+
const start = await this.post(UPLOAD, {
|
|
271
|
+
body: `file_name image.${EXTENSIONS[mime]}`,
|
|
272
|
+
headers: { ...headers, 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': String(image.data.byteLength) },
|
|
273
|
+
}, 'upload')
|
|
274
|
+
let uploadUrl: URL
|
|
275
|
+
try {
|
|
276
|
+
uploadUrl = new URL(start.headers.get('x-goog-upload-url') ?? '')
|
|
277
|
+
if (uploadUrl.origin !== 'https://content-push.googleapis.com' || uploadUrl.username || uploadUrl.password
|
|
278
|
+
|| !/^\/upload(?:\/|$)/.test(uploadUrl.pathname)) throw new Error()
|
|
279
|
+
} catch {
|
|
280
|
+
throw new ManualSynthIdError('response', 'SynthID returned an invalid upload URL')
|
|
281
|
+
}
|
|
282
|
+
const uploaded = await this.post(uploadUrl.href, {
|
|
283
|
+
body: image.data,
|
|
284
|
+
headers: { ...headers, 'X-Goog-Upload-Command': 'upload, finalize', 'X-Goog-Upload-Offset': '0' },
|
|
285
|
+
}, 'upload')
|
|
286
|
+
const blob = uploaded.text.trim()
|
|
287
|
+
if (uploaded.headers.get('x-goog-upload-status') !== 'final' || blob !== DROPZONE + auth.pushFilename) {
|
|
288
|
+
throw new ManualSynthIdError('response', 'SynthID upload did not finalize at the configured path')
|
|
289
|
+
}
|
|
290
|
+
return blob
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private async post(url: string, init: { body: BodyInit; headers: Record<string, string> }, stage: 'auth' | 'upload' | 'detect'): Promise<{ headers: Headers; text: string }> {
|
|
294
|
+
const timeout = AbortSignal.timeout(this.config.timeout)
|
|
295
|
+
const signal = AbortSignal.any([timeout, this.abort.signal])
|
|
296
|
+
try {
|
|
297
|
+
signal.throwIfAborted()
|
|
298
|
+
const response = await this.ctx.http.fetch(url, {
|
|
299
|
+
...init, method: 'POST', headers: { ...WEB_HEADERS, ...init.headers }, signal, redirect: 'error',
|
|
300
|
+
})
|
|
301
|
+
if (!response.ok) {
|
|
302
|
+
await response.body?.cancel()
|
|
303
|
+
const status = response.status
|
|
304
|
+
const kind = status === 429 ? 'rate-limit'
|
|
305
|
+
: status === 403 ? 'permission'
|
|
306
|
+
: status === 401 || status === 400 && stage === 'auth' ? 'auth'
|
|
307
|
+
: status >= 500 ? 'server' : 'request'
|
|
308
|
+
throw new ManualSynthIdError(kind, `SynthID ${stage} returned HTTP ${status}`, stage === 'detect' && status === 401 ? 16 : status,
|
|
309
|
+
status === 429 ? retryAfter(response.headers.get('retry-after')) : undefined)
|
|
310
|
+
}
|
|
311
|
+
return { headers: response.headers, text: await response.text() }
|
|
312
|
+
} catch (error) {
|
|
313
|
+
if (error instanceof SynthIdError) throw error
|
|
314
|
+
if (this.abort.signal.aborted) throw new ManualSynthIdError('cancelled', 'SynthID client was disposed')
|
|
315
|
+
const expired = timeout.aborted || (error as Error)?.name === 'TimeoutError' || (error as { code?: string })?.code === 'ETIMEDOUT'
|
|
316
|
+
throw new ManualSynthIdError(expired ? 'timeout' : 'network', `SynthID ${stage} ${expired ? 'timed out' : 'could not connect'}`)
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
private async refresh(auth: Credentials, tokens: Tokens, force = false): Promise<void> {
|
|
321
|
+
const current = claims(tokens.idToken)
|
|
322
|
+
if (!force && typeof current.exp === 'number' && current.exp > Date.now() / 1000 + 180
|
|
323
|
+
&& (current.user_id ?? current.sub) === auth.userId && (!current.sub || current.sub === auth.userId)) return
|
|
324
|
+
const response = await this.post(TOKEN, {
|
|
325
|
+
body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: tokens.refreshToken }),
|
|
326
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
327
|
+
}, 'auth')
|
|
328
|
+
let value: Record<string, unknown>
|
|
329
|
+
try {
|
|
330
|
+
value = JSON.parse(response.text)
|
|
331
|
+
if (!value || typeof value.id_token !== 'string' || !value.id_token) throw new Error()
|
|
332
|
+
} catch {
|
|
333
|
+
throw new ManualSynthIdError('response', 'SynthID token refresh returned an invalid response')
|
|
334
|
+
}
|
|
335
|
+
const next = claims(value.id_token as string)
|
|
336
|
+
if ((next.user_id ?? next.sub) !== auth.userId || value.user_id && value.user_id !== auth.userId || next.sub && next.sub !== auth.userId) {
|
|
337
|
+
throw new ManualSynthIdError('config', 'SynthID credentials belong to different accounts')
|
|
338
|
+
}
|
|
339
|
+
if (typeof next.exp !== 'number' || !Number.isFinite(next.exp) || next.exp <= Date.now() / 1000) {
|
|
340
|
+
throw new ManualSynthIdError('response', 'SynthID token refresh returned an invalid expiry')
|
|
341
|
+
}
|
|
342
|
+
tokens.idToken = value.id_token as string
|
|
343
|
+
if (typeof value.refresh_token === 'string' && /^[\x21-\x7e]+$/.test(value.refresh_token)) tokens.refreshToken = value.refresh_token
|
|
344
|
+
tokens.updatedAt = Math.max(Date.now(), tokens.updatedAt + 1)
|
|
345
|
+
await this.saveTokens(auth, tokens)
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private async tokenFile(auth: Credentials): Promise<string> {
|
|
349
|
+
if (!this.cachePath) {
|
|
350
|
+
const directory = join(await this.ctx.storage.dir(), 'synthid-manual')
|
|
351
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
352
|
+
const key = createHash('sha256').update(auth.userId + '\0' + auth.refreshToken).digest('hex')
|
|
353
|
+
this.cachePath = join(directory, key + '.json')
|
|
354
|
+
}
|
|
355
|
+
return this.cachePath
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private async loadTokens(auth: Credentials): Promise<Tokens> {
|
|
359
|
+
this.tokens ??= { refreshToken: auth.refreshToken, idToken: '', updatedAt: 0 }
|
|
360
|
+
try {
|
|
361
|
+
const stored: unknown = JSON.parse(await readFile(await this.tokenFile(auth), 'utf8'))
|
|
362
|
+
const saved = stored as Partial<Tokens> | null
|
|
363
|
+
if (!saved || typeof saved.refreshToken !== 'string' || !/^[\x21-\x7e]+$/.test(saved.refreshToken) || typeof saved.idToken !== 'string'
|
|
364
|
+
|| typeof saved.updatedAt !== 'number' || !Number.isFinite(saved.updatedAt)) throw new Error()
|
|
365
|
+
const current = claims(saved.idToken)
|
|
366
|
+
if ((current.user_id ?? current.sub) !== auth.userId || current.sub && current.sub !== auth.userId) throw new Error()
|
|
367
|
+
// Observe token rotation by another entry using the same credentials. Keep newer in-memory tokens if a write failed.
|
|
368
|
+
if (saved.updatedAt >= this.tokens.updatedAt) this.tokens = saved as Tokens
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') this.logger.warn('cannot load SynthID token cache; using available credentials')
|
|
371
|
+
}
|
|
372
|
+
return this.tokens
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
private async saveTokens(auth: Credentials, tokens: Tokens): Promise<void> {
|
|
376
|
+
let temporary: string | undefined
|
|
377
|
+
try {
|
|
378
|
+
const file = await this.tokenFile(auth)
|
|
379
|
+
temporary = file + '.' + randomUUID() + '.tmp'
|
|
380
|
+
await writeFile(temporary, JSON.stringify(tokens), { encoding: 'utf8', mode: 0o600, flag: 'wx' })
|
|
381
|
+
await rename(temporary, file)
|
|
382
|
+
} catch {
|
|
383
|
+
this.logger.warn('cannot save SynthID token cache; credentials may need updating after a restart')
|
|
384
|
+
} finally {
|
|
385
|
+
if (temporary) await unlink(temporary).catch(() => {})
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// These expressions execute in the website, not in Node. Keep them as text:
|
|
2
|
+
// tsx/esbuild's keepNames helper must never be serialized into page.evaluate().
|
|
3
|
+
const liveUser = String.raw`
|
|
4
|
+
let user;
|
|
5
|
+
try {
|
|
6
|
+
const app = window.firebase?.apps?.[0];
|
|
7
|
+
user = app?.auth?.().currentUser;
|
|
8
|
+
} catch {}
|
|
9
|
+
`
|
|
10
|
+
|
|
11
|
+
export const accountScript = String.raw`(async () => {
|
|
12
|
+
const config = window.WIZ_global_data?.yeeU8 || {};
|
|
13
|
+
let accepted = false;
|
|
14
|
+
try { accepted = JSON.parse(localStorage.getItem('firstTime') || '{}').termsAccepted === true; } catch {}
|
|
15
|
+
${liveUser}
|
|
16
|
+
if (user?.uid) {
|
|
17
|
+
return { loggedIn: !user.isAnonymous, email: typeof user.email === 'string' ? user.email : undefined, accepted };
|
|
18
|
+
}
|
|
19
|
+
const shell = {
|
|
20
|
+
loggedIn: config.isLoggedIn === true || config.isLoggedIn === 'true',
|
|
21
|
+
email: typeof config.userEmail === 'string' && config.userEmail ? config.userEmail : undefined,
|
|
22
|
+
accepted,
|
|
23
|
+
};
|
|
24
|
+
const firebase = await new Promise(resolve => {
|
|
25
|
+
let done = false;
|
|
26
|
+
let database;
|
|
27
|
+
const finish = (value = { loggedIn: false }) => {
|
|
28
|
+
if (done) return;
|
|
29
|
+
done = true;
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
database?.close();
|
|
32
|
+
resolve(value);
|
|
33
|
+
};
|
|
34
|
+
const timer = setTimeout(() => finish(), 1500);
|
|
35
|
+
const request = indexedDB.open('firebaseLocalStorageDb');
|
|
36
|
+
request.onerror = () => finish();
|
|
37
|
+
request.onblocked = () => finish();
|
|
38
|
+
request.onupgradeneeded = () => { request.transaction?.abort(); finish(); };
|
|
39
|
+
request.onsuccess = () => {
|
|
40
|
+
database = request.result;
|
|
41
|
+
if (done) { database.close(); return; }
|
|
42
|
+
if (!database.objectStoreNames.contains('firebaseLocalStorage')) { finish(); return; }
|
|
43
|
+
const transaction = database.transaction('firebaseLocalStorage', 'readonly');
|
|
44
|
+
transaction.onerror = () => finish();
|
|
45
|
+
const cursor = transaction.objectStore('firebaseLocalStorage').openCursor();
|
|
46
|
+
cursor.onerror = () => finish();
|
|
47
|
+
cursor.onsuccess = () => {
|
|
48
|
+
const entry = cursor.result;
|
|
49
|
+
if (!entry) { finish(); return; }
|
|
50
|
+
const record = entry.value;
|
|
51
|
+
const saved = record.value;
|
|
52
|
+
if (record.fbase_key?.startsWith('firebase:authUser:') && typeof saved?.uid === 'string' && saved.uid && !saved.isAnonymous) {
|
|
53
|
+
finish({ loggedIn: true, email: typeof saved.email === 'string' ? saved.email : undefined });
|
|
54
|
+
} else entry.continue();
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
});
|
|
58
|
+
return firebase.loggedIn ? { ...firebase, accepted } : shell;
|
|
59
|
+
})()`
|
|
60
|
+
|
|
61
|
+
export const refreshTokenScript = String.raw`(async uid => {
|
|
62
|
+
${liveUser}
|
|
63
|
+
if (user?.uid) {
|
|
64
|
+
if (uid && user.uid !== uid || user.isAnonymous) return '';
|
|
65
|
+
const token = user.refreshToken || user.stsTokenManager?.refreshToken;
|
|
66
|
+
if (typeof token === 'string' && token) return token;
|
|
67
|
+
}
|
|
68
|
+
return new Promise(resolve => {
|
|
69
|
+
let done = false;
|
|
70
|
+
let database;
|
|
71
|
+
const finish = (value = '') => {
|
|
72
|
+
if (done) return;
|
|
73
|
+
done = true;
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
database?.close();
|
|
76
|
+
resolve(value);
|
|
77
|
+
};
|
|
78
|
+
const timer = setTimeout(() => finish(), 1500);
|
|
79
|
+
const request = indexedDB.open('firebaseLocalStorageDb');
|
|
80
|
+
request.onerror = () => finish();
|
|
81
|
+
request.onblocked = () => finish();
|
|
82
|
+
request.onupgradeneeded = () => { request.transaction?.abort(); finish(); };
|
|
83
|
+
request.onsuccess = () => {
|
|
84
|
+
database = request.result;
|
|
85
|
+
if (done) { database.close(); return; }
|
|
86
|
+
if (!database.objectStoreNames.contains('firebaseLocalStorage')) { finish(); return; }
|
|
87
|
+
const transaction = database.transaction('firebaseLocalStorage', 'readonly');
|
|
88
|
+
transaction.onerror = () => finish();
|
|
89
|
+
const cursor = transaction.objectStore('firebaseLocalStorage').openCursor();
|
|
90
|
+
cursor.onerror = () => finish();
|
|
91
|
+
cursor.onsuccess = () => {
|
|
92
|
+
const entry = cursor.result;
|
|
93
|
+
if (!entry) { finish(); return; }
|
|
94
|
+
const record = entry.value;
|
|
95
|
+
const saved = record.value;
|
|
96
|
+
if (record.fbase_key?.startsWith('firebase:authUser:') && saved?.uid && (!uid || saved.uid === uid) && !saved.isAnonymous
|
|
97
|
+
&& typeof saved.stsTokenManager?.refreshToken === 'string' && saved.stsTokenManager.refreshToken) {
|
|
98
|
+
finish(saved.stsTokenManager.refreshToken);
|
|
99
|
+
} else entry.continue();
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
});
|
|
103
|
+
})`
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/** Image-only decoding of synthid.com's TZRKo response. Protocol reference: docs/synthid.md. */
|
|
2
|
+
export type SynthIdResult =
|
|
3
|
+
| { status: 'detected'; source?: string; confidence?: 'very-high' | 'high' | 'medium' }
|
|
4
|
+
| { status: 'not_detected' }
|
|
5
|
+
| { status: 'uncertain'; reason?: number }
|
|
6
|
+
| { status: 'quota_exceeded'; retryAfterSeconds: number }
|
|
7
|
+
|
|
8
|
+
export type SynthIdErrorKind = 'config' | 'runtime' | 'browser' | 'proxy' | 'terms' | 'auth' | 'permission' | 'verification' | 'rate-limit' | 'busy'
|
|
9
|
+
| 'network' | 'timeout' | 'request' | 'response' | 'server' | 'cancelled'
|
|
10
|
+
|
|
11
|
+
export type SynthIdNetworkCode = 'ECONNRESET' | 'ECONNREFUSED' | 'ENOTFOUND' | 'EAI_AGAIN' | 'ETIMEDOUT'
|
|
12
|
+
|
|
13
|
+
/** Messages contain no response bodies, tokens, or upload paths: they are safe to log. */
|
|
14
|
+
export class SynthIdError extends Error {
|
|
15
|
+
readonly name = 'SynthIdError'
|
|
16
|
+
|
|
17
|
+
constructor(readonly kind: SynthIdErrorKind, message: string, readonly code?: number, readonly retryAfterSeconds?: number, readonly networkCode?: SynthIdNetworkCode) {
|
|
18
|
+
super(message)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function invalid(): never {
|
|
23
|
+
throw new SynthIdError('response', 'SynthID returned an unrecognized response')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function json(text: string): unknown {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(text)
|
|
29
|
+
} catch {
|
|
30
|
+
return invalid()
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Boq counts UTF-8 bytes, including for non-ASCII partner names. A response may contain several frames. */
|
|
35
|
+
function* frames(text: string): Generator<unknown> {
|
|
36
|
+
let body = text.trimStart()
|
|
37
|
+
if (body.startsWith(")]}'")) body = body.slice(4).trimStart()
|
|
38
|
+
const bytes = Buffer.from(body, 'utf8')
|
|
39
|
+
let offset = 0
|
|
40
|
+
while (offset < bytes.length) {
|
|
41
|
+
while (offset < bytes.length && [9, 10, 13, 32].includes(bytes[offset])) offset++
|
|
42
|
+
if (offset === bytes.length) break
|
|
43
|
+
// Some responses contain just the JSON array, without a length prefix.
|
|
44
|
+
if (bytes[offset] === 91) {
|
|
45
|
+
const frame = json(bytes.subarray(offset).toString('utf8'))
|
|
46
|
+
if (!Array.isArray(frame)) return invalid()
|
|
47
|
+
yield* frame
|
|
48
|
+
break
|
|
49
|
+
}
|
|
50
|
+
const newline = bytes.indexOf(10, offset)
|
|
51
|
+
if (newline < 0) return invalid()
|
|
52
|
+
const lengthText = bytes.subarray(offset, newline).toString('ascii').trim()
|
|
53
|
+
if (!/^\d+$/.test(lengthText)) return invalid()
|
|
54
|
+
const size = Number(lengthText)
|
|
55
|
+
if (!Number.isSafeInteger(size) || size <= 0) return invalid()
|
|
56
|
+
let frame: unknown[] | undefined
|
|
57
|
+
// Google's current framing counts the newline between the length and JSON.
|
|
58
|
+
// Other responses count from the JSON itself. Accept either exact byte span,
|
|
59
|
+
// requiring a complete array so a truncated frame cannot become a result.
|
|
60
|
+
for (const start of [newline + 1, newline]) {
|
|
61
|
+
if (size > bytes.length - start) continue
|
|
62
|
+
try {
|
|
63
|
+
const candidate: unknown = JSON.parse(bytes.subarray(start, start + size).toString('utf8'))
|
|
64
|
+
if (!Array.isArray(candidate)) continue
|
|
65
|
+
frame = candidate
|
|
66
|
+
offset = start + size
|
|
67
|
+
break
|
|
68
|
+
} catch { /* Try the framing convention that includes the separator. */ }
|
|
69
|
+
}
|
|
70
|
+
if (!frame) return invalid()
|
|
71
|
+
yield* frame
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Recognize only the website's delimited quota status, without retaining its account identifier. */
|
|
76
|
+
function quotaWait(message: unknown): number | undefined {
|
|
77
|
+
if (typeof message !== 'string' || message.length > 1024) return undefined
|
|
78
|
+
const match = /^;[A-Za-z][A-Za-z0-9 _-]{0,63} quota exceeded for user [A-Za-z0-9_-]{1,128} and modality (?:image|audio|video)\. Please wait for -?(?:(\d{1,9})h)?(?:(\d{1,9})m)?(?:(\d{1,9}(?:\.\d{1,9})?)s)?;$/i.exec(message)
|
|
79
|
+
if (!match || match[0] !== message || match.slice(1).every(value => value === undefined)) return undefined
|
|
80
|
+
// The website treats a leading minus as the magnitude of the remaining wait.
|
|
81
|
+
const seconds = Math.ceil(Number(match[1] || 0) * 3600 + Number(match[2] || 0) * 60 + Number(match[3] || 0))
|
|
82
|
+
return Number.isSafeInteger(seconds) ? seconds : undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function parseSynthIdResponse(text: string): SynthIdResult {
|
|
86
|
+
// The terminal telemetry frame can omit its counted trailing newline. Stop
|
|
87
|
+
// after our complete RPC frame so a footer cannot mask a real auth result.
|
|
88
|
+
let frame: unknown[] | undefined
|
|
89
|
+
for (const value of frames(text)) {
|
|
90
|
+
if (Array.isArray(value) && value[0] === 'wrb.fr' && value[1] === 'TZRKo') { frame = value; break }
|
|
91
|
+
}
|
|
92
|
+
if (!frame) return invalid()
|
|
93
|
+
if (frame[2] === null) {
|
|
94
|
+
const status = Array.isArray(frame[5]) ? frame[5] : undefined
|
|
95
|
+
const code = typeof status?.[0] === 'number' ? status[0] : undefined
|
|
96
|
+
const retryAfterSeconds = code === 7 || code === 8 ? quotaWait(status?.[1]) : undefined
|
|
97
|
+
const kind: SynthIdErrorKind = retryAfterSeconds !== undefined ? 'rate-limit'
|
|
98
|
+
: code === 16 ? 'auth' : code === 7 ? 'permission'
|
|
99
|
+
: code === 8 ? 'rate-limit' : code === 3 ? 'request' : code === 13 ? 'server' : 'response'
|
|
100
|
+
throw new SynthIdError(kind, `SynthID RPC failed (${code ?? 'unknown'})`, code, retryAfterSeconds)
|
|
101
|
+
}
|
|
102
|
+
if (typeof frame[2] !== 'string') return invalid()
|
|
103
|
+
const payload = json(frame[2])
|
|
104
|
+
if (!Array.isArray(payload)) return invalid()
|
|
105
|
+
if (Array.isArray(payload[6]) && payload[6].length) {
|
|
106
|
+
const quota = payload[6][0]
|
|
107
|
+
if (!Array.isArray(quota)) return invalid()
|
|
108
|
+
const duration = quota[3]
|
|
109
|
+
const seconds = Array.isArray(duration) ? Number(duration[0] ?? 0) + Number(duration[1] ?? 0) / 1e9 : 0
|
|
110
|
+
if (!Number.isFinite(seconds) || seconds < 0) return invalid()
|
|
111
|
+
return { status: 'quota_exceeded', retryAfterSeconds: Math.ceil(seconds) }
|
|
112
|
+
}
|
|
113
|
+
const entry = Array.isArray(payload[4]) ? payload[4][0] : undefined
|
|
114
|
+
if (!Array.isArray(entry)) return invalid()
|
|
115
|
+
switch (entry[0]) {
|
|
116
|
+
case 3: {
|
|
117
|
+
// Missing or new provider codes must not silently become Google.
|
|
118
|
+
const source = entry[10] === 1 ? 'google'
|
|
119
|
+
: entry[10] === 2 && typeof entry[11] === 'string' ? entry[11].trim().replace(/\s+/g, ' ').slice(0, 80) || undefined
|
|
120
|
+
: undefined
|
|
121
|
+
const confidence = entry[12] === 6 ? 'very-high' : entry[12] === 5 ? 'high' : entry[12] === 4 ? 'medium' : undefined
|
|
122
|
+
// Field 4 is a false-positive metric, not the probability that the whole image is AI-made.
|
|
123
|
+
return { status: 'detected', source, confidence }
|
|
124
|
+
}
|
|
125
|
+
case 2: return { status: 'not_detected' }
|
|
126
|
+
case 1: return { status: 'uncertain', reason: typeof entry[9] === 'number' ? entry[9] : undefined }
|
|
127
|
+
default: return invalid()
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function formatSynthId(result: Exclude<SynthIdResult, { status: 'quota_exceeded' }>): string {
|
|
132
|
+
if (result.status === 'not_detected') return '没有找到 AI 特征,但不能完全确认不是 AI。'
|
|
133
|
+
if (result.status === 'uncertain') {
|
|
134
|
+
const reasons: Record<number, string> = {
|
|
135
|
+
1: '图片为空',
|
|
136
|
+
2: '图片分辨率过低',
|
|
137
|
+
3: '图片细节不足',
|
|
138
|
+
5: '图片质量过低',
|
|
139
|
+
6: '图片可能经过修改,或只在局部使用了 AI',
|
|
140
|
+
}
|
|
141
|
+
return `SynthID 无法判断:${reasons[result.reason ?? 0] ?? '没有足够的信息'}。`
|
|
142
|
+
}
|
|
143
|
+
const sources: Record<string, string> = { google: 'Google', openai: 'OpenAI', nvidia: 'NVIDIA', kakao: 'Kakao' }
|
|
144
|
+
const source = result.source && (Object.hasOwn(sources, result.source.toLowerCase()) ? sources[result.source.toLowerCase()] : result.source)
|
|
145
|
+
return `图片是 ${source || 'AI'} 生成`
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function describeSynthIdFailure(error: SynthIdError): string {
|
|
149
|
+
switch (error.kind) {
|
|
150
|
+
case 'runtime': return 'SynthID HTTP 运行环境不可用,当前需要 Node.js 24 或以上版本。'
|
|
151
|
+
case 'config':
|
|
152
|
+
case 'browser': return 'SynthID 浏览器无法启动,请确认运行 Bot 的电脑已安装 Chrome 或 Edge,并且能打开桌面窗口。'
|
|
153
|
+
case 'proxy': return 'SynthID 浏览器无法使用当前代理,请检查「代理」插件的地址与账号密码;浏览器不支持带账号密码的 SOCKS5 代理。'
|
|
154
|
+
case 'terms': return '请在插件设置中点击「登录 SynthID」,完成登录窗口中的首次使用提示。'
|
|
155
|
+
case 'auth': return 'SynthID 尚未登录或登录已失效,请在插件设置中点击「登录 SynthID」。'
|
|
156
|
+
case 'permission': return 'SynthID 服务拒绝了本次检测请求。'
|
|
157
|
+
case 'verification': return 'SynthID 本次请求未通过网页校验,请稍后再试。'
|
|
158
|
+
case 'rate-limit': return error.retryAfterSeconds
|
|
159
|
+
? `SynthID 检测额度暂时用完,请约 ${error.retryAfterSeconds} 秒后再试。`
|
|
160
|
+
: 'SynthID 检测过于频繁或额度暂时用完,请稍后再试。'
|
|
161
|
+
case 'busy': return 'SynthID 检测队列已满,请稍后再试。'
|
|
162
|
+
case 'network': {
|
|
163
|
+
const reasons: Record<SynthIdNetworkCode, string> = {
|
|
164
|
+
ECONNRESET: '连接被重置(ECONNRESET)', ECONNREFUSED: '连接被拒绝(ECONNREFUSED)',
|
|
165
|
+
ENOTFOUND: '域名解析失败(ENOTFOUND)', EAI_AGAIN: '域名解析暂时失败(EAI_AGAIN)', ETIMEDOUT: '连接超时(ETIMEDOUT)',
|
|
166
|
+
}
|
|
167
|
+
return error.networkCode && reasons[error.networkCode]
|
|
168
|
+
? `登录页加载失败:${reasons[error.networkCode]}。请在 Bot「代理」插件中测试 https://synthid.com/,确认该网站能通过当前代理访问后重试。`
|
|
169
|
+
: '连不上 SynthID 检测服务,请检查网络或代理设置。'
|
|
170
|
+
}
|
|
171
|
+
case 'timeout': return '连不上 SynthID 检测服务,请检查网络或代理设置。'
|
|
172
|
+
case 'request': return 'SynthID 无法处理这张图片,请尝试发送原图。'
|
|
173
|
+
case 'response': return 'SynthID 返回了无法识别的结果,检测接口可能已变更。'
|
|
174
|
+
case 'cancelled': return 'SynthID 检测已取消。'
|
|
175
|
+
default: return 'SynthID 检测失败,请稍后再试。'
|
|
176
|
+
}
|
|
177
|
+
}
|