@occam-scaly/scaly-cli 0.2.4 → 0.2.5

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/bin/scaly.js CHANGED
@@ -78,7 +78,8 @@ Usage:
78
78
  scaly db shell --addon <addOnId> [--ttl-minutes 60] [--local-port 5432] [--host 127.0.0.1]
79
79
  scaly db schema dump --addon <addOnId> [--out .scaly/schema.sql] [--ttl-minutes 60]
80
80
  scaly db migrate <sql-file> --addon <addOnId> [--ttl-minutes 60] [--yes]
81
- scaly deploy --app <appId> [--watch] [--strategy auto|git|restart] [--json]
81
+ scaly deploy --app <appId> [--watch] [--strategy auto|git|restart|upload] [--json]
82
+ - upload flags: [--path <dir>] [--preview] [--yes] [--allow-unsafe] [--max-bytes N] [--max-files N]
82
83
  scaly logs --follow --app <appId> [--since 10m] [--level error|warn|info|debug|all] [--q <str>] [--duration-seconds N] [--max-lines N] [--json]
83
84
  scaly accounts create --email <email> [--name <org>] [--region EU|US|CANADA|ASIA_PACIFIC]
84
85
  scaly stacks create --account <id> --name <stackName> [--size Eco|Basic|...] [--min-idle N]
