agy-family 0.2.2 → 0.2.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 +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 +534 -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 -1156
|
@@ -0,0 +1,534 @@
|
|
|
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, statSync, 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 defaultDesktopAppStoragePaths({
|
|
137
|
+
home = homedir(),
|
|
138
|
+
platform = process.platform,
|
|
139
|
+
env = process.env,
|
|
140
|
+
} = {}) {
|
|
141
|
+
if (platform === 'darwin') {
|
|
142
|
+
return [join(home, 'Library', 'Application Support', 'Antigravity', 'app_storage.json')];
|
|
143
|
+
}
|
|
144
|
+
if (platform === 'win32') {
|
|
145
|
+
const appData = env.APPDATA || join(home, 'AppData', 'Roaming');
|
|
146
|
+
return [join(appData, 'Antigravity', 'app_storage.json')];
|
|
147
|
+
}
|
|
148
|
+
const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
149
|
+
return [join(xdg, 'Antigravity', 'app_storage.json')];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function defaultIdeStateDbPaths({ home = homedir(), platform = process.platform, env = process.env } = {}) {
|
|
153
|
+
if (platform === 'darwin') {
|
|
154
|
+
return [join(home, 'Library', 'Application Support', 'Antigravity', 'User', 'globalStorage', 'state.vscdb')];
|
|
155
|
+
}
|
|
156
|
+
if (platform === 'win32') {
|
|
157
|
+
const appData = env.APPDATA || join(home, 'AppData', 'Roaming');
|
|
158
|
+
return [join(appData, 'Antigravity', 'User', 'globalStorage', 'state.vscdb')];
|
|
159
|
+
}
|
|
160
|
+
const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
161
|
+
return [join(xdg, 'Antigravity', 'User', 'globalStorage', 'state.vscdb')];
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function safeMtimeMs(filePath) {
|
|
165
|
+
try {
|
|
166
|
+
return statSync(filePath).mtimeMs || 0;
|
|
167
|
+
} catch {
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function readEmailFromDesktopAppStorage(filePath) {
|
|
173
|
+
if (!filePath || !existsSync(filePath)) return { email: '', mtimeMs: 0 };
|
|
174
|
+
try {
|
|
175
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
176
|
+
if (!parsed || typeof parsed !== 'object') return { email: '', mtimeMs: 0 };
|
|
177
|
+
const email = normalizeEmail(
|
|
178
|
+
parsed['agy.onboarding.lastLoginUsername'] ||
|
|
179
|
+
parsed['agy.auth.email'] ||
|
|
180
|
+
parsed.email ||
|
|
181
|
+
parsed.userEmail ||
|
|
182
|
+
parsed.account?.email ||
|
|
183
|
+
'',
|
|
184
|
+
);
|
|
185
|
+
return { email, mtimeMs: email ? safeMtimeMs(filePath) : 0 };
|
|
186
|
+
} catch {
|
|
187
|
+
return { email: '', mtimeMs: 0 };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function readEmailFromCliTokenFile(home) {
|
|
192
|
+
const tokPath = join(home, '.gemini', 'jetski-standalone-oauth-token');
|
|
193
|
+
if (!existsSync(tokPath)) return { email: '', mtimeMs: 0 };
|
|
194
|
+
try {
|
|
195
|
+
let raw = readFileSync(tokPath, 'utf8').trim();
|
|
196
|
+
const prefix = 'go-keyring-base64:';
|
|
197
|
+
if (raw.startsWith(prefix)) {
|
|
198
|
+
raw = Buffer.from(raw.slice(prefix.length), 'base64').toString('utf8').trim();
|
|
199
|
+
}
|
|
200
|
+
const parsed = JSON.parse(raw);
|
|
201
|
+
if (!parsed || typeof parsed !== 'object') return { email: '', mtimeMs: 0 };
|
|
202
|
+
const email =
|
|
203
|
+
normalizeEmail(parsed.id_token_email || parsed.email || parsed.token?.email || '') ||
|
|
204
|
+
decodeJwtEmailUnsafe(parsed.id_token || parsed.token?.id_token || '');
|
|
205
|
+
return { email, mtimeMs: email ? safeMtimeMs(tokPath) : 0 };
|
|
206
|
+
} catch {
|
|
207
|
+
return { email: '', mtimeMs: 0 };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function readEmailFromIdeStateDb(dbPath, sqlJsModule = null) {
|
|
212
|
+
if (!dbPath || !existsSync(dbPath)) return '';
|
|
213
|
+
try {
|
|
214
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
215
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
216
|
+
try {
|
|
217
|
+
const row = db.prepare("SELECT value FROM ItemTable WHERE key = 'antigravityAuthStatus'").get();
|
|
218
|
+
if (row?.value) {
|
|
219
|
+
const parsed = JSON.parse(String(row.value));
|
|
220
|
+
const email = normalizeEmail(parsed?.email || parsed?.account?.email || '');
|
|
221
|
+
if (email) return email;
|
|
222
|
+
}
|
|
223
|
+
} finally {
|
|
224
|
+
try {
|
|
225
|
+
db.close();
|
|
226
|
+
} catch {}
|
|
227
|
+
}
|
|
228
|
+
} catch {
|
|
229
|
+
// Fall through to optional sql.js reader if running inside an Electron extension host or TCC-restricted shell.
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (sqlJsModule && typeof sqlJsModule.Database === 'function') {
|
|
233
|
+
let db;
|
|
234
|
+
try {
|
|
235
|
+
const bytes = readFileSync(dbPath);
|
|
236
|
+
db = new sqlJsModule.Database(bytes);
|
|
237
|
+
const res = db.exec("SELECT value FROM ItemTable WHERE key = 'antigravityAuthStatus'");
|
|
238
|
+
const val = res?.[0]?.values?.[0]?.[0];
|
|
239
|
+
if (val) {
|
|
240
|
+
const parsed = JSON.parse(String(val));
|
|
241
|
+
return normalizeEmail(parsed?.email || parsed?.account?.email || '');
|
|
242
|
+
}
|
|
243
|
+
} catch {
|
|
244
|
+
return '';
|
|
245
|
+
} finally {
|
|
246
|
+
try {
|
|
247
|
+
db?.close();
|
|
248
|
+
} catch {}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return '';
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export async function detectLocalActiveAccountHash({
|
|
255
|
+
home = homedir(),
|
|
256
|
+
clientKind = 'cli',
|
|
257
|
+
hintEmail = '',
|
|
258
|
+
hintEmailHash = '',
|
|
259
|
+
ideStateDbPath = '',
|
|
260
|
+
sqlJsModule = null,
|
|
261
|
+
platform = process.platform,
|
|
262
|
+
env = process.env,
|
|
263
|
+
now = Date.now(),
|
|
264
|
+
} = {}) {
|
|
265
|
+
const explicitHint = normalizeSha256Hex(hintEmailHash) || hashEmailSha256(hintEmail) || '';
|
|
266
|
+
|
|
267
|
+
let ideHash = '';
|
|
268
|
+
let ideSource = '';
|
|
269
|
+
let ideMtimeMs = 0;
|
|
270
|
+
|
|
271
|
+
// 1. Antigravity 2.0 Desktop App (`app_storage.json` -> `agy.onboarding.lastLoginUsername`) — directly readable by unified CLI!
|
|
272
|
+
for (const appStoragePath of defaultDesktopAppStoragePaths({ home, platform, env })) {
|
|
273
|
+
const res = readEmailFromDesktopAppStorage(appStoragePath);
|
|
274
|
+
const h = hashEmailSha256(res.email) || '';
|
|
275
|
+
if (h) {
|
|
276
|
+
ideHash = h;
|
|
277
|
+
ideSource = 'desktop-app-storage';
|
|
278
|
+
ideMtimeMs = res.mtimeMs;
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// 2. Fallback for Antigravity 1.x VS Code fork (`state.vscdb`)
|
|
284
|
+
if (!ideHash && ideStateDbPath) {
|
|
285
|
+
ideHash = hashEmailSha256(await readEmailFromIdeStateDb(ideStateDbPath, sqlJsModule)) || '';
|
|
286
|
+
if (ideHash) {
|
|
287
|
+
ideSource = 'ide-state';
|
|
288
|
+
ideMtimeMs = safeMtimeMs(ideStateDbPath);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (!ideHash) {
|
|
292
|
+
for (const candidate of defaultIdeStateDbPaths({ home, platform, env })) {
|
|
293
|
+
ideHash = hashEmailSha256(await readEmailFromIdeStateDb(candidate, sqlJsModule)) || '';
|
|
294
|
+
if (ideHash) {
|
|
295
|
+
ideSource = 'ide-state';
|
|
296
|
+
ideMtimeMs = safeMtimeMs(candidate);
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const cliInfo = readEmailFromCliTokenFile(home);
|
|
303
|
+
const cliHash = hashEmailSha256(cliInfo.email) || '';
|
|
304
|
+
const cliMtimeMs = cliInfo.mtimeMs;
|
|
305
|
+
const cached = readActiveAccountCache(home, now);
|
|
306
|
+
|
|
307
|
+
const resolvedDesktop = ideHash || cached.desktop || explicitHint || cliHash || cached.any || null;
|
|
308
|
+
const resolvedCli = explicitHint || cliHash || cached.cli || ideHash || cached.any || null;
|
|
309
|
+
|
|
310
|
+
let primaryHash = null;
|
|
311
|
+
let primarySource = 'none';
|
|
312
|
+
if (explicitHint) {
|
|
313
|
+
primaryHash = explicitHint;
|
|
314
|
+
primarySource = 'hint';
|
|
315
|
+
} else if (clientKind === 'extension') {
|
|
316
|
+
if (ideHash) {
|
|
317
|
+
primaryHash = ideHash;
|
|
318
|
+
primarySource = ideSource;
|
|
319
|
+
} else if (cached.desktop) {
|
|
320
|
+
primaryHash = cached.desktop;
|
|
321
|
+
primarySource = 'ide-cache';
|
|
322
|
+
} else if (cliHash) {
|
|
323
|
+
primaryHash = cliHash;
|
|
324
|
+
primarySource = 'cli-token';
|
|
325
|
+
} else if (cached.any) {
|
|
326
|
+
primaryHash = cached.any;
|
|
327
|
+
primarySource = 'hook-cache';
|
|
328
|
+
}
|
|
329
|
+
} else if (cliHash && ideHash) {
|
|
330
|
+
// Unified CLI covers BOTH Desktop IDE and agy CLI: prefer whichever auth file was updated most recently
|
|
331
|
+
if (ideMtimeMs > cliMtimeMs) {
|
|
332
|
+
primaryHash = ideHash;
|
|
333
|
+
primarySource = ideSource;
|
|
334
|
+
} else {
|
|
335
|
+
primaryHash = cliHash;
|
|
336
|
+
primarySource = 'cli-token';
|
|
337
|
+
}
|
|
338
|
+
} else if (cliHash) {
|
|
339
|
+
primaryHash = cliHash;
|
|
340
|
+
primarySource = 'cli-token';
|
|
341
|
+
} else if (ideHash) {
|
|
342
|
+
primaryHash = ideHash;
|
|
343
|
+
primarySource = ideSource;
|
|
344
|
+
} else if (cached.desktop || cached.cli || cached.any) {
|
|
345
|
+
primaryHash = cached.cli || cached.desktop || cached.any;
|
|
346
|
+
primarySource = 'hook-cache';
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
emailHash: primaryHash,
|
|
351
|
+
source: primarySource,
|
|
352
|
+
bySource: {
|
|
353
|
+
desktop: resolvedDesktop,
|
|
354
|
+
cli: resolvedCli,
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function makeRawSnap(b) {
|
|
360
|
+
return {
|
|
361
|
+
in: Math.max(0, Math.round(Number(b.inputTokens) || 0)),
|
|
362
|
+
out: Math.max(0, Math.round(Number(b.outputTokens) || 0)),
|
|
363
|
+
cache: Math.max(0, Math.round(Number(b.cacheReadTokens) || 0)),
|
|
364
|
+
think: Math.max(0, Math.round(Number(b.thinkingTokens) || 0)),
|
|
365
|
+
steps: Math.max(0, Math.round(Number(b.steps) || 0)),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function parseFingerprintSnap(fp) {
|
|
370
|
+
if (typeof fp !== 'string' || !fp) return { in: 0, out: 0, cache: 0, think: 0, steps: 0 };
|
|
371
|
+
const parts = fp.split(':');
|
|
372
|
+
return {
|
|
373
|
+
in: Math.max(0, Math.round(Number(parts[0]) || 0)),
|
|
374
|
+
out: Math.max(0, Math.round(Number(parts[1]) || 0)),
|
|
375
|
+
cache: Math.max(0, Math.round(Number(parts[2]) || 0)),
|
|
376
|
+
think: Math.max(0, Math.round(Number(parts[3]) || 0)),
|
|
377
|
+
steps: Math.max(0, Math.round(Number(parts[4]) || 0)),
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function pruneMapByHour(obj, minHourMs) {
|
|
382
|
+
const out = {};
|
|
383
|
+
if (!obj || typeof obj !== 'object') return out;
|
|
384
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
385
|
+
const hourMs = Number(String(k).split('|')[0]);
|
|
386
|
+
if (Number.isFinite(hourMs) && hourMs >= minHourMs && v && typeof v === 'object') {
|
|
387
|
+
out[k] = {
|
|
388
|
+
in: Math.max(0, Number(v.in) || 0),
|
|
389
|
+
out: Math.max(0, Number(v.out) || 0),
|
|
390
|
+
cache: Math.max(0, Number(v.cache) || 0),
|
|
391
|
+
think: Math.max(0, Number(v.think) || 0),
|
|
392
|
+
steps: Math.max(0, Number(v.steps) || 0),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return out;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Filters aggregated hourly buckets against the member's bound Google Family email SHA-256 hash.
|
|
401
|
+
* - `unbound` (no `expectedEmailHash`): passes all buckets through untouched.
|
|
402
|
+
* - `mismatch` (`activeEmailHash` present and != `expectedEmailHash`): accumulates any token/step growth
|
|
403
|
+
* since the last verified snapshot into persistent `excluded` offsets, and omits non-family buckets
|
|
404
|
+
* so non-family account usage is never uploaded.
|
|
405
|
+
* - `verified` (`activeEmailHash === expectedEmailHash`): subtracts accumulated `excluded` offsets per bucket
|
|
406
|
+
* and updates `lastRaw` watermarks, so switching away and switching back within the same hour preserves
|
|
407
|
+
* exact family-only attribution.
|
|
408
|
+
*/
|
|
409
|
+
export function applyAccountAttributionFilter(
|
|
410
|
+
rawBuckets = [],
|
|
411
|
+
{
|
|
412
|
+
expectedEmailHash = '',
|
|
413
|
+
activeEmailHash = '',
|
|
414
|
+
activeBySource = null,
|
|
415
|
+
syncedHashes = null,
|
|
416
|
+
ledger = null,
|
|
417
|
+
now = Date.now(),
|
|
418
|
+
} = {},
|
|
419
|
+
) {
|
|
420
|
+
const expected = normalizeSha256Hex(expectedEmailHash);
|
|
421
|
+
const primaryActive = normalizeSha256Hex(activeEmailHash);
|
|
422
|
+
|
|
423
|
+
if (!expected) {
|
|
424
|
+
return {
|
|
425
|
+
buckets: rawBuckets || [],
|
|
426
|
+
accountStatus: 'unbound',
|
|
427
|
+
pausedByMismatch: false,
|
|
428
|
+
hasMismatchSource: false,
|
|
429
|
+
nextLedger: ledger || null,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const minHourMs = now - LEDGER_RETENTION_MS;
|
|
434
|
+
const validPrev =
|
|
435
|
+
ledger &&
|
|
436
|
+
typeof ledger === 'object' &&
|
|
437
|
+
normalizeSha256Hex(ledger.expectedEmailHash) === expected &&
|
|
438
|
+
Boolean(ledger.initialized);
|
|
439
|
+
|
|
440
|
+
const nextLastRaw = validPrev ? pruneMapByHour(ledger.lastRaw, minHourMs) : {};
|
|
441
|
+
const nextExcluded = validPrev ? pruneMapByHour(ledger.excluded, minHourMs) : {};
|
|
442
|
+
const prevSynced = syncedHashes && typeof syncedHashes === 'object' ? syncedHashes : {};
|
|
443
|
+
|
|
444
|
+
let hasMismatchSource = Boolean(primaryActive && primaryActive !== expected);
|
|
445
|
+
const adjusted = [];
|
|
446
|
+
|
|
447
|
+
for (const b of rawBuckets || []) {
|
|
448
|
+
const key = `${b.hourMs}|${b.source}|${b.model}`;
|
|
449
|
+
const cur = makeRawSnap(b);
|
|
450
|
+
const sourceActive = normalizeSha256Hex(
|
|
451
|
+
activeBySource && typeof activeBySource === 'object' && b.source in activeBySource
|
|
452
|
+
? activeBySource[b.source]
|
|
453
|
+
: primaryActive,
|
|
454
|
+
);
|
|
455
|
+
|
|
456
|
+
if (sourceActive && sourceActive !== expected) {
|
|
457
|
+
hasMismatchSource = true;
|
|
458
|
+
if (!validPrev) {
|
|
459
|
+
const syncedSnap = parseFingerprintSnap(prevSynced[key]);
|
|
460
|
+
nextExcluded[key] = {
|
|
461
|
+
in: Math.max(0, cur.in - syncedSnap.in),
|
|
462
|
+
out: Math.max(0, cur.out - syncedSnap.out),
|
|
463
|
+
cache: Math.max(0, cur.cache - syncedSnap.cache),
|
|
464
|
+
think: Math.max(0, cur.think - syncedSnap.think),
|
|
465
|
+
steps: Math.max(0, cur.steps - syncedSnap.steps),
|
|
466
|
+
};
|
|
467
|
+
} else {
|
|
468
|
+
const prev = nextLastRaw[key] || parseFingerprintSnap(prevSynced[key]);
|
|
469
|
+
const ex = nextExcluded[key] || { in: 0, out: 0, cache: 0, think: 0, steps: 0 };
|
|
470
|
+
nextExcluded[key] = {
|
|
471
|
+
in: ex.in + Math.max(0, cur.in - prev.in),
|
|
472
|
+
out: ex.out + Math.max(0, cur.out - prev.out),
|
|
473
|
+
cache: ex.cache + Math.max(0, cur.cache - prev.cache),
|
|
474
|
+
think: ex.think + Math.max(0, cur.think - prev.think),
|
|
475
|
+
steps: ex.steps + Math.max(0, cur.steps - prev.steps),
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
nextLastRaw[key] = cur;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
nextLastRaw[key] = cur;
|
|
483
|
+
const ex = nextExcluded[key] || { in: 0, out: 0, cache: 0, think: 0, steps: 0 };
|
|
484
|
+
const inputTokens = Math.max(0, cur.in - ex.in);
|
|
485
|
+
const outputTokens = Math.max(0, cur.out - ex.out);
|
|
486
|
+
const cacheReadTokens = Math.max(0, cur.cache - ex.cache);
|
|
487
|
+
const thinkingTokens = Math.max(0, cur.think - ex.think);
|
|
488
|
+
const steps = Math.max(0, cur.steps - ex.steps);
|
|
489
|
+
|
|
490
|
+
if (inputTokens + outputTokens + cacheReadTokens === 0 && steps === 0) continue;
|
|
491
|
+
|
|
492
|
+
adjusted.push({
|
|
493
|
+
hourMs: b.hourMs,
|
|
494
|
+
source: b.source,
|
|
495
|
+
model: b.model,
|
|
496
|
+
inputTokens,
|
|
497
|
+
outputTokens,
|
|
498
|
+
cacheReadTokens,
|
|
499
|
+
thinkingTokens,
|
|
500
|
+
steps: Math.max(1, steps),
|
|
501
|
+
estUsd: estimateUsageUsd({
|
|
502
|
+
model: b.model,
|
|
503
|
+
input: inputTokens,
|
|
504
|
+
output: outputTokens,
|
|
505
|
+
cacheRead: cacheReadTokens,
|
|
506
|
+
}),
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
let accountStatus = 'unknown';
|
|
511
|
+
let pausedByMismatch = false;
|
|
512
|
+
if (primaryActive) {
|
|
513
|
+
if (primaryActive === expected) {
|
|
514
|
+
accountStatus = 'verified';
|
|
515
|
+
} else {
|
|
516
|
+
accountStatus = 'mismatch';
|
|
517
|
+
pausedByMismatch = true;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
return {
|
|
522
|
+
buckets: adjusted,
|
|
523
|
+
accountStatus,
|
|
524
|
+
pausedByMismatch,
|
|
525
|
+
hasMismatchSource,
|
|
526
|
+
nextLedger: {
|
|
527
|
+
expectedEmailHash: expected,
|
|
528
|
+
initialized: true,
|
|
529
|
+
lastRaw: nextLastRaw,
|
|
530
|
+
excluded: nextExcluded,
|
|
531
|
+
updatedAt: now,
|
|
532
|
+
},
|
|
533
|
+
};
|
|
534
|
+
}
|
|
@@ -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
|
|