Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,16 @@ npm install -g tokenphage@latest

### ⬆️ 업데이트

대시보드를 열면 새 버전이 있는지 확인합니다. 새 버전이 확인되면 대시보드 맨 위에 안내 배너가 뜨고, 메뉴에 **⬆ Update to …** 항목이 추가됩니다. 이 항목을 고르면 최신 버전이 자동으로 설치됩니다(전역 설치가 아니면 정확한 수동 명령을 안내).
대시보드를 열면 새 버전이 있는지 확인합니다. 새 버전이 확인되면 대시보드 맨 위에 안내 배너가 뜨고, 메뉴에 **⬆ Update to …** 항목이 추가됩니다. 이 항목을 고르면 최신 버전이 자동으로 설치됩니다. 전역 설치가 아니거나, `sudo`로 설치해 전역 설치 폴더에 쓸 권한이 없으면(macOS·Linux) 그대로 실행할 명령을 안내합니다.

직접 올리고 싶다면 언제든 아래 명령을 실행하면 됩니다.

```bash
npm install -g tokenphage@latest
```

`sudo`로 설치했다면 `sudo npm install -g tokenphage@latest`로 실행하세요.

> 업데이트 알림을 끄려면 `TOKENPHAGE_NO_UPDATE_NOTIFIER=1` 환경 변수를 설정하세요.

## 🚀 빠른 시작
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tokenphage",
"version": "2026.11.1",
"version": "2026.12.1",
"description": "AI 토큰 사용량 GitHub README 뱃지",
"author": "kobenlys <kobenlys@gmail.com>",
"license": "MIT",
Expand Down
34 changes: 27 additions & 7 deletions src/lib/updater.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/**
* 1-클릭 업데이트: 전역(npm i -g) 설치인지 감지해, 전역이면 최신버전을 설치하고,
* 그 외(npx/로컬 의존성/git clone)면 정확한 수동 명령을 안내한다.
* 그 외(npx/로컬 의존성/git clone)면 정확한 수동 명령을, 전역 폴더에 쓸 권한이 없으면(sudo로 설치) sudo 명령을 안내한다.
*
* 현재 프로세스는 설치 직후에도 여전히 "구버전 코드"이므로(핫스왑 불가),
* 성공 시 재실행을 안내하고 호출부(index.js)에서 프로세스를 종료한다.
*/
import { spawn, execFileSync } from 'child_process';
import { realpathSync } from 'fs';
import { realpathSync, accessSync, constants } from 'fs';
import chalk from 'chalk';
import { accent } from '../gradient.js';
import { PACKAGE_NAME } from './update-check.js';
Expand All @@ -26,14 +26,26 @@ function globalRoot() {
}
}

