charge-connect 0.1.3 → 0.1.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.
Files changed (3) hide show
  1. package/cli.js +44 -8
  2. package/collect.js +23 -9
  3. package/package.json +1 -1
package/cli.js CHANGED
@@ -2,15 +2,17 @@
2
2
  // charge-connect CLI — 앱에서 받은 페어링 코드로 연결하고 자동 수집을 등록한다.
3
3
  //
4
4
  // 사용법:
5
- // npx charge-connect <페어링코드> # 페어링 + 첫 수집 + 스케줄 등록 (일반 사용자용 원라이너)
5
+ // npx charge-connect <페어링코드> [--label 이름] # 페어링 + 첫 수집 + 스케줄 등록 (원라이너)
6
+ // # --label(또는 CHARGE_LABEL)로 앱에 표시될 기기명 지정, 기본은 호스트명
6
7
  // charge-connect run # 수집 1회 (스케줄러가 호출)
7
- // charge-connect unpair # 페어링 해제
8
+ // charge-connect unpair # 페어링 해제 (서버 디바이스 토큰도 폐기)
8
9
  //
9
10
  // 설정 파일: ~/.charge/config.json (CHARGE_HOME으로 위치 변경 가능)
10
11
 
11
12
  const fs = require("node:fs");
12
13
  const path = require("node:path");
13
14
  const { execFileSync } = require("node:child_process");
15
+ const { CCUSAGE_PKG } = require("./collect.js"); // 버전 고정을 한 곳에서 관리
14
16
 
15
17
  const HOME = process.env.HOME ?? process.env.USERPROFILE;
16
18
  const CONF_DIR = process.env.CHARGE_HOME ?? path.join(HOME, ".charge");
@@ -28,6 +30,17 @@ const CLOUD = (() => {
28
30
  }
29
31
  })();
30
32
 
