@ostro-cloud/cli 0.0.0-stage → 1.0.0-alpha.10

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/lib/client.js ADDED
@@ -0,0 +1,258 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const crypto = require('crypto');
5
+
6
+ const CONFIG_FILE = path.join(os.homedir(), '.ostro', 'config.json');
7
+
8
+ // Single-domain path-based routing — Cloudflare-compatible
9
+ // Pattern: https://console.ostro-cloud.com/<service>
10
+ const DEFAULT_CONSOLE_HOST = 'https://console.ostro-cloud.com';
11
+ const DEFAULT_CLOUD_DOMAIN = 'ostro-cloud.com';
12
+ const DEFAULT_REGION = 'in-bihar-1';
13
+
14
+ // Service path segments — console.ostro-cloud.com/<path>
15
+ const SERVICE_PATHS = {
16
+ formation: 'formation',
17
+ serverless: 'serverless',
18
+ storage: 's3',
19
+ kubernetes: 'eks',
20
+ gateway: 'apigateway',
21
+ tunnel: 'tunnel',
22
+ dns: 'route53',
23
+ iam: 'iam',
24
+ ec2: 'ec2',
25
+ rds: 'rds',
26
+ cache: 'elasticache',
27
+ secrets: 'secretsmanager',
28
+ cloudwatch: 'logs',
29
+ sns: 'sns',
30
+ sqs: 'sqs',
31
+ efs: 'efs',
32
+ elb: 'elb',
33
+ registry: 'ecr',
34
+ broker: 'mq',
35
+ scheduler: 'scheduler',
36
+ organizations: 'organizations',
37
+ vpc: 'vpc',
38
+ };
39
+
40
+ /**
41
+ * Returns the base URL for a service.
42
+ * Pattern: https://<service>.ostro-cloud.com
43
+ */
44
+ function defaultServiceUrl(service, _region, domain) {
45
+ const seg = SERVICE_PATHS[service] || service;
46
+ const d = domain || process.env.OSTRO_DOMAIN || DEFAULT_CLOUD_DOMAIN;
47
+ return `https://${seg}.${d}`;
48
+ }
49
+
50
+ function getStoredConfig() {
51
+ let fileConfig = {};
52
+ try {
53
+ if (fs.existsSync(CONFIG_FILE)) {
54
+ fileConfig = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
55
+ }
56
+ } catch {}
57
+
58
+ const domain = fileConfig.domain || process.env.OSTRO_DOMAIN || DEFAULT_CLOUD_DOMAIN;
59
+ const region = fileConfig.region || process.env.OSTRO_REGION || process.env.AWS_DEFAULT_REGION || process.env.AWS_REGION || DEFAULT_REGION;
60
+
61
+ // Per-service URL resolution: explicit config/env → domain-derived default
62
+ const svcUrl = (svc, envVar, configKey) =>
63
+ fileConfig[configKey] || process.env[envVar] || defaultServiceUrl(svc, region, domain);
64
+
65
+ return {
66
+ domain,
67
+ region,
68
+ consoleUrl: fileConfig.consoleUrl || process.env.OSTRO_CONSOLE_URL || `https://console.${domain}`,
69
+ formationUrl: svcUrl('formation', 'OSTRO_FORMATION_URL', 'formationUrl'),
70
+ serverlessUrl: svcUrl('serverless', 'OSTRO_SERVERLESS_URL', 'serverlessUrl'),
71
+ s3Url: svcUrl('storage', 'OSTRO_S3_URL', 's3Url'),
72
+ k8sUrl: svcUrl('kubernetes', 'OSTRO_K8S_URL', 'k8sUrl'),
73
+ gatewayUrl: svcUrl('gateway', 'OSTRO_GATEWAY_URL', 'gatewayUrl'),
74
+ tunnelUrl: svcUrl('tunnel', 'OSTRO_TUNNEL_URL', 'tunnelUrl'),
75
+ dnsUrl: svcUrl('dns', 'OSTRO_DNS_URL', 'dnsUrl'),
76
+ iamUrl: svcUrl('iam', 'OSTRO_IAM_URL', 'iamUrl'),
77
+ ec2Url: svcUrl('ec2', 'OSTRO_EC2_URL', 'ec2Url'),
78
+ rdsUrl: svcUrl('rds', 'OSTRO_RDS_URL', 'rdsUrl'),
79
+ cacheUrl: svcUrl('cache', 'OSTRO_CACHE_URL', 'cacheUrl'),
80
+ secretsUrl: svcUrl('secrets', 'OSTRO_SECRETS_URL', 'secretsUrl'),
81
+ cloudwatchUrl: svcUrl('cloudwatch', 'OSTRO_CLOUDWATCH_URL', 'cloudwatchUrl'),
82
+ snsUrl: svcUrl('sns', 'OSTRO_SNS_URL', 'snsUrl'),
83
+ sqsUrl: svcUrl('sqs', 'OSTRO_SQS_URL', 'sqsUrl'),
84
+ efsUrl: svcUrl('efs', 'OSTRO_EFS_URL', 'efsUrl'),
85
+ elbUrl: svcUrl('elb', 'OSTRO_ELB_URL', 'elbUrl'),
86
+ registryUrl: svcUrl('registry', 'OSTRO_REGISTRY_URL', 'registryUrl'),
87
+ brokerUrl: svcUrl('broker', 'OSTRO_BROKER_URL', 'brokerUrl'),
88
+ schedulerUrl: svcUrl('scheduler', 'OSTRO_SCHEDULER_URL', 'schedulerUrl'),
89
+ organizationsUrl: svcUrl('organizations','OSTRO_ORGS_URL', 'organizationsUrl'),
90
+ vpcUrl: svcUrl('vpc', 'OSTRO_VPC_URL', 'vpcUrl'),
91
+ buildHost: fileConfig.buildHost || process.env.OSTRO_BUILD_HOST || null,
92
+ buildUser: fileConfig.buildUser || process.env.OSTRO_BUILD_USER || null,
93
+ accessKeyId: fileConfig.accessKeyId || process.env.OSTRO_ACCESS_KEY_ID || process.env.AWS_ACCESS_KEY_ID || null,
94
+ secretAccessKey: fileConfig.secretAccessKey || process.env.OSTRO_SECRET_ACCESS_KEY || process.env.AWS_SECRET_ACCESS_KEY || null,
95
+ token: fileConfig.token || process.env.OSTRO_SESSION_TOKEN || process.env.AWS_SESSION_TOKEN || process.env.OSTRO_API_KEY || null,
96
+ sessionToken: fileConfig.sessionToken || process.env.OSTRO_SESSION_TOKEN || process.env.AWS_SESSION_TOKEN || null,
97
+ roleArn: fileConfig.roleArn || process.env.OSTRO_ROLE_ARN || null,
98
+ clientId: fileConfig.clientId || process.env.OSTRO_CLIENT_ID || null,
99
+ };
100
+ }
101
+
102
+ // Service key → config field name
103
+ const SERVICE_URL_KEYS = {
104
+ formation: 'formationUrl',
105
+ serverless: 'serverlessUrl',
106
+ storage: 's3Url',
107
+ kubernetes: 'k8sUrl',
108
+ gateway: 'gatewayUrl',
109
+ tunnel: 'tunnelUrl',
110
+ dns: 'dnsUrl',
111
+ iam: 'iamUrl',
112
+ ec2: 'ec2Url',
113
+ rds: 'rdsUrl',
114
+ cache: 'cacheUrl',
115
+ secrets: 'secretsUrl',
116
+ cloudwatch: 'cloudwatchUrl',
117
+ sns: 'snsUrl',
118
+ sqs: 'sqsUrl',
119
+ efs: 'efsUrl',
120
+ elb: 'elbUrl',
121
+ registry: 'registryUrl',
122
+ broker: 'brokerUrl',
123
+ scheduler: 'schedulerUrl',
124
+ organizations: 'organizationsUrl',
125
+ vpc: 'vpcUrl',
126
+ };
127
+
128
+ function resolveServiceUrl(servicePath, explicitUrl) {
129
+ if (explicitUrl) return explicitUrl;
130
+ const config = getStoredConfig();
131
+ const key = SERVICE_URL_KEYS[servicePath] || `${servicePath}Url`;
132
+ if (config[key]) return config[key];
133
+ // Final fallback: derive from domain + region
134
+ return defaultServiceUrl(servicePath, config.region, config.domain);
135
+ }
136
+
137
+ function saveConfig(newConfig) {
138
+ const dir = path.dirname(CONFIG_FILE);
139
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
140
+ let current = {};
141
+ try {
142
+ if (fs.existsSync(CONFIG_FILE)) current = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
143
+ } catch {}
144
+ const merged = { ...current, ...newConfig };
145
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2));
146
+ return merged;
147
+ }
148
+
149
+ async function request(url, options = {}) {
150
+ const config = getStoredConfig();
151
+ let authToken = config.sessionToken || config.token;
152
+
153
+ // If we only have access keys (no session token), exchange them for a JWT
154
+ // via IAM verify-signature so JWT-protected services (formation) accept us.
155
+ if (!authToken && !options.skipAuth) {
156
+ const hasAccessKeys = Boolean(config.accessKeyId && config.secretAccessKey);
157
+ if (!hasAccessKeys) {
158
+ throw new Error('Authentication required. Run "ostro-cloud login" or set OSTRO_ACCESS_KEY_ID / OSTRO_SECRET_ACCESS_KEY / OSTRO_SESSION_TOKEN.');
159
+ }
160
+ authToken = await resolveAuthTokenViaIam(config);
161
+ }
162
+
163
+ const headers = {
164
+ 'Accept': 'application/json',
165
+ 'Content-Type': 'application/json',
166
+ ...(authToken ? { 'Authorization': `Bearer ${authToken}` } : buildHmacHeaders(options.method || 'GET', new URL(url).pathname, config)),
167
+ ...(config.sessionToken ? { 'X-Ostro-Session-Token': config.sessionToken } : {}),
168
+ ...(config.roleArn ? { 'X-Ostro-Role-Arn': config.roleArn } : {}),
169
+ ...(config.clientId ? { 'X-Ostro-Client-Id': config.clientId } : {}),
170
+ ...(options.headers || {})
171
+ };
172
+
173
+ const response = await fetch(url, { ...options, headers });
174
+
175
+ const contentType = response.headers.get('content-type') || '';
176
+ if (contentType.includes('application/json')) {
177
+ const data = await response.json();
178
+ if (!response.ok) throw new Error(data.message || data.error || `HTTP ${response.status}`);
179
+ return data;
180
+ }
181
+ const text = await response.text();
182
+ if (!response.ok) throw new Error(text || `HTTP ${response.status}`);
183
+ return text;
184
+ }
185
+
186
+ /**
187
+ * Exchange access keys for a JWT session token via IAM verify-signature.
188
+ * Caches the token in config so subsequent requests reuse it.
189
+ */
190
+ async function resolveAuthTokenViaIam(config) {
191
+ const iamUrl = config.iamUrl || `https://iam.${config.domain || 'ostro-cloud.com'}`;
192
+ const verifyUrl = `${iamUrl}/api/auth/verify-signature`;
193
+
194
+ const date = new Date().toISOString();
195
+ const canonical = `POST\n/api/auth/verify-signature\n${date}`;
196
+ const signature = crypto.createHmac('sha256', config.secretAccessKey).update(canonical).digest('hex');
197
+ const hmacAuth = `OSTRO4-HMAC-SHA256 Credential=${config.accessKeyId}, Signature=${signature}`;
198
+
199
+ let res;
200
+ try {
201
+ res = await fetch(verifyUrl, {
202
+ method: 'POST',
203
+ headers: {
204
+ 'Content-Type': 'application/json',
205
+ 'Accept': 'application/json',
206
+ 'X-Ostro-Date': date,
207
+ 'Authorization': hmacAuth,
208
+ },
209
+ body: JSON.stringify({
210
+ authorization: hmacAuth,
211
+ xOstroDate: date,
212
+ method: 'POST',
213
+ path: '/api/auth/verify-signature',
214
+ }),
215
+ });
216
+ } catch (err) {
217
+ throw new Error(`IAM verify-signature unavailable: ${err.message}`);
218
+ }
219
+
220
+ if (!res.ok) {
221
+ const txt = await res.text().catch(() => `HTTP ${res.status}`);
222
+ throw new Error(`IAM verify-signature failed: ${txt}`);
223
+ }
224
+
225
+ const data = await res.json().catch(() => ({}));
226
+ const token = data.sessionToken;
227
+ if (!token) {
228
+ throw new Error('IAM verify-signature did not return a session token');
229
+ }
230
+
231
+ // Persist so all subsequent requests (including builds) use Bearer auth
232
+ saveConfig({ sessionToken: token, token, accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey });
233
+
234
+ return token;
235
+ }
236
+
237
+ function buildHmacHeaders(method, pathname, config) {
238
+ if (!config?.accessKeyId || !config?.secretAccessKey) return {};
239
+ const xOstroDate = new Date().toISOString();
240
+ const canonical = `${String(method).toUpperCase()}\n${String(pathname)}\n${xOstroDate}`;
241
+ const signature = crypto.createHmac('sha256', config.secretAccessKey).update(canonical).digest('hex');
242
+ return {
243
+ 'X-Ostro-Date': xOstroDate,
244
+ 'Authorization': `OSTRO4-HMAC-SHA256 Credential=${config.accessKeyId}, Signature=${signature}`,
245
+ };
246
+ }
247
+
248
+ module.exports = {
249
+ getStoredConfig,
250
+ resolveServiceUrl,
251
+ saveConfig,
252
+ request,
253
+ buildHmacHeaders,
254
+ defaultServiceUrl,
255
+ DEFAULT_CLOUD_DOMAIN,
256
+ DEFAULT_REGION,
257
+ resolveAuthTokenViaIam,
258
+ };
@@ -0,0 +1,35 @@
1
+ const { saveConfig, getStoredConfig, defaultServiceUrl, DEFAULT_CLOUD_DOMAIN, DEFAULT_REGION } = require('../client');
2
+
3
+ async function configureCli(options = {}) {
4
+ const updates = {};
5
+
6
+ if (options.domain) updates.domain = options.domain;
7
+ if (options.region) updates.region = options.region;
8
+ if (options.token) updates.token = options.token;
9
+ if (options.sessionToken) updates.sessionToken = options.sessionToken;
10
+ if (options.role) updates.roleArn = options.role;
11
+ // Keep --endpoint for backwards-compat but warn it is superseded by --domain
12
+ if (options.endpoint && !options.domain) {
13
+ console.warn('\x1b[33m⚠ --endpoint is deprecated. Use --domain <ostro-cloud.com> to set the cloud domain.\x1b[0m');
14
+ }
15
+
16
+ const saved = saveConfig(updates);
17
+
18
+ const domain = saved.domain || DEFAULT_CLOUD_DOMAIN;
19
+ const region = saved.region || DEFAULT_REGION;
20
+
21
+ const consoleHost = `https://console.${domain}`;
22
+ console.log('\x1b[32m✔ Ostro Cloud CLI configured.\x1b[0m\n');
23
+ console.log(` Console: \x1b[34m${consoleHost}\x1b[0m`);
24
+ console.log(` Region: \x1b[33m${region}\x1b[0m`);
25
+ console.log(` Domain: \x1b[90m${domain}\x1b[0m`);
26
+ console.log(` Token: \x1b[90m${saved.token ? `${saved.token.slice(0, 15)}…` : 'N/A'}\x1b[0m`);
27
+ console.log(`\n Service endpoints (path-based routing):`);
28
+ for (const svc of ['formation', 'serverless', 'storage', 'kubernetes', 'gateway', 'dns', 'iam', 'ec2', 'rds', 'cloudwatch', 'secrets', 'sns', 'sqs']) {
29
+ const url = defaultServiceUrl(svc, region, domain);
30
+ console.log(` \x1b[36m${svc.padEnd(14)}\x1b[0m ${url}`);
31
+ }
32
+ console.log('');
33
+ }
34
+
35
+ module.exports = { configureCli };
@@ -0,0 +1,61 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { getStoredConfig } = require('../client');
4
+ const { deployFunction } = require('./serverless');
5
+ const { deployStack } = require('./formation');
6
+ const { applyManifest } = require('./k8s');
7
+ const { syncDirectory } = require('./s3');
8
+
9
+ async function universalDeploy(options = {}) {
10
+ const config = getStoredConfig();
11
+ const region = options.region || config.region || null;
12
+ const regionLabel = region ? ` in ${region}` : '';
13
+ console.log(`\x1b[36m🚀 Ostro Cloud Universal Deployer${regionLabel}\x1b[0m\n`);
14
+
15
+ const cwd = process.cwd();
16
+ const templatePath = options.template || (fs.existsSync(path.join(cwd, 'template.yaml')) ? 'template.yaml' : (fs.existsSync(path.join(cwd, 'template.yml')) ? 'template.yml' : null));
17
+
18
+ if (templatePath && fs.existsSync(path.join(cwd, templatePath))) {
19
+ console.log(` Found CloudFormation / SAM template: \x1b[33m${templatePath}\x1b[0m`);
20
+ await deployStack({
21
+ template: templatePath,
22
+ stackName: options.stack || path.basename(cwd) + '-stack',
23
+ region
24
+ });
25
+ return;
26
+ }
27
+
28
+ if (fs.existsSync(path.join(cwd, 'serverless.yaml')) || fs.existsSync(path.join(cwd, 'serverless.yml'))) {
29
+ console.log(` Found Serverless configuration...`);
30
+ const file = fs.existsSync(path.join(cwd, 'serverless.yaml')) ? 'serverless.yaml' : 'serverless.yml';
31
+ await deployFunction('appFunction', { file: 'index.js', region });
32
+ return;
33
+ }
34
+
35
+ if (fs.existsSync(path.join(cwd, 'k8s.yaml')) || fs.existsSync(path.join(cwd, 'deployment.yaml'))) {
36
+ console.log(` Found Kubernetes manifest...`);
37
+ const file = fs.existsSync(path.join(cwd, 'k8s.yaml')) ? 'k8s.yaml' : 'deployment.yaml';
38
+ await applyManifest(file, { region });
39
+ return;
40
+ }
41
+
42
+ if (fs.existsSync(path.join(cwd, 'public')) || fs.existsSync(path.join(cwd, 'dist')) || fs.existsSync(path.join(cwd, 'build'))) {
43
+ const staticDir = fs.existsSync(path.join(cwd, 'dist')) ? 'dist' : (fs.existsSync(path.join(cwd, 'build')) ? 'build' : 'public');
44
+ console.log(` Found static website build directory [${staticDir}]...`);
45
+ await syncDirectory(staticDir, 's3://static-websites', { region });
46
+ return;
47
+ }
48
+
49
+ if (fs.existsSync(path.join(cwd, 'index.js'))) {
50
+ console.log(` Deploying index.js as standalone serverless function...`);
51
+ await deployFunction('customWorker', { file: 'index.js', region });
52
+ return;
53
+ }
54
+
55
+ console.log(`\x1b[33mℹ No deployment manifest (template.yaml, serverless.yaml, k8s.yaml) found in current directory.\x1b[0m`);
56
+ console.log(` Run \x1b[36mostro --help\x1b[0m to see specific service deployment commands.`);
57
+ }
58
+
59
+ module.exports = {
60
+ universalDeploy
61
+ };