/** 현재 실행 중인 CLI가 전역 npm 설치(.../lib/node_modules/...)인지 realpath prefix 매칭으로 판정한다. */
function isGlobalInstall() {
/** 현재 실행 중인 CLI가 전역 npm 설치(.../lib/node_modules/...)면 전역 루트(realpath)를, 아니면 null을 반환한다. */
function globalInstallRoot() {
try {
const script = realpathSync(process.argv[1]);
const root = globalRoot();
return !!root && script.startsWith(realpathSync(root));
if (!root) return null;
const realRoot = realpathSync(root);
return script.startsWith(realRoot) ? realRoot : null;
} catch {
return false; // 불확실하면 전역 아님으로 간주 → 수동 안내(잘못된 npm i -g 방지)
return null; // 불확실하면 전역 아님으로 간주 → 수동 안내(잘못된 npm i -g 방지)
}
}

/** 현재 계정에 dir 쓰기 권한이 없어(EACCES) sudo가 필요한지. 읽기 전용 FS(EROFS) 등은 sudo로도 안 풀려 false. */
function needsSudo(dir) {
try {
accessSync(dir, constants.W_OK);
return false;
} catch (err) {
return err.code === 'EACCES';
}
}

Expand All @@ -60,13 +72,21 @@ function printManual() {
* @returns {Promise<{updated:boolean}>} updated=true면 호출부가 재실행 안내 후 프로세스를 종료해야 한다.
*/
export async function runUpdate(latest) {
const root = globalInstallRoot();
// 전역 설치가 아니면 자동 업데이트가 위험/무의미 → 수동 명령만 안내.
if (!isGlobalInstall()) {
if (!root) {
console.log(chalk.gray(' Not a global npm install — update manually:'));
printManual();
return { updated: false };
}

// 쓸 수 없는 전역 폴더면 npm은 EACCES로 실패하고 같은 명령의 재시도도 실패한다(Windows는 access가 ACL을 안 봐 제외).
if (!isWin && needsSudo(root)) {
console.log(chalk.yellow(` No write permission to the global npm folder (${root}) — update with sudo:`));
console.log(accent(` → sudo ${MANUAL_CMD}`));
return { updated: false };
}

console.log(accent(` Updating to v${latest}...`));
const result = await npmInstallGlobal();

Expand Down
101 changes: 101 additions & 0 deletions test/updater.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, symlinkSync, existsSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { runUpdate } from '../src/lib/updater.js';

// 테스트 목록 — 실제 npm 대신 PATH의 가짜 npm과 임시 전역 폴더로 runUpdate를 돌린다
// 1. update_전역폴더쓰기불가_npm실행없이sudo안내 (실패 입력: #33 재현)
// 2. update_전역폴더쓰기가능_npm설치후updated (성공: 자동 설치 유지)
// 3. update_전역설치아님_npm실행없이수동안내 (경계: 전역 아님 판정 유지)

const SKIP_WIN = process.platform === 'win32' ? 'Windows는 sh 가짜 npm을 실행할 수 없다' : false;
const SKIP_ROOT = process.getuid?.() === 0 ? 'root는 쓰기 권한 검사를 항상 통과한다' : false;

const cleanupDirs = [];
after(() => { for (const d of cleanupDirs) rmSync(d, { recursive: true, force: true }); });

/** npm 전역 설치 모양(<root>/tokenphage, <base>/bin의 bin 링크)과 `root -g`·`install -g`에만 답하는 가짜 npm을 만든다. */
function fakeGlobalInstall() {
const base = mkdtempSync(join(tmpdir(), 'tp-updater-'));
cleanupDirs.push(base);
const root = join(base, 'lib', 'node_modules');
const entry = join(root, 'tokenphage', 'src', 'index.js');
const bin = join(base, 'bin');
const marker = join(base, 'npm-install-ran');
mkdirSync(join(root, 'tokenphage', 'src'), { recursive: true });
writeFileSync(entry, '');
mkdirSync(bin);
symlinkSync(entry, join(bin, 'tokenphage'));
// PATH가 bin 하나뿐이라 sh 내장 명령만 쓴다
writeFileSync(join(bin, 'npm'), [
'#!/bin/sh',
'case "$*" in',
` 'root -g') echo '${root}' ;;`,
` 'install -g tokenphage@latest') : > '${marker}' ;;`,
' *) exit 1 ;;',
'esac',
].join('\n') + '\n', { mode: 0o755 });
return { base, root, bin, marker, script: join(bin, 'tokenphage') };
}

/** PATH·argv[1]·console.log를 바꿔 runUpdate를 부르고 결과와 출력을 돌려준다. */
async function runWith(bin, script) {
const saved = { path: process.env.PATH, argv1: process.argv[1], log: console.log };
const lines = [];
process.env.PATH = bin; // 실제 npm을 찾을 수 없게 한다
process.argv[1] = script;
console.log = (...args) => lines.push(args.join(' '));
try {
return { result: await runUpdate('9.9.9'), out: lines.join('\n') };
} finally {
process.env.PATH = saved.path;
process.argv[1] = saved.argv1;
console.log = saved.log;
}
}

test('update_전역폴더쓰기불가_npm실행없이sudo안내', { skip: SKIP_WIN || SKIP_ROOT }, async (t) => {
// Given: sudo로 설치해 현재 계정이 쓸 수 없는 전역 폴더
const g = fakeGlobalInstall();
chmodSync(g.root, 0o555);
t.after(() => chmodSync(g.root, 0o755)); // 단언이 실패해도 되돌려야 임시 폴더를 지울 수 있다

// When
const { result, out } = await runWith(g.bin, g.script);

// Then
assert.deepEqual(result, { updated: false }); // 수정 전에는 npm을 실행해 updated true
assert.ok(out.includes('sudo npm install -g tokenphage@latest'), out); // 사용자가 그대로 복사해 실행하는 명령
assert.equal(existsSync(g.marker), false); // 같은 계정으로 실패할 npm install은 돌리지 않는다
});

test('update_전역폴더쓰기가능_npm설치후updated', { skip: SKIP_WIN }, async () => {
// Given: 사용자 소유 전역 폴더, 실행 경로는 npm이 만드는 bin 링크
const g = fakeGlobalInstall();

// When
const { result, out } = await runWith(g.bin, g.script);

// Then
assert.deepEqual(result, { updated: true });
assert.equal(existsSync(g.marker), true); // 가짜 npm이 install -g tokenphage@latest 인자로 불렸다
assert.ok(!out.includes('sudo'), out);
});

test('update_전역설치아님_npm실행없이수동안내', { skip: SKIP_WIN }, async () => {
// Given: npx·git clone처럼 전역 폴더 밖에서 실행
const g = fakeGlobalInstall();
const outside = join(g.base, 'elsewhere.js');
writeFileSync(outside, '');

// When
const { result, out } = await runWith(g.bin, outside);

// Then
assert.deepEqual(result, { updated: false });
assert.equal(existsSync(g.marker), false); // 전역이 아니면 npm i -g를 돌리지 않는다
assert.ok(out.includes('npm install -g tokenphage@latest'), out);
assert.ok(!out.includes('sudo'), out);
});
Loading