tokocode 0.0.0-stage → 1.0.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.
@@ -0,0 +1,168 @@
1
+ import os from 'node:os';
2
+ import { API_PREFIX, CLI_VERSION, EXIT, RETRY, TIMEOUTS } from '../config/constants.js';
3
+ import { CliError, isNetworkError, toCliError } from '../utils/errors.js';
4
+ import { openRequest, parseRetryAfter, readBody } from '../utils/http.js';
5
+ import { debug } from '../utils/logger.js';
6
+ /**
7
+ * Client of the TokoCode CLI API (/api/v1/cli). Secrets are only ever sent in headers or JSON
8
+ * bodies over HTTPS, never in URLs; the download URL is always built from the configured store,
9
+ * so a session secret can never be sent to another host.
10
+ */
11
+ export class ApiClient {
12
+ baseUrl;
13
+ constructor(baseUrl) {
14
+ this.baseUrl = baseUrl;
15
+ }
16
+ static clientInfo(requestId) {
17
+ return { version: CLI_VERSION, platform: `${process.platform}-${process.arch}`, ...(requestId ? { request_id: requestId } : {}) };
18
+ }
19
+ meta() {
20
+ return this.withRetry(() => this.call('GET', '/meta'));
21
+ }
22
+ verify(token) {
23
+ return this.withRetry(() => this.call('POST', '/tokens/verify', { token }));
24
+ }
25
+ /**
26
+ * Redeems once; a network failure is retried with the same request id, which the server
27
+ * recognises and answers with the same session (a lost response does not burn the token).
28
+ */
29
+ redeem(token, client) {
30
+ return this.withRetry(() => this.call('POST', '/tokens/redeem', { token, client }), RETRY.redeemAttempts);
31
+ }
32
+ refresh(sessionId, secret) {
33
+ return this.withRetry(() => this.call('POST', `/downloads/${sessionId}/refresh`, {}, secret));
34
+ }
35
+ complete(sessionId, secret, sha256) {
36
+ return this.withRetry(() => this.call('POST', `/downloads/${sessionId}/complete`, { sha256, client: ApiClient.clientInfo() }, secret));
37
+ }
38
+ /** Best-effort failure report; never throws. */
39
+ async reportFailure(sessionId, secret, stage, reason) {
40
+ try {
41
+ await this.call('POST', `/downloads/${sessionId}/failed`, { stage, reason: reason.slice(0, 250) }, secret);
42
+ }
43
+ catch (error) {
44
+ debug('failure report not delivered', error.message);
45
+ }
46
+ }
47
+ downloadUrl(sessionId) {
48
+ return `${this.baseUrl}${API_PREFIX}/downloads/${sessionId}`;
49
+ }
50
+ /**
51
+ * Opens the package stream. Returns the raw response for 200/206/416; other statuses are
52
+ * converted into the server's CliError.
53
+ */
54
+ async openDownload(sessionId, secret, start, etag) {
55
+ const headers = this.headers({ Accept: 'application/zip, application/json', Authorization: `Bearer ${secret}`, 'X-TokoCode-Session': secret });
56
+ if (start > 0) {
57
+ headers.Range = `bytes=${start}-`;
58
+ headers['If-Range'] = `"${etag}"`;
59
+ }
60
+ const response = await openRequest({ method: 'GET', url: this.downloadUrl(sessionId), headers, timeoutMs: TIMEOUTS.downloadIdleMs });
61
+ const status = response.statusCode ?? 0;
62
+ if (status === 200 || status === 206 || status === 416) {
63
+ return response;
64
+ }
65
+ throw await this.errorFrom(response);
66
+ }
67
+ async call(method, path, body, secret) {
68
+ const headers = this.headers(secret ? { Authorization: `Bearer ${secret}`, 'X-TokoCode-Session': secret } : {});
69
+ if (body !== undefined) {
70
+ headers['Content-Type'] = 'application/json';
71
+ }
72
+ const response = await openRequest({
73
+ method,
74
+ url: `${this.baseUrl}${API_PREFIX}${path}`,
75
+ headers,
76
+ body: body === undefined ? undefined : JSON.stringify(body),
77
+ timeoutMs: TIMEOUTS.requestMs,
78
+ });
79
+ const status = response.statusCode ?? 0;
80
+ const text = await readBody(response);
81
+ const envelope = parseEnvelope(text);
82
+ debug(`← ${status} ${path}`, envelope && !envelope.ok ? envelope.error : undefined);
83
+ if (envelope?.ok === true && status >= 200 && status < 300) {
84
+ return envelope.data;
85
+ }
86
+ if (envelope && envelope.ok === false) {
87
+ throw new CliError(envelope.error.code, envelope.error.message, envelope.error.hint, EXIT.error, { status, retryAfter: parseRetryAfter(response.headers['retry-after']) });
88
+ }
89
+ throw unavailable(status, response.headers.location);
90
+ }
91
+ async errorFrom(response) {
92
+ const status = response.statusCode ?? 0;
93
+ let text = '';
94
+ try {
95
+ text = await readBody(response, 64 * 1024);
96
+ }
97
+ catch {
98
+ // The status alone is enough to explain the failure.
99
+ }
100
+ const envelope = parseEnvelope(text);
101
+ if (envelope && envelope.ok === false) {
102
+ return new CliError(envelope.error.code, envelope.error.message, envelope.error.hint, EXIT.error, { status, retryAfter: parseRetryAfter(response.headers['retry-after']) });
103
+ }
104
+ return unavailable(status, response.headers.location);
105
+ }
106
+ headers(extra = {}) {
107
+ return {
108
+ 'User-Agent': `tokocode-cli/${CLI_VERSION} (${process.platform} ${os.release()}; node ${process.version})`,
109
+ 'X-TokoCode-CLI': CLI_VERSION,
110
+ Accept: 'application/json',
111
+ ...extra,
112
+ };
113
+ }
114
+ /**
115
+ * Retries network failures and 5xx/429 answers with exponential backoff (Retry-After honoured).
116
+ */
117
+ async withRetry(action, attempts = 3) {
118
+ let lastError;
119
+ for (let attempt = 1; attempt <= attempts; attempt++) {
120
+ try {
121
+ return await action();
122
+ }
123
+ catch (error) {
124
+ lastError = error;
125
+ const retryable = isNetworkError(error)
126
+ || (error instanceof CliError && (error.code === 'server_unavailable' || error.code === 'rate_limited' || error.code === 'server_busy' || error.code === 'internal_error'));
127
+ if (!retryable || attempt === attempts) {
128
+ break;
129
+ }
130
+ const wait = error instanceof CliError && error.retryAfter !== undefined
131
+ ? Math.min(error.retryAfter, RETRY.maxRetryAfterSeconds) * 1000
132
+ : 1000 * 2 ** (attempt - 1);
133
+ debug(`retry ${attempt}/${attempts - 1} in ${wait}ms`, error.message);
134
+ await sleep(wait);
135
+ }
136
+ }
137
+ throw toCliError(lastError);
138
+ }
139
+ }
140
+ function parseEnvelope(text) {
141
+ try {
142
+ const value = JSON.parse(text);
143
+ return value && typeof value === 'object' && 'ok' in value ? value : null;
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ function unavailable(status, location) {
150
+ // Redirects are never followed: the session secret must only reach the configured store.
151
+ if (status >= 300 && status < 400 && location) {
152
+ let target = location;
153
+ try {
154
+ target = new URL(location).origin;
155
+ }
156
+ catch {
157
+ // Relative Location: show it as is.
158
+ }
159
+ return new CliError('api_redirect', `Alamat toko dialihkan ke ${target}.`, `Jalankan ulang dengan alamat yang benar: --api ${target}`, EXIT.error, { status });
160
+ }
161
+ if (status === 404) {
162
+ return new CliError('api_not_found', 'Layanan instalasi tidak ditemukan di server ini.', 'Pastikan alamat toko benar (opsi --api atau TOKOCODE_API_URL) dan website sudah diperbarui.', EXIT.error, { status });
163
+ }
164
+ return new CliError('server_unavailable', `Server TokoCode sedang tidak tersedia${status ? ` (HTTP ${status})` : ''}.`, 'Coba lagi beberapa saat lagi. Jika berulang, hubungi dukungan TokoCode.', EXIT.error, { status });
165
+ }
166
+ export function sleep(ms) {
167
+ return new Promise((resolve) => setTimeout(resolve, ms));
168
+ }
@@ -0,0 +1,23 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ /**
4
+ * SHA-256 of a file, streamed (constant memory whatever the size).
5
+ */
6
+ export function sha256File(file, onProgress) {
7
+ return new Promise((resolve, reject) => {
8
+ const hash = createHash('sha256');
9
+ let bytes = 0;
10
+ const stream = createReadStream(file, { highWaterMark: 1024 * 1024 });
11
+ stream.on('data', (chunk) => {
12
+ hash.update(chunk);
13
+ bytes += chunk.length;
14
+ onProgress?.(bytes);
15
+ });
16
+ stream.on('error', reject);
17
+ stream.on('end', () => resolve(hash.digest('hex')));
18
+ });
19
+ }
20
+ /** Constant-time comparison is not needed (public checksums); case is normalised. */
21
+ export function sameChecksum(a, b) {
22
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
23
+ }
@@ -0,0 +1,145 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import { Transform } from 'node:stream';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { RETRY } from '../config/constants.js';
6
+ import { CliError, isNetworkError, toCliError } from '../utils/errors.js';
7
+ import { fileSize } from '../utils/filesystem.js';
8
+ import { debug } from '../utils/logger.js';
9
+ import { sleep } from './api.service.js';
10
+ /**
11
+ * Streams the package to `partPath`, resuming with HTTP Range after any interruption.
12
+ *
13
+ * - Network drops and stalls: retried with backoff from the bytes already on disk.
14
+ * - 503/429 (server busy, rate limit): waits for Retry-After, then continues.
15
+ * - session_expired: refreshes the session (new secret) and continues.
16
+ * - package_changed: refreshes, discards the partial file and starts the new build.
17
+ * - A server that ignores Range (200) restarts the file from zero.
18
+ *
19
+ * Resolves with the final session and package (both may have changed on the way).
20
+ */
21
+ export async function downloadPackage(job, callbacks = {}) {
22
+ let { session, pkg } = job;
23
+ let failures = 0;
24
+ let refreshedForExpiry = false;
25
+ for (;;) {
26
+ if (job.signal?.aborted) {
27
+ throw new CliError('cancelled', 'Download dibatalkan.');
28
+ }
29
+ let existing = await fileSize(job.partPath);
30
+ if (existing > pkg.size) {
31
+ await fs.rm(job.partPath, { force: true });
32
+ existing = 0;
33
+ }
34
+ if (existing === pkg.size && pkg.size > 0) {
35
+ callbacks.onProgress?.(existing, pkg.size);
36
+ return { session, pkg };
37
+ }
38
+ if (existing > 0) {
39
+ callbacks.onNotice?.(`Melanjutkan download dari ${Math.floor((existing / pkg.size) * 100)}%`);
40
+ }
41
+ try {
42
+ const before = existing;
43
+ await fetchRange(job, session, pkg, existing, callbacks);
44
+ const after = await fileSize(job.partPath);
45
+ if (after > before) {
46
+ failures = 0;
47
+ }
48
+ refreshedForExpiry = false;
49
+ }
50
+ catch (rawError) {
51
+ const error = rawError instanceof CliError ? rawError : null;
52
+ if (error?.code === 'session_expired' && !refreshedForExpiry) {
53
+ callbacks.onNotice?.('Sesi download habis, memperbarui sesi…');
54
+ ({ session, pkg } = await refreshSession(job, session, pkg, callbacks));
55
+ refreshedForExpiry = true;
56
+ continue;
57
+ }
58
+ if (error?.code === 'package_changed') {
59
+ callbacks.onNotice?.('Paket diperbarui di server, mengunduh versi terbaru…');
60
+ ({ session, pkg } = await refreshSession(job, session, pkg, callbacks));
61
+ await fs.rm(job.partPath, { force: true });
62
+ continue;
63
+ }
64
+ if (error?.code === 'range_invalid') {
65
+ await fs.rm(job.partPath, { force: true });
66
+ failures++;
67
+ if (failures > RETRY.downloadAttempts) {
68
+ throw error;
69
+ }
70
+ continue;
71
+ }
72
+ const busy = error && (error.code === 'server_busy' || error.code === 'rate_limited' || error.code === 'server_unavailable' || error.code === 'internal_error');
73
+ if (!busy && !isNetworkError(rawError) && !(rawError instanceof StallError)) {
74
+ throw toCliError(rawError);
75
+ }
76
+ failures++;
77
+ if (failures > RETRY.downloadAttempts) {
78
+ throw new CliError('download_failed', 'Download gagal setelah beberapa kali percobaan.', 'Periksa koneksi internet Anda, lalu jalankan ulang npx tokocode: download dilanjutkan dari bagian yang sudah tersimpan.', 1, { cause: rawError });
79
+ }
80
+ const wait = error?.retryAfter !== undefined
81
+ ? Math.min(error.retryAfter, RETRY.maxRetryAfterSeconds) * 1000
82
+ : Math.min(30_000, 1000 * 2 ** (failures - 1));
83
+ callbacks.onNotice?.(error?.code === 'server_busy'
84
+ ? `Server sedang sibuk, mencoba lagi dalam ${Math.ceil(wait / 1000)} detik…`
85
+ : `Koneksi terputus, mencoba lagi dalam ${Math.ceil(wait / 1000)} detik (percobaan ${failures}/${RETRY.downloadAttempts})…`);
86
+ debug('download retry', rawError.message);
87
+ await sleep(wait);
88
+ }
89
+ }
90
+ }
91
+ class StallError extends Error {
92
+ code = 'ETIMEDOUT';
93
+ }
94
+ async function fetchRange(job, session, pkg, start, callbacks) {
95
+ const response = await job.api.openDownload(session.id, session.secret, start, pkg.sha256);
96
+ const status = response.statusCode ?? 0;
97
+ if (status === 416) {
98
+ response.resume();
99
+ throw new CliError('range_invalid', 'Bagian file tidak tersedia.', '');
100
+ }
101
+ let offset = start;
102
+ let flags = 'a';
103
+ if (status === 200) {
104
+ // Full body: the server ignored the Range or the file changed (If-Range mismatch).
105
+ offset = 0;
106
+ flags = 'w';
107
+ }
108
+ else {
109
+ const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(String(response.headers['content-range'] ?? ''));
110
+ if (!match || Number(match[1]) !== start || Number(match[3]) !== pkg.size) {
111
+ response.resume();
112
+ await fs.rm(job.partPath, { force: true });
113
+ throw new CliError('range_invalid', 'Respons Range tidak sesuai.', '');
114
+ }
115
+ }
116
+ const declared = Number(response.headers['content-length'] ?? NaN);
117
+ if (Number.isFinite(declared) && offset + declared > pkg.size) {
118
+ response.resume();
119
+ throw new CliError('package_changed', 'Ukuran paket berbeda dengan informasi server.', '');
120
+ }
121
+ let received = offset;
122
+ const counter = new Transform({
123
+ transform(chunk, _encoding, done) {
124
+ received += chunk.length;
125
+ if (received > pkg.size) {
126
+ done(new CliError('package_changed', 'Ukuran paket melebihi informasi server.', ''));
127
+ return;
128
+ }
129
+ callbacks.onProgress?.(received, pkg.size);
130
+ done(null, chunk);
131
+ },
132
+ });
133
+ // A socket that stays silent is destroyed by the request timeout; surface it as a stall.
134
+ response.on('aborted', () => response.destroy(new StallError('Download terhenti.')));
135
+ await pipeline(response, counter, createWriteStream(job.partPath, { flags }), { signal: job.signal });
136
+ if (received < pkg.size) {
137
+ throw Object.assign(new Error('Koneksi terputus sebelum download selesai.'), { code: 'ECONNRESET' });
138
+ }
139
+ }
140
+ async function refreshSession(job, session, pkg, callbacks) {
141
+ const refreshed = await job.api.refresh(session.id, session.secret);
142
+ const next = { session: refreshed.session, pkg: { ...pkg, ...refreshed.package } };
143
+ await callbacks.onSessionChange?.(next.session, next.pkg);
144
+ return next;
145
+ }
@@ -0,0 +1,222 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import yauzl, {} from 'yauzl';
6
+ import { EXTRACTION_LIMITS, SOURCE_DIR_NAMES } from '../config/constants.js';
7
+ import { CliError } from '../utils/errors.js';
8
+ import { freeSpace, humanBytes, isInside } from '../utils/filesystem.js';
9
+ /**
10
+ * Safe ZIP extraction.
11
+ *
12
+ * Pass 1 (scan) reads only the central directory and rejects the archive before anything is
13
+ * written when it contains: absolute paths, drive letters, ".." segments (ZIP Slip), encrypted or
14
+ * unsupported entries, names Windows cannot store (on Windows), too many entries, or a zip bomb.
15
+ * It also detects a single wrapper folder ("project-v1/…") to strip, so the project does not end
16
+ * up nested one level too deep. Symbolic links are skipped, never created.
17
+ *
18
+ * Pass 2 writes every entry into `destination`, re-checking that each resolved path stays inside
19
+ * it. Entry sizes are validated by yauzl while streaming.
20
+ */
21
+ const UNIX_FILE_TYPE = 0o170000;
22
+ const UNIX_SYMLINK = 0o120000;
23
+ const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
24
+ // eslint-disable-next-line no-control-regex
25
+ const WINDOWS_INVALID = /[<>:"|?*\u0000-\u001F]/;
26
+ const JUNK = /(^|\/)(__MACOSX\/|\.DS_Store$|Thumbs\.db$)/;
27
+ export async function scanArchive(zipPath) {
28
+ const zip = await openZip(zipPath);
29
+ const raw = [];
30
+ let totalBytes = 0;
31
+ const problems = [];
32
+ try {
33
+ if (zip.entryCount > EXTRACTION_LIMITS.maxEntries) {
34
+ throw new CliError('zip_too_many_entries', `Paket berisi terlalu banyak file (${zip.entryCount}).`, 'Hubungi dukungan TokoCode.');
35
+ }
36
+ await forEachEntry(zip, async (entry) => {
37
+ const name = entry.fileName.replace(/\\/g, '/');
38
+ if (JUNK.test(name)) {
39
+ return;
40
+ }
41
+ checkPath(name);
42
+ if (entry.isEncrypted()) {
43
+ throw new CliError('zip_encrypted', 'Paket ZIP terenkripsi tidak didukung.', 'Hubungi dukungan TokoCode.');
44
+ }
45
+ if (!entry.canDecodeFileData()) {
46
+ throw new CliError('zip_unsupported', `Metode kompresi file "${name}" tidak didukung.`, 'Hubungi dukungan TokoCode.');
47
+ }
48
+ const mode = (entry.externalFileAttributes >>> 16) & 0xffff;
49
+ const symlink = (mode & UNIX_FILE_TYPE) === UNIX_SYMLINK;
50
+ const directory = name.endsWith('/');
51
+ if (!directory && !symlink) {
52
+ totalBytes += entry.uncompressedSize;
53
+ const ratio = entry.compressedSize > 0 ? entry.uncompressedSize / entry.compressedSize : entry.uncompressedSize > 0 ? Infinity : 0;
54
+ if (entry.uncompressedSize >= EXTRACTION_LIMITS.ratioCheckFromBytes && ratio > EXTRACTION_LIMITS.maxRatio) {
55
+ throw new CliError('zip_bomb', 'Paket ZIP mencurigakan (rasio kompresi tidak wajar).', 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
56
+ }
57
+ if (totalBytes > EXTRACTION_LIMITS.maxTotalBytes) {
58
+ throw new CliError('zip_bomb', `Isi paket terlalu besar (lebih dari ${humanBytes(EXTRACTION_LIMITS.maxTotalBytes)}).`, 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
59
+ }
60
+ }
61
+ if (process.platform === 'win32') {
62
+ const bad = name.split('/').filter((segment) => segment !== '').find((segment) => WINDOWS_RESERVED.test(segment) || WINDOWS_INVALID.test(segment) || /[. ]$/.test(segment));
63
+ if (bad !== undefined && problems.length < 5) {
64
+ problems.push(name);
65
+ }
66
+ }
67
+ raw.push({ name, directory, symlink, executable: (mode & 0o111) !== 0 && !directory, size: entry.uncompressedSize });
68
+ });
69
+ }
70
+ catch (error) {
71
+ zip.close();
72
+ throw unsafeArchive(error);
73
+ }
74
+ zip.close();
75
+ if (problems.length > 0) {
76
+ throw new CliError('zip_windows_names', 'Paket berisi nama file yang tidak dapat disimpan di Windows.', `Contoh: ${problems.join(', ')}. Pasang di WSL/Linux/macOS, atau hubungi dukungan TokoCode.`);
77
+ }
78
+ if (raw.length === 0) {
79
+ throw new CliError('zip_empty', 'Paket ZIP kosong.', 'Hubungi dukungan TokoCode.');
80
+ }
81
+ const strippedRoot = wrapperFolder(raw.map((entry) => entry.name));
82
+ const prefix = strippedRoot === null ? '' : strippedRoot + '/';
83
+ const entries = raw
84
+ .map((entry) => ({ ...entry, relative: entry.name.slice(prefix.length).replace(/\/+$/, '') }))
85
+ .filter((entry) => entry.relative !== '');
86
+ return { entries, totalBytes, strippedRoot };
87
+ }
88
+ /**
89
+ * Extracts into `destination` (an empty folder the caller created for this run).
90
+ */
91
+ export async function extractArchive(zipPath, destination, callbacks = {}) {
92
+ const plan = await scanArchive(zipPath);
93
+ const free = await freeSpace(destination);
94
+ if (free !== null && plan.totalBytes + 50 * 1024 * 1024 > free) {
95
+ throw new CliError('enospc', `Ruang penyimpanan tidak cukup: butuh ${humanBytes(plan.totalBytes)}, tersedia ${humanBytes(free)}.`, 'Kosongkan ruang disk atau pilih lokasi instalasi di drive lain.');
96
+ }
97
+ const byName = new Map(plan.entries.map((entry) => [entry.name, entry]));
98
+ const result = { files: 0, directories: 0, bytes: 0, skippedLinks: [], strippedRoot: plan.strippedRoot };
99
+ const root = path.resolve(destination);
100
+ await fs.mkdir(root, { recursive: true });
101
+ const zip = await openZip(zipPath);
102
+ try {
103
+ await forEachEntry(zip, async (entry) => {
104
+ const planned = byName.get(entry.fileName.replace(/\\/g, '/'));
105
+ if (!planned) {
106
+ return;
107
+ }
108
+ const target = path.resolve(root, ...planned.relative.split('/'));
109
+ if (!isInside(root, target) || target === root) {
110
+ throw new CliError('zip_slip', `Paket berisi path berbahaya: ${planned.name}`, 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
111
+ }
112
+ if (planned.symlink) {
113
+ result.skippedLinks.push(planned.relative);
114
+ return;
115
+ }
116
+ if (planned.directory) {
117
+ await fs.mkdir(target, { recursive: true });
118
+ result.directories++;
119
+ return;
120
+ }
121
+ await fs.mkdir(path.dirname(target), { recursive: true });
122
+ const stream = await openEntry(zip, entry);
123
+ await pipeline(stream, createWriteStream(target, { flags: 'w', mode: planned.executable ? 0o755 : 0o644 }));
124
+ try {
125
+ const modified = entry.getLastModDate();
126
+ await fs.utimes(target, modified, modified);
127
+ }
128
+ catch {
129
+ // Timestamps are cosmetic.
130
+ }
131
+ result.files++;
132
+ result.bytes += planned.size;
133
+ callbacks.onProgress?.(result.bytes, plan.totalBytes);
134
+ });
135
+ }
136
+ catch (error) {
137
+ throw unsafeArchive(error);
138
+ }
139
+ finally {
140
+ zip.close();
141
+ }
142
+ return result;
143
+ }
144
+ /**
145
+ * The single top-level folder that wraps everything ("toko-v1.0/…"), or null. A folder that is a
146
+ * project's own source folder (app/, src/, public/…) is never treated as a wrapper.
147
+ */
148
+ export function wrapperFolder(names) {
149
+ const roots = new Set();
150
+ let hasNested = false;
151
+ for (const name of names) {
152
+ const [first, ...rest] = name.split('/');
153
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === '')) {
154
+ // A file at the root (or the wrapper's own directory entry).
155
+ if (!name.endsWith('/')) {
156
+ return null;
157
+ }
158
+ }
159
+ else if (rest.some((segment) => segment !== '')) {
160
+ hasNested = true;
161
+ }
162
+ roots.add(first ?? '');
163
+ }
164
+ const [only] = [...roots];
165
+ return roots.size === 1 && hasNested && only !== undefined && only !== '' && !SOURCE_DIR_NAMES.has(only.toLowerCase()) ? only : null;
166
+ }
167
+ function checkPath(name) {
168
+ const segments = name.split('/');
169
+ if (name.startsWith('/') || /^[A-Za-z]:/.test(name) || name.startsWith('//') || segments.includes('..') || name.includes('\u0000')) {
170
+ throw new CliError('zip_slip', `Paket berisi path berbahaya: ${name.slice(0, 80)}`, 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.');
171
+ }
172
+ }
173
+ function unsafeArchive(error) {
174
+ if (error instanceof CliError) {
175
+ return error;
176
+ }
177
+ const message = error?.message ?? '';
178
+ if (/invalid relative path|absolute path|invalid characters in fileName/i.test(message)) {
179
+ return new CliError('zip_slip', 'Paket berisi path file berbahaya.', 'Instalasi dihentikan demi keamanan. Hubungi dukungan TokoCode.', 1, { cause: error });
180
+ }
181
+ if (/end of central directory|invalid comment length|not a zip|unexpected EOF|invalid signature|too many length or distance symbols|invalid (stored|code|distance)|unknown compression|uncompressed size|compressed size|crc32/i.test(message)) {
182
+ return new CliError('zip_corrupt', 'File ZIP rusak atau tidak lengkap.', 'Jalankan ulang npx tokocode untuk mengunduh ulang. Jika berulang, hubungi dukungan TokoCode.', 1, { cause: error });
183
+ }
184
+ return error;
185
+ }
186
+ function openZip(file) {
187
+ return new Promise((resolve, reject) => {
188
+ yauzl.open(file, { lazyEntries: true, autoClose: false, decodeStrings: true, validateEntrySizes: true, strictFileNames: false }, (error, zip) => {
189
+ if (error || !zip) {
190
+ reject(unsafeArchive(error ?? new Error('invalid signature')));
191
+ return;
192
+ }
193
+ resolve(zip);
194
+ });
195
+ });
196
+ }
197
+ function forEachEntry(zip, handler) {
198
+ return new Promise((resolve, reject) => {
199
+ let failed = false;
200
+ zip.on('entry', (entry) => {
201
+ handler(entry).then(() => zip.readEntry(), (error) => {
202
+ failed = true;
203
+ reject(error);
204
+ });
205
+ });
206
+ zip.once('end', () => {
207
+ if (!failed) {
208
+ resolve();
209
+ }
210
+ });
211
+ zip.once('error', (error) => {
212
+ failed = true;
213
+ reject(error);
214
+ });
215
+ zip.readEntry();
216
+ });
217
+ }
218
+ function openEntry(zip, entry) {
219
+ return new Promise((resolve, reject) => {
220
+ zip.openReadStream(entry, (error, stream) => (error || !stream ? reject(error ?? new Error('stream unavailable')) : resolve(stream)));
221
+ });
222
+ }
@@ -0,0 +1,65 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { STATE_DIR } from '../config/constants.js';
5
+ import { debug } from '../utils/logger.js';
6
+ import { removeQuietly } from '../utils/filesystem.js';
7
+ /**
8
+ * Resumable installations. After a token is redeemed the CLI keeps the download session (short-
9
+ * lived secret, not the token) in the user's temp folder with owner-only permissions, so running
10
+ * `npx tokocode` again continues an interrupted download instead of needing a new token.
11
+ */
12
+ export function stateDir() {
13
+ return process.env.TOKOCODE_STATE_DIR || STATE_DIR;
14
+ }
15
+ export function statePath(sessionId) {
16
+ return path.join(stateDir(), `${sessionId}.json`);
17
+ }
18
+ export function partPath(sessionId) {
19
+ return path.join(stateDir(), `${sessionId}.zip.part`);
20
+ }
21
+ export async function saveState(state) {
22
+ await fs.mkdir(stateDir(), { recursive: true, mode: 0o700 });
23
+ const file = statePath(state.session.id);
24
+ const temp = `${file}.${randomBytes(4).toString('hex')}.tmp`;
25
+ await fs.writeFile(temp, JSON.stringify(state, null, 2), { mode: 0o600 });
26
+ await fs.rename(temp, file);
27
+ }
28
+ /**
29
+ * Unfinished installations for this store whose recovery window is still open (newest first).
30
+ * Expired ones are cleaned up.
31
+ */
32
+ export async function pendingStates(apiUrl) {
33
+ let files;
34
+ try {
35
+ files = (await fs.readdir(stateDir())).filter((name) => name.endsWith('.json'));
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ const states = [];
41
+ for (const name of files) {
42
+ const file = path.join(stateDir(), name);
43
+ try {
44
+ const state = JSON.parse(await fs.readFile(file, 'utf8'));
45
+ if (state.schema !== 1 || !state.session?.id || !/^[a-f0-9]{32}$/.test(state.session.id)) {
46
+ continue;
47
+ }
48
+ if (Date.parse(state.session.refresh_until) <= Date.now()) {
49
+ await discardState(state.session.id);
50
+ continue;
51
+ }
52
+ if (state.apiUrl === apiUrl) {
53
+ states.push(state);
54
+ }
55
+ }
56
+ catch (error) {
57
+ debug(`ignoring unreadable state ${name}`, error.message);
58
+ }
59
+ }
60
+ return states.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
61
+ }
62
+ export async function discardState(sessionId) {
63
+ await removeQuietly(statePath(sessionId));
64
+ await removeQuietly(partPath(sessionId));
65
+ }
@@ -0,0 +1,39 @@
1
+ import { EXIT } from '../config/constants.js';
2
+ import { CliError } from '../utils/errors.js';
3
+ import { ask, isInteractive, out } from '../utils/terminal.js';
4
+ import { formatToken, normalizeToken } from '../utils/validation.js';
5
+ const MAX_PROMPTS = 3;
6
+ /**
7
+ * Gets the installation token from --token, TOKOCODE_TOKEN or a prompt, and checks its format
8
+ * and checksum locally so a typo is caught before any network call.
9
+ *
10
+ * @returns the token formatted as TK-XXXX-…
11
+ */
12
+ export async function readInstallationToken(fromOption) {
13
+ const provided = fromOption ?? process.env.TOKOCODE_TOKEN;
14
+ if (provided !== undefined && provided !== '') {
15
+ const normalized = normalizeToken(provided);
16
+ if (!normalized) {
17
+ throw invalidFormat();
18
+ }
19
+ return formatToken(normalized);
20
+ }
21
+ if (!isInteractive()) {
22
+ throw new CliError('needs_input', 'Installation token belum diberikan.', 'Jalankan di terminal biasa, atau gunakan opsi --token TK-XXXX-…', EXIT.usage);
23
+ }
24
+ for (let attempt = 1; attempt <= MAX_PROMPTS; attempt++) {
25
+ const answer = await ask('Masukkan installation token Anda:');
26
+ const normalized = normalizeToken(answer);
27
+ if (normalized) {
28
+ return formatToken(normalized);
29
+ }
30
+ out.fail('Format token tidak valid.');
31
+ out.muted(attempt < MAX_PROMPTS
32
+ ? ' Token berbentuk TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX. Salin ulang dari dashboard TokoCode (Akun > Instalasi CLI).'
33
+ : '');
34
+ }
35
+ throw invalidFormat();
36
+ }
37
+ function invalidFormat() {
38
+ return new CliError('token_invalid', 'Token tidak valid atau tidak ditemukan.', 'Silakan periksa kembali installation token Anda. Token berbentuk TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX dan dapat disalin dari dashboard TokoCode (Akun > Instalasi CLI).');
39
+ }
@@ -0,0 +1,2 @@
1
+ /** Shapes of the TokoCode CLI API (/api/v1/cli) and of the CLI's own state. */
2
+ export {};