durebak 0.1.0-alpha.22 → 0.1.0-alpha.24
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 +4 -2
- package/dist/cli.js +27 -4
- package/dist/database.js +4 -0
- package/dist/update-cli.d.ts +18 -0
- package/dist/update-cli.js +86 -0
- package/dist/update-scheduler.d.ts +19 -0
- package/dist/update-scheduler.js +109 -0
- package/dist/update-state.d.ts +74 -0
- package/dist/update-state.js +158 -0
- package/dist/update-trust.d.ts +30 -0
- package/dist/update-trust.js +52 -0
- package/dist/updates.d.ts +29 -0
- package/dist/updates.js +105 -0
- package/docs/USAGE.md +3 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,11 +6,13 @@ Local, durable collaboration between coding-agent sessions. Experimental alpha f
|
|
|
6
6
|
|
|
7
7
|
두레박은 같은 컴퓨터의 코딩 에이전트 세션이 메시지·작업·결과를 주고받는 로컬 협업 런타임입니다. 각 세션은 자기 호스트와 맥락을 유지하고, CLI 또는 MCP로 참여합니다.
|
|
8
8
|
|
|
9
|
-
**현재 소스: 0.1.0-alpha.
|
|
9
|
+
**현재 소스: 0.1.0-alpha.24. 사용자용 협업은 Cooperative 모드입니다.** SQLite 저장소, 인증된 loopback 서버, CLI, MCP stdio bridge가 구현되어 있습니다. 실제 MCP 프로세스 간 통신을 테스트했으며, 호스트별 실제 시험 결과와 제약은 [호스트 테스트](docs/HOST-TESTING.md)에 기록합니다. 요청별 대화·기한·취소 notice·checkpoint, 공유 preview, 보호 작업·비공개 텍스트 첨부, revision별 자기보고 검증·재검증과 CLI 협업 화면을 제공합니다. 내부 실험용 Codex·OpenCode 소유 호스트와 실행 ledger, 비동기 준비 상태 검사도 개발 중입니다. 이 내부 구성의 실제 모델 실행·controller 연결·자동 깨우기는 아직 검증하지 않았습니다. 자동 세션 실행·깨우기와 반복 작업 스케줄러는 후속 기능입니다.
|
|
10
|
+
|
|
11
|
+
npm·GitHub 설치/업데이트 경로, 릴리스 구독과 alpha.24의 `update-check`·opt-in 알림은 [설치·업데이트 안내](https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md)를 참고하세요.
|
|
10
12
|
|
|
11
13
|
## 시작하기
|
|
12
14
|
|
|
13
|
-
Node.js 24 이상과 npm이 필요합니다.
|
|
15
|
+
macOS 또는 Linux, Node.js 24 이상과 npm이 필요합니다. Windows는 이 alpha에서 지원하지 않습니다. Windows CI의 ACL·SQLite 조사는 지원 준비를 위한 시험이며, 제품 실행 검증과 구분합니다.
|
|
14
16
|
|
|
15
17
|
`npx`로 alpha 버전을 실행할 수 있습니다.
|
|
16
18
|
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { handleUpdateCommand, updateCommandContext, cachedUpdateNotice } from './update-cli.js';
|
|
2
3
|
import { managedBindSchema } from './managed-control.js';
|
|
3
4
|
import { resolveHarness, legacyProvider } from './harnesses/registry.js';
|
|
4
5
|
import { harnessCatalog } from './harnesses/catalog.js';
|
|
@@ -19,6 +20,11 @@ import { exportRecord } from './records.js';
|
|
|
19
20
|
import { storagePaths, managedCredentialPath, managedRecordPath } from './paths.js';
|
|
20
21
|
const help = `Durebak ${version} — local cooperative session bus
|
|
21
22
|
|
|
23
|
+
durebak update-check [--channel alpha|beta|rc|stable] Read published update candidates
|
|
24
|
+
durebak update status|disable|unpin [--update-dir PATH]
|
|
25
|
+
durebak update enable --mode notify --channel alpha|beta|rc|stable
|
|
26
|
+
durebak update pin VERSION Pin notification policy version
|
|
27
|
+
durebak update apply --version VERSION Report blocked automatic-apply prerequisites
|
|
22
28
|
durebak harnesses Read harness capability evidence (no host execution)
|
|
23
29
|
durebak serve [--data-dir PATH] Run loopback daemon in foreground
|
|
24
30
|
durebak register --workspace PATH --alias NAME --harness codex|claude-code|opencode|other [--out FILE] [--data-dir PATH]
|
|
@@ -45,11 +51,15 @@ const output = (value) => process.stdout.write(JSON.stringify(value) + '\n');
|
|
|
45
51
|
function required(value, name) { if (!value)
|
|
46
52
|
fail(`missing_${name}`); return value; }
|
|
47
53
|
async function main() {
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
54
|
+
const options = {
|
|
55
|
+
'update-dir': { type: 'string' }, channel: { type: 'string' }, mode: { type: 'string' }, 'native-id': { type: 'string' }, profile: { type: 'string' }, instance: { type: 'string' }, key: { type: 'string' }, 'data-dir': { type: 'string' }, workspace: { type: 'string' }, alias: { type: 'string' }, provider: { type: 'string' }, harness: { type: 'string' }, out: { type: 'string' }, session: { type: 'string' }, json: { type: 'string' }, input: { type: 'string' }, host: { type: 'string' }, help: { type: 'boolean' },
|
|
56
|
+
};
|
|
57
|
+
// Resolve subcommands while respecting values of options placed before them.
|
|
58
|
+
const preliminary = parseArgs({ allowPositionals: true, strict: false, options });
|
|
59
|
+
const applying = preliminary.positionals[0] === 'update' && preliminary.positionals[1] === 'apply';
|
|
60
|
+
const { values, positionals } = parseArgs({ allowPositionals: true, options: { ...options, version: { type: applying ? 'string' : 'boolean' } } });
|
|
51
61
|
const command = positionals[0];
|
|
52
|
-
if (values.version) {
|
|
62
|
+
if (values.version === true) {
|
|
53
63
|
process.stdout.write(version + '\n');
|
|
54
64
|
return;
|
|
55
65
|
}
|
|
@@ -57,6 +67,19 @@ async function main() {
|
|
|
57
67
|
process.stdout.write(help);
|
|
58
68
|
return;
|
|
59
69
|
}
|
|
70
|
+
if (command === 'update' || command === 'update-check') {
|
|
71
|
+
output(await handleUpdateCommand(command === 'update-check' ? 'check' : positionals[1] ?? 'status', positionals.slice(command === 'update-check' ? 1 : 2), { ...(values.mode === undefined ? {} : { mode: values.mode }), ...(values.channel === undefined ? {} : { channel: values.channel }), ...(typeof values.version === 'string' ? { target: values.version } : {}) }, updateCommandContext(values['update-dir'])));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (process.stderr.isTTY && command !== 'mcp' && ['skills', 'harnesses', 'paths', 'serve', 'register', 'revoke', 'setup', 'managed-bind', 'managed-policy', 'dashboard', 'doctor', 'call', 'export'].includes(command)) {
|
|
75
|
+
try {
|
|
76
|
+
const context = updateCommandContext();
|
|
77
|
+
const notice = cachedUpdateNotice(context.directory, version);
|
|
78
|
+
if (notice)
|
|
79
|
+
process.stderr.write(notice);
|
|
80
|
+
}
|
|
81
|
+
catch { /* A stale notification cannot break an unrelated command. */ }
|
|
82
|
+
}
|
|
60
83
|
if (command === 'skills') {
|
|
61
84
|
output(installSkills(required(values.harness, 'harness'), required(values.workspace, 'workspace')));
|
|
62
85
|
return;
|
package/dist/database.js
CHANGED
|
@@ -4,6 +4,10 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { fail } from './domain.js';
|
|
5
5
|
import { migrate } from './migrations.js';
|
|
6
6
|
export function privateDirectory(path) {
|
|
7
|
+
// POSIX mode bits cannot establish private storage on Windows. Refuse
|
|
8
|
+
// before creating anything until an OS-specific ACL backend is available.
|
|
9
|
+
if (typeof process.geteuid !== 'function')
|
|
10
|
+
fail('unsupported_storage_platform');
|
|
7
11
|
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
8
12
|
const stat = lstatSync(path.replace(/\/+$/, '') || '/');
|
|
9
13
|
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || stat.uid !== process.geteuid?.())
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ScheduleRunner } from './update-scheduler.js';
|
|
2
|
+
export interface UpdateCommandContext {
|
|
3
|
+
directory: string;
|
|
4
|
+
current: string;
|
|
5
|
+
platform: string;
|
|
6
|
+
home: string;
|
|
7
|
+
uid: number;
|
|
8
|
+
node: string;
|
|
9
|
+
cli: string;
|
|
10
|
+
}
|
|
11
|
+
export interface UpdateCommandOptions {
|
|
12
|
+
mode?: string;
|
|
13
|
+
channel?: string;
|
|
14
|
+
target?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function updateCommandContext(directory?: string): UpdateCommandContext;
|
|
17
|
+
export declare function handleUpdateCommand(action: string, args: string[], options: UpdateCommandOptions, context?: UpdateCommandContext, run?: ScheduleRunner): Promise<unknown>;
|
|
18
|
+
export declare function cachedUpdateNotice(directory: string, current: string): string | null;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { version } from './version.js';
|
|
5
|
+
import { fail } from './domain.js';
|
|
6
|
+
import { checkUpdates, updateChannel, channelForVersion, compareVersions } from './updates.js';
|
|
7
|
+
import { loadUpdateState, changeUpdateState, runUpdateWorker } from './update-state.js';
|
|
8
|
+
import { installUpdateSchedule, removeUpdateSchedule } from './update-scheduler.js';
|
|
9
|
+
import { automaticUpdateBlockers } from './update-trust.js';
|
|
10
|
+
export function updateCommandContext(directory) { return { directory: resolve(directory ?? join(homedir(), '.durebak-updater')), current: version, platform: process.platform, home: homedir(), uid: process.geteuid?.() ?? -1, node: process.execPath, cli: fileURLToPath(new URL('./cli.js', import.meta.url)) }; }
|
|
11
|
+
function newerVersions(state, current) { return state.report ? [state.report.npm, state.report.github].filter(s => s.status === 'update_available' && s.version !== null && compareVersions(s.version, current) > 0).map(s => s.version) : []; }
|
|
12
|
+
function status(state, context) { return { current: context.current, mode: state.mode, channel: state.channel, pin: state.pin, last_checked_at: state.last_checked_at, next_check_at: state.next_check_at, report: state.report, scheduler: state.scheduler, pending_notice: state.mode === 'notify' && newerVersions(state, context.current).length > 0 && state.last_notice !== null && state.last_notice !== state.last_shown_notice, automatic_apply: false, apply_blockers: automaticUpdateBlockers(context.platform) }; }
|
|
13
|
+
export async function handleUpdateCommand(action, args, options, context = updateCommandContext(), run) {
|
|
14
|
+
const directory = context.directory, current = context.current;
|
|
15
|
+
if (!['check', 'status', 'enable', 'disable', 'pin', 'unpin', 'worker', 'apply'].includes(action))
|
|
16
|
+
fail('unknown_update_command');
|
|
17
|
+
if (args.length !== (action === 'pin' ? 1 : 0))
|
|
18
|
+
fail('invalid_update_arguments');
|
|
19
|
+
if (options.channel !== undefined)
|
|
20
|
+
updateChannel(options.channel);
|
|
21
|
+
if (action === 'apply') {
|
|
22
|
+
if (!options.target)
|
|
23
|
+
fail('missing_update_version');
|
|
24
|
+
channelForVersion(options.target);
|
|
25
|
+
fail('automatic_apply_not_configured');
|
|
26
|
+
}
|
|
27
|
+
if (action === 'enable') {
|
|
28
|
+
if (options.mode === 'auto')
|
|
29
|
+
fail('automatic_apply_not_configured');
|
|
30
|
+
if (options.mode !== 'notify')
|
|
31
|
+
fail('invalid_update_mode');
|
|
32
|
+
if (!options.channel)
|
|
33
|
+
fail('missing_update_channel');
|
|
34
|
+
const channel = updateChannel(options.channel);
|
|
35
|
+
const state = changeUpdateState(directory, current, state => {
|
|
36
|
+
const cache = state.channel === channel ? {} : { report: null, last_notice: null, last_shown_notice: null, last_checked_at: null };
|
|
37
|
+
const receipt = installUpdateSchedule({ ...context, directory }, run);
|
|
38
|
+
return { ...state, ...cache, mode: 'notify', channel, next_check_at: null, scheduler: receipt.kind, scheduler_digest: receipt.digest };
|
|
39
|
+
});
|
|
40
|
+
return status(state, context);
|
|
41
|
+
}
|
|
42
|
+
if (action === 'disable') {
|
|
43
|
+
const disabled = changeUpdateState(directory, current, state => ({ ...state, mode: 'disabled', next_check_at: null }));
|
|
44
|
+
if (disabled.scheduler !== 'none') {
|
|
45
|
+
const state = changeUpdateState(directory, current, state => {
|
|
46
|
+
if (state.mode !== 'disabled' || state.scheduler === 'none')
|
|
47
|
+
return state;
|
|
48
|
+
if (!state.scheduler_digest)
|
|
49
|
+
fail('invalid_update_state');
|
|
50
|
+
removeUpdateSchedule({ ...context, directory }, { kind: state.scheduler, digest: state.scheduler_digest }, run);
|
|
51
|
+
return { ...state, scheduler: 'none', scheduler_digest: null };
|
|
52
|
+
});
|
|
53
|
+
return status(state, context);
|
|
54
|
+
}
|
|
55
|
+
return status(disabled, context);
|
|
56
|
+
}
|
|
57
|
+
if (action === 'pin' || action === 'unpin') {
|
|
58
|
+
const pin = action === 'pin' ? args[0] : null;
|
|
59
|
+
if (pin !== null)
|
|
60
|
+
channelForVersion(pin);
|
|
61
|
+
return status(changeUpdateState(directory, current, state => ({ ...state, pin, next_check_at: null, last_notice: null, last_shown_notice: null })), context);
|
|
62
|
+
}
|
|
63
|
+
const state = loadUpdateState(directory, current);
|
|
64
|
+
if (action === 'status')
|
|
65
|
+
return status(state, context);
|
|
66
|
+
if (action === 'worker')
|
|
67
|
+
return runUpdateWorker(directory, current);
|
|
68
|
+
return checkUpdates({ current, channel: options.channel === undefined ? state.channel : updateChannel(options.channel), ...(state.pin === null ? {} : { pin: state.pin }) });
|
|
69
|
+
}
|
|
70
|
+
// Called only for an interactive terminal. Uses cached data and never fetches.
|
|
71
|
+
export function cachedUpdateNotice(directory, current) {
|
|
72
|
+
const state = loadUpdateState(directory, current);
|
|
73
|
+
if (state.mode !== 'notify' || state.last_notice === null || state.last_notice === state.last_shown_notice || !state.report)
|
|
74
|
+
return null;
|
|
75
|
+
const versions = newerVersions(state, current);
|
|
76
|
+
if (versions.length === 0)
|
|
77
|
+
return null;
|
|
78
|
+
let shown = false;
|
|
79
|
+
changeUpdateState(directory, current, next => {
|
|
80
|
+
if (next.revision !== state.revision || next.mode !== 'notify')
|
|
81
|
+
return next;
|
|
82
|
+
shown = true;
|
|
83
|
+
return { ...next, last_shown_notice: state.last_notice };
|
|
84
|
+
});
|
|
85
|
+
return shown ? `Durebak: 새 버전 ${[...new Set(versions)].join(', ')} — durebak update status로 배포처와 설치 방법을 확인하세요.\n` : null;
|
|
86
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface ScheduleOptions {
|
|
2
|
+
home: string;
|
|
3
|
+
platform: string;
|
|
4
|
+
directory: string;
|
|
5
|
+
node: string;
|
|
6
|
+
cli: string;
|
|
7
|
+
uid: number;
|
|
8
|
+
}
|
|
9
|
+
export interface ScheduleReceipt {
|
|
10
|
+
kind: 'launchd' | 'systemd';
|
|
11
|
+
digest: string;
|
|
12
|
+
}
|
|
13
|
+
export type ScheduleRunner = (command: string, args: string[]) => number;
|
|
14
|
+
export declare function scheduleFiles(options: ScheduleOptions): {
|
|
15
|
+
path: string;
|
|
16
|
+
text: string;
|
|
17
|
+
}[];
|
|
18
|
+
export declare function installUpdateSchedule(options: ScheduleOptions, run?: ScheduleRunner): ScheduleReceipt;
|
|
19
|
+
export declare function removeUpdateSchedule(options: ScheduleOptions, receipt: ScheduleReceipt, run?: ScheduleRunner): void;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { mkdirSync, lstatSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { join, resolve, isAbsolute } from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { fail } from './domain.js';
|
|
6
|
+
const runner = (command, args) => { const result = spawnSync(command, args, { stdio: 'ignore', timeout: 10000, env: { PATH: '/usr/bin:/bin', HOME: process.env.HOME ?? '', XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR ?? '', DBUS_SESSION_BUS_ADDRESS: process.env.DBUS_SESSION_BUS_ADDRESS ?? '' } }); return result.status ?? -1; };
|
|
7
|
+
function id(options) { return 'com.durebak.updates.' + createHash('sha256').update(resolve(options.directory)).digest('hex').slice(0, 20); }
|
|
8
|
+
function validate(options) {
|
|
9
|
+
if (!['darwin', 'linux'].includes(options.platform) || options.uid === 0 || !Number.isSafeInteger(options.uid) || options.uid < 0)
|
|
10
|
+
fail('unsupported_update_scheduler');
|
|
11
|
+
for (const value of [options.home, options.directory, options.node, options.cli])
|
|
12
|
+
if (!isAbsolute(value) || /[\x00-\x1f\x7f]/.test(value))
|
|
13
|
+
fail('unsafe_update_schedule_path');
|
|
14
|
+
}
|
|
15
|
+
const xml = (value) => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
|
|
16
|
+
const unitArg = (value) => '"' + value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%').replaceAll('$', () => '$$') + '"';
|
|
17
|
+
export function scheduleFiles(options) {
|
|
18
|
+
validate(options);
|
|
19
|
+
const label = id(options);
|
|
20
|
+
const args = [options.node, options.cli, 'update', 'worker', '--update-dir', resolve(options.directory)];
|
|
21
|
+
if (options.platform === 'darwin')
|
|
22
|
+
return [{ path: join(options.home, 'Library', 'LaunchAgents', label + '.plist'), text: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array>${args.map(a => '<string>' + xml(a) + '</string>').join('')}</array><key>RunAtLoad</key><true/><key>StartInterval</key><integer>60</integer><key>LimitLoadToSessionType</key><string>Aqua</string></dict></plist>\n` }];
|
|
23
|
+
const base = join(options.home, '.config', 'systemd', 'user', label);
|
|
24
|
+
return [{ path: base + '.service', text: `[Unit]\nDescription=Durebak update notification check\n[Service]\nType=oneshot\nExecStart=${args.map(unitArg).join(' ')}\nTimeoutStartSec=30\n` }, { path: base + '.timer', text: `[Unit]\nDescription=Durebak update notification timer\n[Timer]\nOnCalendar=*-*-* *:*:00\nPersistent=true\nUnit=${label}.service\n[Install]\nWantedBy=timers.target\n` }];
|
|
25
|
+
}
|
|
26
|
+
function safe(stat, directory) { if (stat.uid !== process.geteuid?.() || (stat.mode & 0o022) !== 0 || stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o077) !== 0 || stat.size > 16384))
|
|
27
|
+
fail('unsafe_update_schedule'); }
|
|
28
|
+
function parent(options) {
|
|
29
|
+
safe(lstatSync(options.home), true);
|
|
30
|
+
let path = options.home;
|
|
31
|
+
for (const component of options.platform === 'darwin' ? ['Library', 'LaunchAgents'] : ['.config', 'systemd', 'user']) {
|
|
32
|
+
path = join(path, component);
|
|
33
|
+
try {
|
|
34
|
+
mkdirSync(path, { mode: 0o700 });
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code !== 'EEXIST')
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
safe(lstatSync(path), true);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const digest = (texts) => createHash('sha256').update(texts.join('\0')).digest('hex');
|
|
44
|
+
function read(path) { safe(lstatSync(path), false); return readFileSync(path, 'utf8'); }
|
|
45
|
+
function command(options, action, run) {
|
|
46
|
+
const label = id(options);
|
|
47
|
+
if (options.platform === 'darwin' && action === 'install' && run('/bin/launchctl', ['print', `gui/${options.uid}/${label}`]) === 0)
|
|
48
|
+
return;
|
|
49
|
+
const commands = options.platform === 'darwin' ? action === 'install' ? [['/bin/launchctl', 'bootstrap', `gui/${options.uid}`, scheduleFiles(options)[0].path]] : [['/bin/launchctl', 'bootout', `gui/${options.uid}/${label}`]] : action === 'install' ? [['/usr/bin/systemctl', '--user', 'daemon-reload'], ['/usr/bin/systemctl', '--user', 'enable', '--now', label + '.timer']] : [['/usr/bin/systemctl', '--user', 'disable', '--now', label + '.timer']];
|
|
50
|
+
for (const [exe, ...args] of commands)
|
|
51
|
+
if (run(exe, args) !== 0)
|
|
52
|
+
fail('update_schedule_failed');
|
|
53
|
+
}
|
|
54
|
+
export function installUpdateSchedule(options, run = runner) {
|
|
55
|
+
validate(options);
|
|
56
|
+
parent(options);
|
|
57
|
+
const files = scheduleFiles(options), created = [];
|
|
58
|
+
let registering = false;
|
|
59
|
+
try {
|
|
60
|
+
for (const file of files) {
|
|
61
|
+
try {
|
|
62
|
+
const existing = read(file.path);
|
|
63
|
+
if (existing !== file.text)
|
|
64
|
+
fail('update_schedule_conflict');
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error.code !== 'ENOENT')
|
|
68
|
+
throw error;
|
|
69
|
+
writeFileSync(file.path, file.text, { flag: 'wx', mode: 0o600 });
|
|
70
|
+
created.push(file.path);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
registering = true;
|
|
74
|
+
command(options, 'install', run);
|
|
75
|
+
return { kind: options.platform === 'darwin' ? 'launchd' : 'systemd', digest: digest(files.map(f => f.text)) };
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (created.length) {
|
|
79
|
+
if (registering) {
|
|
80
|
+
try {
|
|
81
|
+
command(options, 'remove', run);
|
|
82
|
+
}
|
|
83
|
+
catch { /* disabled policy keeps any partial registration inert */ }
|
|
84
|
+
}
|
|
85
|
+
for (const path of created) {
|
|
86
|
+
try {
|
|
87
|
+
if (read(path) === files.find(f => f.path === path).text)
|
|
88
|
+
unlinkSync(path);
|
|
89
|
+
}
|
|
90
|
+
catch { /* preserve uncertain file */ }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export function removeUpdateSchedule(options, receipt, run = runner) {
|
|
97
|
+
validate(options);
|
|
98
|
+
parent(options);
|
|
99
|
+
const files = scheduleFiles(options);
|
|
100
|
+
if (receipt.kind !== (options.platform === 'darwin' ? 'launchd' : 'systemd') || digest(files.map(f => read(f.path))) !== receipt.digest)
|
|
101
|
+
fail('update_schedule_conflict');
|
|
102
|
+
command(options, 'remove', run);
|
|
103
|
+
for (const file of files)
|
|
104
|
+
unlinkSync(file.path);
|
|
105
|
+
// The timer was already disabled and stopped before deleting its config.
|
|
106
|
+
// A cache-refresh failure does not undo that completed removal.
|
|
107
|
+
if (options.platform === 'linux')
|
|
108
|
+
run('/usr/bin/systemctl', ['--user', 'daemon-reload']);
|
|
109
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type UpdateReport, type UpdateRequest } from './updates.js';
|
|
3
|
+
declare const stateSchema: z.ZodObject<{
|
|
4
|
+
schema: z.ZodLiteral<1>;
|
|
5
|
+
revision: z.ZodNumber;
|
|
6
|
+
mode: z.ZodEnum<{
|
|
7
|
+
disabled: "disabled";
|
|
8
|
+
notify: "notify";
|
|
9
|
+
}>;
|
|
10
|
+
channel: z.ZodEnum<{
|
|
11
|
+
alpha: "alpha";
|
|
12
|
+
beta: "beta";
|
|
13
|
+
rc: "rc";
|
|
14
|
+
stable: "stable";
|
|
15
|
+
}>;
|
|
16
|
+
pin: z.ZodNullable<z.ZodString>;
|
|
17
|
+
last_checked_at: z.ZodNullable<z.ZodNumber>;
|
|
18
|
+
next_check_at: z.ZodNullable<z.ZodNumber>;
|
|
19
|
+
report: z.ZodNullable<z.ZodObject<{
|
|
20
|
+
current: z.ZodString;
|
|
21
|
+
channel: z.ZodEnum<{
|
|
22
|
+
alpha: "alpha";
|
|
23
|
+
beta: "beta";
|
|
24
|
+
rc: "rc";
|
|
25
|
+
stable: "stable";
|
|
26
|
+
}>;
|
|
27
|
+
automatic_apply: z.ZodLiteral<false>;
|
|
28
|
+
installation_owner: z.ZodLiteral<"unverified">;
|
|
29
|
+
installation_guide_url: z.ZodLiteral<"https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md">;
|
|
30
|
+
npm: z.ZodObject<{
|
|
31
|
+
status: z.ZodEnum<{
|
|
32
|
+
installed_ahead: "installed_ahead";
|
|
33
|
+
pinned: "pinned";
|
|
34
|
+
unavailable: "unavailable";
|
|
35
|
+
up_to_date: "up_to_date";
|
|
36
|
+
update_available: "update_available";
|
|
37
|
+
}>;
|
|
38
|
+
version: z.ZodNullable<z.ZodString>;
|
|
39
|
+
release_url: z.ZodNullable<z.ZodString>;
|
|
40
|
+
install_command: z.ZodNullable<z.ZodString>;
|
|
41
|
+
}, z.core.$strict>;
|
|
42
|
+
github: z.ZodObject<{
|
|
43
|
+
status: z.ZodEnum<{
|
|
44
|
+
installed_ahead: "installed_ahead";
|
|
45
|
+
pinned: "pinned";
|
|
46
|
+
unavailable: "unavailable";
|
|
47
|
+
up_to_date: "up_to_date";
|
|
48
|
+
update_available: "update_available";
|
|
49
|
+
}>;
|
|
50
|
+
version: z.ZodNullable<z.ZodString>;
|
|
51
|
+
release_url: z.ZodNullable<z.ZodString>;
|
|
52
|
+
install_command: z.ZodNullable<z.ZodString>;
|
|
53
|
+
}, z.core.$strict>;
|
|
54
|
+
}, z.core.$strict>>;
|
|
55
|
+
last_notice: z.ZodNullable<z.ZodString>;
|
|
56
|
+
scheduler: z.ZodEnum<{
|
|
57
|
+
launchd: "launchd";
|
|
58
|
+
none: "none";
|
|
59
|
+
systemd: "systemd";
|
|
60
|
+
}>;
|
|
61
|
+
scheduler_digest: z.ZodNullable<z.ZodString>;
|
|
62
|
+
last_shown_notice: z.ZodNullable<z.ZodString>;
|
|
63
|
+
}, z.core.$strict>;
|
|
64
|
+
export type UpdateState = z.infer<typeof stateSchema>;
|
|
65
|
+
export declare function defaultUpdateState(current: string): UpdateState;
|
|
66
|
+
export declare function loadUpdateState(directory: string, current: string): UpdateState;
|
|
67
|
+
export declare function changeUpdateState(directory: string, current: string, change: (state: UpdateState) => UpdateState): UpdateState;
|
|
68
|
+
export declare function runUpdateWorker(directory: string, current: string, request?: UpdateRequest, now?: number): Promise<{
|
|
69
|
+
checked: boolean;
|
|
70
|
+
notice: boolean;
|
|
71
|
+
report?: UpdateReport;
|
|
72
|
+
reason?: string;
|
|
73
|
+
}>;
|
|
74
|
+
export {};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { openSync, closeSync, fstatSync, lstatSync, readSync, writeFileSync, renameSync, unlinkSync, fsyncSync, constants } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { privateDirectory } from './database.js';
|
|
7
|
+
import { fail } from './domain.js';
|
|
8
|
+
import { checkUpdates, channelForVersion, releaseVersion } from './updates.js';
|
|
9
|
+
const channel = z.enum(['stable', 'alpha', 'beta', 'rc']);
|
|
10
|
+
const source = z.object({ status: z.enum(['update_available', 'up_to_date', 'installed_ahead', 'unavailable', 'pinned']), version: releaseVersion.nullable(), release_url: z.string().max(250).nullable(), install_command: z.string().max(250).nullable() }).strict().refine(s => {
|
|
11
|
+
if (s.version === null)
|
|
12
|
+
return s.status === 'unavailable' && s.release_url === null && s.install_command === null;
|
|
13
|
+
return s.release_url === `https://github.com/ggujunhi247/durebak/releases/tag/v${s.version}` && (s.install_command === null || s.install_command === `npm install --global durebak@${s.version} --registry=https://registry.npmjs.org`);
|
|
14
|
+
});
|
|
15
|
+
const reportSchema = z.object({ current: releaseVersion, channel, automatic_apply: z.literal(false), installation_owner: z.literal('unverified'), installation_guide_url: z.literal('https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md'), npm: source, github: source }).strict();
|
|
16
|
+
const stateSchema = z.object({ schema: z.literal(1), revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), mode: z.enum(['disabled', 'notify']), channel, pin: releaseVersion.nullable(), last_checked_at: z.number().int().nonnegative().nullable(), next_check_at: z.number().int().nonnegative().nullable(), report: reportSchema.nullable(), last_notice: z.string().regex(/^[a-f0-9]{64}$/).nullable(), scheduler: z.enum(['none', 'launchd', 'systemd']), scheduler_digest: z.string().regex(/^[a-f0-9]{64}$/).nullable(), last_shown_notice: z.string().regex(/^[a-f0-9]{64}$/).nullable() }).strict();
|
|
17
|
+
export function defaultUpdateState(current) { return { schema: 1, revision: 0, mode: 'disabled', channel: channelForVersion(current), pin: null, last_checked_at: null, next_check_at: null, report: null, last_notice: null, scheduler: 'none', scheduler_digest: null, last_shown_notice: null }; }
|
|
18
|
+
function missing(error) { return error.code === 'ENOENT'; }
|
|
19
|
+
function checkFile(stat) { if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.geteuid?.() || (stat.mode & 0o077) !== 0 || stat.size > 16384)
|
|
20
|
+
fail('unsafe_update_state'); }
|
|
21
|
+
function same(a, b) { return a.dev === b.dev && a.ino === b.ino; }
|
|
22
|
+
export function loadUpdateState(directory, current) {
|
|
23
|
+
try {
|
|
24
|
+
lstatSync(directory);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (missing(error))
|
|
28
|
+
return defaultUpdateState(current);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
privateDirectory(directory);
|
|
32
|
+
const file = join(directory, 'state.json');
|
|
33
|
+
let fd;
|
|
34
|
+
try {
|
|
35
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (missing(error))
|
|
39
|
+
return defaultUpdateState(current);
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
const stat = fstatSync(fd);
|
|
44
|
+
checkFile(stat);
|
|
45
|
+
const buffer = Buffer.alloc(16385);
|
|
46
|
+
const count = readSync(fd, buffer, 0, buffer.length, 0);
|
|
47
|
+
if (count > 16384 || !same(stat, lstatSync(file)) || fstatSync(fd).size !== stat.size || count !== stat.size)
|
|
48
|
+
fail('unsafe_update_state');
|
|
49
|
+
const result = stateSchema.safeParse(JSON.parse(buffer.subarray(0, count).toString('utf8')));
|
|
50
|
+
if (!result.success)
|
|
51
|
+
fail('invalid_update_state');
|
|
52
|
+
return result.data;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof SyntaxError)
|
|
56
|
+
fail('invalid_update_state');
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// SQLite owns the OS locks: process death releases coordination automatically.
|
|
64
|
+
// These files are never removed or reclaimed using PID/age guesses.
|
|
65
|
+
function lock(directory, name) {
|
|
66
|
+
privateDirectory(directory);
|
|
67
|
+
const file = join(directory, name + '.sqlite');
|
|
68
|
+
try {
|
|
69
|
+
closeSync(openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error.code !== 'EEXIST')
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
const inspect = () => { checkFile(lstatSync(file)); for (const suffix of ['-wal', '-shm', '-journal']) {
|
|
76
|
+
try {
|
|
77
|
+
checkFile(lstatSync(file + suffix));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (!missing(error))
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
} };
|
|
84
|
+
inspect();
|
|
85
|
+
const db = new DatabaseSync(file);
|
|
86
|
+
try {
|
|
87
|
+
db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE;');
|
|
88
|
+
inspect();
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
db.close();
|
|
92
|
+
if (error.message.includes('database is locked'))
|
|
93
|
+
fail('update_state_busy');
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
return () => db.close();
|
|
97
|
+
}
|
|
98
|
+
export function changeUpdateState(directory, current, change) {
|
|
99
|
+
const unlock = lock(directory, 'writer.lock');
|
|
100
|
+
let temporary;
|
|
101
|
+
try {
|
|
102
|
+
const previous = loadUpdateState(directory, current), next = stateSchema.parse({ ...change(previous), revision: previous.revision + 1 });
|
|
103
|
+
const text = JSON.stringify(next) + '\n';
|
|
104
|
+
if (Buffer.byteLength(text) > 16384)
|
|
105
|
+
fail('update_state_too_large');
|
|
106
|
+
temporary = join(directory, `.state-${randomUUID()}.json`);
|
|
107
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
108
|
+
try {
|
|
109
|
+
writeFileSync(fd, text);
|
|
110
|
+
fsyncSync(fd);
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
closeSync(fd);
|
|
114
|
+
}
|
|
115
|
+
renameSync(temporary, join(directory, 'state.json'));
|
|
116
|
+
temporary = undefined;
|
|
117
|
+
const directoryFd = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
118
|
+
try {
|
|
119
|
+
fsyncSync(directoryFd);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
closeSync(directoryFd);
|
|
123
|
+
}
|
|
124
|
+
return next;
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
if (temporary !== undefined)
|
|
128
|
+
unlinkSync(temporary);
|
|
129
|
+
unlock();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
export async function runUpdateWorker(directory, current, request, now = Date.now()) {
|
|
133
|
+
const initial = loadUpdateState(directory, current);
|
|
134
|
+
if (initial.mode !== 'notify' || (initial.next_check_at !== null && initial.next_check_at > now))
|
|
135
|
+
return { checked: false, notice: false };
|
|
136
|
+
if (initial.last_checked_at !== null && now < initial.last_checked_at)
|
|
137
|
+
return { checked: false, notice: false, reason: 'clock_reversed' };
|
|
138
|
+
const unlock = lock(directory, 'worker.lock');
|
|
139
|
+
try {
|
|
140
|
+
const before = loadUpdateState(directory, current);
|
|
141
|
+
if (before.mode !== 'notify' || before.revision !== initial.revision)
|
|
142
|
+
return { checked: false, notice: false };
|
|
143
|
+
const report = await checkUpdates({ current, channel: before.channel, ...(before.pin === null ? {} : { pin: before.pin }) }, request);
|
|
144
|
+
const fingerprint = createHash('sha256').update(JSON.stringify([report.channel, report.npm.status, report.npm.version, report.github.status, report.github.version])).digest('hex');
|
|
145
|
+
let notice = false, committed = false;
|
|
146
|
+
changeUpdateState(directory, current, state => {
|
|
147
|
+
if (state.revision !== before.revision || state.mode !== 'notify')
|
|
148
|
+
return state;
|
|
149
|
+
notice = [report.npm.status, report.github.status].includes('update_available') && fingerprint !== state.last_notice;
|
|
150
|
+
committed = true;
|
|
151
|
+
return { ...state, report, last_checked_at: now, next_check_at: now + 3600000, last_notice: notice ? fingerprint : state.last_notice };
|
|
152
|
+
});
|
|
153
|
+
return committed ? { checked: true, notice, report } : { checked: false, notice: false, reason: 'policy_changed' };
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
unlock();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
import { type UpdateChannel } from './updates.js';
|
|
3
|
+
export declare function automaticUpdateBlockers(platform: string): string[];
|
|
4
|
+
export interface UpdateManifestContext {
|
|
5
|
+
current: string;
|
|
6
|
+
channel: UpdateChannel;
|
|
7
|
+
platform: string;
|
|
8
|
+
arch: string;
|
|
9
|
+
schema: number;
|
|
10
|
+
protocol: number;
|
|
11
|
+
now: number;
|
|
12
|
+
}
|
|
13
|
+
export declare function verifyUpdateManifest(input: unknown, keys: Readonly<Record<string, KeyObject>>, context: UpdateManifestContext): {
|
|
14
|
+
schema: 1;
|
|
15
|
+
package: "durebak";
|
|
16
|
+
version: string;
|
|
17
|
+
channel: "alpha" | "beta" | "rc" | "stable";
|
|
18
|
+
platform: "darwin" | "linux" | "win32";
|
|
19
|
+
arch: "arm64" | "x64";
|
|
20
|
+
min_updater: string;
|
|
21
|
+
database_schema: number;
|
|
22
|
+
protocol: number;
|
|
23
|
+
issued_at: number;
|
|
24
|
+
expires_at: number;
|
|
25
|
+
artifact: {
|
|
26
|
+
url: string;
|
|
27
|
+
sha256: string;
|
|
28
|
+
bytes: number;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { verify } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { fail } from './domain.js';
|
|
4
|
+
import { releaseVersion, channelForVersion, compareVersions } from './updates.js';
|
|
5
|
+
// No operational signing identity has been approved or published yet. Do not
|
|
6
|
+
// accept keys from downloaded metadata, environment variables, or CLI input.
|
|
7
|
+
const trustedUpdateKeys = Object.freeze({});
|
|
8
|
+
export function automaticUpdateBlockers(platform) {
|
|
9
|
+
return [...(platform === 'win32' ? ['unsupported_storage_platform'] : []), ...(Object.keys(trustedUpdateKeys).length === 0 ? ['release_trust_not_configured'] : []), 'installation_owner_unverified', 'maintenance_gate_unavailable', 'recovery_worker_unavailable'];
|
|
10
|
+
}
|
|
11
|
+
const envelopeSchema = z.object({ key_id: z.string().regex(/^[a-zA-Z0-9-]{1,64}$/), payload: z.string().max(350000), signature: z.string().max(100) }).strict();
|
|
12
|
+
const timestamp = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
13
|
+
const manifestSchema = z.object({ schema: z.literal(1), package: z.literal('durebak'), version: releaseVersion, channel: z.enum(['alpha', 'beta', 'rc', 'stable']), platform: z.enum(['darwin', 'linux', 'win32']), arch: z.enum(['x64', 'arm64']), min_updater: releaseVersion, database_schema: z.number().int().nonnegative(), protocol: z.number().int().nonnegative(), issued_at: timestamp, expires_at: timestamp, artifact: z.object({ url: z.string().max(300), sha256: z.string().regex(/^[a-f0-9]{64}$/), bytes: z.number().int().min(1).max(67108864) }).strict() }).strict();
|
|
14
|
+
function base64(value) { const bytes = Buffer.from(value, 'base64'); if (bytes.toString('base64') !== value)
|
|
15
|
+
fail('invalid_update_manifest'); return bytes; }
|
|
16
|
+
export function verifyUpdateManifest(input, keys, context) {
|
|
17
|
+
const parsed = envelopeSchema.safeParse(input);
|
|
18
|
+
if (!parsed.success)
|
|
19
|
+
fail('invalid_update_manifest');
|
|
20
|
+
const envelope = parsed.data;
|
|
21
|
+
const key = Object.hasOwn(keys, envelope.key_id) ? keys[envelope.key_id] : undefined;
|
|
22
|
+
if (!key || key.asymmetricKeyType !== 'ed25519')
|
|
23
|
+
fail('unknown_update_key');
|
|
24
|
+
const payload = base64(envelope.payload), signature = base64(envelope.signature);
|
|
25
|
+
if (payload.length > 262144 || signature.length !== 64)
|
|
26
|
+
fail('invalid_update_manifest');
|
|
27
|
+
if (!verify(null, payload, key, signature))
|
|
28
|
+
fail('invalid_update_signature');
|
|
29
|
+
let decoded;
|
|
30
|
+
try {
|
|
31
|
+
decoded = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(payload));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
fail('invalid_update_manifest');
|
|
35
|
+
}
|
|
36
|
+
const result = manifestSchema.safeParse(decoded);
|
|
37
|
+
if (!result.success)
|
|
38
|
+
fail('invalid_update_manifest');
|
|
39
|
+
const release = result.data;
|
|
40
|
+
if (!Number.isSafeInteger(context.now) || context.now < release.issued_at || release.expires_at <= context.now || release.expires_at <= release.issued_at || release.expires_at - release.issued_at > 604800000)
|
|
41
|
+
fail('expired_update_manifest');
|
|
42
|
+
if (release.channel !== context.channel || channelForVersion(release.version) !== context.channel || release.platform !== context.platform || release.arch !== context.arch)
|
|
43
|
+
fail('incompatible_update_manifest');
|
|
44
|
+
if (release.database_schema !== context.schema || release.protocol !== context.protocol)
|
|
45
|
+
fail('manual_migration_required');
|
|
46
|
+
if (compareVersions(release.version, context.current) <= 0 || compareVersions(release.min_updater, context.current) > 0)
|
|
47
|
+
fail('incompatible_update_version');
|
|
48
|
+
const url = `https://github.com/ggujunhi247/durebak/releases/download/v${release.version}/durebak-${release.version}.tgz`;
|
|
49
|
+
if (release.artifact.url !== url)
|
|
50
|
+
fail('unsafe_update_artifact');
|
|
51
|
+
return release;
|
|
52
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export type UpdateChannel = 'stable' | 'alpha' | 'beta' | 'rc';
|
|
3
|
+
export declare const releaseVersion: z.ZodString;
|
|
4
|
+
export declare function updateChannel(value: string): UpdateChannel;
|
|
5
|
+
export declare function channelForVersion(value: string): UpdateChannel;
|
|
6
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
7
|
+
export type SourceStatus = 'update_available' | 'up_to_date' | 'installed_ahead' | 'unavailable' | 'pinned';
|
|
8
|
+
export interface UpdateSource {
|
|
9
|
+
status: SourceStatus;
|
|
10
|
+
version: string | null;
|
|
11
|
+
release_url: string | null;
|
|
12
|
+
install_command: string | null;
|
|
13
|
+
}
|
|
14
|
+
export interface UpdateReport {
|
|
15
|
+
current: string;
|
|
16
|
+
channel: UpdateChannel;
|
|
17
|
+
automatic_apply: false;
|
|
18
|
+
installation_owner: 'unverified';
|
|
19
|
+
installation_guide_url: 'https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md';
|
|
20
|
+
npm: UpdateSource;
|
|
21
|
+
github: UpdateSource;
|
|
22
|
+
}
|
|
23
|
+
export type UpdateRequest = (url: string) => Promise<unknown>;
|
|
24
|
+
export declare function readUpdateJson(url: string, fetcher?: typeof fetch): Promise<unknown>;
|
|
25
|
+
export declare function checkUpdates(options: {
|
|
26
|
+
current: string;
|
|
27
|
+
channel: UpdateChannel;
|
|
28
|
+
pin?: string;
|
|
29
|
+
}, request?: UpdateRequest): Promise<UpdateReport>;
|
package/dist/updates.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { fail } from './domain.js';
|
|
3
|
+
export const releaseVersion = z.string().max(80).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(alpha|beta|rc)\.(0|[1-9]\d*))?$/);
|
|
4
|
+
export function updateChannel(value) {
|
|
5
|
+
if (!['stable', 'alpha', 'beta', 'rc'].includes(value))
|
|
6
|
+
fail('invalid_update_channel');
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
function parts(value) { if (!releaseVersion.safeParse(value).success)
|
|
10
|
+
fail('invalid_update_version'); return value.match(/^(\d+)\.(\d+)\.(\d+)(?:-(alpha|beta|rc)\.(\d+))?$/); }
|
|
11
|
+
export function channelForVersion(value) { return (parts(value)[4] ?? 'stable'); }
|
|
12
|
+
export function compareVersions(a, b) {
|
|
13
|
+
const x = parts(a), y = parts(b);
|
|
14
|
+
for (const i of [1, 2, 3]) {
|
|
15
|
+
const p = BigInt(x[i]), q = BigInt(y[i]);
|
|
16
|
+
if (p !== q)
|
|
17
|
+
return p > q ? 1 : -1;
|
|
18
|
+
}
|
|
19
|
+
const order = ['alpha', 'beta', 'rc', 'stable'];
|
|
20
|
+
const p = order.indexOf(x[4] ?? 'stable'), q = order.indexOf(y[4] ?? 'stable');
|
|
21
|
+
if (p !== q)
|
|
22
|
+
return p > q ? 1 : -1;
|
|
23
|
+
const n = BigInt(x[5] ?? '0'), m = BigInt(y[5] ?? '0');
|
|
24
|
+
return n === m ? 0 : n > m ? 1 : -1;
|
|
25
|
+
}
|
|
26
|
+
const repository = 'https://github.com/ggujunhi247/durebak';
|
|
27
|
+
const registry = 'https://registry.npmjs.org/durebak/';
|
|
28
|
+
const releases = 'https://api.github.com/repos/ggujunhi247/durebak/releases?per_page=10';
|
|
29
|
+
export async function readUpdateJson(url, fetcher = fetch) {
|
|
30
|
+
if (![`${registry}alpha`, `${registry}beta`, `${registry}rc`, `${registry}latest`, releases, ...[2, 3, 4, 5].map(page => `${releases}&page=${page}`)].includes(url))
|
|
31
|
+
fail('unsafe_update_endpoint');
|
|
32
|
+
const response = await fetcher(url, { redirect: 'error', credentials: 'omit', headers: { accept: 'application/json', 'user-agent': 'durebak-update-check' }, signal: AbortSignal.timeout(5000) });
|
|
33
|
+
if (!response.ok || !response.body) {
|
|
34
|
+
await response.body?.cancel();
|
|
35
|
+
fail('update_fetch_failed');
|
|
36
|
+
}
|
|
37
|
+
const length = response.headers.get('content-length');
|
|
38
|
+
if (length !== null && (!/^\d+$/.test(length) || Number(length) > 262144)) {
|
|
39
|
+
await response.body.cancel();
|
|
40
|
+
fail('update_response_too_large');
|
|
41
|
+
}
|
|
42
|
+
const reader = response.body.getReader(), decoder = new TextDecoder('utf-8', { fatal: true });
|
|
43
|
+
let size = 0, text = '';
|
|
44
|
+
try {
|
|
45
|
+
while (true) {
|
|
46
|
+
const { done, value } = await reader.read();
|
|
47
|
+
if (done)
|
|
48
|
+
break;
|
|
49
|
+
size += value.byteLength;
|
|
50
|
+
if (size > 262144)
|
|
51
|
+
fail('update_response_too_large');
|
|
52
|
+
text += decoder.decode(value, { stream: true });
|
|
53
|
+
}
|
|
54
|
+
text += decoder.decode();
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
await reader.cancel();
|
|
58
|
+
}
|
|
59
|
+
return JSON.parse(text);
|
|
60
|
+
}
|
|
61
|
+
const empty = () => ({ status: 'unavailable', version: null, release_url: null, install_command: null });
|
|
62
|
+
function source(current, target, pin) {
|
|
63
|
+
const cmp = compareVersions(target, current);
|
|
64
|
+
return { status: pin ? 'pinned' : cmp > 0 ? 'update_available' : cmp < 0 ? 'installed_ahead' : 'up_to_date', version: target, release_url: `${repository}/releases/tag/v${target}`, install_command: null };
|
|
65
|
+
}
|
|
66
|
+
async function readReleasePages(request) {
|
|
67
|
+
const all = [];
|
|
68
|
+
for (let page = 1; page <= 5; page++) {
|
|
69
|
+
const value = await request(releases + (page === 1 ? '' : `&page=${page}`));
|
|
70
|
+
if (!Array.isArray(value) || value.length > 10)
|
|
71
|
+
return null;
|
|
72
|
+
all.push(...value);
|
|
73
|
+
if (value.length < 10)
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
return all;
|
|
77
|
+
}
|
|
78
|
+
export async function checkUpdates(options, request = readUpdateJson) {
|
|
79
|
+
channelForVersion(options.current);
|
|
80
|
+
updateChannel(options.channel);
|
|
81
|
+
if (options.pin !== undefined)
|
|
82
|
+
channelForVersion(options.pin);
|
|
83
|
+
const report = { current: options.current, channel: options.channel, automatic_apply: false, installation_owner: 'unverified', installation_guide_url: 'https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md', npm: empty(), github: empty() };
|
|
84
|
+
const results = await Promise.allSettled([request(registry + (options.channel === 'stable' ? 'latest' : options.channel)), readReleasePages(request)]);
|
|
85
|
+
const npm = results[0], github = results[1];
|
|
86
|
+
if (npm?.status === 'fulfilled') {
|
|
87
|
+
const parsed = z.object({ name: z.literal('durebak'), version: releaseVersion }).safeParse(npm.value);
|
|
88
|
+
if (parsed.success && channelForVersion(parsed.data.version) === options.channel)
|
|
89
|
+
report.npm = source(options.current, parsed.data.version, options.pin);
|
|
90
|
+
}
|
|
91
|
+
if (github?.status === 'fulfilled') {
|
|
92
|
+
const parsed = z.array(z.object({ tag_name: z.string().max(81), draft: z.boolean(), prerelease: z.boolean(), html_url: z.string().max(250), assets: z.array(z.object({ name: z.string().max(150), browser_download_url: z.string().max(300) })).max(100) })).max(50).safeParse(github.value);
|
|
93
|
+
if (parsed.success) {
|
|
94
|
+
const candidates = parsed.data.filter(item => {
|
|
95
|
+
const v = item.tag_name.slice(1);
|
|
96
|
+
if (!item.tag_name.startsWith('v') || !releaseVersion.safeParse(v).success)
|
|
97
|
+
return false;
|
|
98
|
+
return !item.draft && item.prerelease === (channelForVersion(v) !== 'stable') && channelForVersion(v) === options.channel && item.html_url === `${repository}/releases/tag/v${v}` && item.assets.some(a => a.name === `durebak-${v}.tgz` && a.browser_download_url === `${repository}/releases/download/v${v}/durebak-${v}.tgz`);
|
|
99
|
+
}).map(item => item.tag_name.slice(1)).sort((a, b) => compareVersions(b, a));
|
|
100
|
+
if (candidates[0])
|
|
101
|
+
report.github = source(options.current, candidates[0], options.pin);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return report;
|
|
105
|
+
}
|
package/docs/USAGE.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# 두레박 사용법 — cooperative alpha
|
|
2
2
|
|
|
3
|
-
Node.js 24 이상이 필요하다. GitHub 소스와 npm alpha 채널은 공개되어 있다. 다음 개발 기능은 배포 버전과 구분한다. 아래 절차는 저장소에서 빌드해 실행하는 방법이다.
|
|
3
|
+
macOS 또는 Linux와 Node.js 24 이상이 필요하다. Windows 저장소는 아직 지원하지 않으며, OS 사용자 ID를 확인할 수 없는 환경에서는 파일 생성 전에 `unsupported_storage_platform`으로 중단한다. GitHub 소스와 npm alpha 채널은 공개되어 있다. 다음 개발 기능은 배포 버전과 구분한다. 아래 절차는 저장소에서 빌드해 실행하는 방법이다.
|
|
4
|
+
|
|
5
|
+
배포 파일 설치·업데이트·실제 경로 확인·릴리스 알림은 [설치·업데이트 안내](https://github.com/ggujunhi247/durebak/blob/main/docs/INSTALLATION.md)를 따른다. alpha.24부터 포함하는 `update-check`/`update status`와 opt-in notify 예약은 설치 안내를 따른다. 기존 alpha.23 배포에는 이 명령이 없으며 자동 설치/rollback은 아직 제공하지 않는다.
|
|
4
6
|
|
|
5
7
|
```sh
|
|
6
8
|
npm ci
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "durebak",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.24",
|
|
4
4
|
"description": "Local durable collaboration between coding-agent sessions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"secrets:selftest": "node scripts/test-secret-scan.mjs"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@modelcontextprotocol/sdk": "1.
|
|
35
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
36
36
|
"zod": "4.6.5"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|