agy-family 0.4.0 → 0.5.0

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.4.0",
3
+ "version": "0.5.0",
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",
@@ -9,6 +9,7 @@ process.emitWarning = function (warning, ...args) {
9
9
  return _origEmitWarning.call(this, warning, ...args);
10
10
  };
11
11
 
12
+ import { spawn } from 'node:child_process';
12
13
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
13
14
  import { homedir, userInfo } from 'node:os';
14
15
  import { dirname, join, resolve } from 'node:path';
@@ -32,6 +33,7 @@ import {
32
33
  readMasterConfig,
33
34
  refreshAgyBarAliasQuota,
34
35
  removeMasterConfig,
36
+ requestWebLoginTicket,
35
37
  shouldAutoRefreshMasterQuota,
36
38
  syncLocalPricingCache,
37
39
  writeActiveAccountCache,
@@ -59,7 +61,7 @@ import {
59
61
  writeHostConfig,
60
62
  } from '../src/host.mjs';
61
63
 
62
- const CLI_VERSION = '0.4.0';
64
+ const CLI_VERSION = '0.5.0';
63
65
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
64
66
  const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
65
67
 
@@ -140,6 +142,8 @@ One CLI for both joining a family group ("上车") and hosting your own board ("
140
142
  Join a Family Group (Member):
141
143
  agy-family join <agyfam://join?...> [--no-hook] [--daemon]
142
144
  Join a Google Family Group board & enable /family in IDE + CLI
145
+ agy-family open [--link] [--readonly] [--ttl 60]
146
+ Open the family board in your browser passwordlessly via a one-time CLI ticket
143
147
  agy-family sync [--dry-run] [--watch] [--full] [--quiet]
144
148
  Sync local Desktop IDE + CLI numeric usage (delta by default)
145
149
  agy-family status [--period today|7d|cycle|30d]
@@ -167,6 +171,22 @@ Privacy guarantee:
167
171
  Prompts, replies, code, file paths, and Google credentials are NEVER read or uploaded.`);
168
172
  }
169
173
 
174
+ function openUrlInSystemBrowser(targetUrl, platform = process.platform) {
175
+ if (platform === 'darwin') {
176
+ const child = spawn('open', [targetUrl], { detached: true, stdio: 'ignore' });
177
+ child.unref();
178
+ return true;
179
+ }
180
+ if (platform === 'win32') {
181
+ const child = spawn('cmd', ['/c', 'start', '', targetUrl], { detached: true, stdio: 'ignore', windowsHide: true });
182
+ child.unref();
183
+ return true;
184
+ }
185
+ const child = spawn('xdg-open', [targetUrl], { detached: true, stdio: 'ignore' });
186
+ child.unref();
187
+ return true;
188
+ }
189
+
170
190
  function formatMasterQuotaLine(mq) {
171
191
  if (!mq || !mq.configured) return '';
172
192
  const fmtSlot = (pct, resetAt) => {
@@ -554,9 +574,55 @@ async function main() {
554
574
  return;
555
575
  }
556
576
 
577
+ if (cmd === 'open') {
578
+ const printLinkOnly = args.includes('--link') || args.includes('--print-link') || args.includes('--url-only');
579
+ const readonly = args.includes('--readonly') || args.includes('--member');
580
+ const ttlFlag = readFlag(args, '--ttl');
581
+ const ttlSec = ttlFlag ? Number(ttlFlag) || 60 : printLinkOnly ? 300 : 60;
582
+ const urlOverride = readFlag(args, '--url');
583
+ const adminKeyOverride = readFlag(args, '--admin-key');
584
+
585
+ const host = readHostConfig();
586
+ const cfg = getOrCreateClientConfig();
587
+ const targetUrl = (urlOverride || host?.url || cfg?.url || '').replace(/\/+$/, '');
588
+ if (!targetUrl) {
589
+ console.error('Not joined or linked to any family board yet. Run "agy-family join <invite>" or "agy-family deploy".');
590
+ process.exit(1);
591
+ }
592
+
593
+ const hostMatches = Boolean(host?.url && host.url.replace(/\/+$/, '') === targetUrl && host.adminKey);
594
+ const clientMatches = Boolean(cfg?.url && cfg.url.replace(/\/+$/, '') === targetUrl && cfg.token);
595
+ const useAdminKey = readonly ? '' : (adminKeyOverride || (hostMatches ? host.adminKey : ''));
596
+ const useToken = clientMatches ? cfg.token : (!useAdminKey && cfg?.token ? cfg.token : '');
597
+
598
+ const res = await requestWebLoginTicket({
599
+ url: targetUrl,
600
+ token: useToken,
601
+ adminKey: useAdminKey,
602
+ readonly,
603
+ ttlSec,
604
+ });
605
+
606
+ const roleLabel = res.scope === 'admin'
607
+ ? `admin${res.memberName ? ` + ${res.memberName}` : ''}`
608
+ : (res.memberName || 'member');
609
+ if (printLinkOnly) {
610
+ console.log(`One-time login link (${roleLabel}, valid ${res.expiresInSec}s, single use):`);
611
+ console.log(res.enterUrl);
612
+ return;
613
+ }
614
+
615
+ openUrlInSystemBrowser(res.enterUrl);
616
+ console.log(`✓ Opened family board in browser (${roleLabel}, one-time ticket valid ${res.expiresInSec}s)`);
617
+ console.log(` Board URL : ${targetUrl}`);
618
+ return;
619
+ }
620
+
557
621
  if (cmd === 'status') {
558
622
  const cfg = getOrCreateClientConfig();
559
- if (!cfg.url) {
623
+ const host = readHostConfig();
624
+ const targetUrl = cfg.url || host?.url || '';
625
+ if (!targetUrl) {
560
626
  console.error('Not joined to any family group yet. Run: agy-family join <agyfam://join?...>');
561
627
  process.exit(1);
562
628
  }
@@ -564,7 +630,14 @@ async function main() {
564
630
  const period = pIdx >= 0 ? args[pIdx + 1] || 'today' : 'today';
565
631
  const kIdx = args.indexOf('--view-key');
566
632
  const viewKey = kIdx >= 0 ? args[kIdx + 1] || '' : cfg.viewKey || '';
567
- const board = await fetchBoardSummary({ url: cfg.url, viewKey, period });
633
+ const hostMatches = Boolean(host?.url && host.url.replace(/\/+$/, '') === targetUrl.replace(/\/+$/, '') && host.adminKey);
634
+ const board = await fetchBoardSummary({
635
+ url: targetUrl,
636
+ viewKey,
637
+ token: cfg.token || '',
638
+ adminKey: hostMatches ? host.adminKey : '',
639
+ period,
640
+ });
568
641
  const s = board.summary || {};
569
642
  const headerExtra =
570
643
  s.quotaMode === 'pool'
@@ -18,6 +18,7 @@ import {
18
18
  getOrCreateSharedDeviceId,
19
19
  hashEmailSha256,
20
20
  pushSyncPayload,
21
+ requestWebLoginTicket,
21
22
  writeActiveAccountCache,
22
23
  } from '../../core/src/index.mjs';
23
24
 
@@ -404,6 +405,11 @@ export function parseFamilySlashCommand(rawInput) {
404
405
  if (flag && flag !== '--full' && flag !== 'full') return null;
405
406
  return { kind: 'sync', fullSync: Boolean(flag) };
406
407
  }
408
+ if (sub === 'open' && rest.length <= 2) {
409
+ const flag = rest[1]?.toLowerCase();
410
+ if (flag && flag !== '--link' && flag !== 'link') return null;
411
+ return { kind: 'open', linkOnly: Boolean(flag) };
412
+ }
407
413
  if (sub === 'audit' && rest.length === 1) {
408
414
  return { kind: 'audit' };
409
415
  }
@@ -620,7 +626,8 @@ export async function handlePreInvocation(
620
626
  [
621
627
  '### `/family` 指令速查 *(0 tokens)*',
622
628
  '',
623
- '- `/family` 或 `/family 7d` / `/family cycle` / `/family 30d` — 查看家庭组用量排行与个人额度进度',
629
+ '- `/family` 或 `/family 7d` / `/family cycle` / `/family 30d` — 查看家庭组用量排行与主号订阅余量',
630
+ '- `/family open` — 生成一次性免密登录链接打开网页看板(无需任何密码)',
624
631
  '- `/family sync` 或 `/family sync --full` — 立即增量/全量同步本机 IDE + CLI 用量',
625
632
  '- `/family audit` — 查看最近一次上报的脱敏 JSON(隐私审计)',
626
633
  '- `/family join agyfam://join?d=...` — 粘贴邀请码加入或切换家庭组',
@@ -684,7 +691,51 @@ export async function handlePreInvocation(
684
691
  }
685
692
 
686
693
  const cfg = readJsonSafe(cfgPath);
694
+ const hostCfg = readJsonSafe(join(clientConfigDir(home), 'host.json'));
695
+ const effectiveUrl = cfg?.url || hostCfg?.url || '';
696
+ const effectiveToken = cfg?.token || '';
697
+ const effectiveAdminKey =
698
+ hostCfg?.url && effectiveUrl && hostCfg.url.replace(/\/+$/, '') === effectiveUrl.replace(/\/+$/, '')
699
+ ? hostCfg.adminKey || ''
700
+ : '';
701
+
702
+ if (cmd.kind === 'open') {
703
+ if (!effectiveUrl || (!effectiveToken && !effectiveAdminKey)) {
704
+ return buildZeroTokenMarkdownResponse(
705
+ '尚未加入家庭组。请粘贴家庭组管理员发来的邀请码执行:\n\n`/family join agyfam://join?d=...`',
706
+ );
707
+ }
708
+ try {
709
+ const ticketRes = await requestWebLoginTicket({
710
+ url: effectiveUrl,
711
+ token: effectiveToken,
712
+ adminKey: effectiveAdminKey,
713
+ ttlSec: 120,
714
+ fetchFn,
715
+ });
716
+ const roleNote = ticketRes.scope === 'admin' ? '管理员免密会话' : '成员免密会话';
717
+ return buildZeroTokenMarkdownResponse(
718
+ `### 一次性免密登录链接(${roleNote} · ${ticketRes.expiresInSec}s 单次有效 · 0 tokens)\n\n${ticketRes.enterUrl}\n\n也可在终端直接运行 \`agy-family open\` 自动拉起浏览器。`,
719
+ );
720
+ } catch (err) {
721
+ return buildZeroTokenMarkdownResponse(`❌ 无法签发一次性登录票据:${err?.message || err}`);
722
+ }
723
+ }
724
+
687
725
  if (!cfg?.url || !cfg?.token) {
726
+ if (effectiveUrl && effectiveAdminKey && cmd.kind === 'status') {
727
+ try {
728
+ const board = await fetchBoardSummary({
729
+ url: effectiveUrl,
730
+ period: cmd.period,
731
+ adminKey: effectiveAdminKey,
732
+ fetchFn,
733
+ });
734
+ return buildZeroTokenMarkdownResponse(formatStatusMarkdown(board, { url: effectiveUrl }));
735
+ } catch (err) {
736
+ return buildZeroTokenMarkdownResponse(`❌ 无法拉取家庭组看板(${effectiveUrl}):${err?.message || err}`);
737
+ }
738
+ }
688
739
  return buildZeroTokenMarkdownResponse(
689
740
  '尚未加入家庭组。请粘贴家庭组管理员发来的邀请码执行:\n\n`/family join agyfam://join?d=...`',
690
741
  );
@@ -712,7 +763,14 @@ export async function handlePreInvocation(
712
763
 
713
764
  // Default: /family [today|7d|cycle|30d]
714
765
  try {
715
- const board = await fetchBoardSummary({ url: cfg.url, period: cmd.period, viewKey: cfg.viewKey || '', fetchFn });
766
+ const board = await fetchBoardSummary({
767
+ url: cfg.url,
768
+ period: cmd.period,
769
+ viewKey: cfg.viewKey || '',
770
+ token: cfg.token || '',
771
+ adminKey: effectiveAdminKey,
772
+ fetchFn,
773
+ });
716
774
  return buildZeroTokenMarkdownResponse(formatStatusMarkdown(board, cfg));
717
775
  } catch (err) {
718
776
  return buildZeroTokenMarkdownResponse(`❌ 无法拉取家庭组看板(${cfg.url}):${err?.message || err}`);
@@ -736,7 +794,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
736
794
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
737
795
  deviceId,
738
796
  clientKind: 'cli',
739
- clientVersion: '0.4.0',
797
+ clientVersion: '0.5.0',
740
798
  home,
741
799
  fileCache: cache,
742
800
  syncedHashes: prevHashes,
@@ -83,7 +83,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
83
83
  export async function buildSyncPayload({
84
84
  deviceId,
85
85
  clientKind = 'cli',
86
- clientVersion = '0.4.0',
86
+ clientVersion = '0.5.0',
87
87
  home,
88
88
  roots = null,
89
89
  sourceFilter = 'all',
@@ -164,7 +164,7 @@ export async function buildSyncPayload({
164
164
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
165
165
  client: {
166
166
  kind: clientKind === 'extension' ? 'extension' : 'cli',
167
- version: String(clientVersion || '0.4.0').slice(0, 24),
167
+ version: String(clientVersion || '0.5.0').slice(0, 24),
168
168
  ...(platformLabel ? { platform: platformLabel } : {}),
169
169
  },
170
170
  account: {
@@ -228,15 +228,27 @@ export async function pushSyncPayload({ url, token, payload, fetchFn = globalThi
228
228
  }
229
229
  }
230
230
 
231
- export async function fetchBoardSummary({ url, viewKey = '', period = 'today', fetchFn = globalThis.fetch, timeoutMs = 10_000 } = {}) {
231
+ export async function fetchBoardSummary({
232
+ url,
233
+ viewKey = '',
234
+ token = '',
235
+ adminKey = '',
236
+ period = 'today',
237
+ fetchFn = globalThis.fetch,
238
+ timeoutMs = 10_000,
239
+ } = {}) {
232
240
  const base = normalizeBaseUrl(url);
233
241
  const qs = new URLSearchParams({ period });
234
242
  if (viewKey) qs.set('key', viewKey);
243
+ const headers = {};
244
+ if (token) headers.Authorization = `Bearer ${String(token).trim()}`;
245
+ if (adminKey) headers['X-Admin-Key'] = String(adminKey).trim();
235
246
  const controller = new AbortController();
236
247
  const timer = setTimeout(() => controller.abort(), timeoutMs);
237
248
  try {
238
249
  const res = await fetchFn(`${base}/api/board?${qs.toString()}`, {
239
250
  method: 'GET',
251
+ headers,
240
252
  signal: controller.signal,
241
253
  });
242
254
  const json = await res.json();
@@ -246,3 +258,44 @@ export async function fetchBoardSummary({ url, viewKey = '', period = 'today', f
246
258
  clearTimeout(timer);
247
259
  }
248
260
  }
261
+
262
+ export async function requestWebLoginTicket({
263
+ url,
264
+ token = '',
265
+ adminKey = '',
266
+ readonly = false,
267
+ ttlSec = 60,
268
+ fetchFn = globalThis.fetch,
269
+ timeoutMs = 10_000,
270
+ } = {}) {
271
+ const base = normalizeBaseUrl(url);
272
+ const headers = { 'Content-Type': 'application/json' };
273
+ if (token) headers.Authorization = `Bearer ${String(token).trim()}`;
274
+ if (adminKey) headers['X-Admin-Key'] = String(adminKey).trim();
275
+ if (!headers.Authorization && !headers['X-Admin-Key']) {
276
+ throw new Error('Not joined or linked to any family board. Run "agy-family join <invite>" or "agy-family host link".');
277
+ }
278
+ const controller = new AbortController();
279
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
280
+ try {
281
+ const res = await fetchFn(`${base}/api/auth/ticket`, {
282
+ method: 'POST',
283
+ headers,
284
+ body: JSON.stringify({ readonly: Boolean(readonly), ttlSec }),
285
+ signal: controller.signal,
286
+ });
287
+ const text = await res.text();
288
+ let json = null;
289
+ try {
290
+ json = JSON.parse(text);
291
+ } catch {
292
+ json = null;
293
+ }
294
+ if (!res.ok) {
295
+ throw new Error(json?.error || `Ticket request failed (HTTP ${res.status}): ${text.slice(0, 160)}`);
296
+ }
297
+ return json;
298
+ } finally {
299
+ clearTimeout(timer);
300
+ }
301
+ }
@@ -26,7 +26,7 @@ import {
26
26
  import { FAVICON_SVG, renderDashboardHtml } from './ui.mjs';
27
27
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
28
28
 
29
- export const SERVER_VERSION = '0.4.0';
29
+ export const SERVER_VERSION = '0.5.0';
30
30
  const MAX_BUCKETS_PER_SYNC = 1000;
31
31
  const MAX_DEVICES_PER_MEMBER = 8;
32
32
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -48,9 +48,60 @@ const ALLOWED_SETTINGS_KEYS = new Set([
48
48
  'customPricing',
49
49
  'webhookUrl',
50
50
  'webhookType',
51
+ 'boardAccessMode',
51
52
  'boardViewKey',
52
53
  ]);
53
54
 
55
+ const SESSION_COOKIE_NAME = 'agf_session';
56
+ const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
57
+ const SESSION_TTL_SEC = 7 * 24 * 60 * 60;
58
+
59
+ function parseCookieValue(request, name) {
60
+ const header = request.headers.get('cookie') || '';
61
+ if (!header) return '';
62
+ for (const part of header.split(';')) {
63
+ const idx = part.indexOf('=');
64
+ if (idx <= 0) continue;
65
+ const k = part.slice(0, idx).trim();
66
+ if (k === name) {
67
+ try {
68
+ return decodeURIComponent(part.slice(idx + 1).trim());
69
+ } catch {
70
+ return part.slice(idx + 1).trim();
71
+ }
72
+ }
73
+ }
74
+ return '';
75
+ }
76
+
77
+ function isHttpsRequest(request, url) {
78
+ if (url.protocol === 'https:') return true;
79
+ const proto = (request.headers.get('x-forwarded-proto') || '').split(',')[0].trim().toLowerCase();
80
+ return proto === 'https';
81
+ }
82
+
83
+ function buildSessionCookie(value, request, url, maxAgeSec = SESSION_TTL_SEC) {
84
+ const parts = [
85
+ `${SESSION_COOKIE_NAME}=${encodeURIComponent(value)}`,
86
+ 'Path=/',
87
+ 'HttpOnly',
88
+ 'SameSite=Lax',
89
+ `Max-Age=${Math.max(0, Math.floor(maxAgeSec))}`,
90
+ ];
91
+ if (isHttpsRequest(request, url)) parts.push('Secure');
92
+ return parts.join('; ');
93
+ }
94
+
95
+ function renderTicketErrorHtml(title, detail) {
96
+ const escHtml = (s) =>
97
+ String(s || '')
98
+ .replaceAll('&', '&amp;')
99
+ .replaceAll('<', '&lt;')
100
+ .replaceAll('>', '&gt;')
101
+ .replaceAll('"', '&quot;');
102
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escHtml(title)}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f7f7f4;color:#26251e;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;padding:24px}.card{max-width:420px;width:100%;background:#fff;border:1px solid rgba(38,37,30,.12);border-radius:12px;padding:24px;box-shadow:0 8px 24px rgba(38,37,30,.06)}h1{margin:0 0 8px;font-size:17px;font-weight:600}p{margin:0 0 14px;font-size:13px;line-height:1.6;color:#626058}code{display:block;padding:10px 12px;border-radius:8px;background:#f2f1ed;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px;color:#26251e;margin-bottom:14px}a{display:inline-block;padding:7px 14px;border-radius:8px;background:#26251e;color:#fff;text-decoration:none;font-size:12.5px;font-weight:500}</style></head><body><div class="card"><h1>${escHtml(title)}</h1><p>${escHtml(detail)}</p><code>agy-family open</code><a href="/">返回看板首页</a></div></body></html>`;
103
+ }
104
+
54
105
  function parseQuotaPctInput(val) {
55
106
  if (val === null || val === undefined || val === '') return null;
56
107
  const n = Number(val);
@@ -371,7 +422,114 @@ export function createApp({
371
422
  }
372
423
  }
373
424
 
374
- async function requireAdmin(request, now) {
425
+ async function resolveCallerAuth(request, now) {
426
+ // 1. Check HttpOnly browser session cookie (`agf_session`)
427
+ const rawCookie = parseCookieValue(request, SESSION_COOKIE_NAME);
428
+ if (rawCookie) {
429
+ try {
430
+ const sHash = await sha256Hex(rawCookie);
431
+ const sess = await db.get(
432
+ 'SELECT session_hash, member_id, token_hash_snapshot, scope, expires_at FROM web_sessions WHERE session_hash = ? AND expires_at > ?',
433
+ [sHash, now],
434
+ );
435
+ if (sess) {
436
+ if (sess.member_id) {
437
+ const mem = await db.get('SELECT id, name, role, token_hash, active FROM members WHERE id = ?', [sess.member_id]);
438
+ if (!mem || !mem.active || (sess.token_hash_snapshot && mem.token_hash !== sess.token_hash_snapshot)) {
439
+ await db.run('DELETE FROM web_sessions WHERE session_hash = ?', [sHash]).catch(() => {});
440
+ } else {
441
+ return {
442
+ authenticated: true,
443
+ via: 'cookie',
444
+ scope: sess.scope === 'admin' ? 'admin' : 'member',
445
+ isAdmin: sess.scope === 'admin',
446
+ memberId: mem.id,
447
+ memberName: mem.name,
448
+ memberRole: mem.role,
449
+ sessionHash: sHash,
450
+ };
451
+ }
452
+ } else {
453
+ return {
454
+ authenticated: true,
455
+ via: 'cookie',
456
+ scope: sess.scope === 'admin' ? 'admin' : 'member',
457
+ isAdmin: sess.scope === 'admin',
458
+ memberId: null,
459
+ memberName: null,
460
+ memberRole: null,
461
+ sessionHash: sHash,
462
+ };
463
+ }
464
+ }
465
+ } catch {
466
+ // Table may not exist yet during partial migration; fall through cleanly.
467
+ }
468
+ }
469
+
470
+ // 2. Check Admin Key header
471
+ const xAdmin = request.headers.get('x-admin-key') || '';
472
+ if (adminKey && xAdmin && (await timingSafeEqualStr(xAdmin, adminKey))) {
473
+ return {
474
+ authenticated: true,
475
+ via: 'admin-key',
476
+ scope: 'admin',
477
+ isAdmin: true,
478
+ memberId: null,
479
+ memberName: null,
480
+ memberRole: null,
481
+ };
482
+ }
483
+
484
+ // 3. Check Authorization: Bearer <token> (admin key OR active member token)
485
+ const bearer = extractBearer(request);
486
+ if (bearer) {
487
+ if (adminKey && (await timingSafeEqualStr(bearer, adminKey))) {
488
+ return {
489
+ authenticated: true,
490
+ via: 'admin-key',
491
+ scope: 'admin',
492
+ isAdmin: true,
493
+ memberId: null,
494
+ memberName: null,
495
+ memberRole: null,
496
+ };
497
+ }
498
+ const mHash = await sha256Hex(bearer);
499
+ const mem = await db.get('SELECT id, name, role, active FROM members WHERE token_hash = ? AND active = 1', [mHash]);
500
+ if (mem) {
501
+ return {
502
+ authenticated: true,
503
+ via: 'member-token',
504
+ scope: 'member',
505
+ isAdmin: false,
506
+ memberId: mem.id,
507
+ memberName: mem.name,
508
+ memberRole: mem.role,
509
+ };
510
+ }
511
+ }
512
+
513
+ return {
514
+ authenticated: false,
515
+ via: 'none',
516
+ scope: 'none',
517
+ isAdmin: false,
518
+ memberId: null,
519
+ memberName: null,
520
+ memberRole: null,
521
+ };
522
+ }
523
+
524
+ function hasValidCsrfGuard(request, url) {
525
+ if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') return true;
526
+ if ((request.headers.get('x-requested-with') || '').toLowerCase() === 'agy-family') return true;
527
+ const origin = request.headers.get('origin') || '';
528
+ if (origin && origin === url.origin) return true;
529
+ return false;
530
+ }
531
+
532
+ async function requireAdmin(request, now, url = null) {
375
533
  if (!adminKey) {
376
534
  return adminJsonRes(
377
535
  {
@@ -391,34 +549,98 @@ export function createApp({
391
549
  );
392
550
  }
393
551
  const provided = request.headers.get('x-admin-key') || extractBearer(request);
394
- const ok = await timingSafeEqualStr(provided, adminKey);
395
- if (!ok) {
552
+ if (provided) {
553
+ const ok = await timingSafeEqualStr(provided, adminKey);
554
+ if (ok) {
555
+ clearAuthFailure('admin', ip);
556
+ return null;
557
+ }
396
558
  recordAuthFailure('admin', ip, now);
397
559
  return adminJsonRes({ error: 'Invalid admin key.' }, 401);
398
560
  }
399
- clearAuthFailure('admin', ip);
400
- return null;
561
+
562
+ // Passwordless admin access via HttpOnly CLI session cookie (with CSRF guard on mutations)
563
+ const caller = await resolveCallerAuth(request, now);
564
+ if (caller.via === 'cookie' && caller.isAdmin) {
565
+ const reqUrl = url || new URL(request.url);
566
+ if (!hasValidCsrfGuard(request, reqUrl)) {
567
+ return adminJsonRes({ error: 'Cross-site request blocked.' }, 403);
568
+ }
569
+ clearAuthFailure('admin', ip);
570
+ return null;
571
+ }
572
+
573
+ recordAuthFailure('admin', ip, now);
574
+ return adminJsonRes({ error: 'Invalid admin key.' }, 401);
401
575
  }
402
576
 
403
- async function requireViewKeyIfEnabled(request, url, settings, now) {
404
- if (!settings.boardViewKey) return null;
405
- const ip = extractClientIp(request);
406
- const blocked = checkRateLimit('view', ip, now);
407
- if (blocked) {
408
- return jsonRes(
409
- { error: `Too many failed view-key attempts. Retry in ${blocked.retrySec}s.` },
410
- 429,
411
- { 'Retry-After': String(blocked.retrySec) },
412
- );
577
+ async function requireBoardAccess(request, url, settings, now) {
578
+ const viewer = await resolveCallerAuth(request, now);
579
+ const accessMode = settings.boardAccessMode === 'cli-only' ? 'cli-only' : 'public';
580
+ const effectiveAuthMode = accessMode === 'cli-only' ? 'cli-only' : settings.boardViewKey ? 'view-key' : 'public';
581
+
582
+ if (viewer.authenticated) {
583
+ return {
584
+ ok: true,
585
+ viewer: {
586
+ authenticated: true,
587
+ via: viewer.via,
588
+ scope: viewer.scope,
589
+ isAdmin: viewer.isAdmin,
590
+ memberId: viewer.memberId,
591
+ memberName: viewer.memberName,
592
+ authMode: effectiveAuthMode,
593
+ },
594
+ };
413
595
  }
414
- const providedKey = request.headers.get('x-view-key') || url.searchParams.get('key') || '';
415
- const ok = await timingSafeEqualStr(providedKey, settings.boardViewKey);
416
- if (!ok) {
417
- recordAuthFailure('view', ip, now);
418
- return jsonRes({ error: 'View key required.' }, 401);
596
+
597
+ if (accessMode === 'cli-only') {
598
+ return {
599
+ ok: false,
600
+ response: adminJsonRes(
601
+ {
602
+ error: 'CLI authentication required. Run "agy-family open" from an enrolled device.',
603
+ authMode: 'cli-only',
604
+ },
605
+ 401,
606
+ ),
607
+ };
419
608
  }
420
- clearAuthFailure('view', ip);
421
- return null;
609
+
610
+ if (settings.boardViewKey) {
611
+ const ip = extractClientIp(request);
612
+ const blocked = checkRateLimit('view', ip, now);
613
+ if (blocked) {
614
+ return {
615
+ ok: false,
616
+ response: jsonRes(
617
+ { error: `Too many failed view-key attempts. Retry in ${blocked.retrySec}s.`, authMode: 'view-key' },
618
+ 429,
619
+ { 'Retry-After': String(blocked.retrySec) },
620
+ ),
621
+ };
622
+ }
623
+ const providedKey = request.headers.get('x-view-key') || url.searchParams.get('key') || '';
624
+ const ok = await timingSafeEqualStr(providedKey, settings.boardViewKey);
625
+ if (!ok) {
626
+ recordAuthFailure('view', ip, now);
627
+ return { ok: false, response: jsonRes({ error: 'View key required.', authMode: 'view-key' }, 401) };
628
+ }
629
+ clearAuthFailure('view', ip);
630
+ }
631
+
632
+ return {
633
+ ok: true,
634
+ viewer: {
635
+ authenticated: false,
636
+ via: 'none',
637
+ scope: 'none',
638
+ isAdmin: false,
639
+ memberId: null,
640
+ memberName: null,
641
+ authMode: effectiveAuthMode,
642
+ },
643
+ };
422
644
  }
423
645
 
424
646
  return async function fetch(request) {
@@ -426,7 +648,7 @@ export function createApp({
426
648
  const path = url.pathname.replace(/\/+$/, '') || '/';
427
649
 
428
650
  if (request.method === 'OPTIONS') {
429
- if (path.startsWith('/api/admin/')) {
651
+ if (path.startsWith('/api/admin/') || path.startsWith('/api/auth/')) {
430
652
  return new Response(null, { status: 204 });
431
653
  }
432
654
  return jsonRes({ ok: true }, 204);
@@ -453,17 +675,195 @@ export function createApp({
453
675
  });
454
676
  }
455
677
 
456
- // Public Transparent Dashboard UI
678
+ // One-time CLI login ticket redemption -> HttpOnly session cookie -> redirect to clean /
679
+ if (request.method === 'GET' && path === '/auth/enter') {
680
+ const rawTicket = (url.searchParams.get('t') || '').trim();
681
+ if (!rawTicket) {
682
+ return htmlRes(
683
+ renderTicketErrorHtml('登录票据缺失', '请在终端运行下方命令重新免密打开家庭组看板:'),
684
+ 400,
685
+ );
686
+ }
687
+ const tHash = await sha256Hex(rawTicket);
688
+ const ticketRow = await db.get(
689
+ 'SELECT ticket_hash, member_id, scope, expires_at FROM web_tickets WHERE ticket_hash = ? AND expires_at > ?',
690
+ [tHash, now],
691
+ );
692
+ // Atomic single-use burn + opportunistic cleanup of expired tickets
693
+ await db.run('DELETE FROM web_tickets WHERE ticket_hash = ? OR expires_at <= ?', [tHash, now]);
694
+ if (!ticketRow) {
695
+ return htmlRes(
696
+ renderTicketErrorHtml('登录票据已失效或已使用', '一次性登录链接仅限单次使用(60 秒有效)。请在终端重新执行:'),
697
+ 401,
698
+ );
699
+ }
700
+
701
+ let tokenHashSnapshot = null;
702
+ if (ticketRow.member_id) {
703
+ const mem = await db.get('SELECT id, token_hash, active FROM members WHERE id = ?', [ticketRow.member_id]);
704
+ if (!mem || !mem.active) {
705
+ return htmlRes(
706
+ renderTicketErrorHtml('成员权限已失效', '该家庭组成员已被停用或移除,无法登录看板。'),
707
+ 403,
708
+ );
709
+ }
710
+ tokenHashSnapshot = mem.token_hash;
711
+ }
712
+
713
+ const rawSession = randomToken('ags', 24);
714
+ const sessionHash = await sha256Hex(rawSession);
715
+ await runBatchedWrites(db, [
716
+ { sql: 'DELETE FROM web_sessions WHERE expires_at <= ?', params: [now] },
717
+ {
718
+ sql: 'INSERT INTO web_sessions (session_hash, member_id, token_hash_snapshot, scope, expires_at, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
719
+ params: [
720
+ sessionHash,
721
+ ticketRow.member_id || null,
722
+ tokenHashSnapshot,
723
+ ticketRow.scope === 'admin' ? 'admin' : 'member',
724
+ now + SESSION_TTL_MS,
725
+ now,
726
+ now,
727
+ ],
728
+ },
729
+ ]);
730
+
731
+ return new Response(null, {
732
+ status: 302,
733
+ headers: {
734
+ Location: '/',
735
+ 'Set-Cookie': buildSessionCookie(rawSession, request, url, SESSION_TTL_SEC),
736
+ 'Cache-Control': 'no-store',
737
+ 'Referrer-Policy': 'no-referrer',
738
+ 'X-Content-Type-Options': 'nosniff',
739
+ },
740
+ });
741
+ }
742
+
743
+ // Mint one-time CLI login ticket (authenticated via member Bearer token and/or Admin Key)
744
+ if (request.method === 'POST' && path === '/api/auth/ticket') {
745
+ const ip = extractClientIp(request);
746
+ const blocked = checkRateLimit('ticket', ip, now);
747
+ if (blocked) {
748
+ return adminJsonRes(
749
+ { error: `Too many failed auth attempts. Retry in ${blocked.retrySec}s.` },
750
+ 429,
751
+ { 'Retry-After': String(blocked.retrySec) },
752
+ );
753
+ }
754
+
755
+ let body = {};
756
+ try {
757
+ const txt = await request.text();
758
+ body = txt.trim() ? JSON.parse(txt) : {};
759
+ } catch {
760
+ return adminJsonRes({ error: 'Invalid JSON body.' }, 400);
761
+ }
762
+
763
+ const xAdmin = request.headers.get('x-admin-key') || '';
764
+ const bearer = extractBearer(request);
765
+ const isAdminByHeader = Boolean(adminKey && xAdmin && (await timingSafeEqualStr(xAdmin, adminKey)));
766
+ const isAdminByBearer = Boolean(!isAdminByHeader && adminKey && bearer && (await timingSafeEqualStr(bearer, adminKey)));
767
+ const isAdminAuth = isAdminByHeader || isAdminByBearer;
768
+
769
+ let memberRow = null;
770
+ if (bearer && !isAdminByBearer) {
771
+ const mHash = await sha256Hex(bearer);
772
+ memberRow = await db.get('SELECT id, name, role, token_hash, active FROM members WHERE token_hash = ? AND active = 1', [mHash]);
773
+ }
774
+
775
+ if (!isAdminAuth && !memberRow) {
776
+ recordAuthFailure('ticket', ip, now);
777
+ return adminJsonRes({ error: 'Valid member token or admin key required.' }, 401);
778
+ }
779
+ clearAuthFailure('ticket', ip);
780
+
781
+ const wantReadonly = Boolean(body?.readonly);
782
+ const scope = isAdminAuth && !wantReadonly ? 'admin' : 'member';
783
+ const ttlSec = Math.max(30, Math.min(300, Math.round(Number(body?.ttlSec) || 60)));
784
+ const rawTicket = randomToken('agt', 24);
785
+ const ticketHash = await sha256Hex(rawTicket);
786
+
787
+ await runBatchedWrites(db, [
788
+ { sql: 'DELETE FROM web_tickets WHERE expires_at <= ?', params: [now] },
789
+ {
790
+ sql: 'INSERT INTO web_tickets (ticket_hash, member_id, scope, expires_at, created_at) VALUES (?, ?, ?, ?, ?)',
791
+ params: [ticketHash, memberRow?.id || null, scope, now + ttlSec * 1000, now],
792
+ },
793
+ ]);
794
+
795
+ const origin = inferPublicOrigin(request, publicBaseUrl);
796
+ return adminJsonRes({
797
+ ok: true,
798
+ ticket: rawTicket,
799
+ enterUrl: `${origin}/auth/enter?t=${encodeURIComponent(rawTicket)}`,
800
+ scope,
801
+ memberId: memberRow?.id || null,
802
+ memberName: memberRow?.name || null,
803
+ expiresInSec: ttlSec,
804
+ });
805
+ }
806
+
807
+ // Emergency browser Admin Key -> HttpOnly admin session cookie (works even in cli-only mode)
808
+ if (request.method === 'POST' && path === '/api/auth/admin-session') {
809
+ const authErr = await requireAdmin(request, now, url);
810
+ if (authErr) return authErr;
811
+ const rawSession = randomToken('ags', 24);
812
+ const sessionHash = await sha256Hex(rawSession);
813
+ await runBatchedWrites(db, [
814
+ { sql: 'DELETE FROM web_sessions WHERE expires_at <= ?', params: [now] },
815
+ {
816
+ sql: 'INSERT INTO web_sessions (session_hash, member_id, token_hash_snapshot, scope, expires_at, created_at, last_seen_at) VALUES (?, NULL, NULL, ?, ?, ?, ?)',
817
+ params: [sessionHash, 'admin', now + SESSION_TTL_MS, now, now],
818
+ },
819
+ ]);
820
+ return adminJsonRes(
821
+ { ok: true, scope: 'admin', isAdmin: true },
822
+ 200,
823
+ { 'Set-Cookie': buildSessionCookie(rawSession, request, url, SESSION_TTL_SEC) },
824
+ );
825
+ }
826
+
827
+ // Current web session viewer identity
828
+ if (request.method === 'GET' && path === '/api/auth/me') {
829
+ const settings = await loadSettings(db, envDefaults);
830
+ const caller = await resolveCallerAuth(request, now);
831
+ const authMode = settings.boardAccessMode === 'cli-only' ? 'cli-only' : settings.boardViewKey ? 'view-key' : 'public';
832
+ return adminJsonRes({
833
+ authenticated: caller.authenticated,
834
+ authMode,
835
+ scope: caller.scope,
836
+ isAdmin: caller.isAdmin,
837
+ memberId: caller.memberId,
838
+ memberName: caller.memberName,
839
+ });
840
+ }
841
+
842
+ // Logout browser session (deletes session row + clears HttpOnly cookie)
843
+ if (request.method === 'POST' && path === '/api/auth/logout') {
844
+ const rawCookie = parseCookieValue(request, SESSION_COOKIE_NAME);
845
+ if (rawCookie) {
846
+ const sHash = await sha256Hex(rawCookie);
847
+ await db.run('DELETE FROM web_sessions WHERE session_hash = ?', [sHash]).catch(() => {});
848
+ }
849
+ return adminJsonRes(
850
+ { ok: true },
851
+ 200,
852
+ { 'Set-Cookie': buildSessionCookie('', request, url, 0) },
853
+ );
854
+ }
855
+
856
+ // Dashboard Shell HTML
457
857
  if (request.method === 'GET' && path === '/') {
458
858
  const settings = await loadSettings(db, envDefaults);
459
859
  return htmlRes(renderDashboardHtml({ boardTitle: settings.boardTitle }));
460
860
  }
461
861
 
462
- // Public Board JSON
862
+ // Board JSON
463
863
  if (request.method === 'GET' && path === '/api/board') {
464
864
  const settings = await loadSettings(db, envDefaults);
465
- const viewErr = await requireViewKeyIfEnabled(request, url, settings, now);
466
- if (viewErr) return viewErr;
865
+ const access = await requireBoardAccess(request, url, settings, now);
866
+ if (!access.ok) return access.response;
467
867
  const from = (url.searchParams.get('from') || '').trim();
468
868
  const to = (url.searchParams.get('to') || '').trim();
469
869
  const rawPeriod = url.searchParams.get('period');
@@ -476,14 +876,15 @@ export function createApp({
476
876
  ? url.searchParams.get('source')
477
877
  : 'all';
478
878
  const board = await buildBoardPayload(db, { period, from, to, source, envDefaults, now });
479
- return jsonRes(board);
879
+ const payload = { ...board, viewer: access.viewer };
880
+ return jsonRes(payload, 200, {}, { allowCors: settings.boardAccessMode !== 'cli-only' });
480
881
  }
481
882
 
482
- // Public Board CSV Settlement Export
883
+ // Board CSV Settlement Export
483
884
  if (request.method === 'GET' && path === '/api/board/export.csv') {
484
885
  const settings = await loadSettings(db, envDefaults);
485
- const viewErr = await requireViewKeyIfEnabled(request, url, settings, now);
486
- if (viewErr) return viewErr;
886
+ const access = await requireBoardAccess(request, url, settings, now);
887
+ if (!access.ok) return access.response;
487
888
  const from = (url.searchParams.get('from') || '').trim();
488
889
  const to = (url.searchParams.get('to') || '').trim();
489
890
  const rawPeriod = url.searchParams.get('period');
@@ -510,12 +911,12 @@ export function createApp({
510
911
  });
511
912
  }
512
913
 
513
- // Public Per-Member Drill-Down Detail
914
+ // Per-Member Drill-Down Detail
514
915
  const boardMemberMatch = path.match(/^\/api\/board\/member\/([^/]+)$/);
515
916
  if (request.method === 'GET' && boardMemberMatch) {
516
917
  const settings = await loadSettings(db, envDefaults);
517
- const viewErr = await requireViewKeyIfEnabled(request, url, settings, now);
518
- if (viewErr) return viewErr;
918
+ const access = await requireBoardAccess(request, url, settings, now);
919
+ if (!access.ok) return access.response;
519
920
  const memberId = decodeURIComponent(boardMemberMatch[1]);
520
921
  const from = (url.searchParams.get('from') || '').trim();
521
922
  const to = (url.searchParams.get('to') || '').trim();
@@ -526,8 +927,8 @@ export function createApp({
526
927
  ? 'custom'
527
928
  : 'today';
528
929
  const detail = await buildMemberDetailPayload(db, memberId, { period, from, to, envDefaults, now });
529
- if (!detail) return jsonRes({ error: 'Member not found.' }, 404);
530
- return jsonRes(detail);
930
+ if (!detail) return jsonRes({ error: 'Member not found.' }, 404, {}, { allowCors: settings.boardAccessMode !== 'cli-only' });
931
+ return jsonRes(detail, 200, {}, { allowCors: settings.boardAccessMode !== 'cli-only' });
531
932
  }
532
933
 
533
934
  // Member Usage Sync (Bearer member token)
@@ -966,7 +1367,7 @@ export function createApp({
966
1367
 
967
1368
  // --- Admin Routes (strict same-origin, zero wildcard CORS) ---
968
1369
  if (path.startsWith('/api/admin/')) {
969
- const authErr = await requireAdmin(request, now);
1370
+ const authErr = await requireAdmin(request, now, url);
970
1371
  if (authErr) return authErr;
971
1372
 
972
1373
  if (request.method === 'GET' && path === '/api/admin/overview') {
@@ -1146,7 +1547,11 @@ export function createApp({
1146
1547
 
1147
1548
  const token = randomToken('agf');
1148
1549
  const tokenHash = await sha256Hex(token);
1149
- await db.run('UPDATE members SET token_hash = ? WHERE id = ?', [tokenHash, id]);
1550
+ await runBatchedWrites(db, [
1551
+ { sql: 'UPDATE members SET token_hash = ? WHERE id = ?', params: [tokenHash, id] },
1552
+ { sql: 'DELETE FROM web_sessions WHERE member_id = ?', params: [id] },
1553
+ { sql: 'DELETE FROM web_tickets WHERE member_id = ?', params: [id] },
1554
+ ]);
1150
1555
 
1151
1556
  const settings = await loadSettings(db, envDefaults);
1152
1557
  const origin = inferPublicOrigin(request, publicBaseUrl);
@@ -1229,6 +1634,10 @@ export function createApp({
1229
1634
  id,
1230
1635
  ],
1231
1636
  });
1637
+ if (!nextActive) {
1638
+ stmts.push({ sql: 'DELETE FROM web_sessions WHERE member_id = ?', params: [id] });
1639
+ stmts.push({ sql: 'DELETE FROM web_tickets WHERE member_id = ?', params: [id] });
1640
+ }
1232
1641
  await runBatchedWrites(db, stmts);
1233
1642
  return adminJsonRes({
1234
1643
  ok: true,
@@ -1249,6 +1658,8 @@ export function createApp({
1249
1658
  { sql: 'DELETE FROM device_odometers WHERE member_id = ?', params: [id] },
1250
1659
  { sql: 'DELETE FROM member_devices WHERE member_id = ?', params: [id] },
1251
1660
  { sql: 'DELETE FROM subscription_quotas WHERE scope = ?', params: [`member:${id}`] },
1661
+ { sql: 'DELETE FROM web_sessions WHERE member_id = ?', params: [id] },
1662
+ { sql: 'DELETE FROM web_tickets WHERE member_id = ?', params: [id] },
1252
1663
  { sql: 'DELETE FROM integrity_events WHERE member_id = ?', params: [id] },
1253
1664
  { sql: 'DELETE FROM members WHERE id = ?', params: [id] },
1254
1665
  ]);
@@ -1271,6 +1682,9 @@ export function createApp({
1271
1682
  const n = Number(body.monthlyPlanCost);
1272
1683
  body.monthlyPlanCost = Number.isFinite(n) && n > 0 ? Math.round(n * 100) / 100 : 0;
1273
1684
  }
1685
+ if (body && body.boardAccessMode !== undefined) {
1686
+ body.boardAccessMode = body.boardAccessMode === 'cli-only' ? 'cli-only' : 'public';
1687
+ }
1274
1688
  if (body && body.monthlyPlanCurrency !== undefined) {
1275
1689
  const cur = String(body.monthlyPlanCurrency || 'USD').toUpperCase();
1276
1690
  body.monthlyPlanCurrency = ['USD', 'CNY', 'EUR', 'JPY'].includes(cur) ? cur : 'USD';
@@ -117,6 +117,25 @@ export const SCHEMA_STATEMENTS = Object.freeze([
117
117
  updated_at INTEGER NOT NULL
118
118
  )`,
119
119
  `CREATE INDEX IF NOT EXISTS idx_subscription_quotas_updated ON subscription_quotas (updated_at DESC)`,
120
+ `CREATE TABLE IF NOT EXISTS web_tickets (
121
+ ticket_hash TEXT PRIMARY KEY,
122
+ member_id TEXT,
123
+ scope TEXT NOT NULL DEFAULT 'member',
124
+ expires_at INTEGER NOT NULL,
125
+ created_at INTEGER NOT NULL
126
+ )`,
127
+ `CREATE INDEX IF NOT EXISTS idx_web_tickets_expires ON web_tickets (expires_at)`,
128
+ `CREATE TABLE IF NOT EXISTS web_sessions (
129
+ session_hash TEXT PRIMARY KEY,
130
+ member_id TEXT,
131
+ token_hash_snapshot TEXT,
132
+ scope TEXT NOT NULL DEFAULT 'member',
133
+ expires_at INTEGER NOT NULL,
134
+ created_at INTEGER NOT NULL,
135
+ last_seen_at INTEGER NOT NULL
136
+ )`,
137
+ `CREATE INDEX IF NOT EXISTS idx_web_sessions_member ON web_sessions (member_id)`,
138
+ `CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at)`,
120
139
  ]);
121
140
 
122
141
  export const DEFAULT_SETTINGS = Object.freeze({
@@ -136,6 +155,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
136
155
  pricingCache: null,
137
156
  webhookUrl: '',
138
157
  webhookType: 'auto',
158
+ boardAccessMode: 'public',
139
159
  boardViewKey: '',
140
160
  });
141
161
 
@@ -993,7 +993,7 @@ export async function buildBoardPayload(
993
993
  }
994
994
 
995
995
  const membersRaw = await db.all(
996
- 'SELECT id, name, role, color, quota_pct, expected_email_hash, 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 WHERE active = 1 ORDER BY created_at ASC',
996
+ '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 WHERE active = 1 ORDER BY created_at ASC',
997
997
  );
998
998
  const quotasMap = resolveFamilyQuotas(membersRaw);
999
999
 
@@ -1338,6 +1338,7 @@ export async function buildBoardPayload(
1338
1338
  lastClientVersion: agg.lastClientVersion,
1339
1339
  online: !isOffline,
1340
1340
  accountBound: Boolean(raw.expected_email_hash),
1341
+ emailHint: raw.email_hint || '',
1341
1342
  accountStatus: raw.expected_email_hash ? raw.last_account_status || 'unknown' : 'unbound',
1342
1343
  integrityFlags7d: integrityByMember.get(raw.id) || 0,
1343
1344
  };
@@ -1571,7 +1572,7 @@ export async function buildMemberDetailPayload(
1571
1572
  { period = 'today', from = '', to = '', envDefaults = {}, now = Date.now() } = {},
1572
1573
  ) {
1573
1574
  const member = await db.get(
1574
- 'SELECT id, name, role, color, quota_pct, expected_email_hash, 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 WHERE id = ? AND active = 1',
1575
+ '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 WHERE id = ? AND active = 1',
1575
1576
  [memberId],
1576
1577
  );
1577
1578
  if (!member) return null;
@@ -1865,6 +1866,7 @@ export async function buildMemberDetailPayload(
1865
1866
  period: win.period,
1866
1867
  online,
1867
1868
  accountBound: Boolean(member.expected_email_hash),
1869
+ emailHint: member.email_hint || '',
1868
1870
  accountStatus: member.expected_email_hash ? member.last_account_status || 'unknown' : 'unbound',
1869
1871
  lastSeenAt: member.last_seen_at || null,
1870
1872
  lastClientKind: member.last_client_kind || null,
@@ -1924,7 +1924,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
1924
1924
 
1925
1925
  <footer class="foot">
1926
1926
  <span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
1927
- <span class="mono">agy-family v0.4.0 · MIT</span>
1927
+ <span class="mono">agy-family v0.5.0 · MIT</span>
1928
1928
  </footer>
1929
1929
  </main>
1930
1930
 
@@ -2090,6 +2090,13 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
2090
2090
  <div class="field"><label data-i18n="boardNameLbl">家庭组看板名称</label><input id="setBoardTitle" /></div>
2091
2091
  <div class="field"><label data-i18n="resetDay">月度重置日</label><input id="setResetDay" class="mono" type="number" min="1" max="28" /></div>
2092
2092
  </div>
2093
+ <div class="field">
2094
+ <label data-i18n="accessModeLbl">看板访问权限</label>
2095
+ <select id="setAccessMode">
2096
+ <option value="cli-only">仅限 CLI / 成员登录(推荐 · 零密码 · agy-family open)</option>
2097
+ <option value="public">公开只读(知道网址即可看脱敏看板)</option>
2098
+ </select>
2099
+ </div>
2093
2100
  <div class="row-2">
2094
2101
  <div class="field"><label data-i18n="planCostLbl">月订阅总费(可选,按占比算分摊)</label><input id="setPlanCost" class="mono" type="number" min="0" step="0.01" placeholder="如:249.99 或 1800" /></div>
2095
2102
  <div class="field">
@@ -2224,7 +2231,7 @@ const I18N = {
2224
2231
  masterManualHead: '手动更新主号订阅余量(兜底校准)',
2225
2232
  masterTierLbl: '订阅套餐等级', masterLabelLbl: '主号脱敏备注(选填)', saveMasterQuota: '更新主号订阅额度',
2226
2233
  rulesNote: '遵循 Google 家庭组规则(最多 6 人:1 位主号 + 最多 5 位家庭成员)。按「组内使用占比 (%) vs 分配份额 (%)」核算成员比例,主号实时同步套餐 5h / 周剩余额度。',
2227
- boardNameLbl: '家庭组看板名称',
2234
+ boardNameLbl: '家庭组看板名称', accessModeLbl: '看板访问权限',
2228
2235
  resetDay: '月度重置日', warnPct: '份额预警比例 (%)', offlineHrs: '离线判定 (h)',
2229
2236
  tzLbl: '统计时区',
2230
2237
  viewKeyLbl: '家庭组查看密码(留空则公开,新邀请码自动携带)',
@@ -2264,7 +2271,7 @@ const I18N = {
2264
2271
  masterManualHead: 'Manual Master Quota Calibration',
2265
2272
  masterTierLbl: 'Subscription tier', masterLabelLbl: 'Masked account label (optional)', saveMasterQuota: 'Update master quota',
2266
2273
  rulesNote: 'Follows Google Family Group rules (up to 6 people: 1 master + 5 members). Shares are evaluated in percentages (%), while the master account syncs live 5h / weekly subscription quota.',
2267
- boardNameLbl: 'Board title',
2274
+ boardNameLbl: 'Board title', accessModeLbl: 'Board access mode',
2268
2275
  resetDay: 'Billing reset day', warnPct: 'Share warn %', offlineHrs: 'Offline hours',
2269
2276
  tzLbl: 'Timezone',
2270
2277
  viewKeyLbl: 'Family group view key (optional; auto-carried in new invites)',
@@ -2296,6 +2303,10 @@ let chartMode = 'hourly';
2296
2303
  let chartModeManual = false;
2297
2304
  let lastBoardData = null;
2298
2305
  let adminKey = sessionStorage.getItem('agf_admin_key') || '';
2306
+ let isAdminSession = false;
2307
+ function hasAdminAuth() {
2308
+ return Boolean(adminKey || isAdminSession);
2309
+ }
2299
2310
  let expandedMemberId = null;
2300
2311
  let focusedMemberDetail = null;
2301
2312
  let latestInviteUri = '';
@@ -2413,7 +2424,7 @@ async function copyText(str) {
2413
2424
  function updateAdminHeaderTitle() {
2414
2425
  const map = { members: 'tabMembers', master: 'tabMaster', rules: 'tabRules', audit: 'tabAudit' };
2415
2426
  const el = document.getElementById('adminActiveTitle');
2416
- if (el) el.textContent = adminKey ? t(map[currentAdminTab] || 'adminPanel') : t('adminPanel');
2427
+ if (el) el.textContent = hasAdminAuth() ? t(map[currentAdminTab] || 'adminPanel') : t('adminPanel');
2417
2428
  }
2418
2429
 
2419
2430
  function fmtResetCountdown(ms) {
@@ -2607,10 +2618,71 @@ async function fetchBoard(opts) {
2607
2618
 
2608
2619
  const qs = buildBoardQueryParams(true);
2609
2620
  try {
2610
- const res = await fetch('/api/board?' + qs.toString(), { headers: viewHeaders() });
2621
+ const res = await fetch('/api/board?' + qs.toString(), { headers: viewHeaders(), credentials: 'same-origin' });
2611
2622
  if (seq !== boardReqSeq) return;
2612
2623
  if (res.status === 401 || res.status === 429) {
2613
2624
  const errJson = await res.json().catch(() => ({}));
2625
+ const authMode = errJson.authMode || 'view-key';
2626
+ if (authMode === 'cli-only') {
2627
+ const lockSvg = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" style="color:var(--primary);margin-bottom:8px"><rect x="4" y="11" width="16" height="10" rx="2.5" stroke="currentColor" stroke-width="1.7"/><path d="M8 11V7.5a4 4 0 0 1 8 0V11" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>';
2628
+ document.getElementById('app').innerHTML =
2629
+ '<div class="gate">' + lockSvg +
2630
+ '<h2 style="font-size:17px;font-weight:600;margin:0">' + esc(lang === 'zh' ? '仅限家庭组成员访问' : 'Members-only family board') + '</h2>' +
2631
+ '<p style="color:var(--body);font-size:12.5px;line-height:1.6;margin:8px 0 14px">' +
2632
+ esc(lang === 'zh'
2633
+ ? '该看板已启用 CLI 零密码鉴权,无需输入密码。请在已加入家庭组的电脑终端执行:'
2634
+ : 'This board uses passwordless CLI authentication. Run the command below on any enrolled device:') +
2635
+ '</p>' +
2636
+ '<div style="display:flex;align-items:center;gap:8px;margin-bottom:14px">' +
2637
+ '<div class="code-block mono" style="flex:1;margin:0;text-align:left">agy-family open</div>' +
2638
+ '<button type="button" class="btn btn-primary btn-sm" id="copyOpenCmdBtn">' + esc(lang === 'zh' ? '复制' : 'Copy') + '</button>' +
2639
+ '</div>' +
2640
+ '<div style="font-size:11.5px;color:var(--muted);margin-bottom:14px">' +
2641
+ esc(lang === 'zh'
2642
+ ? '或手机临时访问:在电脑运行 agy-family open --link 生成一次性链接。'
2643
+ : 'On mobile? Run "agy-family open --link" on desktop for a 5-minute single-use link.') +
2644
+ '</div>' +
2645
+ '<details class="adv-details" style="text-align:left"><summary>' + esc(lang === 'zh' ? '管理员应急密钥解锁' : 'Manager emergency key unlock') + '</summary>' +
2646
+ '<div class="adv-details-body">' +
2647
+ '<div class="field"><input id="gateAdminKey" type="password" class="mono" placeholder="adm_..." /></div>' +
2648
+ '<button type="button" class="btn btn-sm btn-primary" id="gateAdminUnlockBtn">' + esc(lang === 'zh' ? '验证并进入' : 'Unlock') + '</button>' +
2649
+ '<div id="gateAdminErr" class="msg-line" style="color:var(--danger)"></div>' +
2650
+ '</div>' +
2651
+ '</details>' +
2652
+ '</div>';
2653
+ document.getElementById('copyOpenCmdBtn')?.addEventListener('click', async () => {
2654
+ try {
2655
+ await copyText('agy-family open');
2656
+ showToast(lang === 'zh' ? '已复制 agy-family open' : 'Copied agy-family open');
2657
+ } catch {}
2658
+ });
2659
+ document.getElementById('gateAdminUnlockBtn')?.addEventListener('click', async () => {
2660
+ const btn = document.getElementById('gateAdminUnlockBtn');
2661
+ const keyVal = (document.getElementById('gateAdminKey')?.value || '').trim();
2662
+ const errEl = document.getElementById('gateAdminErr');
2663
+ if (errEl) errEl.textContent = '';
2664
+ if (!keyVal) return;
2665
+ await withBtnLoading(btn, async () => {
2666
+ const r = await fetch('/api/auth/admin-session', {
2667
+ method: 'POST',
2668
+ credentials: 'same-origin',
2669
+ headers: { 'Content-Type': 'application/json', 'X-Admin-Key': keyVal, 'X-Requested-With': 'agy-family' },
2670
+ body: '{}',
2671
+ });
2672
+ const j = await r.json().catch(() => ({}));
2673
+ if (!r.ok) {
2674
+ if (errEl) errEl.textContent = j.error || 'Invalid admin key';
2675
+ return;
2676
+ }
2677
+ location.reload();
2678
+ });
2679
+ });
2680
+ document.getElementById('gateAdminKey')?.addEventListener('keydown', (e) => {
2681
+ if (e.key === 'Enter') document.getElementById('gateAdminUnlockBtn')?.click();
2682
+ });
2683
+ return;
2684
+ }
2685
+
2614
2686
  document.getElementById('app').innerHTML =
2615
2687
  '<div class="gate"><h2 style="font-size:16px;font-weight:600">' + esc(lang === 'zh' ? '需要家庭组查看密码' : 'Family group view key required') +
2616
2688
  '</h2><p style="color:var(--body);font-size:12.5px;margin:8px 0 14px">' +
@@ -2626,6 +2698,12 @@ async function fetchBoard(opts) {
2626
2698
  }
2627
2699
  const data = await res.json();
2628
2700
  if (seq !== boardReqSeq) return;
2701
+ if (data.viewer) {
2702
+ isAdminSession = Boolean(data.viewer.isAdmin);
2703
+ if (data.viewer.memberId && !myMemberId) {
2704
+ myMemberId = data.viewer.memberId;
2705
+ }
2706
+ }
2629
2707
  const isTabOrManual = !silent && hasLoadedBoard;
2630
2708
  hasLoadedBoard = true;
2631
2709
  lastBoardData = data;
@@ -2819,7 +2897,7 @@ async function loadMemberDetail(memberId) {
2819
2897
  '</div>';
2820
2898
  const qs = buildBoardQueryParams(false);
2821
2899
  try {
2822
- const res = await fetch('/api/board/member/' + encodeURIComponent(memberId) + '?' + qs.toString(), { headers: viewHeaders() });
2900
+ const res = await fetch('/api/board/member/' + encodeURIComponent(memberId) + '?' + qs.toString(), { headers: viewHeaders(), credentials: 'same-origin' });
2823
2901
  if (seq !== detailReqSeq) return;
2824
2902
  if (!res.ok) throw new Error('HTTP ' + res.status);
2825
2903
  const d = await res.json();
@@ -3082,6 +3160,9 @@ function renderMemberRows(d) {
3082
3160
  if (hasPlanSplit && m.usedUsd > 0) subParts.push((lang === 'zh' ? '分摊 ' : 'split ') + fmtMoney(m.estPlanSplit, planCur));
3083
3161
  subParts.push((lang === 'zh' ? '参考 ' : 'ref ') + fmtUsd(m.usedUsd));
3084
3162
 
3163
+ const emailHintHtml = m.emailHint
3164
+ ? '<span class="mono" style="color:var(--body)">· ' + esc(m.emailHint) + '</span>'
3165
+ : '';
3085
3166
  const devMetaBits = [];
3086
3167
  if (m.lastPlatform) devMetaBits.push(m.lastPlatform);
3087
3168
  if (m.lastMaskedIp && m.lastMaskedIp !== 'local') {
@@ -3102,7 +3183,7 @@ function renderMemberRows(d) {
3102
3183
  '<span class="dot" style="background:' + esc(m.color) + '"></span>' +
3103
3184
  '<div>' +
3104
3185
  '<div class="member-name-row"><span class="member-name">' + esc(m.name) + '</span>' + roleTag + meTag + acctTag + statusTag + integrityTag + '</div>' +
3105
- '<div class="member-sub"><span class="live-dot ' + (m.online ? 'on' : 'off') + '"></span><span>' + esc(m.online ? t('online') : t('offline')) + '</span><span>' + esc(fmtAgo(m.lastSeenAt)) + '</span>' + devMetaHtml + '</div>' +
3186
+ '<div class="member-sub"><span class="live-dot ' + (m.online ? 'on' : 'off') + '"></span><span>' + esc(m.online ? t('online') : t('offline')) + '</span><span>' + esc(fmtAgo(m.lastSeenAt)) + '</span>' + emailHintHtml + devMetaHtml + '</div>' +
3106
3187
  '</div>' +
3107
3188
  '</div></td>' +
3108
3189
  '<td><div class="meter-box"' + (meterTip ? ' title="' + esc(meterTip) + '"' : '') + '>' +
@@ -3428,9 +3509,12 @@ function renderModelBreakdown(d) {
3428
3509
 
3429
3510
  // Admin API helpers
3430
3511
  async function adminReq(path, opts = {}) {
3512
+ const hdrs = { 'Content-Type': 'application/json', 'X-Requested-With': 'agy-family', ...(opts.headers || {}) };
3513
+ if (adminKey) hdrs['X-Admin-Key'] = adminKey;
3431
3514
  const res = await fetch(path, {
3515
+ credentials: 'same-origin',
3432
3516
  ...opts,
3433
- headers: { 'Content-Type': 'application/json', 'X-Admin-Key': adminKey, ...(opts.headers || {}) },
3517
+ headers: hdrs,
3434
3518
  });
3435
3519
  const json = await res.json().catch(() => ({}));
3436
3520
  if (!res.ok) throw new Error(json.error || 'HTTP ' + res.status);
@@ -3513,6 +3597,8 @@ async function loadAdmin() {
3513
3597
  updateAdminHeaderTitle();
3514
3598
 
3515
3599
  document.getElementById('setBoardTitle').value = data.settings.boardTitle || '';
3600
+ const amSel = document.getElementById('setAccessMode');
3601
+ if (amSel) amSel.value = data.settings.boardAccessMode === 'cli-only' ? 'cli-only' : 'public';
3516
3602
  document.getElementById('setResetDay').value = data.settings.cycleResetDay ?? 1;
3517
3603
  document.getElementById('setWarnPct').value = data.settings.warnPct ?? 80;
3518
3604
  document.getElementById('setOfflineHrs').value = data.settings.offlineAlertHours ?? 48;
@@ -3806,14 +3892,14 @@ function activateAdminTab(tab) {
3806
3892
  document.getElementById('adminTabs').addEventListener('click', (e) => {
3807
3893
  const btn = e.target.closest('button[data-tab]');
3808
3894
  if (!btn) return;
3809
- if (!adminKey) return;
3895
+ if (!hasAdminAuth()) return;
3810
3896
  activateAdminTab(btn.getAttribute('data-tab'));
3811
3897
  });
3812
3898
 
3813
3899
  document.getElementById('masterQuotaBtn')?.addEventListener('click', () => {
3814
3900
  pendingAdminTab = 'master';
3815
3901
  document.getElementById('adminBtn').click();
3816
- if (adminKey) activateAdminTab('master');
3902
+ if (hasAdminAuth()) activateAdminTab('master');
3817
3903
  });
3818
3904
 
3819
3905
  function toggleMemberExpand(id) {
@@ -4410,7 +4496,7 @@ document.getElementById('exportCsvBtn').addEventListener('click', async () => {
4410
4496
  await withBtnLoading(btn, async () => {
4411
4497
  const qs = buildBoardQueryParams(true);
4412
4498
  try {
4413
- const res = await fetch('/api/board/export.csv?' + qs.toString(), { headers: viewHeaders() });
4499
+ const res = await fetch('/api/board/export.csv?' + qs.toString(), { headers: viewHeaders(), credentials: 'same-origin' });
4414
4500
  if (!res.ok) return;
4415
4501
  const blob = await res.blob();
4416
4502
  const objUrl = URL.createObjectURL(blob);
@@ -4452,7 +4538,12 @@ document.getElementById('themeBtn').addEventListener('click', () => {
4452
4538
  document.getElementById('adminBtn').addEventListener('click', () => {
4453
4539
  document.getElementById('adminOverlay').classList.add('open');
4454
4540
  updateAdminHeaderTitle();
4455
- if (adminKey) loadAdmin().catch(() => { adminKey = ''; });
4541
+ if (hasAdminAuth()) {
4542
+ loadAdmin().catch(() => {
4543
+ adminKey = '';
4544
+ isAdminSession = false;
4545
+ });
4546
+ }
4456
4547
  });
4457
4548
  document.getElementById('closeAdmin').addEventListener('click', () => {
4458
4549
  document.getElementById('adminOverlay').classList.remove('open');
@@ -4460,9 +4551,18 @@ document.getElementById('closeAdmin').addEventListener('click', () => {
4460
4551
  document.getElementById('adminOverlay').addEventListener('click', (e) => {
4461
4552
  if (e.target === e.currentTarget) document.getElementById('adminOverlay').classList.remove('open');
4462
4553
  });
4463
- document.getElementById('adminLockBtn').addEventListener('click', () => {
4554
+ document.getElementById('adminLockBtn').addEventListener('click', async () => {
4464
4555
  adminKey = '';
4556
+ const wasCookieAdmin = isAdminSession;
4557
+ isAdminSession = false;
4465
4558
  sessionStorage.removeItem('agf_admin_key');
4559
+ if (wasCookieAdmin) {
4560
+ await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' }).catch(() => {});
4561
+ }
4562
+ if (lastBoardData?.viewer?.authMode === 'cli-only') {
4563
+ location.reload();
4564
+ return;
4565
+ }
4466
4566
  document.getElementById('adminContent').style.display = 'none';
4467
4567
  document.getElementById('adminAuthBox').style.display = 'block';
4468
4568
  document.getElementById('adminLockBtn').style.display = 'none';
@@ -4578,6 +4678,7 @@ document.getElementById('saveSettingsBtn').addEventListener('click', async () =>
4578
4678
  method: 'PATCH',
4579
4679
  body: JSON.stringify({
4580
4680
  boardTitle: document.getElementById('setBoardTitle').value.trim(),
4681
+ boardAccessMode: document.getElementById('setAccessMode')?.value === 'cli-only' ? 'cli-only' : 'public',
4581
4682
  defaultDailyCapUsd: 0,
4582
4683
  defaultWeeklyCapUsd: 0,
4583
4684
  defaultCycleCapUsd: 0,
@@ -0,0 +1,23 @@
1
+ -- One-time CLI login tickets and HttpOnly browser sessions for passwordless CLI-only board access.
2
+ CREATE TABLE IF NOT EXISTS web_tickets (
3
+ ticket_hash TEXT PRIMARY KEY,
4
+ member_id TEXT,
5
+ scope TEXT NOT NULL DEFAULT 'member',
6
+ expires_at INTEGER NOT NULL,
7
+ created_at INTEGER NOT NULL
8
+ );
9
+
10
+ CREATE INDEX IF NOT EXISTS idx_web_tickets_expires ON web_tickets (expires_at);
11
+
12
+ CREATE TABLE IF NOT EXISTS web_sessions (
13
+ session_hash TEXT PRIMARY KEY,
14
+ member_id TEXT,
15
+ token_hash_snapshot TEXT,
16
+ scope TEXT NOT NULL DEFAULT 'member',
17
+ expires_at INTEGER NOT NULL,
18
+ created_at INTEGER NOT NULL,
19
+ last_seen_at INTEGER NOT NULL
20
+ );
21
+
22
+ CREATE INDEX IF NOT EXISTS idx_web_sessions_member ON web_sessions (member_id);
23
+ CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at);