33
+ // 앱 기기 목록에 표시될 이름 — 기본은 호스트명이지만 실명이 든 경우가 흔하므로
34
+ // 최초 페어링 때 --label 또는 CHARGE_LABEL로 덮어쓸 수 있게 하고, 무엇으로 등록되는지 알려준다.
35
+ // 주의: 라벨은 서버가 같은 머신을 알아보는 유일한 키다(중복제거). 이미 페어링된 머신을
36
+ // 다른 라벨로 재페어링하면 새 디바이스로 잡혀 일별 사용량이 이중 집계되므로, 사후 변경은 권하지 않는다.
37
+ function resolveLabel() {
38
+ const i = process.argv.indexOf("--label");
39
+ const flag = i > -1 && process.argv[i + 1] && !process.argv[i + 1].startsWith("-") ? process.argv[i + 1] : null;
40
+ const raw = flag ?? process.env.CHARGE_LABEL ?? require("node:os").hostname();
41
+ return String(raw).trim().slice(0, 64) || require("node:os").hostname();
42
+ }
43
+
31
44
  async function pair(code) {
32
45
  const url = process.env.CHARGE_URL ?? CLOUD.url;
33
46
  const anon = process.env.CHARGE_ANON ?? CLOUD.anon;
@@ -35,10 +48,11 @@ async function pair(code) {
35
48
  console.error("백엔드 주소가 없습니다 (collector/cloud.json 또는 CHARGE_URL/CHARGE_ANON).");
36
49
  process.exit(1);
37
50
  }
51
+ const label = resolveLabel();
38
52
  const res = await fetch(`${url}/rest/v1/rpc/charge_claim_pairing_code`, {
39
53
  method: "POST",
40
54
  headers: { apikey: anon, Authorization: `Bearer ${anon}`, "Content-Type": "application/json" },
41
- body: JSON.stringify({ p_code: code, p_label: require("node:os").hostname() }),
55
+ body: JSON.stringify({ p_code: code, p_label: label }),
42
56
  signal: AbortSignal.timeout(15_000),
43
57
  });
44
58
  const token = res.ok ? await res.json() : null;
@@ -52,7 +66,29 @@ async function pair(code) {
52
66
  try { fs.chmodSync(CONF_DIR, 0o700); } catch {}
53
67
  fs.writeFileSync(CONF, JSON.stringify({ url, anon, token }, null, 2), { mode: 0o600 });
54
68
  try { fs.chmodSync(CONF, 0o600); } catch {}
55
- console.log("✓ 페어링 완료");
69
+ console.log(`✓ 페어링 완료 — 이 컴퓨터가 '${label}'(으)로 등록되었습니다.`);
70
+ }
71
+
72
+ // 페어링 해제: 서버의 디바이스 토큰까지 폐기한다.
73
+ // 로컬 config만 지우면 그 토큰은 서버에서 계속 유효해, 유출됐을 경우 남이 업로드에 쓸 수 있다.
74
+ async function unpair() {
75
+ let conf = null;
76
+ try { conf = JSON.parse(fs.readFileSync(CONF, "utf8")); } catch {}
77
+ if (conf?.url && conf?.anon && conf?.token) {
78
+ try {
79
+ const res = await fetch(`${conf.url}/rest/v1/rpc/charge_revoke_device`, {
80
+ method: "POST",
81
+ headers: { apikey: conf.anon, Authorization: `Bearer ${conf.anon}`, "Content-Type": "application/json" },
82
+ body: JSON.stringify({ p_token: conf.token }),
83
+ signal: AbortSignal.timeout(15_000),
84
+ });
85
+ if (!res.ok) console.error(`서버 디바이스 폐기 실패 (${res.status}) — 앱 설정의 기기 목록에서 직접 제거하세요.`);
86
+ } catch {
87
+ console.error("서버 디바이스 폐기 요청에 실패했습니다 — 앱 설정의 기기 목록에서 직접 제거하세요.");
88
+ }
89
+ }
90
+ fs.rmSync(CONF, { force: true });
91
+ console.log("✓ 페어링 해제 (스케줄 해제는 install.sh/install.ps1 안내 참고)");
56
92
  }
57
93
 
58
94
  // npx 캐시는 언제든 청소될 수 있으므로, 스케줄 등록 전에 런타임을 ~/.charge/app 으로 복사한다
@@ -96,7 +132,7 @@ async function offerCcusageInstall() {
96
132
  run("ccusage", ["--version"], { stdio: "ignore", timeout: 15_000 });
97
133
  return; // 이미 설치돼 있다
98
134
  } catch {}
99
- const hint = "'npm i -g ccusage'를 해두면 수집이 빨라집니다";
135
+ const hint = `'npm i -g ${CCUSAGE_PKG}'를 해두면 수집이 빨라집니다`;
100
136
  // 파이프/CI처럼 물어볼 콘솔이 없으면 안내만 하고 넘어간다
101
137
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
102
138
  console.log(`참고: ${hint} (지금은 npx 대체 실행으로 동작).`);
@@ -110,7 +146,8 @@ async function offerCcusageInstall() {
110
146
  return;
111
147
  }
112
148
  try {
113
- run("npm", ["install", "-g", "ccusage"], { stdio: "inherit", timeout: 300_000 });
149
+ // 전역 설치도 버전을 고정한다 — @latest면 설치 시점 최신본의 라이프사이클 스크립트를 그대로 실행한다
150
+ run("npm", ["install", "-g", CCUSAGE_PKG], { stdio: "inherit", timeout: 300_000 });
114
151
  console.log("✓ ccusage 설치 완료");
115
152
  } catch {
116
153
  console.error(
@@ -131,8 +168,7 @@ async function offerCcusageInstall() {
131
168
  return;
132
169
  }
133
170
  if (arg === "unpair") {
134
- fs.rmSync(CONF, { force: true });
135
- console.log("✓ 페어링 해제 (스케줄 해제는 install.sh/install.ps1 안내 참고)");
171
+ await unpair();
136
172
  return;
137
173
  }
138
174
  // 페어링 코드로 간주: 페어링 → 스케줄 등록 → 첫 수집.
package/collect.js CHANGED
@@ -22,12 +22,14 @@ const HOME = process.env.HOME ?? process.env.USERPROFILE;
22
22
  // 5분마다 도는 작업이라 그냥 이어 붙이면 끝없이 자라므로 5MB에서 .old로 민다.
23
23
  const logArg = process.argv.indexOf("--log");
24
24
  const LOG_FILE = logArg > -1 ? process.argv[logArg + 1] : null;
25
- if (logArg > -1 && (!LOG_FILE || LOG_FILE.startsWith("-"))) {
25
+ // 아래 로그 리다이렉션·핸들러 등록·process.exit은 스크립트로 직접 실행될 때만 해야 한다.
26
+ // cli.js가 버전 상수를 require할 때 이 부작용이 딸려오면 CLI 콘솔이 파일로 새거나 조기 종료된다.
27
+ if (require.main === module && logArg > -1 && (!LOG_FILE || LOG_FILE.startsWith("-"))) {
26
28
  // 값을 안 주면 조용히 로그가 꺼지고, 다음 옵션을 삼키면 "--dry-run"이라는 파일에 쓰게 된다
27
29
  console.error("--log 뒤에는 파일 경로가 필요합니다.");
28
30
  process.exit(1);
29
31
  }
30
- if (LOG_FILE) {
32
+ if (require.main === module && LOG_FILE) {
31
33
  try {
32
34
  if (fs.statSync(LOG_FILE).size > 5 * 1024 * 1024) fs.renameSync(LOG_FILE, `${LOG_FILE}.old`);
33
35
  } catch {}
@@ -63,6 +65,13 @@ const EXTRA_PATH = WIN
63
65
  : ":/opt/homebrew/bin:/usr/local/bin";
64
66
  const DEFAULT_CODEXBAR_CLI = "/Applications/CodexBar.app/Contents/Helpers/CodexBarCLI";
65
67
 
68
+ // ccusage는 정확한 버전으로 고정한다 — @latest로 5분마다 무인 실행하면 ccusage npm
69
+ // 계정/배포가 탈취됐을 때 별도 조작 없이 악성 코드가 모든 사용자 PC에서 돌게 된다.
70
+ // 이 프로세스는 Claude/Codex 자격증명이 있는 홈에서 사용자 권한으로 실행되므로 위험이 크다.
71
+ // 갱신은 릴리스마다 새 버전을 검토한 뒤 의도적으로만 올린다.
72
+ const CCUSAGE_VERSION = "20.0.19";
73
+ const CCUSAGE_PKG = `ccusage@${CCUSAGE_VERSION}`;
74
+
66
75
  // 모든 외부 명령은 비동기로 실행한다 — 동기(execFileSync)는 이벤트 루프를 세워
67
76
  // 진행 중인 fetch(AbortSignal 타이머 포함)를 전부 타임아웃시킨다.
68
77
  const execOpts = (timeout) => ({
@@ -93,9 +102,10 @@ async function runCcusage(args) {
93
102
  try {
94
103
  return JSON.parse(await runAsync("ccusage", args));
95
104
  } catch (e) {
96
- console.error(`ccusage 직접 실행 실패(${e.code ?? e.message}), npx로 재시도 — 'npm i -g ccusage'를 해두면 빨라집니다`);
105
+ console.error(`ccusage 직접 실행 실패(${e.code ?? e.message}), npx로 재시도 — 'npm i -g ${CCUSAGE_PKG}'를 해두면 빨라집니다`);
97
106
  // --prefer-offline: npx 캐시가 있으면 레지스트리 조회 없이 재사용 (5분마다 재다운로드 방지)
98
- return JSON.parse(await runAsync("npx", ["-y", "--prefer-offline", "ccusage@latest", ...args], 300_000));
107
+ // 버전은 CCUSAGE_PKG로 고정 — @latest 자동 추적은 공급망 탈취를 무인 실행 채널로 만든다.
108
+ return JSON.parse(await runAsync("npx", ["-y", "--prefer-offline", CCUSAGE_PKG, ...args], 300_000));
99
109
  }
100
110
  }
101
111
 
@@ -491,15 +501,18 @@ function codexBarEntryToProvider(entry) {
491
501
  });
492
502
 
493
503
  if (!primary && !secondary && extras.length === 0) return null;
504
+ // 불투명 식별자(계정 ID·조직)를 이메일보다 먼저 쓴다 — account는 salt 없는 sha256의
505
+ // 앞 12자(48비트)라, 이메일을 넣으면 DB 유출 시 사전 대입으로 원문이 역산된다.
506
+ // 고엔트로피 ID는 그 대입이 통하지 않는다. 이메일은 다른 식별자가 전혀 없을 때만 폴백.
494
507
  const rawAccount = textValue(
495
- identity.accountEmail,
496
- identity.email,
497
- usage.accountEmail,
498
- entry.accountEmail,
499
508
  identity.accountId,
500
509
  usage.accountId,
501
510
  identity.accountOrganization,
502
- usage.accountOrganization
511
+ usage.accountOrganization,
512
+ identity.accountEmail,
513
+ identity.email,
514
+ usage.accountEmail,
515
+ entry.accountEmail
503
516
  );
504
517
  const plan = usefulPlan(
505
518
  usage.plan,
@@ -709,6 +722,7 @@ if (require.main === module) {
709
722
  }
710
723
 
711
724
  module.exports = {
725
+ CCUSAGE_PKG,
712
726
  accountHash,
713
727
  codexBarEntryToProvider,
714
728
  collectCodexBarProviders,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "charge-connect",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Connects your computer to the Charge iPhone app and uploads AI coding usage",
5
5
  "bin": {
6
6
  "charge-connect": "cli.js"