agy-family 0.2.2 → 0.2.3
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 +1 -1
- package/README.zh-CN.md +1 -0
- package/package.json +1 -1
- package/packages/cli/bin/agy-family.mjs +58 -13
- package/packages/cli/src/hook.mjs +61 -4
- package/packages/core/src/account.mjs +461 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/core/src/invite.mjs +20 -1
- package/packages/core/src/sync.mjs +70 -5
- package/packages/server-core/src/index.mjs +145 -17
- package/packages/server-core/src/schema.mjs +17 -1
- package/packages/server-core/src/stats.mjs +25 -3
- package/packages/server-core/src/ui.mjs +1209 -1141
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
// Privacy-preserving Google Family account verification & non-family usage exclusion engine.
|
|
2
|
+
//
|
|
3
|
+
// Design guarantees:
|
|
4
|
+
// 1. Plaintext email addresses NEVER leave the client or appear on public board endpoints;
|
|
5
|
+
// only normalized lowercase SHA-256 hex digests (`expectedEmailHash` / `activeEmailHash`) are compared.
|
|
6
|
+
// 2. Reads local active account email strictly read-only (zero OS Keychain prompts, zero network calls).
|
|
7
|
+
// 3. When a member switches to a non-family Google account (`activeEmailHash !== expectedEmailHash`),
|
|
8
|
+
// deltas accrued during that session are recorded in local `excluded` offsets and omitted from sync,
|
|
9
|
+
// so even switching accounts mid-hour never pollutes family group usage or share percentages.
|
|
10
|
+
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { dirname, join } from 'node:path';
|
|
15
|
+
import { estimateUsageUsd } from './pricing.mjs';
|
|
16
|
+
|
|
17
|
+
const SHA256_HEX_RE = /^[a-f0-9]{64}$/i;
|
|
18
|
+
const EMAIL_BASIC_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
19
|
+
const LEDGER_RETENTION_MS = 35 * 24 * 60 * 60 * 1000;
|
|
20
|
+
const ACTIVE_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
21
|
+
|
|
22
|
+
export function normalizeEmail(rawEmail) {
|
|
23
|
+
const s = String(rawEmail || '').trim().toLowerCase();
|
|
24
|
+
if (!s || !EMAIL_BASIC_RE.test(s)) return '';
|
|
25
|
+
return s;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function isSha256Hex(val) {
|
|
29
|
+
return SHA256_HEX_RE.test(String(val || '').trim());
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function normalizeSha256Hex(val) {
|
|
33
|
+
const s = String(val || '').trim().toLowerCase();
|
|
34
|
+
return SHA256_HEX_RE.test(s) ? s : '';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function hashEmailSha256(rawEmail) {
|
|
38
|
+
const clean = normalizeEmail(rawEmail);
|
|
39
|
+
if (!clean) return null;
|
|
40
|
+
return createHash('sha256').update(clean).digest('hex');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function maskEmailHint(rawEmail) {
|
|
44
|
+
const clean = normalizeEmail(rawEmail);
|
|
45
|
+
if (!clean) return '';
|
|
46
|
+
const at = clean.indexOf('@');
|
|
47
|
+
const local = clean.slice(0, at);
|
|
48
|
+
const domain = clean.slice(at + 1);
|
|
49
|
+
if (local.length <= 1) return `***@${domain}`;
|
|
50
|
+
if (local.length === 2) return `${local[0]}***@${domain}`;
|
|
51
|
+
return `${local.slice(0, 2)}***@${domain}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function decodeJwtEmailUnsafe(jwt) {
|
|
55
|
+
if (typeof jwt !== 'string' || !jwt.includes('.')) return '';
|
|
56
|
+
const parts = jwt.trim().split('.');
|
|
57
|
+
if (parts.length < 2 || !parts[1]) return '';
|
|
58
|
+
try {
|
|
59
|
+
const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
|
60
|
+
return normalizeEmail(claims?.email || '');
|
|
61
|
+
} catch {
|
|
62
|
+
return '';
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function extractEmailFromHookPayload(payload) {
|
|
67
|
+
if (!payload || typeof payload !== 'object') return '';
|
|
68
|
+
const candidate =
|
|
69
|
+
payload.email ||
|
|
70
|
+
payload.user_email ||
|
|
71
|
+
payload.userEmail ||
|
|
72
|
+
payload.account?.email ||
|
|
73
|
+
payload.user?.email ||
|
|
74
|
+
'';
|
|
75
|
+
return normalizeEmail(candidate);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function writeActiveAccountCache(
|
|
79
|
+
emailHash,
|
|
80
|
+
{ home = homedir(), slot = 'any', source = 'detected', now = Date.now() } = {},
|
|
81
|
+
) {
|
|
82
|
+
const cleanHash = normalizeSha256Hex(emailHash);
|
|
83
|
+
if (!cleanHash) return false;
|
|
84
|
+
const cacheFile = join(home, '.config', 'agy-family', 'active-account.json');
|
|
85
|
+
try {
|
|
86
|
+
let existing = {};
|
|
87
|
+
if (existsSync(cacheFile)) {
|
|
88
|
+
try {
|
|
89
|
+
existing = JSON.parse(readFileSync(cacheFile, 'utf8')) || {};
|
|
90
|
+
} catch {
|
|
91
|
+
existing = {};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const entry = { emailHash: cleanHash, source: String(source || 'detected').slice(0, 24), observedAt: now };
|
|
95
|
+
const next = {
|
|
96
|
+
...existing,
|
|
97
|
+
emailHash: cleanHash,
|
|
98
|
+
source: entry.source,
|
|
99
|
+
observedAt: now,
|
|
100
|
+
...(slot === 'desktop' || slot === 'cli' ? { [slot]: entry } : {}),
|
|
101
|
+
};
|
|
102
|
+
mkdirSync(dirname(cacheFile), { recursive: true });
|
|
103
|
+
writeFileSync(cacheFile, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
104
|
+
try {
|
|
105
|
+
chmodSync(cacheFile, 0o600);
|
|
106
|
+
} catch {
|
|
107
|
+
// Ignore chmod errors on non-POSIX filesystems.
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
} catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function readActiveAccountCache(home, now) {
|
|
116
|
+
try {
|
|
117
|
+
const cacheFile = join(home, '.config', 'agy-family', 'active-account.json');
|
|
118
|
+
if (!existsSync(cacheFile)) return { any: '', desktop: '', cli: '' };
|
|
119
|
+
const cached = JSON.parse(readFileSync(cacheFile, 'utf8')) || {};
|
|
120
|
+
const fresh = (entry) =>
|
|
121
|
+
entry &&
|
|
122
|
+
normalizeSha256Hex(entry.emailHash) &&
|
|
123
|
+
now - Number(entry.observedAt || 0) <= ACTIVE_CACHE_TTL_MS
|
|
124
|
+
? normalizeSha256Hex(entry.emailHash)
|
|
125
|
+
: '';
|
|
126
|
+
return {
|
|
127
|
+
any: fresh(cached),
|
|
128
|
+
desktop: fresh(cached.desktop),
|
|
129
|
+
cli: fresh(cached.cli),
|
|
130
|
+
};
|
|
131
|
+
} catch {
|
|
132
|
+
return { any: '', desktop: '', cli: '' };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function defaultIdeStateDbPaths({ home = homedir(), platform = process.platform, env = process.env } = {}) {
|
|
137
|
+
if (platform === 'darwin') {
|
|
138
|
+
return [join(home, 'Library', 'Application Support', 'Antigravity', 'User', 'globalStorage', 'state.vscdb')];
|
|
139
|
+
}
|
|
140
|
+
if (platform === 'win32') {
|
|
141
|
+
const appData = env.APPDATA || join(home, 'AppData', 'Roaming');
|
|
142
|
+
return [join(appData, 'Antigravity', 'User', 'globalStorage', 'state.vscdb')];
|
|
143
|
+
}
|
|
144
|
+
const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
145
|
+
return [join(xdg, 'Antigravity', 'User', 'globalStorage', 'state.vscdb')];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function readEmailFromCliTokenFile(home) {
|
|
149
|
+
const tokPath = join(home, '.gemini', 'jetski-standalone-oauth-token');
|
|
150
|
+
if (!existsSync(tokPath)) return '';
|
|
151
|
+
try {
|
|
152
|
+
let raw = readFileSync(tokPath, 'utf8').trim();
|
|
153
|
+
const prefix = 'go-keyring-base64:';
|
|
154
|
+
if (raw.startsWith(prefix)) {
|
|
155
|
+
raw = Buffer.from(raw.slice(prefix.length), 'base64').toString('utf8').trim();
|
|
156
|
+
}
|
|
157
|
+
const parsed = JSON.parse(raw);
|
|
158
|
+
if (!parsed || typeof parsed !== 'object') return '';
|
|
159
|
+
return (
|
|
160
|
+
normalizeEmail(parsed.id_token_email || parsed.email || parsed.token?.email || '') ||
|
|
161
|
+
decodeJwtEmailUnsafe(parsed.id_token || parsed.token?.id_token || '')
|
|
162
|
+
);
|
|
163
|
+
} catch {
|
|
164
|
+
return '';
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function readEmailFromIdeStateDb(dbPath, sqlJsModule = null) {
|
|
169
|
+
if (!dbPath || !existsSync(dbPath)) return '';
|
|
170
|
+
try {
|
|
171
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
172
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
173
|
+
try {
|
|
174
|
+
const row = db.prepare("SELECT value FROM ItemTable WHERE key = 'antigravityAuthStatus'").get();
|
|
175
|
+
if (row?.value) {
|
|
176
|
+
const parsed = JSON.parse(String(row.value));
|
|
177
|
+
const email = normalizeEmail(parsed?.email || parsed?.account?.email || '');
|
|
178
|
+
if (email) return email;
|
|
179
|
+
}
|
|
180
|
+
} finally {
|
|
181
|
+
try {
|
|
182
|
+
db.close();
|
|
183
|
+
} catch {}
|
|
184
|
+
}
|
|
185
|
+
} catch {
|
|
186
|
+
// Fall through to optional sql.js reader if running inside an Electron extension host or TCC-restricted shell.
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (sqlJsModule && typeof sqlJsModule.Database === 'function') {
|
|
190
|
+
let db;
|
|
191
|
+
try {
|
|
192
|
+
const bytes = readFileSync(dbPath);
|
|
193
|
+
db = new sqlJsModule.Database(bytes);
|
|
194
|
+
const res = db.exec("SELECT value FROM ItemTable WHERE key = 'antigravityAuthStatus'");
|
|
195
|
+
const val = res?.[0]?.values?.[0]?.[0];
|
|
196
|
+
if (val) {
|
|
197
|
+
const parsed = JSON.parse(String(val));
|
|
198
|
+
return normalizeEmail(parsed?.email || parsed?.account?.email || '');
|
|
199
|
+
}
|
|
200
|
+
} catch {
|
|
201
|
+
return '';
|
|
202
|
+
} finally {
|
|
203
|
+
try {
|
|
204
|
+
db?.close();
|
|
205
|
+
} catch {}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return '';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function detectLocalActiveAccountHash({
|
|
212
|
+
home = homedir(),
|
|
213
|
+
clientKind = 'cli',
|
|
214
|
+
hintEmail = '',
|
|
215
|
+
hintEmailHash = '',
|
|
216
|
+
ideStateDbPath = '',
|
|
217
|
+
sqlJsModule = null,
|
|
218
|
+
platform = process.platform,
|
|
219
|
+
env = process.env,
|
|
220
|
+
now = Date.now(),
|
|
221
|
+
} = {}) {
|
|
222
|
+
const explicitHint = normalizeSha256Hex(hintEmailHash) || hashEmailSha256(hintEmail) || '';
|
|
223
|
+
|
|
224
|
+
let ideHash = '';
|
|
225
|
+
let ideSource = '';
|
|
226
|
+
if (ideStateDbPath) {
|
|
227
|
+
ideHash = hashEmailSha256(await readEmailFromIdeStateDb(ideStateDbPath, sqlJsModule)) || '';
|
|
228
|
+
if (ideHash) ideSource = 'ide-state';
|
|
229
|
+
}
|
|
230
|
+
if (!ideHash) {
|
|
231
|
+
for (const candidate of defaultIdeStateDbPaths({ home, platform, env })) {
|
|
232
|
+
ideHash = hashEmailSha256(await readEmailFromIdeStateDb(candidate, sqlJsModule)) || '';
|
|
233
|
+
if (ideHash) {
|
|
234
|
+
ideSource = 'ide-state';
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const cliHash = hashEmailSha256(readEmailFromCliTokenFile(home)) || '';
|
|
241
|
+
const cached = readActiveAccountCache(home, now);
|
|
242
|
+
|
|
243
|
+
const resolvedDesktop = ideHash || cached.desktop || explicitHint || cliHash || cached.any || null;
|
|
244
|
+
const resolvedCli = explicitHint || cliHash || cached.cli || ideHash || cached.any || null;
|
|
245
|
+
|
|
246
|
+
let primaryHash = null;
|
|
247
|
+
let primarySource = 'none';
|
|
248
|
+
if (explicitHint) {
|
|
249
|
+
primaryHash = explicitHint;
|
|
250
|
+
primarySource = 'hint';
|
|
251
|
+
} else if (clientKind === 'extension') {
|
|
252
|
+
if (ideHash) {
|
|
253
|
+
primaryHash = ideHash;
|
|
254
|
+
primarySource = ideSource;
|
|
255
|
+
} else if (cached.desktop) {
|
|
256
|
+
primaryHash = cached.desktop;
|
|
257
|
+
primarySource = 'ide-cache';
|
|
258
|
+
} else if (cliHash) {
|
|
259
|
+
primaryHash = cliHash;
|
|
260
|
+
primarySource = 'cli-token';
|
|
261
|
+
} else if (cached.any) {
|
|
262
|
+
primaryHash = cached.any;
|
|
263
|
+
primarySource = 'hook-cache';
|
|
264
|
+
}
|
|
265
|
+
} else if (cliHash) {
|
|
266
|
+
primaryHash = cliHash;
|
|
267
|
+
primarySource = 'cli-token';
|
|
268
|
+
} else if (ideHash) {
|
|
269
|
+
primaryHash = ideHash;
|
|
270
|
+
primarySource = ideSource;
|
|
271
|
+
} else if (cached.desktop || cached.cli || cached.any) {
|
|
272
|
+
primaryHash = cached.cli || cached.desktop || cached.any;
|
|
273
|
+
primarySource = 'hook-cache';
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
emailHash: primaryHash,
|
|
278
|
+
source: primarySource,
|
|
279
|
+
bySource: {
|
|
280
|
+
desktop: resolvedDesktop,
|
|
281
|
+
cli: resolvedCli,
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function makeRawSnap(b) {
|
|
287
|
+
return {
|
|
288
|
+
in: Math.max(0, Math.round(Number(b.inputTokens) || 0)),
|
|
289
|
+
out: Math.max(0, Math.round(Number(b.outputTokens) || 0)),
|
|
290
|
+
cache: Math.max(0, Math.round(Number(b.cacheReadTokens) || 0)),
|
|
291
|
+
think: Math.max(0, Math.round(Number(b.thinkingTokens) || 0)),
|
|
292
|
+
steps: Math.max(0, Math.round(Number(b.steps) || 0)),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function parseFingerprintSnap(fp) {
|
|
297
|
+
if (typeof fp !== 'string' || !fp) return { in: 0, out: 0, cache: 0, think: 0, steps: 0 };
|
|
298
|
+
const parts = fp.split(':');
|
|
299
|
+
return {
|
|
300
|
+
in: Math.max(0, Math.round(Number(parts[0]) || 0)),
|
|
301
|
+
out: Math.max(0, Math.round(Number(parts[1]) || 0)),
|
|
302
|
+
cache: Math.max(0, Math.round(Number(parts[2]) || 0)),
|
|
303
|
+
think: Math.max(0, Math.round(Number(parts[3]) || 0)),
|
|
304
|
+
steps: Math.max(0, Math.round(Number(parts[4]) || 0)),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function pruneMapByHour(obj, minHourMs) {
|
|
309
|
+
const out = {};
|
|
310
|
+
if (!obj || typeof obj !== 'object') return out;
|
|
311
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
312
|
+
const hourMs = Number(String(k).split('|')[0]);
|
|
313
|
+
if (Number.isFinite(hourMs) && hourMs >= minHourMs && v && typeof v === 'object') {
|
|
314
|
+
out[k] = {
|
|
315
|
+
in: Math.max(0, Number(v.in) || 0),
|
|
316
|
+
out: Math.max(0, Number(v.out) || 0),
|
|
317
|
+
cache: Math.max(0, Number(v.cache) || 0),
|
|
318
|
+
think: Math.max(0, Number(v.think) || 0),
|
|
319
|
+
steps: Math.max(0, Number(v.steps) || 0),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return out;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Filters aggregated hourly buckets against the member's bound Google Family email SHA-256 hash.
|
|
328
|
+
* - `unbound` (no `expectedEmailHash`): passes all buckets through untouched.
|
|
329
|
+
* - `mismatch` (`activeEmailHash` present and != `expectedEmailHash`): accumulates any token/step growth
|
|
330
|
+
* since the last verified snapshot into persistent `excluded` offsets, and omits non-family buckets
|
|
331
|
+
* so non-family account usage is never uploaded.
|
|
332
|
+
* - `verified` (`activeEmailHash === expectedEmailHash`): subtracts accumulated `excluded` offsets per bucket
|
|
333
|
+
* and updates `lastRaw` watermarks, so switching away and switching back within the same hour preserves
|
|
334
|
+
* exact family-only attribution.
|
|
335
|
+
*/
|
|
336
|
+
export function applyAccountAttributionFilter(
|
|
337
|
+
rawBuckets = [],
|
|
338
|
+
{
|
|
339
|
+
expectedEmailHash = '',
|
|
340
|
+
activeEmailHash = '',
|
|
341
|
+
activeBySource = null,
|
|
342
|
+
syncedHashes = null,
|
|
343
|
+
ledger = null,
|
|
344
|
+
now = Date.now(),
|
|
345
|
+
} = {},
|
|
346
|
+
) {
|
|
347
|
+
const expected = normalizeSha256Hex(expectedEmailHash);
|
|
348
|
+
const primaryActive = normalizeSha256Hex(activeEmailHash);
|
|
349
|
+
|
|
350
|
+
if (!expected) {
|
|
351
|
+
return {
|
|
352
|
+
buckets: rawBuckets || [],
|
|
353
|
+
accountStatus: 'unbound',
|
|
354
|
+
pausedByMismatch: false,
|
|
355
|
+
hasMismatchSource: false,
|
|
356
|
+
nextLedger: ledger || null,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const minHourMs = now - LEDGER_RETENTION_MS;
|
|
361
|
+
const validPrev =
|
|
362
|
+
ledger &&
|
|
363
|
+
typeof ledger === 'object' &&
|
|
364
|
+
normalizeSha256Hex(ledger.expectedEmailHash) === expected &&
|
|
365
|
+
Boolean(ledger.initialized);
|
|
366
|
+
|
|
367
|
+
const nextLastRaw = validPrev ? pruneMapByHour(ledger.lastRaw, minHourMs) : {};
|
|
368
|
+
const nextExcluded = validPrev ? pruneMapByHour(ledger.excluded, minHourMs) : {};
|
|
369
|
+
const prevSynced = syncedHashes && typeof syncedHashes === 'object' ? syncedHashes : {};
|
|
370
|
+
|
|
371
|
+
let hasMismatchSource = Boolean(primaryActive && primaryActive !== expected);
|
|
372
|
+
const adjusted = [];
|
|
373
|
+
|
|
374
|
+
for (const b of rawBuckets || []) {
|
|
375
|
+
const key = `${b.hourMs}|${b.source}|${b.model}`;
|
|
376
|
+
const cur = makeRawSnap(b);
|
|
377
|
+
const sourceActive = normalizeSha256Hex(
|
|
378
|
+
activeBySource && typeof activeBySource === 'object' && b.source in activeBySource
|
|
379
|
+
? activeBySource[b.source]
|
|
380
|
+
: primaryActive,
|
|
381
|
+
);
|
|
382
|
+
|
|
383
|
+
if (sourceActive && sourceActive !== expected) {
|
|
384
|
+
hasMismatchSource = true;
|
|
385
|
+
if (!validPrev) {
|
|
386
|
+
const syncedSnap = parseFingerprintSnap(prevSynced[key]);
|
|
387
|
+
nextExcluded[key] = {
|
|
388
|
+
in: Math.max(0, cur.in - syncedSnap.in),
|
|
389
|
+
out: Math.max(0, cur.out - syncedSnap.out),
|
|
390
|
+
cache: Math.max(0, cur.cache - syncedSnap.cache),
|
|
391
|
+
think: Math.max(0, cur.think - syncedSnap.think),
|
|
392
|
+
steps: Math.max(0, cur.steps - syncedSnap.steps),
|
|
393
|
+
};
|
|
394
|
+
} else {
|
|
395
|
+
const prev = nextLastRaw[key] || parseFingerprintSnap(prevSynced[key]);
|
|
396
|
+
const ex = nextExcluded[key] || { in: 0, out: 0, cache: 0, think: 0, steps: 0 };
|
|
397
|
+
nextExcluded[key] = {
|
|
398
|
+
in: ex.in + Math.max(0, cur.in - prev.in),
|
|
399
|
+
out: ex.out + Math.max(0, cur.out - prev.out),
|
|
400
|
+
cache: ex.cache + Math.max(0, cur.cache - prev.cache),
|
|
401
|
+
think: ex.think + Math.max(0, cur.think - prev.think),
|
|
402
|
+
steps: ex.steps + Math.max(0, cur.steps - prev.steps),
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
nextLastRaw[key] = cur;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
nextLastRaw[key] = cur;
|
|
410
|
+
const ex = nextExcluded[key] || { in: 0, out: 0, cache: 0, think: 0, steps: 0 };
|
|
411
|
+
const inputTokens = Math.max(0, cur.in - ex.in);
|
|
412
|
+
const outputTokens = Math.max(0, cur.out - ex.out);
|
|
413
|
+
const cacheReadTokens = Math.max(0, cur.cache - ex.cache);
|
|
414
|
+
const thinkingTokens = Math.max(0, cur.think - ex.think);
|
|
415
|
+
const steps = Math.max(0, cur.steps - ex.steps);
|
|
416
|
+
|
|
417
|
+
if (inputTokens + outputTokens + cacheReadTokens === 0 && steps === 0) continue;
|
|
418
|
+
|
|
419
|
+
adjusted.push({
|
|
420
|
+
hourMs: b.hourMs,
|
|
421
|
+
source: b.source,
|
|
422
|
+
model: b.model,
|
|
423
|
+
inputTokens,
|
|
424
|
+
outputTokens,
|
|
425
|
+
cacheReadTokens,
|
|
426
|
+
thinkingTokens,
|
|
427
|
+
steps: Math.max(1, steps),
|
|
428
|
+
estUsd: estimateUsageUsd({
|
|
429
|
+
model: b.model,
|
|
430
|
+
input: inputTokens,
|
|
431
|
+
output: outputTokens,
|
|
432
|
+
cacheRead: cacheReadTokens,
|
|
433
|
+
}),
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
let accountStatus = 'unknown';
|
|
438
|
+
let pausedByMismatch = false;
|
|
439
|
+
if (primaryActive) {
|
|
440
|
+
if (primaryActive === expected) {
|
|
441
|
+
accountStatus = 'verified';
|
|
442
|
+
} else {
|
|
443
|
+
accountStatus = 'mismatch';
|
|
444
|
+
pausedByMismatch = true;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
return {
|
|
449
|
+
buckets: adjusted,
|
|
450
|
+
accountStatus,
|
|
451
|
+
pausedByMismatch,
|
|
452
|
+
hasMismatchSource,
|
|
453
|
+
nextLedger: {
|
|
454
|
+
expectedEmailHash: expected,
|
|
455
|
+
initialized: true,
|
|
456
|
+
lastRaw: nextLastRaw,
|
|
457
|
+
excluded: nextExcluded,
|
|
458
|
+
updatedAt: now,
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
}
|
|
@@ -36,11 +36,21 @@ export function normalizeBaseUrl(rawUrl) {
|
|
|
36
36
|
return parsed.toString().replace(/\/+$/, '');
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
export function encodeInviteUri({
|
|
39
|
+
export function encodeInviteUri({
|
|
40
|
+
url,
|
|
41
|
+
token,
|
|
42
|
+
memberName = '',
|
|
43
|
+
boardTitle = '',
|
|
44
|
+
viewKey = '',
|
|
45
|
+
expectedEmailHash = '',
|
|
46
|
+
}) {
|
|
40
47
|
const cleanUrl = normalizeBaseUrl(url);
|
|
41
48
|
const cleanToken = String(token || '').trim();
|
|
42
49
|
if (!cleanToken) throw new Error('Invite token is required.');
|
|
43
50
|
const cleanViewKey = String(viewKey || '').trim().slice(0, 120);
|
|
51
|
+
const cleanEmailHash = /^[a-f0-9]{64}$/i.test(String(expectedEmailHash || '').trim())
|
|
52
|
+
? String(expectedEmailHash).trim().toLowerCase()
|
|
53
|
+
: '';
|
|
44
54
|
const payload = {
|
|
45
55
|
v: 1,
|
|
46
56
|
u: cleanUrl,
|
|
@@ -48,6 +58,7 @@ export function encodeInviteUri({ url, token, memberName = '', boardTitle = '',
|
|
|
48
58
|
...(memberName ? { m: String(memberName).trim().slice(0, 40) } : {}),
|
|
49
59
|
...(boardTitle ? { b: String(boardTitle).trim().slice(0, 60) } : {}),
|
|
50
60
|
...(cleanViewKey ? { k: cleanViewKey } : {}),
|
|
61
|
+
...(cleanEmailHash ? { e: cleanEmailHash } : {}),
|
|
51
62
|
};
|
|
52
63
|
return `${INVITE_SCHEME}?d=${toBase64Url(JSON.stringify(payload))}`;
|
|
53
64
|
}
|
|
@@ -73,12 +84,16 @@ export function decodeInviteInput(rawInput) {
|
|
|
73
84
|
throw new Error('Invite URI payload could not be decoded.');
|
|
74
85
|
}
|
|
75
86
|
const viewKey = String(obj.k || obj.viewKey || '').trim();
|
|
87
|
+
const expectedEmailHash = /^[a-f0-9]{64}$/i.test(String(obj.e || obj.expectedEmailHash || '').trim())
|
|
88
|
+
? String(obj.e || obj.expectedEmailHash).trim().toLowerCase()
|
|
89
|
+
: '';
|
|
76
90
|
return {
|
|
77
91
|
url: normalizeBaseUrl(obj.u),
|
|
78
92
|
token: String(obj.t || '').trim(),
|
|
79
93
|
memberName: String(obj.m || '').trim(),
|
|
80
94
|
boardTitle: String(obj.b || '').trim(),
|
|
81
95
|
...(viewKey ? { viewKey } : {}),
|
|
96
|
+
...(expectedEmailHash ? { expectedEmailHash } : {}),
|
|
82
97
|
};
|
|
83
98
|
}
|
|
84
99
|
|
|
@@ -86,12 +101,16 @@ export function decodeInviteInput(rawInput) {
|
|
|
86
101
|
if (text.startsWith('{')) {
|
|
87
102
|
const obj = JSON.parse(text);
|
|
88
103
|
const viewKey = String(obj.viewKey || obj.k || '').trim();
|
|
104
|
+
const expectedEmailHash = /^[a-f0-9]{64}$/i.test(String(obj.expectedEmailHash || obj.e || '').trim())
|
|
105
|
+
? String(obj.expectedEmailHash || obj.e).trim().toLowerCase()
|
|
106
|
+
: '';
|
|
89
107
|
return {
|
|
90
108
|
url: normalizeBaseUrl(obj.url || obj.u),
|
|
91
109
|
token: String(obj.token || obj.t || '').trim(),
|
|
92
110
|
memberName: String(obj.memberName || obj.m || '').trim(),
|
|
93
111
|
boardTitle: String(obj.boardTitle || obj.b || '').trim(),
|
|
94
112
|
...(viewKey ? { viewKey } : {}),
|
|
113
|
+
...(expectedEmailHash ? { expectedEmailHash } : {}),
|
|
95
114
|
};
|
|
96
115
|
}
|
|
97
116
|
|
|
@@ -5,6 +5,11 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'n
|
|
|
5
5
|
import { homedir } from 'node:os';
|
|
6
6
|
import { dirname, join } from 'node:path';
|
|
7
7
|
import { aggregateHourlyBuckets, DEFAULT_LOOKBACK_DAYS } from './buckets.mjs';
|
|
8
|
+
import {
|
|
9
|
+
applyAccountAttributionFilter,
|
|
10
|
+
detectLocalActiveAccountHash,
|
|
11
|
+
normalizeSha256Hex,
|
|
12
|
+
} from './account.mjs';
|
|
8
13
|
import { normalizeBaseUrl } from './invite.mjs';
|
|
9
14
|
import { scanLocalUsage } from './scanner.mjs';
|
|
10
15
|
|
|
@@ -77,13 +82,19 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
|
|
|
77
82
|
export async function buildSyncPayload({
|
|
78
83
|
deviceId,
|
|
79
84
|
clientKind = 'cli',
|
|
80
|
-
clientVersion = '0.2.
|
|
85
|
+
clientVersion = '0.2.3',
|
|
81
86
|
home,
|
|
82
87
|
roots = null,
|
|
83
88
|
sourceFilter = 'all',
|
|
84
89
|
reader = null,
|
|
85
90
|
fileCache = null,
|
|
86
91
|
syncedHashes = null,
|
|
92
|
+
expectedEmailHash = '',
|
|
93
|
+
activeEmailHash = null,
|
|
94
|
+
hintEmail = '',
|
|
95
|
+
ideStateDbPath = '',
|
|
96
|
+
sqlJsModule = null,
|
|
97
|
+
accountLedger = null,
|
|
87
98
|
fullSync = false,
|
|
88
99
|
lookbackDays = DEFAULT_LOOKBACK_DAYS,
|
|
89
100
|
now = Date.now(),
|
|
@@ -92,8 +103,50 @@ export async function buildSyncPayload({
|
|
|
92
103
|
const sinceMs = now - Math.max(1, Number(lookbackDays) || DEFAULT_LOOKBACK_DAYS) * 24 * 60 * 60 * 1000;
|
|
93
104
|
const allBuckets = aggregateHourlyBuckets(scan.entries, { sinceMs, now });
|
|
94
105
|
|
|
106
|
+
const detected =
|
|
107
|
+
activeEmailHash !== null && activeEmailHash !== undefined
|
|
108
|
+
? {
|
|
109
|
+
emailHash: normalizeSha256Hex(activeEmailHash) || null,
|
|
110
|
+
source: 'explicit',
|
|
111
|
+
bySource: {
|
|
112
|
+
desktop: normalizeSha256Hex(activeEmailHash) || null,
|
|
113
|
+
cli: normalizeSha256Hex(activeEmailHash) || null,
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
: await detectLocalActiveAccountHash({
|
|
117
|
+
home,
|
|
118
|
+
clientKind,
|
|
119
|
+
hintEmail,
|
|
120
|
+
ideStateDbPath,
|
|
121
|
+
sqlJsModule,
|
|
122
|
+
now,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const attr = applyAccountAttributionFilter(allBuckets, {
|
|
126
|
+
expectedEmailHash,
|
|
127
|
+
activeEmailHash: detected.emailHash || '',
|
|
128
|
+
activeBySource: detected.bySource,
|
|
129
|
+
syncedHashes,
|
|
130
|
+
ledger: accountLedger,
|
|
131
|
+
now,
|
|
132
|
+
});
|
|
133
|
+
|
|
95
134
|
const useDelta = !fullSync && syncedHashes && typeof syncedHashes === 'object';
|
|
96
|
-
const diff = diffSyncBuckets(
|
|
135
|
+
const diff = diffSyncBuckets(attr.buckets, useDelta ? syncedHashes : null, { fullSync: !useDelta });
|
|
136
|
+
const nextSyncedHashes =
|
|
137
|
+
attr.hasMismatchSource && syncedHashes && typeof syncedHashes === 'object'
|
|
138
|
+
? { ...syncedHashes, ...diff.nextSyncedHashes }
|
|
139
|
+
: diff.nextSyncedHashes;
|
|
140
|
+
|
|
141
|
+
const cleanExpected = normalizeSha256Hex(expectedEmailHash);
|
|
142
|
+
const effectiveReportedHash =
|
|
143
|
+
diff.buckets.length > 0 && cleanExpected && attr.accountStatus === 'mismatch'
|
|
144
|
+
? cleanExpected
|
|
145
|
+
: detected.emailHash || null;
|
|
146
|
+
const effectiveStatus =
|
|
147
|
+
diff.buckets.length > 0 && cleanExpected && attr.accountStatus === 'mismatch'
|
|
148
|
+
? 'verified'
|
|
149
|
+
: attr.accountStatus;
|
|
97
150
|
|
|
98
151
|
const payload = {
|
|
99
152
|
schemaVersion: 1,
|
|
@@ -101,22 +154,34 @@ export async function buildSyncPayload({
|
|
|
101
154
|
deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
|
|
102
155
|
client: {
|
|
103
156
|
kind: clientKind === 'extension' ? 'extension' : 'cli',
|
|
104
|
-
version: String(clientVersion || '0.2.
|
|
157
|
+
version: String(clientVersion || '0.2.3').slice(0, 24),
|
|
158
|
+
},
|
|
159
|
+
account: {
|
|
160
|
+
emailHash: effectiveReportedHash,
|
|
161
|
+
source: detected.source || 'none',
|
|
162
|
+
status: effectiveStatus,
|
|
105
163
|
},
|
|
106
164
|
syncedAt: now,
|
|
107
165
|
lookbackDays: Math.max(1, Number(lookbackDays) || DEFAULT_LOOKBACK_DAYS),
|
|
108
|
-
odometer:
|
|
166
|
+
odometer:
|
|
167
|
+
attr.pausedByMismatch && diff.buckets.length === 0
|
|
168
|
+
? null
|
|
169
|
+
: scan.odometer || { dbFiles: 0, allTimeSteps: 0, allTimeTokens: 0 },
|
|
109
170
|
buckets: diff.buckets,
|
|
110
171
|
};
|
|
111
172
|
|
|
112
173
|
return {
|
|
113
174
|
payload,
|
|
114
175
|
scan,
|
|
115
|
-
nextSyncedHashes
|
|
176
|
+
nextSyncedHashes,
|
|
177
|
+
nextAccountLedger: attr.nextLedger,
|
|
178
|
+
detectedAccount: detected,
|
|
116
179
|
stats: {
|
|
117
180
|
totalBuckets: diff.totalBuckets,
|
|
118
181
|
changedBuckets: diff.changedBuckets,
|
|
119
182
|
deltaSaved: Math.max(0, diff.totalBuckets - diff.changedBuckets),
|
|
183
|
+
accountStatus: effectiveStatus,
|
|
184
|
+
pausedByMismatch: attr.pausedByMismatch && diff.buckets.length === 0,
|
|
120
185
|
},
|
|
121
186
|
};
|
|
122
187
|
}
|