agy-family 0.2.11 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.2.11",
3
+ "version": "0.3.1",
4
4
  "description": "Zero-privacy-leak transparent usage dashboard, /family slash command, and fair-use budget guardrail for Google One / Antigravity family groups.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,7 +47,7 @@ import {
47
47
  writeHostConfig,
48
48
  } from '../src/host.mjs';
49
49
 
50
- const CLI_VERSION = '0.2.11';
50
+ const CLI_VERSION = '0.3.1';
51
51
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
52
52
  const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
53
53
 
@@ -716,7 +716,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
716
716
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
717
717
  deviceId,
718
718
  clientKind: 'cli',
719
- clientVersion: '0.2.11',
719
+ clientVersion: '0.3.1',
720
720
  home,
721
721
  fileCache: cache,
722
722
  syncedHashes: prevHashes,
@@ -82,7 +82,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
82
82
  export async function buildSyncPayload({
83
83
  deviceId,
84
84
  clientKind = 'cli',
85
- clientVersion = '0.2.11',
85
+ clientVersion = '0.3.1',
86
86
  home,
87
87
  roots = null,
88
88
  sourceFilter = 'all',
@@ -149,13 +149,17 @@ export async function buildSyncPayload({
149
149
  ? 'verified'
150
150
  : attr.accountStatus;
151
151
 
152
+ const rawPlat = typeof process !== 'undefined' ? process.platform : '';
153
+ const platformLabel = rawPlat === 'darwin' ? 'macOS' : rawPlat === 'win32' ? 'Windows' : rawPlat === 'linux' ? 'Linux' : '';
154
+
152
155
  const payload = {
153
156
  schemaVersion: 1,
154
157
  syncMode: useDelta ? 'delta' : 'full',
155
158
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
156
159
  client: {
157
160
  kind: clientKind === 'extension' ? 'extension' : 'cli',
158
- version: String(clientVersion || '0.2.11').slice(0, 24),
161
+ version: String(clientVersion || '0.3.1').slice(0, 24),
162
+ ...(platformLabel ? { platform: platformLabel } : {}),
159
163
  },
160
164
  account: {
161
165
  emailHash: effectiveReportedHash,
@@ -9,6 +9,7 @@ import { ensureSchema, MAX_FAMILY_MEMBERS } from './schema.mjs';
9
9
  import {
10
10
  buildBoardCsv,
11
11
  buildBoardPayload,
12
+ buildEffectivePricingTable,
12
13
  buildMemberDetailPayload,
13
14
  checkOfflineMembersAndAlert,
14
15
  computeCreditsReconciliation,
@@ -23,7 +24,7 @@ import {
23
24
  import { FAVICON_SVG, renderDashboardHtml } from './ui.mjs';
24
25
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
25
26
 
26
- export const SERVER_VERSION = '0.2.11';
27
+ export const SERVER_VERSION = '0.3.1';
27
28
  const MAX_BUCKETS_PER_SYNC = 1000;
28
29
  const MAX_DEVICES_PER_MEMBER = 8;
29
30
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -129,9 +130,48 @@ function extractClientIp(request) {
129
130
  if (cfIp) return cfIp.trim().slice(0, 64);
130
131
  const xff = request.headers.get('x-forwarded-for');
131
132
  if (xff) return xff.split(',')[0].trim().slice(0, 64);
133
+ const xri = request.headers.get('x-real-ip');
134
+ if (xri) return xri.trim().slice(0, 64);
132
135
  return 'local';
133
136
  }
134
137
 
138
+ function extractClientGeo(request) {
139
+ const cf = request && typeof request === 'object' && request.cf && typeof request.cf === 'object' ? request.cf : null;
140
+ const country = String(cf?.country || request.headers.get('cf-ipcountry') || '')
141
+ .trim()
142
+ .toUpperCase()
143
+ .slice(0, 8);
144
+ const city = String(cf?.city || '')
145
+ .trim()
146
+ .slice(0, 48);
147
+ return {
148
+ country: country && country !== 'XX' && country !== 'T1' ? country : '',
149
+ city,
150
+ };
151
+ }
152
+
153
+ function normalizeClientPlatform(raw) {
154
+ const s = String(raw || '').trim().toLowerCase();
155
+ if (!s) return '';
156
+ if (s === 'darwin' || s === 'macos' || s === 'mac') return 'macOS';
157
+ if (s === 'win32' || s === 'windows' || s === 'win') return 'Windows';
158
+ if (s === 'linux') return 'Linux';
159
+ return '';
160
+ }
161
+
162
+ const UPSERT_MEMBER_DEVICE_SQL = `INSERT INTO member_devices
163
+ (member_id, device_id, platform, client_kind, client_version, last_ip, last_country, last_city, last_seen_at, first_seen_at)
164
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
165
+ ON CONFLICT (member_id, device_id)
166
+ DO UPDATE SET
167
+ platform = CASE WHEN excluded.platform != '' THEN excluded.platform ELSE member_devices.platform END,
168
+ client_kind = excluded.client_kind,
169
+ client_version = CASE WHEN excluded.client_version != '' THEN excluded.client_version ELSE member_devices.client_version END,
170
+ last_ip = CASE WHEN excluded.last_ip != '' AND excluded.last_ip != 'local' THEN excluded.last_ip ELSE COALESCE(member_devices.last_ip, excluded.last_ip) END,
171
+ last_country = CASE WHEN excluded.last_country != '' THEN excluded.last_country ELSE member_devices.last_country END,
172
+ last_city = CASE WHEN excluded.last_city != '' THEN excluded.last_city ELSE member_devices.last_city END,
173
+ last_seen_at = excluded.last_seen_at`;
174
+
135
175
  async function readJsonBody(request, maxBytes = 512 * 1024) {
136
176
  const text = await request.text();
137
177
  if (text.length > maxBytes) throw new HttpError(413, 'Request payload too large.');
@@ -653,10 +693,28 @@ export function createApp({
653
693
 
654
694
  const clientKind = body.client?.kind === 'extension' ? 'extension' : 'cli';
655
695
  const clientVersion = String(body.client?.version || '').slice(0, 24);
696
+ const clientPlatform = normalizeClientPlatform(body.client?.platform);
697
+ const syncIp = extractClientIp(request);
698
+ const syncGeo = extractClientGeo(request);
656
699
  writeStmts.push({
657
700
  sql: 'UPDATE members SET last_seen_at = ?, last_client_kind = ?, last_client_version = ?, last_email_hash = COALESCE(?, last_email_hash), last_account_status = ? WHERE id = ?',
658
701
  params: [now, clientKind, clientVersion, reportedEmailHash, accountStatus, member.id],
659
702
  });
703
+ writeStmts.push({
704
+ sql: UPSERT_MEMBER_DEVICE_SQL,
705
+ params: [
706
+ member.id,
707
+ deviceId,
708
+ clientPlatform,
709
+ clientKind,
710
+ clientVersion,
711
+ syncIp,
712
+ syncGeo.country,
713
+ syncGeo.city,
714
+ now,
715
+ now,
716
+ ],
717
+ });
660
718
 
661
719
  await runBatchedWrites(db, writeStmts);
662
720
  const accepted = normalizedBuckets.length;
@@ -812,6 +870,31 @@ export function createApp({
812
870
  "SELECT id, name, role, color, quota_pct, expected_email_hash, email_hint, last_account_status, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at, last_seen_at, last_client_kind, last_client_version FROM members ORDER BY CASE WHEN role = 'manager' THEN 0 ELSE 1 END, created_at ASC",
813
871
  );
814
872
  const resolvedQuotas = resolveFamilyQuotas((membersRows || []).filter((m) => m.active));
873
+ let deviceRows = [];
874
+ try {
875
+ deviceRows = await db.all(
876
+ 'SELECT member_id, device_id, platform, client_kind, client_version, last_ip, last_country, last_city, last_seen_at, first_seen_at FROM member_devices ORDER BY last_seen_at DESC',
877
+ );
878
+ } catch {
879
+ deviceRows = [];
880
+ }
881
+ const devicesByMember = new Map();
882
+ for (const d of deviceRows || []) {
883
+ const list = devicesByMember.get(d.member_id) || [];
884
+ list.push({
885
+ deviceId: d.device_id,
886
+ platform: d.platform || '',
887
+ clientKind: d.client_kind || '',
888
+ clientVersion: d.client_version || '',
889
+ lastIp: d.last_ip || '',
890
+ lastCountry: d.last_country || '',
891
+ lastCity: d.last_city || '',
892
+ lastSeenAt: d.last_seen_at || null,
893
+ firstSeenAt: d.first_seen_at || null,
894
+ });
895
+ devicesByMember.set(d.member_id, list);
896
+ }
897
+
815
898
  const members = (membersRows || []).map((m) => {
816
899
  const q = resolvedQuotas.get(m.id);
817
900
  const { expected_email_hash, ...rest } = m;
@@ -821,6 +904,7 @@ export function createApp({
821
904
  account_status: expected_email_hash ? m.last_account_status || 'unknown' : 'unbound',
822
905
  effective_quota_pct: q ? q.quotaPct : 0,
823
906
  is_auto_quota: q ? q.isAutoQuota : m.quota_pct === null || m.quota_pct === undefined,
907
+ devices: devicesByMember.get(m.id) || [],
824
908
  };
825
909
  });
826
910
  const snapshots = await db.all(
@@ -837,12 +921,21 @@ export function createApp({
837
921
  } catch {
838
922
  integrityEvents = [];
839
923
  }
840
- return adminJsonRes({ settings, members, maxMembers: MAX_FAMILY_MEMBERS, snapshots, alerts, integrityEvents });
924
+ return adminJsonRes({
925
+ settings,
926
+ serverVersion: SERVER_VERSION,
927
+ pricingTable: buildEffectivePricingTable(settings),
928
+ members,
929
+ maxMembers: MAX_FAMILY_MEMBERS,
930
+ snapshots,
931
+ alerts,
932
+ integrityEvents,
933
+ });
841
934
  }
842
935
 
843
936
  if (request.method === 'POST' && path === '/api/admin/members') {
844
- const countRow = await db.get('SELECT COUNT(*) AS cnt FROM members');
845
- if ((Number(countRow?.cnt) || 0) >= MAX_FAMILY_MEMBERS) {
937
+ const existingRows = await db.all('SELECT color FROM members');
938
+ if ((existingRows || []).length >= MAX_FAMILY_MEMBERS) {
846
939
  return adminJsonRes(
847
940
  {
848
941
  error: `Google 家庭组最多支持 ${MAX_FAMILY_MEMBERS} 位成员(1 位家庭组管理员 + 5 位家庭成员)。`,
@@ -856,7 +949,10 @@ export function createApp({
856
949
  const name = String(body.name || '').trim().slice(0, 40);
857
950
  if (!name) return adminJsonRes({ error: 'Member name is required.' }, 400);
858
951
  const role = body.role === 'manager' ? 'manager' : 'member';
859
- const color = /^#[0-9a-fA-F]{6}$/.test(String(body.color || '')) ? body.color : '#2383e2';
952
+ const defaultPalette = ['#f54e00', '#1f8a65', '#3b7dd8', '#8b5cf6', '#c08532', '#cf2d56'];
953
+ const usedColors = new Set((existingRows || []).map((r) => String(r.color || '').toLowerCase()));
954
+ const nextAutoColor = defaultPalette.find((c) => !usedColors.has(c)) || defaultPalette[(existingRows || []).length % defaultPalette.length];
955
+ const color = /^#[0-9a-fA-F]{6}$/.test(String(body.color || '')) ? body.color : nextAutoColor;
860
956
  const quotaPct = parseQuotaPctInput(body.quotaPct);
861
957
  const emailParsed = await parseMemberEmailInput(body.email);
862
958
  const expectedEmailHash = emailParsed.action === 'set' ? emailParsed.hash : null;
@@ -1044,6 +1140,7 @@ export function createApp({
1044
1140
  await runBatchedWrites(db, [
1045
1141
  { sql: 'DELETE FROM usage_buckets WHERE member_id = ?', params: [id] },
1046
1142
  { sql: 'DELETE FROM device_odometers WHERE member_id = ?', params: [id] },
1143
+ { sql: 'DELETE FROM member_devices WHERE member_id = ?', params: [id] },
1047
1144
  { sql: 'DELETE FROM integrity_events WHERE member_id = ?', params: [id] },
1048
1145
  { sql: 'DELETE FROM members WHERE id = ?', params: [id] },
1049
1146
  ]);
@@ -85,6 +85,20 @@ export const SCHEMA_STATEMENTS = Object.freeze([
85
85
  )`,
86
86
  `CREATE INDEX IF NOT EXISTS idx_integrity_events_time ON integrity_events (detected_at DESC)`,
87
87
  `CREATE INDEX IF NOT EXISTS idx_integrity_events_member ON integrity_events (member_id, detected_at DESC)`,
88
+ `CREATE TABLE IF NOT EXISTS member_devices (
89
+ member_id TEXT NOT NULL,
90
+ device_id TEXT NOT NULL,
91
+ platform TEXT,
92
+ client_kind TEXT,
93
+ client_version TEXT,
94
+ last_ip TEXT,
95
+ last_country TEXT,
96
+ last_city TEXT,
97
+ last_seen_at INTEGER NOT NULL,
98
+ first_seen_at INTEGER NOT NULL,
99
+ PRIMARY KEY (member_id, device_id)
100
+ )`,
101
+ `CREATE INDEX IF NOT EXISTS idx_member_devices_member ON member_devices (member_id, last_seen_at DESC)`,
88
102
  ]);
89
103
 
90
104
  export const DEFAULT_SETTINGS = Object.freeze({