-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_console.mjs
More file actions
212 lines (191 loc) · 7.97 KB
/
Copy pathfetch_console.mjs
File metadata and controls
212 lines (191 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env node
/**
* OpenCode Go console fetcher — mirrors the opencode.ai console's usage
* meters (micro-cent precision, $12/$30/$60 windows) into a JSON cache the
* TUI widget reads.
*
* Part of github.com/E-R-Butch/hermes-opencode-go-widget (MIT).
*
* node fetch_console.mjs fetch with the cached cookie
* node fetch_console.mjs --extract (re)extract the cookie from Chrome, then fetch
*
* Auth: only ever talks to opencode.ai. The cookie is stored 0600 at
* ~/.hermes/opencode-go/console_cookie and is never printed. Extraction
* reads Chrome's cookie DB (read-only copy) and decrypts with the
* "Chrome Safe Storage" key from the login keychain (one-time approval).
*/
import { execFileSync } from 'node:child_process'
import { createDecipheriv, createHash, pbkdf2Sync } from 'node:crypto'
import { chmodSync, copyFileSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
const HOME = process.env.HOME || homedir()
const HERMES_HOME = (process.env.HERMES_HOME && process.env.HERMES_HOME.trim()) || join(HOME, '.hermes')
const DIR = join(HERMES_HOME, 'opencode-go')
const COOKIE_FILE = join(DIR, 'console_cookie')
const CACHE_FILE = join(DIR, 'console.json')
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36'
const SCALE = 100_000_000 // micro-cents per dollar
class AuthExpired extends Error {}
const say = (...a) => console.log(...a)
function writeCache(value) {
mkdirSync(DIR, { recursive: true, mode: 0o700 })
const tmp = CACHE_FILE + '.tmp'
writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 })
renameSync(tmp, CACHE_FILE)
}
// ---------------------------------------------------------------- extraction
function chromeSafeStorageKey() {
const attempts = [
['find-generic-password', '-w', '-s', 'Chrome Safe Storage', '-a', 'Chrome'],
['find-generic-password', '-w', '-s', 'Chrome Safe Storage']
]
let lastErr = null
for (const args of attempts) {
try {
const out = execFileSync('security', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
const value = out.trim()
if (value) return value
} catch (error) {
lastErr = error
}
}
throw new Error('could not read "Chrome Safe Storage" from the keychain' + (lastErr ? ': ' + (lastErr.stderr || lastErr.message).toString().slice(0, 200) : ''))
}
function decryptCookie(hex, hostKey, key) {
const raw = Buffer.from(hex, 'hex')
if (raw.length < 3) return null
const version = raw.slice(0, 3).toString('latin1')
if (version !== 'v10' && version !== 'v11' && version !== 'v12') {
say('[extract] unexpected encrypted_value prefix:', JSON.stringify(version.slice(0, 2)))
return null
}
const decipher = createDecipheriv('aes-128-cbc', key, Buffer.alloc(16, 0x20))
decipher.setAutoPadding(false)
let plain = Buffer.concat([decipher.update(raw.slice(3)), decipher.final()])
const pad = plain[plain.length - 1]
if (pad > 0 && pad <= 16 && pad <= plain.length) plain = plain.slice(0, plain.length - pad)
const digest = createHash('sha256').update(hostKey).digest()
if (plain.length > 32 && plain.slice(0, 32).equals(digest)) plain = plain.slice(32)
return plain.toString('utf8')
}
function extractCookie() {
const key = pbkdf2Sync(chromeSafeStorageKey(), 'saltysalt', 1003, 16, 'sha1')
const src = join(HOME, 'Library/Application Support/Google/Chrome/Default/Cookies')
const tmp = join(DIR, '.chrome-cookies.db')
mkdirSync(DIR, { recursive: true, mode: 0o700 })
copyFileSync(src, tmp)
for (const suffix of ['-wal', '-shm']) {
try { copyFileSync(src + suffix, tmp + suffix) } catch {}
}
let rows
try {
const out = execFileSync('sqlite3', [
'-json', tmp,
"SELECT host_key, name, hex(encrypted_value) AS ev FROM cookies WHERE host_key = 'opencode.ai'"
], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
rows = JSON.parse(out || '[]')
} finally {
for (const suffix of ['', '-wal', '-shm']) {
try { unlinkSync(tmp + suffix) } catch {}
}
}
const values = {}
for (const row of rows) {
try {
const value = decryptCookie(row.ev, row.host_key, key)
if (value) values[row.name] = value
} catch (error) {
say('[extract] failed to decrypt cookie:', row.name, '-', String(error.message).slice(0, 80))
}
}
const parts = ['auth', '__Host-console_session', 'oc_locale']
.filter(name => values[name])
.map(name => name + '=' + values[name])
if (!values['auth'] && !values['__Host-console_session']) {
throw new AuthExpired('no opencode.ai session cookie found in Chrome — log in at opencode.ai first')
}
const header = parts.join('; ')
writeFileSync(COOKIE_FILE, header + '\n', { mode: 0o600 })
chmodSync(COOKIE_FILE, 0o600)
say('[extract] cookies found:', rows.map(r => r.name).join(', '), '| header bytes:', header.length)
return header
}
function loadCookie({ extract }) {
if (extract) return extractCookie()
try {
const value = readFileSync(COOKIE_FILE, 'utf8').trim()
if (value) return value
} catch {}
throw new Error('no cached console cookie — run once with --extract')
}
// ---------------------------------------------------------------- fetching
async function consoleGet(path, cookieHeader, extraHeaders = {}) {
const res = await fetch('https://opencode.ai' + path, {
headers: {
Accept: 'application/json',
Cookie: cookieHeader,
'User-Agent': UA,
...extraHeaders
},
signal: AbortSignal.timeout(15_000)
})
const text = await res.text()
if (res.status === 401) throw new AuthExpired('console session rejected (HTTP 401)')
if (res.status !== 200) throw new Error(path + ' HTTP ' + res.status)
return text
}
const dollars = mc => (Number(mc) / SCALE)
async function main() {
const extract = process.argv.includes('--extract')
const cookieHeader = loadCookie({ extract })
const orgs = JSON.parse(await consoleGet('/console/api/orgs', cookieHeader))
const org = Array.isArray(orgs)
? orgs.find(o => o && typeof o.id === 'string' && /^(wrk_|org_)/.test(o.id))
: null
if (!org) throw new Error('no workspace found in /console/api/orgs')
say('[orgs]', orgs.map(o => o.id + (o.name ? ' (' + o.name + ')' : '')).join(' | '))
const go = JSON.parse(await consoleGet('/console/api/go/status', cookieHeader, { 'x-org-id': org.id }))
let billing = null
try {
billing = JSON.parse(await consoleGet('/console/api/billing/status', cookieHeader, { 'x-org-id': org.id }))
} catch (error) {
say('[billing] could not fetch:', String(error.message).slice(0, 120))
}
say('[go/status] top keys:', Object.keys(go).join(','))
const access = go.access || {}
say('[go/status] access keys:', Object.keys(access).join(','), '| endsAt:', access.endsAt)
for (const [name, meter] of Object.entries(access.meters || {})) {
say(
' meter', name + ':',
'$' + dollars(meter.usedMicroCents).toFixed(2), 'of $' + dollars(meter.limitMicroCents).toFixed(2),
'| resetsAt:', meter.resetsAt ?? '(none)', '| keys:', Object.keys(meter).join(',')
)
}
if (billing) say('[billing/status]', JSON.stringify(billing).slice(0, 400))
writeCache({
fetchedAt: Date.now(),
error: null,
workspaceId: org.id,
workspaceName: typeof org.name === 'string' ? org.name : null,
useBalance: go.useBalance ?? null,
cancelAtPeriodEnd: go.cancelAtPeriodEnd ?? null,
renewalCurrency: go.renewalCurrency ?? null,
endsAt: access.endsAt ?? null,
meters: access.meters ?? null,
billing
})
say('[cache] wrote', CACHE_FILE)
}
main().catch(error => {
const expired = error instanceof AuthExpired
try {
writeCache({
fetchedAt: Date.now(),
error: expired ? 'auth-expired' : 'fetch-failed',
message: String(error.message).slice(0, 300)
})
} catch {}
say('[error]', expired ? 'auth-expired:' : 'fetch-failed:', String(error.message).slice(0, 300))
process.exit(expired ? 2 : 1)
})