@openchamber/web 1.15.0 → 1.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/assets/{DiagramView-HR2xZxJ8.js → DiagramView-Elkp8b4l.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-sm01Q7R7.js → MarkdownRendererImpl-DLhrL6oX.js} +3 -3
- package/dist/assets/{MultiRunWindow-DlFUaNQK.js → MultiRunWindow-DVpNCqnE.js} +1 -1
- package/dist/assets/{OnboardingScreen-DVRz82mJ.js → OnboardingScreen-CpcR0gyq.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DHO5Je6v.js +1 -0
- package/dist/assets/{SettingsWindow-CkInZcj7.js → SettingsWindow-Bewo7vwh.js} +1 -1
- package/dist/assets/{TerminalView-D_9BAjtv.js → TerminalView-D9C7fNLm.js} +3 -3
- package/dist/assets/es-D9nOo8Wx.js +15 -0
- package/dist/assets/fr-DEF71lgt.js +13 -0
- package/dist/assets/index-BklNmnVr.js +2 -0
- package/dist/assets/index-C3uMIExE.css +1 -0
- package/dist/assets/ja-CpNfaEje.js +15 -0
- package/dist/assets/ko-DLS_rnE-.js +15 -0
- package/dist/assets/main-B0CxEOP5.js +237 -0
- package/dist/assets/{main-DzNa8r0N.js → main-Ck3ZNw8-.js} +2 -2
- package/dist/assets/miniChat-BAJj2Ome.js +2 -0
- package/dist/assets/mobile-CJoX4Cdj.js +2 -0
- package/dist/assets/pl-BjtFn5-n.js +15 -0
- package/dist/assets/pt-BR-C0_4Rnzn.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-D4-OXCXM.js +2 -0
- package/dist/assets/renderMobileApp-DHWdI195.js +16 -0
- package/dist/assets/runtimeEndpointReset-B0P2DED1.js +167 -0
- package/dist/assets/uk-BDu4E0s0.js +15 -0
- package/dist/assets/{useAppFontEffects-DzBg8hrC.js → useAppFontEffects-9LFMCKYW.js} +195 -136
- package/dist/assets/zh-CN-BcwMqxIR.js +15 -0
- package/dist/assets/zh-TW-bNDQjKEu.js +15 -0
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +106 -1
- package/server/lib/notifications/DOCUMENTATION.md +1 -1
- package/server/lib/notifications/apns-runtime.js +3 -1
- package/server/lib/notifications/runtime.js +135 -33
- package/server/lib/opencode/DOCUMENTATION.md +1 -0
- package/server/lib/opencode/agents.js +3 -0
- package/server/lib/opencode/bootstrap-runtime.js +5 -0
- package/server/lib/opencode/core-routes.js +75 -2
- package/server/lib/opencode/core-routes.test.js +81 -0
- package/server/lib/opencode/feature-routes-runtime.js +6 -0
- package/server/lib/opencode/settings-helpers.js +30 -0
- package/server/lib/opencode/settings-helpers.test.js +14 -0
- package/server/lib/opencode/settings-normalization-runtime.js +19 -4
- package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
- package/server/lib/opencode/settings-runtime.js +25 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/tunnel-auth.js +4 -9
- package/server/lib/package-manager.js +1 -1
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
- package/server/lib/permission-auto-accept/runtime.js +263 -0
- package/server/lib/permission-auto-accept/runtime.test.js +137 -0
- package/server/lib/projects/project-config.js +8 -0
- package/server/lib/quota/DOCUMENTATION.md +5 -2
- package/server/lib/quota/credentials/providers.js +43 -0
- package/server/lib/quota/credentials/store.js +48 -0
- package/server/lib/quota/credentials/store.test.js +26 -0
- package/server/lib/quota/opencode-go-credentials.js +11 -0
- package/server/lib/quota/opencode-go-credentials.test.js +32 -0
- package/server/lib/quota/providers/codex.js +7 -4
- package/server/lib/quota/providers/codex.test.js +48 -0
- package/server/lib/quota/providers/cursor.js +28 -39
- package/server/lib/quota/providers/index.js +7 -0
- package/server/lib/quota/providers/ollama-cloud.js +23 -42
- package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
- package/server/lib/quota/providers/opencode-go.js +70 -0
- package/server/lib/quota/providers/opencode-go.test.js +17 -0
- package/server/lib/quota/routes.js +78 -7
- package/server/lib/quota/routes.test.js +40 -0
- package/server/lib/relay/DOCUMENTATION.md +20 -0
- package/server/lib/relay/host-lock.js +101 -0
- package/server/lib/relay/host-lock.test.js +129 -0
- package/server/lib/relay/identity.js +24 -4
- package/server/lib/relay/service.js +95 -8
- package/server/lib/relay/signing-key.js +30 -7
- package/server/lib/scheduled-tasks/runtime.js +104 -0
- package/server/lib/session-goal/DOCUMENTATION.md +176 -0
- package/server/lib/session-goal/objectives.js +61 -0
- package/server/lib/session-goal/routes.js +36 -0
- package/server/lib/session-goal/runtime.js +764 -0
- package/server/lib/small-model/DOCUMENTATION.md +3 -1
- package/server/lib/small-model/call.js +45 -8
- package/server/lib/small-model/call.test.js +338 -0
- package/server/lib/small-model/index.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-DvoOalMY.js +0 -1
- package/dist/assets/es-cjUissX4.js +0 -15
- package/dist/assets/fr-DqbXnTdK.js +0 -13
- package/dist/assets/index-Dg0nmvQU.css +0 -1
- package/dist/assets/index-ltrmNGAf.js +0 -2
- package/dist/assets/ja-Cetyq6Eg.js +0 -15
- package/dist/assets/ko-DtunWisP.js +0 -15
- package/dist/assets/main-BC0m8s1v.js +0 -236
- package/dist/assets/miniChat-BRYDE-Se.js +0 -2
- package/dist/assets/mobile-C3QJVA97.js +0 -2
- package/dist/assets/pl-DctGLgve.js +0 -15
- package/dist/assets/pt-BR-CXPhf78S.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +0 -2
- package/dist/assets/renderMobileApp-wkBjh5WR.js +0 -16
- package/dist/assets/runtimeEndpointReset-C42u8PvG.js +0 -167
- package/dist/assets/uk-Bdrc-kqF.js +0 -15
- package/dist/assets/zh-CN-CeCVKrHP.js +0 -15
- package/dist/assets/zh-TW-CoqiQING.js +0 -15
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
vi.mock('../../opencode/auth.js', () => ({
|
|
4
|
+
readAuthFile: () => ({ openai: { access: 'test-token' } }),
|
|
5
|
+
}));
|
|
6
|
+
|
|
7
|
+
import { fetchQuota } from './codex.js';
|
|
8
|
+
|
|
9
|
+
afterEach(() => {
|
|
10
|
+
vi.unstubAllGlobals();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const mockUsage = (rateLimit) => {
|
|
14
|
+
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
|
15
|
+
ok: true,
|
|
16
|
+
json: async () => ({ rate_limit: rateLimit }),
|
|
17
|
+
}));
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
describe('Codex quota windows', () => {
|
|
21
|
+
it('labels a weekly-only primary window from its duration', async () => {
|
|
22
|
+
mockUsage({
|
|
23
|
+
primary_window: {
|
|
24
|
+
used_percent: 3,
|
|
25
|
+
limit_window_seconds: 604800,
|
|
26
|
+
reset_at: 1784491827,
|
|
27
|
+
},
|
|
28
|
+
secondary_window: null,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const result = await fetchQuota();
|
|
32
|
+
|
|
33
|
+
expect(result.usage.windows.weekly.usedPercent).toBe(3);
|
|
34
|
+
expect(result.usage.windows['5h']).toBeUndefined();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('labels five-hour and weekly windows from their durations', async () => {
|
|
38
|
+
mockUsage({
|
|
39
|
+
primary_window: { used_percent: 10, limit_window_seconds: 18000 },
|
|
40
|
+
secondary_window: { used_percent: 20, limit_window_seconds: 604800 },
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const result = await fetchQuota();
|
|
44
|
+
|
|
45
|
+
expect(result.usage.windows['5h'].usedPercent).toBe(10);
|
|
46
|
+
expect(result.usage.windows.weekly.usedPercent).toBe(20);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { existsSync, readFileSync
|
|
1
|
+
import { existsSync, readFileSync } from 'fs';
|
|
2
2
|
import { homedir } from 'os';
|
|
3
3
|
import { join } from 'path';
|
|
4
4
|
import { execFileSync } from 'child_process';
|
|
5
|
+
import { readManagedCredential, writeManagedCredential } from '../credentials/providers.js';
|
|
5
6
|
import {
|
|
6
7
|
buildResult,
|
|
7
8
|
formatMoney,
|
|
@@ -54,25 +55,6 @@ const readStateValue = (key) => {
|
|
|
54
55
|
}
|
|
55
56
|
};
|
|
56
57
|
|
|
57
|
-
const writeStateValue = (key, value) => {
|
|
58
|
-
if (!existsSync(STATE_DB)) return false;
|
|
59
|
-
try {
|
|
60
|
-
const escaped = String(value).replace(/'/g, "''");
|
|
61
|
-
const escapedKey = String(key).replace(/'/g, "''");
|
|
62
|
-
execFileSync('sqlite3', [
|
|
63
|
-
STATE_DB,
|
|
64
|
-
`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ('${escapedKey}', '${escaped}');`
|
|
65
|
-
], {
|
|
66
|
-
encoding: 'utf8',
|
|
67
|
-
windowsHide: true,
|
|
68
|
-
stdio: ['ignore', 'ignore', 'ignore']
|
|
69
|
-
});
|
|
70
|
-
return true;
|
|
71
|
-
} catch {
|
|
72
|
-
return false;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
|
|
76
58
|
const readFileToken = (path) => {
|
|
77
59
|
try {
|
|
78
60
|
if (!path || !existsSync(path)) return null;
|
|
@@ -83,16 +65,6 @@ const readFileToken = (path) => {
|
|
|
83
65
|
}
|
|
84
66
|
};
|
|
85
67
|
|
|
86
|
-
const writeFileToken = (path, value) => {
|
|
87
|
-
try {
|
|
88
|
-
if (!path) return false;
|
|
89
|
-
writeFileSync(path, `${value}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
90
|
-
return true;
|
|
91
|
-
} catch {
|
|
92
|
-
return false;
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
|
|
96
68
|
const loadAuthState = () => {
|
|
97
69
|
const envAccessToken = process.env.CURSOR_TOKEN || process.env.CURSOR_ACCESS_TOKEN || null;
|
|
98
70
|
const envRefreshToken = process.env.CURSOR_REFRESH_TOKEN || null;
|
|
@@ -113,15 +85,15 @@ const loadAuthState = () => {
|
|
|
113
85
|
return {
|
|
114
86
|
accessToken: fileAccessToken,
|
|
115
87
|
refreshToken: fileRefreshToken,
|
|
116
|
-
source: 'file'
|
|
117
|
-
accessTokenPath
|
|
88
|
+
source: 'file'
|
|
118
89
|
};
|
|
119
90
|
}
|
|
120
91
|
|
|
92
|
+
const managed = readManagedCredential(providerId);
|
|
121
93
|
return {
|
|
122
|
-
accessToken:
|
|
123
|
-
refreshToken:
|
|
124
|
-
source: '
|
|
94
|
+
accessToken: managed?.accessToken || null,
|
|
95
|
+
refreshToken: managed?.refreshToken || null,
|
|
96
|
+
source: 'managed'
|
|
125
97
|
};
|
|
126
98
|
};
|
|
127
99
|
|
|
@@ -133,8 +105,18 @@ const tokenNeedsRefresh = (token) => {
|
|
|
133
105
|
};
|
|
134
106
|
|
|
135
107
|
const persistAccessToken = (auth, accessToken) => {
|
|
136
|
-
if (auth.source === '
|
|
137
|
-
|
|
108
|
+
if (auth.source === 'managed') writeManagedCredential(providerId, { accessToken, refreshToken: auth.refreshToken || '' });
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export const importCursorCredential = async () => {
|
|
112
|
+
const credential = {
|
|
113
|
+
accessToken: readStateValue('cursorAuth/accessToken') || '',
|
|
114
|
+
refreshToken: readStateValue('cursorAuth/refreshToken') || '',
|
|
115
|
+
};
|
|
116
|
+
if (!credential.accessToken && !credential.refreshToken) throw new Error('Cursor credentials are unavailable');
|
|
117
|
+
const accessToken = await resolveCredentialAccessToken({ ...credential, source: 'import' });
|
|
118
|
+
if (!accessToken) throw new Error('Cursor credentials are invalid');
|
|
119
|
+
return writeManagedCredential(providerId, { ...credential, accessToken });
|
|
138
120
|
};
|
|
139
121
|
|
|
140
122
|
const refreshAccessToken = async (auth) => {
|
|
@@ -165,13 +147,20 @@ const refreshAccessToken = async (auth) => {
|
|
|
165
147
|
return body.access_token;
|
|
166
148
|
};
|
|
167
149
|
|
|
168
|
-
const
|
|
169
|
-
const auth = loadAuthState();
|
|
150
|
+
const resolveCredentialAccessToken = async (auth) => {
|
|
170
151
|
if (!auth.accessToken && !auth.refreshToken) return null;
|
|
171
152
|
if (!tokenNeedsRefresh(auth.accessToken)) return auth.accessToken;
|
|
172
153
|
return refreshAccessToken(auth);
|
|
173
154
|
};
|
|
174
155
|
|
|
156
|
+
const resolveAccessToken = async () => resolveCredentialAccessToken(loadAuthState());
|
|
157
|
+
|
|
158
|
+
export const validateCursorCredential = async (credential) => {
|
|
159
|
+
const accessToken = await resolveCredentialAccessToken({ ...credential, source: 'validation' });
|
|
160
|
+
if (!accessToken) throw new Error('Cursor credentials are invalid');
|
|
161
|
+
await connectPost(USAGE_URL, accessToken);
|
|
162
|
+
};
|
|
163
|
+
|
|
175
164
|
const connectPost = async (url, accessToken) => {
|
|
176
165
|
const response = await fetch(url, {
|
|
177
166
|
method: 'POST',
|
|
@@ -22,6 +22,7 @@ import * as minimaxCodingPlan from './minimax-coding-plan.js';
|
|
|
22
22
|
import * as minimaxCnCodingPlan from './minimax-cn-coding-plan.js';
|
|
23
23
|
import * as ollamaCloud from './ollama-cloud.js';
|
|
24
24
|
import * as wafer from './wafer.js';
|
|
25
|
+
import * as opencodeGo from './opencode-go.js';
|
|
25
26
|
|
|
26
27
|
const registry = {
|
|
27
28
|
claude: {
|
|
@@ -113,6 +114,12 @@ const registry = {
|
|
|
113
114
|
providerName: wafer.providerName,
|
|
114
115
|
isConfigured: wafer.isConfigured,
|
|
115
116
|
fetchQuota: wafer.fetchQuota
|
|
117
|
+
},
|
|
118
|
+
'opencode-go': {
|
|
119
|
+
providerId: opencodeGo.providerId,
|
|
120
|
+
providerName: opencodeGo.providerName,
|
|
121
|
+
isConfigured: opencodeGo.isConfigured,
|
|
122
|
+
fetchQuota: opencodeGo.fetchQuota
|
|
116
123
|
}
|
|
117
124
|
};
|
|
118
125
|
|
|
@@ -1,26 +1,11 @@
|
|
|
1
|
-
import { homedir } from 'os';
|
|
2
|
-
import { readFileSync, existsSync } from 'fs';
|
|
3
|
-
import { join } from 'path';
|
|
4
1
|
import { buildResult, toUsageWindow, toNumber } from '../utils/index.js';
|
|
5
|
-
|
|
6
|
-
const COOKIE_PATH = join(homedir(), '.config', 'ollama-quota', 'cookie');
|
|
2
|
+
import { readManagedCredential } from '../credentials/providers.js';
|
|
7
3
|
|
|
8
4
|
export const providerId = 'ollama-cloud';
|
|
9
5
|
export const providerName = 'Ollama Cloud';
|
|
10
6
|
const aliases = ['ollama-cloud', 'ollamacloud'];
|
|
11
7
|
|
|
12
|
-
const
|
|
13
|
-
try {
|
|
14
|
-
if (!existsSync(COOKIE_PATH)) return null;
|
|
15
|
-
const content = readFileSync(COOKIE_PATH, 'utf-8');
|
|
16
|
-
const trimmed = content.trim();
|
|
17
|
-
return trimmed || null;
|
|
18
|
-
} catch {
|
|
19
|
-
return null;
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
const parseOllamaSettingsHtml = (html) => {
|
|
8
|
+
export const parseOllamaSettingsHtml = (html) => {
|
|
24
9
|
const windows = {};
|
|
25
10
|
const sessionMatch = html.match(/Session\s+usage[^0-9]*([0-9.]+)%/i);
|
|
26
11
|
if (sessionMatch) {
|
|
@@ -54,14 +39,29 @@ const parseOllamaSettingsHtml = (html) => {
|
|
|
54
39
|
};
|
|
55
40
|
|
|
56
41
|
export const isConfigured = () => {
|
|
57
|
-
|
|
58
|
-
|
|
42
|
+
return Boolean(readManagedCredential(providerId));
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const fetchOllamaCloudUsage = async (credential, fetchImpl = fetch) => {
|
|
46
|
+
const response = await fetchImpl('https://ollama.com/settings', {
|
|
47
|
+
method: 'GET',
|
|
48
|
+
headers: { Cookie: credential.cookie, 'User-Agent': 'OpenChamber quota provider' },
|
|
49
|
+
redirect: 'manual',
|
|
50
|
+
signal: AbortSignal.timeout(15_000),
|
|
51
|
+
});
|
|
52
|
+
if (response.status === 401 || response.status === 403 || (response.status >= 300 && response.status < 400)) {
|
|
53
|
+
throw new Error('Ollama Cloud authentication failed');
|
|
54
|
+
}
|
|
55
|
+
if (!response.ok) throw new Error(`Ollama Cloud returned HTTP ${response.status}`);
|
|
56
|
+
const windows = parseOllamaSettingsHtml(await response.text());
|
|
57
|
+
if (Object.keys(windows).length === 0) throw new Error('Ollama Cloud usage data could not be parsed');
|
|
58
|
+
return windows;
|
|
59
59
|
};
|
|
60
60
|
|
|
61
61
|
export const fetchQuota = async () => {
|
|
62
|
-
const
|
|
62
|
+
const credential = readManagedCredential(providerId);
|
|
63
63
|
|
|
64
|
-
if (!
|
|
64
|
+
if (!credential) {
|
|
65
65
|
return buildResult({
|
|
66
66
|
providerId,
|
|
67
67
|
providerName,
|
|
@@ -72,26 +72,7 @@ export const fetchQuota = async () => {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
try {
|
|
75
|
-
const
|
|
76
|
-
method: 'GET',
|
|
77
|
-
headers: {
|
|
78
|
-
Cookie: cookie,
|
|
79
|
-
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
if (!response.ok) {
|
|
84
|
-
return buildResult({
|
|
85
|
-
providerId,
|
|
86
|
-
providerName,
|
|
87
|
-
ok: false,
|
|
88
|
-
configured: true,
|
|
89
|
-
error: `API error: ${response.status}`
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const html = await response.text();
|
|
94
|
-
const windows = parseOllamaSettingsHtml(html);
|
|
75
|
+
const windows = await fetchOllamaCloudUsage(credential);
|
|
95
76
|
|
|
96
77
|
return buildResult({
|
|
97
78
|
providerId,
|
|
@@ -109,4 +90,4 @@ export const fetchQuota = async () => {
|
|
|
109
90
|
error: error instanceof Error ? error.message : 'Request failed'
|
|
110
91
|
});
|
|
111
92
|
}
|
|
112
|
-
};
|
|
93
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { fetchOllamaCloudUsage } from './ollama-cloud.js';
|
|
3
|
+
|
|
4
|
+
describe('Ollama Cloud quota provider', () => {
|
|
5
|
+
it('rejects redirects without forwarding credentials', async () => {
|
|
6
|
+
await expect(fetchOllamaCloudUsage({ cookie: 'session=secret' }, async () => new Response('', { status: 302 }))).rejects.toThrow('authentication failed');
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it('rejects successful pages without usage data', async () => {
|
|
10
|
+
await expect(fetchOllamaCloudUsage({ cookie: 'session=secret' }, async () => new Response('<html></html>'))).rejects.toThrow('could not be parsed');
|
|
11
|
+
});
|
|
12
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { readOpenCodeGoCredential } from '../opencode-go-credentials.js';
|
|
2
|
+
import { buildResult, toUsageWindow } from '../utils/index.js';
|
|
3
|
+
|
|
4
|
+
export const providerId = 'opencode-go';
|
|
5
|
+
export const providerName = 'OpenCode Go';
|
|
6
|
+
export const aliases = ['opencode-go'];
|
|
7
|
+
|
|
8
|
+
const patterns = {
|
|
9
|
+
'5h': 'rollingUsage',
|
|
10
|
+
weekly: 'weeklyUsage',
|
|
11
|
+
monthly: 'monthlyUsage',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const captureNumber = (name, body) => {
|
|
15
|
+
const match = body.match(new RegExp(`["']?${name}["']?\\s*:\\s*["']?(-?\\d+(?:\\.\\d+)?)`));
|
|
16
|
+
const value = match ? Number(match[1]) : null;
|
|
17
|
+
return Number.isFinite(value) ? value : null;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const parseOpenCodeGoUsage = (html, now = Date.now()) => {
|
|
21
|
+
if (typeof html !== 'string') return {};
|
|
22
|
+
const normalized = html.replaceAll('"', '"').replaceAll('"', '"').replaceAll('\\u0022', '"').replaceAll('\\"', '"');
|
|
23
|
+
const windows = {};
|
|
24
|
+
for (const [key, field] of Object.entries(patterns)) {
|
|
25
|
+
const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
26
|
+
const match = normalized.match(new RegExp(`["']?${escaped}["']?\\s*:\\s*(?:\\$R\\[\\d+\\]\\s*=\\s*)?\\{([^{}]*)\\}`, 's'));
|
|
27
|
+
if (!match) continue;
|
|
28
|
+
const usedPercent = captureNumber('usagePercent', match[1]);
|
|
29
|
+
const resetInSec = captureNumber('resetInSec', match[1]);
|
|
30
|
+
if (usedPercent === null || resetInSec === null) continue;
|
|
31
|
+
windows[key] = toUsageWindow({
|
|
32
|
+
usedPercent: Math.min(100, Math.max(0, usedPercent)),
|
|
33
|
+
resetAt: now + Math.max(0, resetInSec) * 1000,
|
|
34
|
+
windowSeconds: null,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return windows;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const fetchOpenCodeGoUsage = async (credential, fetchImpl = fetch) => {
|
|
41
|
+
const response = await fetchImpl(`https://opencode.ai/workspace/${encodeURIComponent(credential.workspaceId)}/go`, {
|
|
42
|
+
headers: {
|
|
43
|
+
Accept: 'text/html,application/xhtml+xml',
|
|
44
|
+
Cookie: `auth=${credential.authCookie}`,
|
|
45
|
+
'User-Agent': 'OpenChamber quota provider',
|
|
46
|
+
},
|
|
47
|
+
redirect: 'manual',
|
|
48
|
+
signal: AbortSignal.timeout(15_000),
|
|
49
|
+
});
|
|
50
|
+
if (response.status === 401 || response.status === 403 || (response.status >= 300 && response.status < 400)) {
|
|
51
|
+
throw new Error('OpenCode Go authentication failed');
|
|
52
|
+
}
|
|
53
|
+
if (!response.ok) throw new Error(`OpenCode Go dashboard returned HTTP ${response.status}`);
|
|
54
|
+
const windows = parseOpenCodeGoUsage(await response.text());
|
|
55
|
+
if (Object.keys(windows).length === 0) throw new Error('OpenCode Go usage data could not be parsed');
|
|
56
|
+
return windows;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export const isConfigured = () => Boolean(readOpenCodeGoCredential());
|
|
60
|
+
|
|
61
|
+
export const fetchQuota = async () => {
|
|
62
|
+
const credential = readOpenCodeGoCredential();
|
|
63
|
+
if (!credential) return buildResult({ providerId, providerName, ok: false, configured: false, error: 'Not configured' });
|
|
64
|
+
try {
|
|
65
|
+
const windows = await fetchOpenCodeGoUsage(credential);
|
|
66
|
+
return buildResult({ providerId, providerName, ok: true, configured: true, usage: { windows } });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return buildResult({ providerId, providerName, ok: false, configured: true, error: error instanceof Error ? error.message : 'Request failed' });
|
|
69
|
+
}
|
|
70
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { fetchOpenCodeGoUsage, parseOpenCodeGoUsage } from './opencode-go.js';
|
|
3
|
+
|
|
4
|
+
describe('OpenCode Go quota provider', () => {
|
|
5
|
+
it('parses partial SSR usage windows in either field order', () => {
|
|
6
|
+
const windows = parseOpenCodeGoUsage('rollingUsage:$R[1]={usagePercent:25,resetInSec:60} weeklyUsage:$R[2]={resetInSec:120,usagePercent:40}', 1_000);
|
|
7
|
+
expect(windows['5h'].usedPercent).toBe(25);
|
|
8
|
+
expect(windows['5h'].resetAt).toBe(61_000);
|
|
9
|
+
expect(windows.weekly.usedPercent).toBe(40);
|
|
10
|
+
expect(windows.monthly).toBeUndefined();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('does not expose credentials in authentication errors', async () => {
|
|
14
|
+
const credential = { workspaceId: 'wrk_test', authCookie: 'secret' };
|
|
15
|
+
await expect(fetchOpenCodeGoUsage(credential, async () => new Response('', { status: 403 }))).rejects.toThrow('authentication failed');
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -1,24 +1,95 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import { deleteManagedCredential, getManagedCredentialStatus, normalizers, readManagedCredential, writeManagedCredential } from './credentials/providers.js';
|
|
3
|
+
import { fetchOpenCodeGoUsage } from './providers/opencode-go.js';
|
|
4
|
+
import { fetchOllamaCloudUsage } from './providers/ollama-cloud.js';
|
|
5
|
+
import { importCursorCredential, validateCursorCredential } from './providers/cursor.js';
|
|
6
|
+
|
|
7
|
+
const validators = {
|
|
8
|
+
'opencode-go': fetchOpenCodeGoUsage,
|
|
9
|
+
'ollama-cloud': fetchOllamaCloudUsage,
|
|
10
|
+
cursor: validateCursorCredential,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const getProvider = (req, res) => {
|
|
14
|
+
const providerId = req.params.providerId;
|
|
15
|
+
if (!normalizers[providerId]) {
|
|
16
|
+
res.status(404).json({ code: 'UNSUPPORTED_PROVIDER', error: 'Unsupported credential provider' });
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
return providerId;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const credentialError = (res, error) => res.status(400).json({
|
|
23
|
+
code: 'INVALID_CREDENTIAL',
|
|
24
|
+
error: error instanceof Error ? error.message : 'Credential validation failed',
|
|
25
|
+
});
|
|
26
|
+
|
|
1
27
|
export function registerQuotaRoutes(app, { getQuotaProviders }) {
|
|
2
28
|
app.get('/api/quota/providers', async (_req, res) => {
|
|
3
29
|
try {
|
|
4
30
|
const { listConfiguredQuotaProviders } = await getQuotaProviders();
|
|
5
|
-
|
|
6
|
-
res.json({ providers });
|
|
31
|
+
res.json({ providers: listConfiguredQuotaProviders() });
|
|
7
32
|
} catch (error) {
|
|
8
33
|
console.error('Failed to list quota providers:', error);
|
|
9
34
|
res.status(500).json({ error: error.message || 'Failed to list quota providers' });
|
|
10
35
|
}
|
|
11
36
|
});
|
|
12
37
|
|
|
38
|
+
app.get('/api/quota/credentials/:providerId', (req, res) => {
|
|
39
|
+
const providerId = getProvider(req, res);
|
|
40
|
+
if (providerId) res.json(getManagedCredentialStatus(providerId));
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
app.put('/api/quota/credentials/:providerId', express.json({ limit: '16kb' }), async (req, res) => {
|
|
44
|
+
const providerId = getProvider(req, res);
|
|
45
|
+
if (!providerId) return;
|
|
46
|
+
const credential = normalizers[providerId](req.body);
|
|
47
|
+
if (!credential) return credentialError(res, new Error('Invalid credential'));
|
|
48
|
+
try {
|
|
49
|
+
await validators[providerId](credential);
|
|
50
|
+
res.json(writeManagedCredential(providerId, credential));
|
|
51
|
+
} catch (error) {
|
|
52
|
+
credentialError(res, error);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
app.post('/api/quota/credentials/:providerId/validate', async (req, res) => {
|
|
57
|
+
const providerId = getProvider(req, res);
|
|
58
|
+
if (!providerId) return;
|
|
59
|
+
const credential = readManagedCredential(providerId);
|
|
60
|
+
if (!credential) return res.status(404).json({ code: 'NOT_CONFIGURED', error: 'Not configured' });
|
|
61
|
+
try {
|
|
62
|
+
await validators[providerId](credential);
|
|
63
|
+
res.json({ valid: true });
|
|
64
|
+
} catch (error) {
|
|
65
|
+
credentialError(res, error);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
app.post('/api/quota/credentials/:providerId/import', async (req, res) => {
|
|
70
|
+
const providerId = getProvider(req, res);
|
|
71
|
+
if (!providerId) return;
|
|
72
|
+
if (providerId !== 'cursor') return res.status(404).json({ code: 'IMPORT_UNAVAILABLE', error: 'Import unavailable' });
|
|
73
|
+
try {
|
|
74
|
+
res.json(await importCursorCredential());
|
|
75
|
+
} catch (error) {
|
|
76
|
+
credentialError(res, error);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
app.delete('/api/quota/credentials/:providerId', (req, res) => {
|
|
81
|
+
const providerId = getProvider(req, res);
|
|
82
|
+
if (!providerId) return;
|
|
83
|
+
deleteManagedCredential(providerId);
|
|
84
|
+
res.json({ configured: false });
|
|
85
|
+
});
|
|
86
|
+
|
|
13
87
|
app.get('/api/quota/:providerId', async (req, res) => {
|
|
14
88
|
try {
|
|
15
89
|
const { providerId } = req.params;
|
|
16
|
-
if (!providerId) {
|
|
17
|
-
return res.status(400).json({ error: 'Provider ID is required' });
|
|
18
|
-
}
|
|
90
|
+
if (!providerId) return res.status(400).json({ error: 'Provider ID is required' });
|
|
19
91
|
const { fetchQuotaForProvider } = await getQuotaProviders();
|
|
20
|
-
|
|
21
|
-
res.json(result);
|
|
92
|
+
res.json(await fetchQuotaForProvider(providerId));
|
|
22
93
|
} catch (error) {
|
|
23
94
|
console.error('Failed to fetch quota:', error);
|
|
24
95
|
res.status(500).json({ error: error.message || 'Failed to fetch quota' });
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { afterAll, describe, expect, it, mock } from 'bun:test';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { registerQuotaRoutes } from './routes.js';
|
|
7
|
+
|
|
8
|
+
const previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
|
|
9
|
+
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-go-routes-'));
|
|
10
|
+
process.env.OPENCHAMBER_DATA_DIR = temporaryDirectory;
|
|
11
|
+
|
|
12
|
+
afterAll(() => {
|
|
13
|
+
if (previousDataDir === undefined) delete process.env.OPENCHAMBER_DATA_DIR;
|
|
14
|
+
else process.env.OPENCHAMBER_DATA_DIR = previousDataDir;
|
|
15
|
+
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe('OpenCode Go credential routes', () => {
|
|
19
|
+
it('parses a JSON credential payload before validation', async () => {
|
|
20
|
+
const originalFetch = globalThis.fetch;
|
|
21
|
+
globalThis.fetch = mock(async () => new Response('rollingUsage:$R[1]={usagePercent:25,resetInSec:60}'));
|
|
22
|
+
const app = express();
|
|
23
|
+
registerQuotaRoutes(app, { getQuotaProviders: async () => ({}) });
|
|
24
|
+
const server = app.listen(0);
|
|
25
|
+
try {
|
|
26
|
+
const address = server.address();
|
|
27
|
+
if (!address || typeof address === 'string') throw new Error('Test server did not start');
|
|
28
|
+
const response = await originalFetch(`http://127.0.0.1:${address.port}/api/quota/credentials/opencode-go`, {
|
|
29
|
+
method: 'PUT',
|
|
30
|
+
headers: { 'Content-Type': 'application/json' },
|
|
31
|
+
body: JSON.stringify({ workspaceId: 'wrk_test', authCookie: 'auth=secret' }),
|
|
32
|
+
});
|
|
33
|
+
expect(response.status).toBe(200);
|
|
34
|
+
expect(await response.json()).toEqual({ configured: true, workspaceId: 'wrk_test', secretMasked: '••••••••' });
|
|
35
|
+
} finally {
|
|
36
|
+
globalThis.fetch = originalFetch;
|
|
37
|
+
server.close();
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -23,6 +23,7 @@ Host side (`packages/web/server/lib/relay/`):
|
|
|
23
23
|
- `identity.js` — the host's stable identity: the long-lived signing keypair (shared with the push relay, defines the routing id) plus a long-lived encryption keypair (the E2EE trust anchor). Reused across restarts; never rotated implicitly.
|
|
24
24
|
- `signing-key.js` — storage/derivation of the signing keypair and the routing id, shared with the notifications runtime.
|
|
25
25
|
- `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect/backoff, and the E2EE responder handshake per connection.
|
|
26
|
+
- `host-lock.js` — the per-machine host claim. Every local instance sharing the data dir shares the relay identity (same serverId), so concurrent relay hosts evict each other at the relay worker (`4001: Control replaced`) and paired devices land on whichever local process won last. The claim file (`<data-dir>/relay-host.lock`, `{ pid }`) makes this deterministic: `service.js` only starts the host when no LIVE process holds the claim (stale claims from dead pids are ignored), goes to `standby` otherwise, and a 30s watcher both takes over when the claimant dies and stands down when another process claims. Explicit user intent — creating a pairing link or hitting `/relay/enable` — force-claims; the previous holder's watcher sees the takeover and backs off instead of fighting. The claim is cooperative (the relay worker still enforces the single host slot); it only decides which process keeps retrying.
|
|
26
27
|
- `tunnel-host.js` — the per-connection dispatcher: decrypts tunnel frames and forwards HTTP/SSE/WS to the local server over loopback, then streams responses back. Enforces a path allowlist and never injects credentials.
|
|
27
28
|
- `e2ee.js`, `tunnel-codec.js` — host-side (JS) mirrors of the shared crypto and framing (see "Two implementations" below).
|
|
28
29
|
|
|
@@ -59,6 +60,25 @@ The host dispatcher restricts tunneled traffic to explicit path allowlists (one
|
|
|
59
60
|
4. **Handshake.** Over that connection pair, client and host run the E2EE handshake and derive a shared encrypted channel the relay cannot read.
|
|
60
61
|
5. **Traffic.** All normal app traffic is multiplexed and encrypted through that channel. On the host, decrypted requests are dispatched to the local server over loopback; responses stream back encrypted. Reconnects re-establish a fresh channel and the app's existing retry machinery recovers.
|
|
61
62
|
|
|
63
|
+
## Candidate refresh (staying off the relay when direct works)
|
|
64
|
+
|
|
65
|
+
Pairing-payload transport candidates are a snapshot: when DHCP hands the host
|
|
66
|
+
machine a new LAN address, a device's saved direct candidate goes stale and the
|
|
67
|
+
device silently degrades to relay-only. To recover, an already-paired client can
|
|
68
|
+
call `GET /api/client-auth/connection/candidates` (UI session or client bearer;
|
|
69
|
+
registered with the auth/access routes) over any live transport — including
|
|
70
|
+
through the tunnel — to learn the server's **current** LAN URLs plus the relay
|
|
71
|
+
candidate, and update its saved candidate set (mobile: `mobileConnections.ts`;
|
|
72
|
+
desktop: `desktopRelayRestore.ts`).
|
|
73
|
+
|
|
74
|
+
Identity gating: the response carries the stable `serverId` (base64url SHA-256 of
|
|
75
|
+
the public signing JWK — the same identity the relay routes by, exposed by the
|
|
76
|
+
relay service's `getServerId()` and echoed unauthenticated on `/health` and
|
|
77
|
+
`/api/version`). Clients ignore a refresh whose `serverId` does not match their
|
|
78
|
+
pinned relay identity, and verify `/health`'s `serverId` on a learned address
|
|
79
|
+
**before** sending their bearer token to it — a re-assigned LAN address may now
|
|
80
|
+
belong to a different machine.
|
|
81
|
+
|
|
62
82
|
## Two implementations, kept in sync
|
|
63
83
|
|
|
64
84
|
The E2EE and framing logic exists twice: TypeScript in `packages/ui/src/lib/relay/` (shared by the client and the normative reference) and a JavaScript mirror in this module (the host, which is plain JS ESM). They **must stay byte-compatible** — a client encrypted by one must decrypt on the other. A cross-compatibility test (`cross-compat.test.js`) imports the TS modules directly and exercises a full TS-client ↔ JS-host exchange. Any change to the wire format, frame codec, handshake, or batching must update both sides and keep that test green.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Per-machine relay-host claim. Every OpenChamber instance on a machine shares
|
|
2
|
+
// the same data dir and therefore the same relay signing key / serverId, so if
|
|
3
|
+
// two processes run a relay host at once they fight over the single host slot
|
|
4
|
+
// at the relay worker (each new connection closes the previous one with
|
|
5
|
+
// "4001: Control replaced") and paired devices land on whichever instance won
|
|
6
|
+
// last — often a dev/worktree instance running different code.
|
|
7
|
+
//
|
|
8
|
+
// The claim file (`relay-host.lock` in the shared data dir) makes the contest
|
|
9
|
+
// deterministic instead of a network race:
|
|
10
|
+
// - an instance only starts its relay host when there is no LIVE claimant
|
|
11
|
+
// (a dead claimant's stale file is ignored);
|
|
12
|
+
// - explicit user intent (creating a pairing link) claims unconditionally —
|
|
13
|
+
// the instance the user is interacting with must be the one devices reach;
|
|
14
|
+
// - a running host that discovers another live process has claimed backs off
|
|
15
|
+
// instead of reconnecting, which is what ends the replace/reconnect fight.
|
|
16
|
+
//
|
|
17
|
+
// This is a cooperative claim, not an OS lock: correctness does not depend on
|
|
18
|
+
// atomicity (the relay worker still enforces a single host); the claim only
|
|
19
|
+
// decides which process KEEPS retrying and which stands down.
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {{
|
|
23
|
+
* lockFilePath: string,
|
|
24
|
+
* fs?: typeof import('node:fs'),
|
|
25
|
+
* process?: NodeJS.Process,
|
|
26
|
+
* logger?: Pick<Console, 'warn'>,
|
|
27
|
+
* }} deps
|
|
28
|
+
*/
|
|
29
|
+
export const createRelayHostLock = ({ lockFilePath, fs, process: proc, logger = console }) => {
|
|
30
|
+
const fsImpl = fs;
|
|
31
|
+
const selfPid = proc.pid;
|
|
32
|
+
|
|
33
|
+
const isPidAlive = (pid) => {
|
|
34
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
35
|
+
try {
|
|
36
|
+
proc.kill(pid, 0);
|
|
37
|
+
return true;
|
|
38
|
+
} catch (error) {
|
|
39
|
+
// EPERM means the process exists but belongs to another user — treat as
|
|
40
|
+
// alive; only ESRCH (no such process) means the claim is stale.
|
|
41
|
+
return error?.code === 'EPERM';
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const readClaim = () => {
|
|
46
|
+
try {
|
|
47
|
+
const raw = fsImpl.readFileSync(lockFilePath, 'utf8');
|
|
48
|
+
const parsed = JSON.parse(raw);
|
|
49
|
+
const pid = Number(parsed?.pid);
|
|
50
|
+
return Number.isInteger(pid) && pid > 0 ? { pid } : null;
|
|
51
|
+
} catch {
|
|
52
|
+
// Missing file or unparsable content: no valid claim.
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const writeClaim = () => {
|
|
58
|
+
try {
|
|
59
|
+
fsImpl.writeFileSync(lockFilePath, JSON.stringify({ pid: selfPid, claimedAt: new Date().toISOString() }));
|
|
60
|
+
return true;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
// An unwritable data dir must not take the relay down with it — fall back
|
|
63
|
+
// to pre-lock behavior (start the host, let the relay worker arbitrate).
|
|
64
|
+
logger.warn(`[Relay] could not write host claim file: ${error?.message ?? error}`);
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** The pid of the current live claimant, or null when the claim is free/stale. */
|
|
70
|
+
const liveClaimantPid = () => {
|
|
71
|
+
const claim = readClaim();
|
|
72
|
+
if (!claim) return null;
|
|
73
|
+
return isPidAlive(claim.pid) ? claim.pid : null;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** Claim unless another LIVE process already holds it. Re-claiming our own is a no-op refresh. */
|
|
77
|
+
const tryClaim = () => {
|
|
78
|
+
const holder = liveClaimantPid();
|
|
79
|
+
if (holder !== null && holder !== selfPid) return false;
|
|
80
|
+
return writeClaim();
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** Unconditional claim — explicit user intent (pairing) overrides any holder. */
|
|
84
|
+
const forceClaim = () => writeClaim();
|
|
85
|
+
|
|
86
|
+
/** True while this process is the live claimant. */
|
|
87
|
+
const holdsClaim = () => liveClaimantPid() === selfPid;
|
|
88
|
+
|
|
89
|
+
/** Release only our own claim; never delete another process's. */
|
|
90
|
+
const release = () => {
|
|
91
|
+
const claim = readClaim();
|
|
92
|
+
if (!claim || claim.pid !== selfPid) return;
|
|
93
|
+
try {
|
|
94
|
+
fsImpl.unlinkSync(lockFilePath);
|
|
95
|
+
} catch {
|
|
96
|
+
// Already gone or unwritable — nothing to do.
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
return { tryClaim, forceClaim, holdsClaim, liveClaimantPid, release };
|
|
101
|
+
};
|