@@ -1856,9 +1857,15 @@ async function runDeploy(rest) {
1856
1857
  const f = parseKv(rest);
1857
1858
  const json = parseBool(f.json, false);
1858
1859
  const watch = f.watch !== undefined ? parseBool(f.watch, true) : false;
1859
- const strategy = String(f.strategy || 'auto').toLowerCase(); // auto|git|restart
1860
+ const strategy = String(f.strategy || 'auto').toLowerCase(); // auto|git|restart|upload
1860
1861
  const pollSeconds = Number(f['poll-seconds'] || 5);
1861
1862
  const timeoutMinutes = Number(f['timeout-minutes'] || 20);
1863
+ const preview = parseBool(f.preview, false);
1864
+ const yes = parseBool(f.yes, false);
1865
+ const allowUnsafe = parseBool(f['allow-unsafe'], false);
1866
+ const maxBytes = f['max-bytes'] != null ? Number(f['max-bytes']) : undefined;
1867
+ const maxFiles = f['max-files'] != null ? Number(f['max-files']) : undefined;
1868
+ const uploadPath = f.path || f['project-path'] || f.project_path || '.';
1862
1869
 
1863
1870
  const appId = f.app || f['app-id'] || (f._ && f._[0]);
1864
1871
  if (!appId) {
@@ -1964,6 +1971,140 @@ async function runDeploy(rest) {
1964
1971
  return ok ? 0 : 1;
1965
1972
  }
1966
1973
 
1974
+ if (chosen === 'upload') {
1975
+ const path = require('path');
1976
+ const readline = require('readline');
1977
+ const artifacts = require('../lib/scaly-artifacts');
1978
+
1979
+ const rootPath = path.resolve(process.cwd(), String(uploadPath || '.'));
1980
+ const scalyIgnorePath = path.join(rootPath, '.scalyignore');
1981
+
1982
+ let plan;
1983
+ try {
1984
+ plan = await artifacts.planDirectoryUpload({
1985
+ rootPath,
1986
+ scalyIgnorePath,
1987
+ maxBytes,
1988
+ maxFiles,
1989
+ allowUnsafe
1990
+ });
1991
+ } catch (e) {
1992
+ const msg = String(e && e.message ? e.message : e);
1993
+ const out = {
1994
+ ok: false,
1995
+ strategy: 'upload',
1996
+ error: { message: msg, code: e && e.code, details: e && e.details }
1997
+ };
1998
+ if (json) console.log(JSON.stringify(out));
1999
+ else console.error(msg);
2000
+ return 2;
2001
+ }
2002
+
2003
+ if (preview) {
2004
+ const out = { ok: true, strategy: 'upload', preview: true, app, plan };
2005
+ if (json) console.log(JSON.stringify(out));
2006
+ else {
2007
+ console.log(`[deploy] preview upload path=${rootPath}`);
2008
+ console.log(
2009
+ `[deploy] included=${plan.included_count} excluded=${plan.excluded_count} bytes=${plan.total_bytes}`
2010
+ );
2011
+ console.log(`[deploy] preview_hash=${plan.preview_hash}`);
2012
+ if (plan.scalyignore_path)
2013
+ console.log(`[deploy] using .scalyignore: ${plan.scalyignore_path}`);
2014
+ }
2015
+ return 0;
2016
+ }
2017
+
2018
+ if (!yes) {
2019
+ const rl = readline.createInterface({
2020
+ input: process.stdin,
2021
+ output: process.stdout
2022
+ });
2023
+ const answer = await new Promise((resolve) =>
2024
+ rl.question(
2025
+ `Upload ${plan.included_count} files (${plan.total_bytes} bytes) for app ${app.name}? (y/N) `,
2026
+ resolve
2027
+ )
2028
+ );
2029
+ rl.close();
2030
+ if (!/^y(es)?$/i.test(String(answer || '').trim())) {
2031
+ if (json) console.log(JSON.stringify({ ok: false, aborted: true }));
2032
+ else console.error('Aborted.');
2033
+ return 1;
2034
+ }
2035
+ }
2036
+
2037
+ const tmpZip = artifacts.defaultTempZipPath({ appId });
2038
+ let zipInfo;
2039
+ try {
2040
+ zipInfo = await artifacts.createZip({
2041
+ rootPath,
2042
+ files: plan.files,
2043
+ outPath: tmpZip
2044
+ });
2045
+ } catch (e) {
2046
+ const msg = String(e && e.message ? e.message : e);
2047
+ if (json)
2048
+ console.log(JSON.stringify({ ok: false, error: { message: msg } }));
2049
+ else console.error(msg);
2050
+ return 1;
2051
+ }
2052
+
2053
+ let link;
2054
+ try {
2055
+ link = await deploy.createAppUploadLink(appId);
2056
+ } catch (e) {
2057
+ const msg = String(e && e.message ? e.message : e);
2058
+ if (json)
2059
+ console.log(JSON.stringify({ ok: false, error: { message: msg } }));
2060
+ else console.error(msg);
2061
+ return 1;
2062
+ }
2063
+ if (!link || !link.url) {
2064
+ const msg = 'Failed to create upload link (missing url).';
2065
+ if (json)
2066
+ console.log(JSON.stringify({ ok: false, error: { message: msg } }));
2067
+ else console.error(msg);
2068
+ return 1;
2069
+ }
2070
+
2071
+ try {
2072
+ await artifacts.uploadToSignedUrl({
2073
+ url: link.url,
2074
+ filePath: zipInfo.out_path
2075
+ });
2076
+ } catch (e) {
2077
+ const msg = String(e && e.message ? e.message : e);
2078
+ if (json)
2079
+ console.log(JSON.stringify({ ok: false, error: { message: msg } }));
2080
+ else console.error(msg);
2081
+ return 1;
2082
+ }
2083
+
2084
+ const out = {
2085
+ ok: true,
2086
+ strategy: 'upload',
2087
+ app,
2088
+ upload: { bytes_uploaded: zipInfo.bytes_written, sha256: zipInfo.sha256 },
2089
+ artifact: { path: zipInfo.out_path },
2090
+ plan: {
2091
+ included_count: plan.included_count,
2092
+ excluded_count: plan.excluded_count,
2093
+ total_bytes: plan.total_bytes,
2094
+ preview_hash: plan.preview_hash
2095
+ }
2096
+ };
2097
+
2098
+ if (json) console.log(JSON.stringify(out));
2099
+ else
2100
+ console.log(
2101
+ `[deploy] uploaded ${zipInfo.bytes_written} bytes (${zipInfo.sha256})`
2102
+ );
2103
+
2104
+ // Upload triggers app version + deployment server-side.
2105
+ return 0;
2106
+ }
2107
+
1967
2108
  // restart strategy
1968
2109
  const dep = await deploy.restartStackServices(app.stackId);
1969
2110
  if (!dep?.id) {
@@ -0,0 +1,274 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+
8
+ const fg = require('fast-glob');
9
+ const ignore = require('ignore');
10
+ const archiver = require('archiver');
11
+
12
+ const DEFAULT_MAX_BYTES = 100 * 1024 * 1024; // 100MB
13
+ const DEFAULT_MAX_FILES = 25_000;
14
+
15
+ const SAFE_DEFAULT_IGNORE = [
16
+ '.git/',
17
+ 'node_modules/',
18
+ '.venv/',
19
+ 'venv/',
20
+ '__pycache__/',
21
+ '.pytest_cache/',
22
+ '.mypy_cache/',
23
+ '.ruff_cache/',
24
+ '.next/',
25
+ '.turbo/',
26
+ 'dist/',
27
+ 'build/',
28
+ '.DS_Store'
29
+ ];
30
+
31
+ const SENSITIVE_PATH_PATTERNS = [
32
+ // dotenv
33
+ /(^|\/)\.env(\..*)?$/i,
34
+ // ssh / aws creds
35
+ /(^|\/)\.ssh(\/|$)/i,
36
+ /(^|\/)\.aws(\/|$)/i,
37
+ // private keys
38
+ /\.pem$/i,
39
+ /\.key$/i,
40
+ /id_rsa/i,
41
+ /id_ed25519/i
42
+ ];
43
+
44
+ function isSensitivePath(relPath) {
45
+ const p = String(relPath || '').replace(/\\/g, '/');
46
+ return SENSITIVE_PATH_PATTERNS.some((re) => re.test(p));
47
+ }
48
+
49
+ function readLinesIfExists(filePath) {
50
+ try {
51
+ if (!fs.existsSync(filePath)) return [];
52
+ const text = fs.readFileSync(filePath, 'utf8');
53
+ return text
54
+ .split(/\r?\n/g)
55
+ .map((l) => l.trim())
56
+ .filter((l) => l && !l.startsWith('#'));
57
+ } catch {
58
+ return [];
59
+ }
60
+ }
61
+
62
+ function buildIgnoreMatcher({ rootPath, scalyIgnorePath }) {
63
+ const ig = ignore();
64
+ ig.add(SAFE_DEFAULT_IGNORE);
65
+ const scalyIgnoreLines = readLinesIfExists(scalyIgnorePath);
66
+ if (scalyIgnoreLines.length) ig.add(scalyIgnoreLines);
67
+ return { ig, scalyIgnoreLines };
68
+ }
69
+
70
+ async function planDirectoryUpload({
71
+ rootPath,
72
+ scalyIgnorePath,
73
+ maxBytes = DEFAULT_MAX_BYTES,
74
+ maxFiles = DEFAULT_MAX_FILES,
75
+ allowUnsafe = false
76
+ }) {
77
+ const absRoot = path.resolve(String(rootPath || '.'));
78
+ const stat = fs.statSync(absRoot);
79
+ if (!stat.isDirectory()) {
80
+ const e = new Error(`Not a directory: ${absRoot}`);
81
+ e.code = 'SCALY_ARTIFACT_NOT_DIR';
82
+ throw e;
83
+ }
84
+
85
+ const { ig, scalyIgnoreLines } = buildIgnoreMatcher({
86
+ rootPath: absRoot,
87
+ scalyIgnorePath
88
+ });
89
+
90
+ const entries = await fg(['**/*'], {
91
+ cwd: absRoot,
92
+ dot: true,
93
+ onlyFiles: true,
94
+ followSymbolicLinks: false
95
+ });
96
+
97
+ if (entries.length > maxFiles) {
98
+ const e = new Error(
99
+ `Too many files to upload (${entries.length} > ${maxFiles}). Add exclusions to .scalyignore or increase --max-files.`
100
+ );
101
+ e.code = 'SCALY_ARTIFACT_TOO_MANY_FILES';
102
+ throw e;
103
+ }
104
+
105
+ const included = [];
106
+ const excluded = [];
107
+ const blockedSensitive = [];
108
+ let totalBytes = 0;
109
+ const largest = [];
110
+
111
+ for (const rel of entries) {
112
+ const relPosix = String(rel).replace(/\\/g, '/');
113
+
114
+ if (ig.ignores(relPosix)) {
115
+ excluded.push(relPosix);
116
+ continue;
117
+ }
118
+
119
+ const abs = path.join(absRoot, rel);
120
+ const st = fs.lstatSync(abs);
121
+ if (st.isSymbolicLink()) {
122
+ excluded.push(relPosix);
123
+ continue;
124
+ }
125
+
126
+ if (!allowUnsafe && isSensitivePath(relPosix)) {
127
+ blockedSensitive.push(relPosix);
128
+ continue;
129
+ }
130
+
131
+ const size = st.size || 0;
132
+ totalBytes += size;
133
+ included.push({ path: relPosix, bytes: size });
134
+
135
+ if (largest.length < 10) {
136
+ largest.push({ path: relPosix, bytes: size });
137
+ largest.sort((a, b) => b.bytes - a.bytes);
138
+ } else if (size > largest[largest.length - 1].bytes) {
139
+ largest[largest.length - 1] = { path: relPosix, bytes: size };
140
+ largest.sort((a, b) => b.bytes - a.bytes);
141
+ }
142
+
143
+ if (totalBytes > maxBytes) {
144
+ const e = new Error(
145
+ `Upload too large (${totalBytes} bytes > ${maxBytes}). Add exclusions to .scalyignore, lower artifacts, or increase --max-bytes.`
146
+ );
147
+ e.code = 'SCALY_ARTIFACT_TOO_LARGE';
148
+ e.details = { total_bytes: totalBytes, max_bytes: maxBytes };
149
+ throw e;
150
+ }
151
+ }
152
+
153
+ if (!allowUnsafe && blockedSensitive.length) {
154
+ const e = new Error(
155
+ `Refusing to upload ${blockedSensitive.length} potentially sensitive files. Add them to .scalyignore or re-run with --allow-unsafe.`
156
+ );
157
+ e.code = 'SCALY_ARTIFACT_SENSITIVE';
158
+ e.details = { blocked: blockedSensitive.slice(0, 50) };
159
+ throw e;
160
+ }
161
+
162
+ const previewHash = crypto
163
+ .createHash('sha256')
164
+ .update(
165
+ JSON.stringify(
166
+ included
167
+ .slice()
168
+ .sort((a, b) => a.path.localeCompare(b.path))
169
+ .map((f) => [f.path, f.bytes])
170
+ )
171
+ )
172
+ .digest('hex');
173
+
174
+ return {
175
+ root: absRoot,
176
+ scalyignore_path:
177
+ scalyIgnorePath && fs.existsSync(scalyIgnorePath)
178
+ ? scalyIgnorePath
179
+ : null,
180
+ scalyignore_rules: scalyIgnoreLines,
181
+ safe_default_rules: SAFE_DEFAULT_IGNORE,
182
+ allow_unsafe: !!allowUnsafe,
183
+ included_count: included.length,
184
+ excluded_count: excluded.length,
185
+ total_bytes: totalBytes,
186
+ largest_files: largest,
187
+ preview_hash: `sha256:${previewHash}`,
188
+ files: included
189
+ };
190
+ }
191
+
192
+ async function createZip({ rootPath, files, outPath }) {
193
+ const absRoot = path.resolve(String(rootPath || '.'));
194
+ const absOut = path.resolve(String(outPath));
195
+ fs.mkdirSync(path.dirname(absOut), { recursive: true });
196
+
197
+ const output = fs.createWriteStream(absOut);
198
+ const archive = archiver('zip', { zlib: { level: 9 } });
199
+ const hash = crypto.createHash('sha256');
200
+ let bytesWritten = 0;
201
+
202
+ const done = new Promise((resolve, reject) => {
203
+ output.on('close', () =>
204
+ resolve({
205
+ out_path: absOut,
206
+ bytes_written: bytesWritten,
207
+ sha256: `sha256:${hash.digest('hex')}`
208
+ })
209
+ );
210
+ output.on('error', reject);
211
+ archive.on('error', reject);
212
+ });
213
+
214
+ archive.on('data', (chunk) => {
215
+ bytesWritten += chunk.length;
216
+ hash.update(chunk);
217
+ });
218
+
219
+ archive.pipe(output);
220
+
221
+ for (const entry of files || []) {
222
+ const rel = typeof entry === 'string' ? entry : entry.path;
223
+ if (!rel) continue;
224
+ const abs = path.join(absRoot, rel);
225
+ archive.file(abs, { name: rel });
226
+ }
227
+
228
+ await archive.finalize();
229
+ return await done;
230
+ }
231
+
232
+ function defaultTempZipPath({ appId }) {
233
+ const safe = String(appId || 'app')
234
+ .replace(/[^a-zA-Z0-9._-]/g, '_')
235
+ .slice(0, 64);
236
+ return path.join(os.tmpdir(), `scaly-upload-${safe}-${Date.now()}.zip`);
237
+ }
238
+
239
+ async function uploadToSignedUrl({
240
+ url,
241
+ filePath,
242
+ contentType = 'application/zip'
243
+ }) {
244
+ const axios = require('axios');
245
+ const abs = path.resolve(String(filePath));
246
+ const st = fs.statSync(abs);
247
+ const stream = fs.createReadStream(abs);
248
+ const res = await axios.put(url, stream, {
249
+ headers: {
250
+ 'content-type': contentType,
251
+ 'content-length': st.size
252
+ },
253
+ maxBodyLength: Infinity,
254
+ maxContentLength: Infinity,
255
+ timeout: 10 * 60_000,
256
+ validateStatus: () => true
257
+ });
258
+ if (res.status < 200 || res.status >= 300) {
259
+ const e = new Error(`Upload failed (HTTP ${res.status})`);
260
+ e.code = 'SCALY_UPLOAD_FAILED';
261
+ throw e;
262
+ }
263
+ return { ok: true, status: res.status, bytes_uploaded: st.size };
264
+ }
265
+
266
+ module.exports = {
267
+ DEFAULT_MAX_BYTES,
268
+ DEFAULT_MAX_FILES,
269
+ SAFE_DEFAULT_IGNORE,
270
+ planDirectoryUpload,
271
+ createZip,
272
+ defaultTempZipPath,
273
+ uploadToSignedUrl
274
+ };
@@ -36,6 +36,12 @@ const TRIGGER_GIT_DEPLOY = `
36
36
  }
37
37
  `;
38
38
 
39
+ const CREATE_APP_UPLOAD_LINK = `
40
+ mutation CreateAppUploadLink($where: AppWhereUniqueInput!) {
41
+ createAppUploadLink(where: $where) { url }
42
+ }
43
+ `;
44
+
39
45
  const LIST_GIT_DEPLOYMENTS = `
40
46
  query ListGitDeployments($appId: String!, $limit: Int) {
41
47
  listGitDeployments(appId: $appId, limit: $limit) {
@@ -110,6 +116,13 @@ async function triggerGitDeploy(appId) {
110
116
  return data?.triggerGitDeploy || null;
111
117
  }
112
118
 
119
+ async function createAppUploadLink(appId) {
120
+ const data = await api.graphqlRequest(CREATE_APP_UPLOAD_LINK, {
121
+ where: { id: appId }
122
+ });
123
+ return data?.createAppUploadLink || null;
124
+ }
125
+
113
126
  async function listGitDeployments(appId, limit = 10) {
114
127
  const data = await api.graphqlRequest(LIST_GIT_DEPLOYMENTS, { appId, limit });
115
128
  return data?.listGitDeployments || [];
@@ -131,6 +144,7 @@ module.exports = {
131
144
  getAppBasic,
132
145
  getAppGitSource,
133
146
  triggerGitDeploy,
147
+ createAppUploadLink,
134
148
  listGitDeployments,
135
149
  restartStackServices,
136
150
  getDeployment
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@occam-scaly/scaly-cli",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Scaly CLI (auth + project config helpers)",
5
5
  "bin": {
6
6
  "scaly": "./bin/scaly.js"
@@ -10,6 +10,9 @@
10
10
  },
11
11
  "dependencies": {
12
12
  "axios": "^1.7.9",
13
+ "archiver": "^7.0.1",
14
+ "fast-glob": "^3.3.3",
15
+ "ignore": "^7.0.5",
13
16
  "ws": "^8.18.3",
14
17
  "yaml": "^2.8.1"
15
18
  },