@geekmidas/cli 10.0.0-alpha.27 → 10.0.0-alpha.29
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/dist/{HostingerProvider-BY26bWwB.mjs → HostingerProvider-Btxpto71.mjs} +2 -2
- package/dist/{HostingerProvider-BY26bWwB.mjs.map → HostingerProvider-Btxpto71.mjs.map} +1 -1
- package/dist/{bundler-mwH7WOb1.mjs → bundler-7iaO93G8.mjs} +3 -3
- package/dist/{bundler-mwH7WOb1.mjs.map → bundler-7iaO93G8.mjs.map} +1 -1
- package/dist/{bundler-mjqGAvu1.cjs → bundler-CYF5mWi9.cjs} +2 -2
- package/dist/{bundler-mjqGAvu1.cjs.map → bundler-CYF5mWi9.cjs.map} +1 -1
- package/dist/{config-7R_-WyHq.cjs → config-BTFLHfRb.cjs} +2 -2
- package/dist/{config-7R_-WyHq.cjs.map → config-BTFLHfRb.cjs.map} +1 -1
- package/dist/{config-DXrrYvob.mjs → config-Dqxa-_Ge.mjs} +2 -2
- package/dist/{config-DXrrYvob.mjs.map → config-Dqxa-_Ge.mjs.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.d.cts +2 -2
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/deploy/sniffer-loader.cjs +1 -1
- package/dist/{discover-B_HtYJCr.cjs → discover-BTh87DOO.cjs} +24 -2
- package/dist/{discover-B_HtYJCr.cjs.map → discover-BTh87DOO.cjs.map} +1 -1
- package/dist/{discover-0fhCbnk0.mjs → discover-CXGlQHm1.mjs} +24 -2
- package/dist/{discover-0fhCbnk0.mjs.map → discover-CXGlQHm1.mjs.map} +1 -1
- package/dist/{github-Ba5kXEJo.mjs → github-DPpNfzu4.mjs} +4 -4
- package/dist/{github-Ba5kXEJo.mjs.map → github-DPpNfzu4.mjs.map} +1 -1
- package/dist/{github-CQflOKKV.cjs → github-ZL3RcUVD.cjs} +6 -6
- package/dist/{github-CQflOKKV.cjs.map → github-ZL3RcUVD.cjs.map} +1 -1
- package/dist/{index-BqWKWRm0.d.mts → index-p89EzILa.d.mts} +2 -2
- package/dist/{index-BPN7kghQ.d.cts.map → index-p89EzILa.d.mts.map} +1 -1
- package/dist/{index-BPN7kghQ.d.cts → index-rU9u761a.d.cts} +2 -2
- package/dist/{index-BqWKWRm0.d.mts.map → index-rU9u761a.d.cts.map} +1 -1
- package/dist/index.cjs +901 -822
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +894 -817
- package/dist/index.mjs.map +1 -1
- package/dist/{openapi-3NLVvtz-.mjs → openapi-D-Lk5Hr5.mjs} +3 -3
- package/dist/{openapi-3NLVvtz-.mjs.map → openapi-D-Lk5Hr5.mjs.map} +1 -1
- package/dist/{openapi-rhJdy2GC.cjs → openapi-K4H5tHzA.cjs} +3 -3
- package/dist/{openapi-rhJdy2GC.cjs.map → openapi-K4H5tHzA.cjs.map} +1 -1
- package/dist/openapi.cjs +1 -1
- package/dist/openapi.d.cts +1 -1
- package/dist/openapi.d.mts +1 -1
- package/dist/openapi.mjs +1 -1
- package/dist/reconcile/public.cjs +1 -1
- package/dist/reconcile/public.d.cts +13 -1
- package/dist/reconcile/public.d.cts.map +1 -1
- package/dist/reconcile/public.d.mts +13 -1
- package/dist/reconcile/public.d.mts.map +1 -1
- package/dist/reconcile/public.mjs +1 -1
- package/dist/{reconcile-szmJw_Sb.cjs → reconcile-BxZTV2vl.cjs} +5 -82
- package/dist/reconcile-BxZTV2vl.cjs.map +1 -0
- package/dist/{reconcile-DhbCvh4K.mjs → reconcile-yNq6Shau.mjs} +5 -82
- package/dist/reconcile-yNq6Shau.mjs.map +1 -0
- package/dist/{storage-TP0x118M.mjs → storage-BjTLjDDp.mjs} +1 -8
- package/dist/{storage-TP0x118M.mjs.map → storage-BjTLjDDp.mjs.map} +1 -1
- package/dist/{storage-DgypfSD6.cjs → storage-C2JC31V9.cjs} +1 -8
- package/dist/{storage-DgypfSD6.cjs.map → storage-C2JC31V9.cjs.map} +1 -1
- package/dist/{types-7R81hu0i.d.mts → types-CzK6hsXP.d.mts} +1 -17
- package/dist/types-CzK6hsXP.d.mts.map +1 -0
- package/dist/{types-N7c2O2m7.d.cts → types-DOOAevjG.d.cts} +1 -17
- package/dist/types-DOOAevjG.d.cts.map +1 -0
- package/dist/workspace/index.d.cts +2 -2
- package/dist/workspace/index.d.mts +2 -2
- package/dist/{workspace-DgeVgxmm.cjs → workspace-B3ApLW6p.cjs} +129 -10
- package/dist/workspace-B3ApLW6p.cjs.map +1 -0
- package/dist/{workspace-CUmR_k4J.mjs → workspace-DnHW8ooI.mjs} +125 -12
- package/dist/workspace-DnHW8ooI.mjs.map +1 -0
- package/package.json +14 -14
- package/dist/reconcile-DhbCvh4K.mjs.map +0 -1
- package/dist/reconcile-szmJw_Sb.cjs.map +0 -1
- package/dist/transfer-BV00TxZv.mjs +0 -122
- package/dist/transfer-BV00TxZv.mjs.map +0 -1
- package/dist/transfer-BYIn7z8m.cjs +0 -151
- package/dist/transfer-BYIn7z8m.cjs.map +0 -1
- package/dist/types-7R81hu0i.d.mts.map +0 -1
- package/dist/types-N7c2O2m7.d.cts.map +0 -1
- package/dist/workspace-CUmR_k4J.mjs.map +0 -1
- package/dist/workspace-DgeVgxmm.cjs.map +0 -1
package/dist/openapi.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const require_openapi = require("./openapi-
|
|
3
|
+
const require_openapi = require("./openapi-K4H5tHzA.cjs");
|
|
4
4
|
exports.OPENAPI_OUTPUT_PATH = require_openapi.OPENAPI_OUTPUT_PATH;
|
|
5
5
|
exports.generateOpenApi = require_openapi.generateOpenApi;
|
|
6
6
|
exports.generateOpenApiFrom = require_openapi.generateOpenApiFrom;
|
package/dist/openapi.d.cts
CHANGED
package/dist/openapi.d.mts
CHANGED
package/dist/openapi.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
|
-
import { a as openapiCommand, i as openApiPathFor, n as generateOpenApi, o as resolveOpenApiConfig, r as generateOpenApiFrom, t as OPENAPI_OUTPUT_PATH } from "./openapi-
|
|
2
|
+
import { a as openapiCommand, i as openApiPathFor, n as generateOpenApi, o as resolveOpenApiConfig, r as generateOpenApiFrom, t as OPENAPI_OUTPUT_PATH } from "./openapi-D-Lk5Hr5.mjs";
|
|
3
3
|
export { OPENAPI_OUTPUT_PATH, generateOpenApi, generateOpenApiFrom, openApiPathFor, openapiCommand, resolveOpenApiConfig };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_discover = require("../discover-
|
|
2
|
+
const require_discover = require("../discover-BTh87DOO.cjs");
|
|
3
3
|
const require_emit = require("../emit-BdoPFjZf.cjs");
|
|
4
4
|
exports.MANIFEST_PATH = require_emit.MANIFEST_PATH;
|
|
5
5
|
exports.discover = require_discover.discover;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as EmailBackend, t as CacheBackend } from "../types-
|
|
1
|
+
import { n as EmailBackend, t as CacheBackend } from "../types-DOOAevjG.cjs";
|
|
2
2
|
import { ConstructManifest, Declaration, RouteInfo } from "@geekmidas/manifest";
|
|
3
3
|
//#region src/reconcile/discover.d.ts
|
|
4
4
|
/** The construct face discovery needs: an id, and the ability to declare. */
|
|
@@ -37,6 +37,18 @@ interface DiscoverOptions {
|
|
|
37
37
|
* caller, which wants the manifest and nothing else, is unchanged.
|
|
38
38
|
*/
|
|
39
39
|
sources?: Record<string, ConstructSource>;
|
|
40
|
+
/**
|
|
41
|
+
* Filled in, when provided, with the ids each owner's runnables declared an
|
|
42
|
+
* edge to — keyed by the surface an endpoint was built from, or the worker
|
|
43
|
+
* a cron or subscriber was.
|
|
44
|
+
*
|
|
45
|
+
* A runnable is not a declaration: a surface's endpoints are found by the
|
|
46
|
+
* glob, not listed by the surface, so its node says `endpoints: []` until a
|
|
47
|
+
* build folds the routes in. Anything deciding what an app's process reaches
|
|
48
|
+
* — which keys its container is given — needs those edges before any build,
|
|
49
|
+
* and discovery is already importing the files they are in.
|
|
50
|
+
*/
|
|
51
|
+
runnables?: Record<string, string[]>;
|
|
40
52
|
}
|
|
41
53
|
/** Where a construct was declared, and under what name. */
|
|
42
54
|
interface ConstructSource {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.d.cts","names":[],"sources":["../../src/reconcile/discover.ts","../../src/reconcile/emit.ts"],"mappings":";;;;UA8BU;EACT;EACA,WAAW;;;;;;;;;wBAUI,aAAa,iBAAiB,SAAS;UAYtC;;EAEhB;EACA;;;;;;;EAOA;;;;;;;;;;;;EAYA,UAAU,eAAe;;;
|
|
1
|
+
{"version":3,"file":"public.d.cts","names":[],"sources":["../../src/reconcile/discover.ts","../../src/reconcile/emit.ts"],"mappings":";;;;UA8BU;EACT;EACA,WAAW;;;;;;;;;wBAUI,aAAa,iBAAiB,SAAS;UAYtC;;EAEhB;EACA;;;;;;;EAOA;;;;;;;;;;;;EAYA,UAAU,eAAe;;;;;;;;;;;;EAYzB,YAAY;;;UAII;;EAEhB;;EAEA;;;;;;;EAOA;;;;;;;;;;wBAWqB,SACrB,SAAS,kBACP,QAAQ;;;;qBC/EE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA8BG,WACf,UAAU,mBACV,iBAAiB,aACjB;EAAW;IACT;;;;;;wBA2Ja,eACf,UAAU,mBACV,WAAU;;wBA8BW,oBACrB,UAAU,mBACV,iBACA,WAAU,WACR;;UAUc;EAChB,QAAQ;EACR,QAAQ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as EmailBackend, t as CacheBackend } from "../types-
|
|
1
|
+
import { n as EmailBackend, t as CacheBackend } from "../types-CzK6hsXP.mjs";
|
|
2
2
|
import { ConstructManifest, Declaration, RouteInfo } from "@geekmidas/manifest";
|
|
3
3
|
//#region src/reconcile/discover.d.ts
|
|
4
4
|
/** The construct face discovery needs: an id, and the ability to declare. */
|
|
@@ -37,6 +37,18 @@ interface DiscoverOptions {
|
|
|
37
37
|
* caller, which wants the manifest and nothing else, is unchanged.
|
|
38
38
|
*/
|
|
39
39
|
sources?: Record<string, ConstructSource>;
|
|
40
|
+
/**
|
|
41
|
+
* Filled in, when provided, with the ids each owner's runnables declared an
|
|
42
|
+
* edge to — keyed by the surface an endpoint was built from, or the worker
|
|
43
|
+
* a cron or subscriber was.
|
|
44
|
+
*
|
|
45
|
+
* A runnable is not a declaration: a surface's endpoints are found by the
|
|
46
|
+
* glob, not listed by the surface, so its node says `endpoints: []` until a
|
|
47
|
+
* build folds the routes in. Anything deciding what an app's process reaches
|
|
48
|
+
* — which keys its container is given — needs those edges before any build,
|
|
49
|
+
* and discovery is already importing the files they are in.
|
|
50
|
+
*/
|
|
51
|
+
runnables?: Record<string, string[]>;
|
|
40
52
|
}
|
|
41
53
|
/** Where a construct was declared, and under what name. */
|
|
42
54
|
interface ConstructSource {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.d.mts","names":[],"sources":["../../src/reconcile/discover.ts","../../src/reconcile/emit.ts"],"mappings":";;;;UA8BU;EACT;EACA,WAAW;;;;;;;;;wBAUI,aAAa,iBAAiB,SAAS;UAYtC;;EAEhB;EACA;;;;;;;EAOA;;;;;;;;;;;;EAYA,UAAU,eAAe;;;
|
|
1
|
+
{"version":3,"file":"public.d.mts","names":[],"sources":["../../src/reconcile/discover.ts","../../src/reconcile/emit.ts"],"mappings":";;;;UA8BU;EACT;EACA,WAAW;;;;;;;;;wBAUI,aAAa,iBAAiB,SAAS;UAYtC;;EAEhB;EACA;;;;;;;EAOA;;;;;;;;;;;;EAYA,UAAU,eAAe;;;;;;;;;;;;EAYzB,YAAY;;;UAII;;EAEhB;;EAEA;;;;;;;EAOA;;;;;;;;;;wBAWqB,SACrB,SAAS,kBACP,QAAQ;;;;qBC/EE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA8BG,WACf,UAAU,mBACV,iBAAiB,aACjB;EAAW;IACT;;;;;;wBA2Ja,eACf,UAAU,mBACV,WAAU;;wBA8BW,oBACrB,UAAU,mBACV,iBACA,WAAU,WACR;;UAUc;EAChB,QAAQ;EACR,QAAQ"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as isDeclarable, t as discover } from "../discover-
|
|
1
|
+
import { n as isDeclarable, t as discover } from "../discover-CXGlQHm1.mjs";
|
|
2
2
|
import { a as writeManifestModule, i as withRoutes, n as manifestModule, t as MANIFEST_PATH } from "../emit-Bzq7JsMP.mjs";
|
|
3
3
|
export { MANIFEST_PATH, discover, isDeclarable, manifestModule, withRoutes, writeManifestModule };
|
|
@@ -23,12 +23,6 @@ const SERVICE_DEFAULTS = {
|
|
|
23
23
|
port: 6379,
|
|
24
24
|
username: "default"
|
|
25
25
|
},
|
|
26
|
-
rabbitmq: {
|
|
27
|
-
host: "localhost",
|
|
28
|
-
port: 5672,
|
|
29
|
-
username: "app",
|
|
30
|
-
vhost: "/"
|
|
31
|
-
},
|
|
32
26
|
minio: {
|
|
33
27
|
host: "localhost",
|
|
34
28
|
port: 9e3,
|
|
@@ -86,13 +80,6 @@ function generateRedisUrl(creds) {
|
|
|
86
80
|
return `redis://:${encodeURIComponent(password)}@${host}:${port}`;
|
|
87
81
|
}
|
|
88
82
|
/**
|
|
89
|
-
* Generate connection URL for RabbitMQ.
|
|
90
|
-
*/
|
|
91
|
-
function generateRabbitmqUrl(creds) {
|
|
92
|
-
const { username, password, host, port, vhost } = creds;
|
|
93
|
-
return `amqp://${username}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(vhost ?? "/")}`;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
83
|
* Generate endpoint URL for MinIO (S3-compatible).
|
|
97
84
|
*/
|
|
98
85
|
function generateMinioEndpoint(creds) {
|
|
@@ -100,14 +87,6 @@ function generateMinioEndpoint(creds) {
|
|
|
100
87
|
return `http://${host}:${port}`;
|
|
101
88
|
}
|
|
102
89
|
/**
|
|
103
|
-
* Generate a LocalStack-compatible access key ID.
|
|
104
|
-
* Must start with 'LSIA' prefix and be at least 20 characters.
|
|
105
|
-
* @see https://docs.localstack.cloud/aws/capabilities/config/credentials/
|
|
106
|
-
*/
|
|
107
|
-
function generateLocalStackAccessKeyId() {
|
|
108
|
-
return `LSIA${(0, node_crypto.randomBytes)(12).toString("base64url").slice(0, 16)}`;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
90
|
* Generate connection URL for pg-boss (uses PostgreSQL protocol).
|
|
112
91
|
* Format: pgboss://user:pass@host:port/db?schema=pgboss
|
|
113
92
|
*/
|
|
@@ -116,56 +95,14 @@ function generatePgBossUrl(creds) {
|
|
|
116
95
|
return `pgboss://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}?schema=pgboss`;
|
|
117
96
|
}
|
|
118
97
|
/**
|
|
119
|
-
* Generate event connection strings based on the events backend.
|
|
120
|
-
*/
|
|
121
|
-
function generateEventConnectionStrings(eventsBackend, services) {
|
|
122
|
-
switch (eventsBackend) {
|
|
123
|
-
case "pgboss": {
|
|
124
|
-
const creds = services.pgboss;
|
|
125
|
-
if (!creds) throw new Error("pgboss credentials required for pgboss events");
|
|
126
|
-
const url = generatePgBossUrl(creds);
|
|
127
|
-
return {
|
|
128
|
-
publisher: url,
|
|
129
|
-
subscriber: url
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
case "sns": {
|
|
133
|
-
const creds = services.localstack;
|
|
134
|
-
if (!creds) throw new Error("localstack credentials required for sns events");
|
|
135
|
-
const endpoint = `http://${creds.host}:${creds.port}`;
|
|
136
|
-
const region = creds.region ?? "us-east-1";
|
|
137
|
-
const accessKeyId = creds.accessKeyId ?? creds.username;
|
|
138
|
-
const secretKey = encodeURIComponent(creds.password);
|
|
139
|
-
return {
|
|
140
|
-
publisher: `sns://${accessKeyId}:${secretKey}@${creds.host}:${creds.port}?region=${region}&endpoint=${encodeURIComponent(endpoint)}`,
|
|
141
|
-
subscriber: `sqs://${accessKeyId}:${secretKey}@${creds.host}:${creds.port}?region=${region}&endpoint=${encodeURIComponent(endpoint)}`
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
case "rabbitmq": {
|
|
145
|
-
const creds = services.rabbitmq;
|
|
146
|
-
if (!creds) throw new Error("rabbitmq credentials required for rabbitmq events");
|
|
147
|
-
const url = generateRabbitmqUrl(creds);
|
|
148
|
-
return {
|
|
149
|
-
publisher: url,
|
|
150
|
-
subscriber: url
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
98
|
* Generate connection URLs from service credentials.
|
|
157
99
|
*/
|
|
158
|
-
function generateConnectionUrls(services
|
|
100
|
+
function generateConnectionUrls(services) {
|
|
159
101
|
const urls = {};
|
|
160
102
|
if (services.postgres) urls.DATABASE_URL = generatePostgresUrl(services.postgres);
|
|
161
103
|
if (services.redis) urls.REDIS_URL = generateRedisUrl(services.redis);
|
|
162
|
-
if (services.rabbitmq) urls.RABBITMQ_URL = generateRabbitmqUrl(services.rabbitmq);
|
|
163
104
|
if (services.minio) urls.STORAGE_ENDPOINT = generateMinioEndpoint(services.minio);
|
|
164
|
-
if (
|
|
165
|
-
const eventUrls = generateEventConnectionStrings(eventsBackend, services);
|
|
166
|
-
urls.EVENT_PUBLISHER_CONNECTION_STRING = eventUrls.publisher;
|
|
167
|
-
urls.EVENT_SUBSCRIBER_CONNECTION_STRING = eventUrls.subscriber;
|
|
168
|
-
} else if (services.pgboss) {
|
|
105
|
+
if (services.pgboss) {
|
|
169
106
|
const pgbossUrl = generatePgBossUrl(services.pgboss);
|
|
170
107
|
urls.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;
|
|
171
108
|
urls.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;
|
|
@@ -177,22 +114,11 @@ function generateConnectionUrls(services, eventsBackend) {
|
|
|
177
114
|
return urls;
|
|
178
115
|
}
|
|
179
116
|
/**
|
|
180
|
-
* Generate LocalStack service credentials with LSIA-prefixed access key.
|
|
181
|
-
*/
|
|
182
|
-
function generateLocalStackCredentials() {
|
|
183
|
-
return {
|
|
184
|
-
...SERVICE_DEFAULTS.localstack,
|
|
185
|
-
password: generateSecurePassword(),
|
|
186
|
-
accessKeyId: generateLocalStackAccessKeyId()
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
117
|
* Create a new StageSecrets object with generated credentials.
|
|
191
118
|
* @param stage - The deployment stage (e.g., 'development', 'production')
|
|
192
119
|
* @param services - List of services to generate credentials for
|
|
193
120
|
* @param options - Optional configuration
|
|
194
121
|
* @param options.projectName - Project name used to derive the database name (e.g., 'myapp' → 'myapp_dev')
|
|
195
|
-
* @param options.eventsBackend - Event backend type (pgboss, sns, rabbitmq)
|
|
196
122
|
*/
|
|
197
123
|
function createStageSecrets(stage, services, options) {
|
|
198
124
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -211,15 +137,12 @@ function createStageSecrets(stage, services, options) {
|
|
|
211
137
|
port: serviceCredentials.postgres.port,
|
|
212
138
|
database: serviceCredentials.postgres.database
|
|
213
139
|
};
|
|
214
|
-
const eventsBackend = options?.eventsBackend;
|
|
215
|
-
if (eventsBackend === "sns") serviceCredentials.localstack = generateLocalStackCredentials();
|
|
216
140
|
return {
|
|
217
141
|
stage,
|
|
218
142
|
createdAt: now,
|
|
219
143
|
updatedAt: now,
|
|
220
|
-
eventsBackend,
|
|
221
144
|
services: serviceCredentials,
|
|
222
|
-
urls: generateConnectionUrls(serviceCredentials
|
|
145
|
+
urls: generateConnectionUrls(serviceCredentials),
|
|
223
146
|
custom: {}
|
|
224
147
|
};
|
|
225
148
|
}
|
|
@@ -241,7 +164,7 @@ function rotateServicePassword(secrets, service) {
|
|
|
241
164
|
...secrets,
|
|
242
165
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
243
166
|
services: newServices,
|
|
244
|
-
urls: generateConnectionUrls(newServices
|
|
167
|
+
urls: generateConnectionUrls(newServices)
|
|
245
168
|
};
|
|
246
169
|
}
|
|
247
170
|
//#endregion
|
|
@@ -406,4 +329,4 @@ Object.defineProperty(exports, "writeDockerEnvFromSecrets", {
|
|
|
406
329
|
}
|
|
407
330
|
});
|
|
408
331
|
|
|
409
|
-
//# sourceMappingURL=reconcile-
|
|
332
|
+
//# sourceMappingURL=reconcile-BxZTV2vl.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile-BxZTV2vl.cjs","names":["randomBytes","join","mkdir","dirname","writeFile"],"sources":["../src/secrets/generator.ts","../src/setup/fullstack-secrets.ts","../src/secrets/reconcile.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport type {\n\tSecretServiceName,\n\tServiceCredentials,\n\tStageSecrets,\n} from './types';\n\n/**\n * Generate a secure random password using URL-safe base64 characters.\n * @param length Password length (default: 32)\n */\nexport function generateSecurePassword(length = 32): string {\n\treturn randomBytes(Math.ceil((length * 3) / 4))\n\t\t.toString('base64url')\n\t\t.slice(0, length);\n}\n\n/** Default service configurations (localhost for local dev via Docker port mapping) */\nconst SERVICE_DEFAULTS: Record<\n\tSecretServiceName,\n\tOmit<ServiceCredentials, 'password'>\n> = {\n\tpostgres: {\n\t\thost: 'localhost',\n\t\tport: 5432,\n\t\tusername: 'app',\n\t\tdatabase: 'app',\n\t},\n\tredis: {\n\t\thost: 'localhost',\n\t\tport: 6379,\n\t\tusername: 'default',\n\t},\n\tminio: {\n\t\thost: 'localhost',\n\t\tport: 9000,\n\t\tusername: 'app',\n\t\tbucket: 'app',\n\t},\n\tmailpit: {\n\t\thost: 'localhost',\n\t\tport: 1025,\n\t\tusername: 'app',\n\t},\n\tlocalstack: {\n\t\thost: 'localhost',\n\t\tport: 4566,\n\t\tusername: 'localstack',\n\t\tregion: 'us-east-1',\n\t},\n};\n\n/** Default credentials for pgboss (not a Docker service, reuses postgres) */\nconst PGBOSS_DEFAULTS: Omit<ServiceCredentials, 'password'> = {\n\thost: 'localhost',\n\tport: 5432,\n\tusername: 'pgboss',\n\tdatabase: 'app',\n};\n\n/**\n * Generate credentials for a specific service.\n */\nexport function generateServiceCredentials(\n\tservice: SecretServiceName,\n): ServiceCredentials {\n\tconst defaults = SERVICE_DEFAULTS[service];\n\treturn {\n\t\t...defaults,\n\t\tpassword: generateSecurePassword(),\n\t};\n}\n\n/**\n * Generate credentials for multiple services.\n */\nexport function generateServicesCredentials(\n\tservices: SecretServiceName[],\n): StageSecrets['services'] {\n\tconst result: StageSecrets['services'] = {};\n\n\tfor (const service of services) {\n\t\tresult[service] = generateServiceCredentials(service);\n\t}\n\n\treturn result;\n}\n\n/**\n * Generate connection URL for PostgreSQL.\n */\nexport function generatePostgresUrl(creds: ServiceCredentials): string {\n\tconst { username, password, host, port, database } = creds;\n\treturn `postgresql://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}`;\n}\n\n/**\n * Generate connection URL for Redis.\n */\nexport function generateRedisUrl(creds: ServiceCredentials): string {\n\tconst { password, host, port } = creds;\n\treturn `redis://:${encodeURIComponent(password)}@${host}:${port}`;\n}\n\n/**\n * Generate endpoint URL for MinIO (S3-compatible).\n */\nexport function generateMinioEndpoint(creds: ServiceCredentials): string {\n\tconst { host, port } = creds;\n\treturn `http://${host}:${port}`;\n}\n\n/**\n * Generate a LocalStack-compatible access key ID.\n * Must start with 'LSIA' prefix and be at least 20 characters.\n * @see https://docs.localstack.cloud/aws/capabilities/config/credentials/\n */\nexport function generateLocalStackAccessKeyId(): string {\n\tconst suffix = randomBytes(12).toString('base64url').slice(0, 16);\n\treturn `LSIA${suffix}`;\n}\n\n/**\n * Generate connection URL for pg-boss (uses PostgreSQL protocol).\n * Format: pgboss://user:pass@host:port/db?schema=pgboss\n */\nexport function generatePgBossUrl(creds: ServiceCredentials): string {\n\tconst { username, password, host, port, database } = creds;\n\treturn `pgboss://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}?schema=pgboss`;\n}\n\n/**\n * Generate connection URLs from service credentials.\n */\nexport function generateConnectionUrls(\n\tservices: StageSecrets['services'],\n): StageSecrets['urls'] {\n\tconst urls: StageSecrets['urls'] = {};\n\n\tif (services.postgres) {\n\t\turls.DATABASE_URL = generatePostgresUrl(services.postgres);\n\t}\n\n\tif (services.redis) {\n\t\turls.REDIS_URL = generateRedisUrl(services.redis);\n\t}\n\n\tif (services.minio) {\n\t\turls.STORAGE_ENDPOINT = generateMinioEndpoint(services.minio);\n\t}\n\n\t// A topic's or queue's own broker URL is reconcile's, derived from the\n\t// declaration. This pair is what a worker's crons schedule through.\n\tif (services.pgboss) {\n\t\tconst pgbossUrl = generatePgBossUrl(services.pgboss);\n\t\turls.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;\n\t\turls.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;\n\t}\n\n\tif (services.mailpit) {\n\t\turls.SMTP_HOST = services.mailpit.host;\n\t\turls.SMTP_PORT = String(services.mailpit.port);\n\t}\n\n\treturn urls;\n}\n\n/**\n * Generate LocalStack service credentials with LSIA-prefixed access key.\n */\nexport function generateLocalStackCredentials(): ServiceCredentials {\n\tconst defaults = SERVICE_DEFAULTS.localstack;\n\treturn {\n\t\t...defaults,\n\t\tpassword: generateSecurePassword(),\n\t\taccessKeyId: generateLocalStackAccessKeyId(),\n\t};\n}\n\n/**\n * Create a new StageSecrets object with generated credentials.\n * @param stage - The deployment stage (e.g., 'development', 'production')\n * @param services - List of services to generate credentials for\n * @param options - Optional configuration\n * @param options.projectName - Project name used to derive the database name (e.g., 'myapp' → 'myapp_dev')\n */\nexport function createStageSecrets(\n\tstage: string,\n\tservices: SecretServiceName[],\n\toptions?: { projectName?: string },\n): StageSecrets {\n\tconst now = new Date().toISOString();\n\tconst serviceCredentials = generateServicesCredentials(services);\n\n\t// Override service defaults with project-derived names if provided\n\tif (options?.projectName) {\n\t\tif (serviceCredentials.postgres) {\n\t\t\tserviceCredentials.postgres.database = `${options.projectName.replace(/-/g, '_')}_dev`;\n\t\t}\n\t\tif (serviceCredentials.minio) {\n\t\t\tserviceCredentials.minio.bucket = options.projectName;\n\t\t\tserviceCredentials.minio.username = options.projectName;\n\t\t}\n\t}\n\n\t// Always create pgboss credentials when postgres is available.\n\t// pgboss reuses postgres host/port/database but with a dedicated user,\n\t// so subscribers work out of the box without explicit events config.\n\tif (serviceCredentials.postgres && !serviceCredentials.pgboss) {\n\t\tserviceCredentials.pgboss = {\n\t\t\t...PGBOSS_DEFAULTS,\n\t\t\tpassword: generateSecurePassword(),\n\t\t\thost: serviceCredentials.postgres.host,\n\t\t\tport: serviceCredentials.postgres.port,\n\t\t\tdatabase: serviceCredentials.postgres.database,\n\t\t};\n\t}\n\n\tconst urls = generateConnectionUrls(serviceCredentials);\n\n\treturn {\n\t\tstage,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tservices: serviceCredentials,\n\t\turls,\n\t\tcustom: {},\n\t};\n}\n\n/**\n * Rotate password for a specific service.\n */\nexport function rotateServicePassword(\n\tsecrets: StageSecrets,\n\tservice: SecretServiceName,\n): StageSecrets {\n\tconst currentCreds = secrets.services[service];\n\tif (!currentCreds) {\n\t\tthrow new Error(`Service \"${service}\" not configured in secrets`);\n\t}\n\n\tconst newCreds: ServiceCredentials = {\n\t\t...currentCreds,\n\t\tpassword: generateSecurePassword(),\n\t};\n\n\tconst newServices = {\n\t\t...secrets.services,\n\t\t[service]: newCreds,\n\t};\n\n\treturn {\n\t\t...secrets,\n\t\tupdatedAt: new Date().toISOString(),\n\t\tservices: newServices,\n\t\turls: generateConnectionUrls(newServices),\n\t};\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { generateSecurePassword } from '../secrets/generator.js';\nimport type { StageSecrets } from '../secrets/types.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/**\n * Generate a secure random password for database users.\n * Uses a combination of timestamp and random bytes for uniqueness.\n */\nexport function generateDbPassword(): string {\n\treturn `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Generate database URL for an app.\n * All apps connect to the same database, but use different users/schemas.\n */\nexport function generateDbUrl(\n\tappName: string,\n\tpassword: string,\n\tprojectName: string,\n\thost = 'localhost',\n\tport = 5432,\n): string {\n\tconst userName = appName.replace(/-/g, '_');\n\tconst dbName = `${projectName.replace(/-/g, '_')}_dev`;\n\treturn `postgresql://${userName}:${password}@${host}:${port}/${dbName}`;\n}\n\n/**\n * Generate fullstack-aware custom secrets for a workspace.\n *\n * Generates:\n * - Common secrets: PORT, LOG_LEVEL, JWT_SECRET (no `NODE_ENV` — the command\n * decides that; see `gkm init`)\n * - Per-app database passwords and URLs for backend apps with db service\n * - Better-auth secrets for apps using the better-auth framework\n */\nexport function generateFullstackCustomSecrets(\n\tworkspace: NormalizedWorkspace,\n\tcontainers: readonly string[] = [],\n): Record<string, string> {\n\t// A Postgres exists because something declared a database, not because\n\t// config carried a flag saying so.\n\tconst hasDb = containers.includes('postgres');\n\tconst customs: Record<string, string> = {\n\t\tPORT: '3000',\n\t\tLOG_LEVEL: 'debug',\n\t\tJWT_SECRET: `dev-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n\t};\n\n\tif (!hasDb) {\n\t\treturn customs;\n\t}\n\n\t// Collect all frontend ports for trusted origins\n\tconst frontendPorts: number[] = [];\n\n\tfor (const [appName, appConfig] of Object.entries(workspace.apps)) {\n\t\tif (appConfig.type === 'web') {\n\t\t\tfrontendPorts.push(appConfig.port);\n\t\t\tconst upperName = appName.toUpperCase();\n\t\t\tcustoms[`${upperName}_URL`] = `http://localhost:${appConfig.port}`;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Mobile apps (Expo, etc.) don't run on a host port the backend\n\t\t// cares about for CORS, and don't need DB credentials.\n\t\tif (appConfig.type === 'mobile') {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Backend apps with database: generate per-app DB passwords and URLs\n\t\tconst password = generateDbPassword();\n\t\tconst upperName = appName.toUpperCase();\n\n\t\tcustoms[`${upperName}_DATABASE_URL`] = generateDbUrl(\n\t\t\tappName,\n\t\t\tpassword,\n\t\t\tworkspace.name,\n\t\t);\n\t\tcustoms[`${upperName}_DB_PASSWORD`] = password;\n\n\t\t// Better-auth framework secrets\n\t\tif (appConfig.framework === 'better-auth') {\n\t\t\tcustoms.AUTH_PORT = String(appConfig.port);\n\t\t\tcustoms.AUTH_URL = `http://localhost:${appConfig.port}`;\n\t\t\tcustoms.BETTER_AUTH_SECRET = `better-auth-${Date.now()}-${generateSecurePassword(16)}`;\n\t\t\tcustoms.BETTER_AUTH_URL = `http://localhost:${appConfig.port}`;\n\t\t}\n\t}\n\n\t// Generate trusted origins for better-auth (all app ports)\n\tif (customs.BETTER_AUTH_SECRET) {\n\t\tconst allPorts = Object.values(workspace.apps).map((a) => a.port);\n\t\tcustoms.BETTER_AUTH_TRUSTED_ORIGINS = allPorts\n\t\t\t.map((p) => `http://localhost:${p}`)\n\t\t\t.join(',');\n\t}\n\n\treturn customs;\n}\n\n/**\n * Extract *_DB_PASSWORD keys from secrets and write docker/.env.\n *\n * The docker/.env file contains database passwords that the PostgreSQL\n * init script reads to create per-app database users.\n */\nexport async function writeDockerEnvFromSecrets(\n\tsecrets: StageSecrets,\n\tworkspaceRoot: string,\n): Promise<void> {\n\tconst dbPasswordEntries = Object.entries(secrets.custom).filter(([key]) =>\n\t\tkey.endsWith('_DB_PASSWORD'),\n\t);\n\n\t// Always include pgboss password when pgboss credentials exist\n\tif (\n\t\tsecrets.services.pgboss &&\n\t\t!dbPasswordEntries.some(([key]) => key === 'PGBOSS_DB_PASSWORD')\n\t) {\n\t\tdbPasswordEntries.push([\n\t\t\t'PGBOSS_DB_PASSWORD',\n\t\t\tsecrets.services.pgboss.password,\n\t\t]);\n\t}\n\n\tif (dbPasswordEntries.length === 0) {\n\t\treturn;\n\t}\n\n\tconst envContent = `# Auto-generated docker environment file\n# Contains database passwords for docker-compose postgres init\n# This file is gitignored - do not commit to version control\n${dbPasswordEntries.map(([key, value]) => `${key}=${value}`).join('\\n')}\n`;\n\n\tconst envPath = join(workspaceRoot, 'docker', '.env');\n\tawait mkdir(dirname(envPath), { recursive: true });\n\tawait writeFile(envPath, envContent);\n}\n","import { generateFullstackCustomSecrets } from '../setup/fullstack-secrets.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport type { StageSecrets } from './types.js';\n\nexport interface ReconcileResult {\n\t/** The updated secrets with missing keys backfilled */\n\tsecrets: StageSecrets;\n\t/** Keys that were added */\n\taddedKeys: string[];\n}\n\n/**\n * Reconcile missing custom secrets for a workspace.\n *\n * Compares current secrets against what generateFullstackCustomSecrets()\n * would produce and backfills any missing keys without overwriting\n * existing values.\n *\n * @returns ReconcileResult if keys were added, null if secrets are up-to-date\n */\nexport function reconcileMissingSecrets(\n\tsecrets: StageSecrets,\n\tworkspace: NormalizedWorkspace,\n\tcontainers: readonly string[] = [],\n): ReconcileResult | null {\n\tconst isMultiApp = Object.keys(workspace.apps).length > 1;\n\tif (!isMultiApp) {\n\t\treturn null;\n\t}\n\n\tconst expectedCustom = generateFullstackCustomSecrets(workspace, containers);\n\tconst addedKeys: string[] = [];\n\tconst mergedCustom = { ...secrets.custom };\n\n\tfor (const [key, value] of Object.entries(expectedCustom)) {\n\t\tif (!(key in mergedCustom)) {\n\t\t\tmergedCustom[key] = value;\n\t\t\taddedKeys.push(key);\n\t\t}\n\t}\n\n\tif (addedKeys.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tsecrets: {\n\t\t\t...secrets,\n\t\t\tupdatedAt: new Date().toISOString(),\n\t\t\tcustom: mergedCustom,\n\t\t},\n\t\taddedKeys,\n\t};\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,uBAAuB,SAAS,IAAY;CAC3D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SAAS,UAAU;AACpC;;;;;;;;;;;;;AC1HA,SAAgB,wBACf,SACA,WACA,aAAgC,CAAC,GACR;CAEzB,IAAI,EADe,OAAO,KAAK,UAAU,IAAI,CAAC,CAAC,SAAS,IAEvD,OAAO;CAGR,MAAM,iBAAiB,+BAA+B,WAAW,UAAU;CAC3E,MAAM,YAAsB,CAAC;CAC7B,MAAM,eAAe,EAAE,GAAG,QAAQ,OAAO;CAEzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACvD,IAAI,EAAE,OAAO,eAAe;EAC3B,aAAa,OAAO;EACpB,UAAU,KAAK,GAAG;CACnB;CAGD,IAAI,UAAU,WAAW,GACxB,OAAO;CAGR,OAAO;EACN,SAAS;GACR,GAAG;GACH,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;GAClC,QAAQ;EACT;EACA;CACD;AACD"}
|
|
@@ -23,12 +23,6 @@ const SERVICE_DEFAULTS = {
|
|
|
23
23
|
port: 6379,
|
|
24
24
|
username: "default"
|
|
25
25
|
},
|
|
26
|
-
rabbitmq: {
|
|
27
|
-
host: "localhost",
|
|
28
|
-
port: 5672,
|
|
29
|
-
username: "app",
|
|
30
|
-
vhost: "/"
|
|
31
|
-
},
|
|
32
26
|
minio: {
|
|
33
27
|
host: "localhost",
|
|
34
28
|
port: 9e3,
|
|
@@ -86,13 +80,6 @@ function generateRedisUrl(creds) {
|
|
|
86
80
|
return `redis://:${encodeURIComponent(password)}@${host}:${port}`;
|
|
87
81
|
}
|
|
88
82
|
/**
|
|
89
|
-
* Generate connection URL for RabbitMQ.
|
|
90
|
-
*/
|
|
91
|
-
function generateRabbitmqUrl(creds) {
|
|
92
|
-
const { username, password, host, port, vhost } = creds;
|
|
93
|
-
return `amqp://${username}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(vhost ?? "/")}`;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
83
|
* Generate endpoint URL for MinIO (S3-compatible).
|
|
97
84
|
*/
|
|
98
85
|
function generateMinioEndpoint(creds) {
|
|
@@ -100,14 +87,6 @@ function generateMinioEndpoint(creds) {
|
|
|
100
87
|
return `http://${host}:${port}`;
|
|
101
88
|
}
|
|
102
89
|
/**
|
|
103
|
-
* Generate a LocalStack-compatible access key ID.
|
|
104
|
-
* Must start with 'LSIA' prefix and be at least 20 characters.
|
|
105
|
-
* @see https://docs.localstack.cloud/aws/capabilities/config/credentials/
|
|
106
|
-
*/
|
|
107
|
-
function generateLocalStackAccessKeyId() {
|
|
108
|
-
return `LSIA${randomBytes(12).toString("base64url").slice(0, 16)}`;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
90
|
* Generate connection URL for pg-boss (uses PostgreSQL protocol).
|
|
112
91
|
* Format: pgboss://user:pass@host:port/db?schema=pgboss
|
|
113
92
|
*/
|
|
@@ -116,56 +95,14 @@ function generatePgBossUrl(creds) {
|
|
|
116
95
|
return `pgboss://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}?schema=pgboss`;
|
|
117
96
|
}
|
|
118
97
|
/**
|
|
119
|
-
* Generate event connection strings based on the events backend.
|
|
120
|
-
*/
|
|
121
|
-
function generateEventConnectionStrings(eventsBackend, services) {
|
|
122
|
-
switch (eventsBackend) {
|
|
123
|
-
case "pgboss": {
|
|
124
|
-
const creds = services.pgboss;
|
|
125
|
-
if (!creds) throw new Error("pgboss credentials required for pgboss events");
|
|
126
|
-
const url = generatePgBossUrl(creds);
|
|
127
|
-
return {
|
|
128
|
-
publisher: url,
|
|
129
|
-
subscriber: url
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
case "sns": {
|
|
133
|
-
const creds = services.localstack;
|
|
134
|
-
if (!creds) throw new Error("localstack credentials required for sns events");
|
|
135
|
-
const endpoint = `http://${creds.host}:${creds.port}`;
|
|
136
|
-
const region = creds.region ?? "us-east-1";
|
|
137
|
-
const accessKeyId = creds.accessKeyId ?? creds.username;
|
|
138
|
-
const secretKey = encodeURIComponent(creds.password);
|
|
139
|
-
return {
|
|
140
|
-
publisher: `sns://${accessKeyId}:${secretKey}@${creds.host}:${creds.port}?region=${region}&endpoint=${encodeURIComponent(endpoint)}`,
|
|
141
|
-
subscriber: `sqs://${accessKeyId}:${secretKey}@${creds.host}:${creds.port}?region=${region}&endpoint=${encodeURIComponent(endpoint)}`
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
case "rabbitmq": {
|
|
145
|
-
const creds = services.rabbitmq;
|
|
146
|
-
if (!creds) throw new Error("rabbitmq credentials required for rabbitmq events");
|
|
147
|
-
const url = generateRabbitmqUrl(creds);
|
|
148
|
-
return {
|
|
149
|
-
publisher: url,
|
|
150
|
-
subscriber: url
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
98
|
* Generate connection URLs from service credentials.
|
|
157
99
|
*/
|
|
158
|
-
function generateConnectionUrls(services
|
|
100
|
+
function generateConnectionUrls(services) {
|
|
159
101
|
const urls = {};
|
|
160
102
|
if (services.postgres) urls.DATABASE_URL = generatePostgresUrl(services.postgres);
|
|
161
103
|
if (services.redis) urls.REDIS_URL = generateRedisUrl(services.redis);
|
|
162
|
-
if (services.rabbitmq) urls.RABBITMQ_URL = generateRabbitmqUrl(services.rabbitmq);
|
|
163
104
|
if (services.minio) urls.STORAGE_ENDPOINT = generateMinioEndpoint(services.minio);
|
|
164
|
-
if (
|
|
165
|
-
const eventUrls = generateEventConnectionStrings(eventsBackend, services);
|
|
166
|
-
urls.EVENT_PUBLISHER_CONNECTION_STRING = eventUrls.publisher;
|
|
167
|
-
urls.EVENT_SUBSCRIBER_CONNECTION_STRING = eventUrls.subscriber;
|
|
168
|
-
} else if (services.pgboss) {
|
|
105
|
+
if (services.pgboss) {
|
|
169
106
|
const pgbossUrl = generatePgBossUrl(services.pgboss);
|
|
170
107
|
urls.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;
|
|
171
108
|
urls.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;
|
|
@@ -177,22 +114,11 @@ function generateConnectionUrls(services, eventsBackend) {
|
|
|
177
114
|
return urls;
|
|
178
115
|
}
|
|
179
116
|
/**
|
|
180
|
-
* Generate LocalStack service credentials with LSIA-prefixed access key.
|
|
181
|
-
*/
|
|
182
|
-
function generateLocalStackCredentials() {
|
|
183
|
-
return {
|
|
184
|
-
...SERVICE_DEFAULTS.localstack,
|
|
185
|
-
password: generateSecurePassword(),
|
|
186
|
-
accessKeyId: generateLocalStackAccessKeyId()
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
117
|
* Create a new StageSecrets object with generated credentials.
|
|
191
118
|
* @param stage - The deployment stage (e.g., 'development', 'production')
|
|
192
119
|
* @param services - List of services to generate credentials for
|
|
193
120
|
* @param options - Optional configuration
|
|
194
121
|
* @param options.projectName - Project name used to derive the database name (e.g., 'myapp' → 'myapp_dev')
|
|
195
|
-
* @param options.eventsBackend - Event backend type (pgboss, sns, rabbitmq)
|
|
196
122
|
*/
|
|
197
123
|
function createStageSecrets(stage, services, options) {
|
|
198
124
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -211,15 +137,12 @@ function createStageSecrets(stage, services, options) {
|
|
|
211
137
|
port: serviceCredentials.postgres.port,
|
|
212
138
|
database: serviceCredentials.postgres.database
|
|
213
139
|
};
|
|
214
|
-
const eventsBackend = options?.eventsBackend;
|
|
215
|
-
if (eventsBackend === "sns") serviceCredentials.localstack = generateLocalStackCredentials();
|
|
216
140
|
return {
|
|
217
141
|
stage,
|
|
218
142
|
createdAt: now,
|
|
219
143
|
updatedAt: now,
|
|
220
|
-
eventsBackend,
|
|
221
144
|
services: serviceCredentials,
|
|
222
|
-
urls: generateConnectionUrls(serviceCredentials
|
|
145
|
+
urls: generateConnectionUrls(serviceCredentials),
|
|
223
146
|
custom: {}
|
|
224
147
|
};
|
|
225
148
|
}
|
|
@@ -241,7 +164,7 @@ function rotateServicePassword(secrets, service) {
|
|
|
241
164
|
...secrets,
|
|
242
165
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
243
166
|
services: newServices,
|
|
244
|
-
urls: generateConnectionUrls(newServices
|
|
167
|
+
urls: generateConnectionUrls(newServices)
|
|
245
168
|
};
|
|
246
169
|
}
|
|
247
170
|
//#endregion
|
|
@@ -353,4 +276,4 @@ function reconcileMissingSecrets(secrets, workspace, containers = []) {
|
|
|
353
276
|
//#endregion
|
|
354
277
|
export { createStageSecrets as a, generateServiceCredentials as c, writeDockerEnvFromSecrets as i, rotateServicePassword as l, reconcile_exports as n, generateConnectionUrls as o, generateFullstackCustomSecrets as r, generateSecurePassword as s, reconcileMissingSecrets as t };
|
|
355
278
|
|
|
356
|
-
//# sourceMappingURL=reconcile-
|
|
279
|
+
//# sourceMappingURL=reconcile-yNq6Shau.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile-yNq6Shau.mjs","names":[],"sources":["../src/secrets/generator.ts","../src/setup/fullstack-secrets.ts","../src/secrets/reconcile.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport type {\n\tSecretServiceName,\n\tServiceCredentials,\n\tStageSecrets,\n} from './types';\n\n/**\n * Generate a secure random password using URL-safe base64 characters.\n * @param length Password length (default: 32)\n */\nexport function generateSecurePassword(length = 32): string {\n\treturn randomBytes(Math.ceil((length * 3) / 4))\n\t\t.toString('base64url')\n\t\t.slice(0, length);\n}\n\n/** Default service configurations (localhost for local dev via Docker port mapping) */\nconst SERVICE_DEFAULTS: Record<\n\tSecretServiceName,\n\tOmit<ServiceCredentials, 'password'>\n> = {\n\tpostgres: {\n\t\thost: 'localhost',\n\t\tport: 5432,\n\t\tusername: 'app',\n\t\tdatabase: 'app',\n\t},\n\tredis: {\n\t\thost: 'localhost',\n\t\tport: 6379,\n\t\tusername: 'default',\n\t},\n\tminio: {\n\t\thost: 'localhost',\n\t\tport: 9000,\n\t\tusername: 'app',\n\t\tbucket: 'app',\n\t},\n\tmailpit: {\n\t\thost: 'localhost',\n\t\tport: 1025,\n\t\tusername: 'app',\n\t},\n\tlocalstack: {\n\t\thost: 'localhost',\n\t\tport: 4566,\n\t\tusername: 'localstack',\n\t\tregion: 'us-east-1',\n\t},\n};\n\n/** Default credentials for pgboss (not a Docker service, reuses postgres) */\nconst PGBOSS_DEFAULTS: Omit<ServiceCredentials, 'password'> = {\n\thost: 'localhost',\n\tport: 5432,\n\tusername: 'pgboss',\n\tdatabase: 'app',\n};\n\n/**\n * Generate credentials for a specific service.\n */\nexport function generateServiceCredentials(\n\tservice: SecretServiceName,\n): ServiceCredentials {\n\tconst defaults = SERVICE_DEFAULTS[service];\n\treturn {\n\t\t...defaults,\n\t\tpassword: generateSecurePassword(),\n\t};\n}\n\n/**\n * Generate credentials for multiple services.\n */\nexport function generateServicesCredentials(\n\tservices: SecretServiceName[],\n): StageSecrets['services'] {\n\tconst result: StageSecrets['services'] = {};\n\n\tfor (const service of services) {\n\t\tresult[service] = generateServiceCredentials(service);\n\t}\n\n\treturn result;\n}\n\n/**\n * Generate connection URL for PostgreSQL.\n */\nexport function generatePostgresUrl(creds: ServiceCredentials): string {\n\tconst { username, password, host, port, database } = creds;\n\treturn `postgresql://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}`;\n}\n\n/**\n * Generate connection URL for Redis.\n */\nexport function generateRedisUrl(creds: ServiceCredentials): string {\n\tconst { password, host, port } = creds;\n\treturn `redis://:${encodeURIComponent(password)}@${host}:${port}`;\n}\n\n/**\n * Generate endpoint URL for MinIO (S3-compatible).\n */\nexport function generateMinioEndpoint(creds: ServiceCredentials): string {\n\tconst { host, port } = creds;\n\treturn `http://${host}:${port}`;\n}\n\n/**\n * Generate a LocalStack-compatible access key ID.\n * Must start with 'LSIA' prefix and be at least 20 characters.\n * @see https://docs.localstack.cloud/aws/capabilities/config/credentials/\n */\nexport function generateLocalStackAccessKeyId(): string {\n\tconst suffix = randomBytes(12).toString('base64url').slice(0, 16);\n\treturn `LSIA${suffix}`;\n}\n\n/**\n * Generate connection URL for pg-boss (uses PostgreSQL protocol).\n * Format: pgboss://user:pass@host:port/db?schema=pgboss\n */\nexport function generatePgBossUrl(creds: ServiceCredentials): string {\n\tconst { username, password, host, port, database } = creds;\n\treturn `pgboss://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}?schema=pgboss`;\n}\n\n/**\n * Generate connection URLs from service credentials.\n */\nexport function generateConnectionUrls(\n\tservices: StageSecrets['services'],\n): StageSecrets['urls'] {\n\tconst urls: StageSecrets['urls'] = {};\n\n\tif (services.postgres) {\n\t\turls.DATABASE_URL = generatePostgresUrl(services.postgres);\n\t}\n\n\tif (services.redis) {\n\t\turls.REDIS_URL = generateRedisUrl(services.redis);\n\t}\n\n\tif (services.minio) {\n\t\turls.STORAGE_ENDPOINT = generateMinioEndpoint(services.minio);\n\t}\n\n\t// A topic's or queue's own broker URL is reconcile's, derived from the\n\t// declaration. This pair is what a worker's crons schedule through.\n\tif (services.pgboss) {\n\t\tconst pgbossUrl = generatePgBossUrl(services.pgboss);\n\t\turls.EVENT_PUBLISHER_CONNECTION_STRING = pgbossUrl;\n\t\turls.EVENT_SUBSCRIBER_CONNECTION_STRING = pgbossUrl;\n\t}\n\n\tif (services.mailpit) {\n\t\turls.SMTP_HOST = services.mailpit.host;\n\t\turls.SMTP_PORT = String(services.mailpit.port);\n\t}\n\n\treturn urls;\n}\n\n/**\n * Generate LocalStack service credentials with LSIA-prefixed access key.\n */\nexport function generateLocalStackCredentials(): ServiceCredentials {\n\tconst defaults = SERVICE_DEFAULTS.localstack;\n\treturn {\n\t\t...defaults,\n\t\tpassword: generateSecurePassword(),\n\t\taccessKeyId: generateLocalStackAccessKeyId(),\n\t};\n}\n\n/**\n * Create a new StageSecrets object with generated credentials.\n * @param stage - The deployment stage (e.g., 'development', 'production')\n * @param services - List of services to generate credentials for\n * @param options - Optional configuration\n * @param options.projectName - Project name used to derive the database name (e.g., 'myapp' → 'myapp_dev')\n */\nexport function createStageSecrets(\n\tstage: string,\n\tservices: SecretServiceName[],\n\toptions?: { projectName?: string },\n): StageSecrets {\n\tconst now = new Date().toISOString();\n\tconst serviceCredentials = generateServicesCredentials(services);\n\n\t// Override service defaults with project-derived names if provided\n\tif (options?.projectName) {\n\t\tif (serviceCredentials.postgres) {\n\t\t\tserviceCredentials.postgres.database = `${options.projectName.replace(/-/g, '_')}_dev`;\n\t\t}\n\t\tif (serviceCredentials.minio) {\n\t\t\tserviceCredentials.minio.bucket = options.projectName;\n\t\t\tserviceCredentials.minio.username = options.projectName;\n\t\t}\n\t}\n\n\t// Always create pgboss credentials when postgres is available.\n\t// pgboss reuses postgres host/port/database but with a dedicated user,\n\t// so subscribers work out of the box without explicit events config.\n\tif (serviceCredentials.postgres && !serviceCredentials.pgboss) {\n\t\tserviceCredentials.pgboss = {\n\t\t\t...PGBOSS_DEFAULTS,\n\t\t\tpassword: generateSecurePassword(),\n\t\t\thost: serviceCredentials.postgres.host,\n\t\t\tport: serviceCredentials.postgres.port,\n\t\t\tdatabase: serviceCredentials.postgres.database,\n\t\t};\n\t}\n\n\tconst urls = generateConnectionUrls(serviceCredentials);\n\n\treturn {\n\t\tstage,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tservices: serviceCredentials,\n\t\turls,\n\t\tcustom: {},\n\t};\n}\n\n/**\n * Rotate password for a specific service.\n */\nexport function rotateServicePassword(\n\tsecrets: StageSecrets,\n\tservice: SecretServiceName,\n): StageSecrets {\n\tconst currentCreds = secrets.services[service];\n\tif (!currentCreds) {\n\t\tthrow new Error(`Service \"${service}\" not configured in secrets`);\n\t}\n\n\tconst newCreds: ServiceCredentials = {\n\t\t...currentCreds,\n\t\tpassword: generateSecurePassword(),\n\t};\n\n\tconst newServices = {\n\t\t...secrets.services,\n\t\t[service]: newCreds,\n\t};\n\n\treturn {\n\t\t...secrets,\n\t\tupdatedAt: new Date().toISOString(),\n\t\tservices: newServices,\n\t\turls: generateConnectionUrls(newServices),\n\t};\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { generateSecurePassword } from '../secrets/generator.js';\nimport type { StageSecrets } from '../secrets/types.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\n/**\n * Generate a secure random password for database users.\n * Uses a combination of timestamp and random bytes for uniqueness.\n */\nexport function generateDbPassword(): string {\n\treturn `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Generate database URL for an app.\n * All apps connect to the same database, but use different users/schemas.\n */\nexport function generateDbUrl(\n\tappName: string,\n\tpassword: string,\n\tprojectName: string,\n\thost = 'localhost',\n\tport = 5432,\n): string {\n\tconst userName = appName.replace(/-/g, '_');\n\tconst dbName = `${projectName.replace(/-/g, '_')}_dev`;\n\treturn `postgresql://${userName}:${password}@${host}:${port}/${dbName}`;\n}\n\n/**\n * Generate fullstack-aware custom secrets for a workspace.\n *\n * Generates:\n * - Common secrets: PORT, LOG_LEVEL, JWT_SECRET (no `NODE_ENV` — the command\n * decides that; see `gkm init`)\n * - Per-app database passwords and URLs for backend apps with db service\n * - Better-auth secrets for apps using the better-auth framework\n */\nexport function generateFullstackCustomSecrets(\n\tworkspace: NormalizedWorkspace,\n\tcontainers: readonly string[] = [],\n): Record<string, string> {\n\t// A Postgres exists because something declared a database, not because\n\t// config carried a flag saying so.\n\tconst hasDb = containers.includes('postgres');\n\tconst customs: Record<string, string> = {\n\t\tPORT: '3000',\n\t\tLOG_LEVEL: 'debug',\n\t\tJWT_SECRET: `dev-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n\t};\n\n\tif (!hasDb) {\n\t\treturn customs;\n\t}\n\n\t// Collect all frontend ports for trusted origins\n\tconst frontendPorts: number[] = [];\n\n\tfor (const [appName, appConfig] of Object.entries(workspace.apps)) {\n\t\tif (appConfig.type === 'web') {\n\t\t\tfrontendPorts.push(appConfig.port);\n\t\t\tconst upperName = appName.toUpperCase();\n\t\t\tcustoms[`${upperName}_URL`] = `http://localhost:${appConfig.port}`;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Mobile apps (Expo, etc.) don't run on a host port the backend\n\t\t// cares about for CORS, and don't need DB credentials.\n\t\tif (appConfig.type === 'mobile') {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Backend apps with database: generate per-app DB passwords and URLs\n\t\tconst password = generateDbPassword();\n\t\tconst upperName = appName.toUpperCase();\n\n\t\tcustoms[`${upperName}_DATABASE_URL`] = generateDbUrl(\n\t\t\tappName,\n\t\t\tpassword,\n\t\t\tworkspace.name,\n\t\t);\n\t\tcustoms[`${upperName}_DB_PASSWORD`] = password;\n\n\t\t// Better-auth framework secrets\n\t\tif (appConfig.framework === 'better-auth') {\n\t\t\tcustoms.AUTH_PORT = String(appConfig.port);\n\t\t\tcustoms.AUTH_URL = `http://localhost:${appConfig.port}`;\n\t\t\tcustoms.BETTER_AUTH_SECRET = `better-auth-${Date.now()}-${generateSecurePassword(16)}`;\n\t\t\tcustoms.BETTER_AUTH_URL = `http://localhost:${appConfig.port}`;\n\t\t}\n\t}\n\n\t// Generate trusted origins for better-auth (all app ports)\n\tif (customs.BETTER_AUTH_SECRET) {\n\t\tconst allPorts = Object.values(workspace.apps).map((a) => a.port);\n\t\tcustoms.BETTER_AUTH_TRUSTED_ORIGINS = allPorts\n\t\t\t.map((p) => `http://localhost:${p}`)\n\t\t\t.join(',');\n\t}\n\n\treturn customs;\n}\n\n/**\n * Extract *_DB_PASSWORD keys from secrets and write docker/.env.\n *\n * The docker/.env file contains database passwords that the PostgreSQL\n * init script reads to create per-app database users.\n */\nexport async function writeDockerEnvFromSecrets(\n\tsecrets: StageSecrets,\n\tworkspaceRoot: string,\n): Promise<void> {\n\tconst dbPasswordEntries = Object.entries(secrets.custom).filter(([key]) =>\n\t\tkey.endsWith('_DB_PASSWORD'),\n\t);\n\n\t// Always include pgboss password when pgboss credentials exist\n\tif (\n\t\tsecrets.services.pgboss &&\n\t\t!dbPasswordEntries.some(([key]) => key === 'PGBOSS_DB_PASSWORD')\n\t) {\n\t\tdbPasswordEntries.push([\n\t\t\t'PGBOSS_DB_PASSWORD',\n\t\t\tsecrets.services.pgboss.password,\n\t\t]);\n\t}\n\n\tif (dbPasswordEntries.length === 0) {\n\t\treturn;\n\t}\n\n\tconst envContent = `# Auto-generated docker environment file\n# Contains database passwords for docker-compose postgres init\n# This file is gitignored - do not commit to version control\n${dbPasswordEntries.map(([key, value]) => `${key}=${value}`).join('\\n')}\n`;\n\n\tconst envPath = join(workspaceRoot, 'docker', '.env');\n\tawait mkdir(dirname(envPath), { recursive: true });\n\tawait writeFile(envPath, envContent);\n}\n","import { generateFullstackCustomSecrets } from '../setup/fullstack-secrets.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport type { StageSecrets } from './types.js';\n\nexport interface ReconcileResult {\n\t/** The updated secrets with missing keys backfilled */\n\tsecrets: StageSecrets;\n\t/** Keys that were added */\n\taddedKeys: string[];\n}\n\n/**\n * Reconcile missing custom secrets for a workspace.\n *\n * Compares current secrets against what generateFullstackCustomSecrets()\n * would produce and backfills any missing keys without overwriting\n * existing values.\n *\n * @returns ReconcileResult if keys were added, null if secrets are up-to-date\n */\nexport function reconcileMissingSecrets(\n\tsecrets: StageSecrets,\n\tworkspace: NormalizedWorkspace,\n\tcontainers: readonly string[] = [],\n): ReconcileResult | null {\n\tconst isMultiApp = Object.keys(workspace.apps).length > 1;\n\tif (!isMultiApp) {\n\t\treturn null;\n\t}\n\n\tconst expectedCustom = generateFullstackCustomSecrets(workspace, containers);\n\tconst addedKeys: string[] = [];\n\tconst mergedCustom = { ...secrets.custom };\n\n\tfor (const [key, value] of Object.entries(expectedCustom)) {\n\t\tif (!(key in mergedCustom)) {\n\t\t\tmergedCustom[key] = value;\n\t\t\taddedKeys.push(key);\n\t\t}\n\t}\n\n\tif (addedKeys.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tsecrets: {\n\t\t\t...secrets,\n\t\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AAK,CAAC;CACjD,MAAM,UAAU,SAAS,UAAU;AACpC;;;;;;;;;;;;;AC1HA,SAAgB,wBACf,SACA,WACA,aAAgC,CAAC,GACR;CAEzB,IAAI,EADe,OAAO,KAAK,UAAU,IAAI,CAAC,CAAC,SAAS,IAEvD,OAAO;CAGR,MAAM,iBAAiB,+BAA+B,WAAW,UAAU;CAC3E,MAAM,YAAsB,CAAC;CAC7B,MAAM,eAAe,EAAE,GAAG,QAAQ,OAAO;CAEzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACvD,IAAI,EAAE,OAAO,eAAe;EAC3B,aAAa,OAAO;EACpB,UAAU,KAAK,GAAG;CACnB;CAGD,IAAI,UAAU,WAAW,GACxB,OAAO;CAGR,OAAO;EACN,SAAS;GACR,GAAG;GACH,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;GAClC,QAAQ;EACT;EACA;CACD;AACD"}
|
|
@@ -208,13 +208,6 @@ function toEmbeddableSecrets(secrets) {
|
|
|
208
208
|
REDIS_HOST: secrets.services.redis.host,
|
|
209
209
|
REDIS_PORT: String(secrets.services.redis.port)
|
|
210
210
|
},
|
|
211
|
-
...secrets.services.rabbitmq && {
|
|
212
|
-
RABBITMQ_USER: secrets.services.rabbitmq.username,
|
|
213
|
-
RABBITMQ_PASSWORD: secrets.services.rabbitmq.password,
|
|
214
|
-
RABBITMQ_HOST: secrets.services.rabbitmq.host,
|
|
215
|
-
RABBITMQ_PORT: String(secrets.services.rabbitmq.port),
|
|
216
|
-
RABBITMQ_VHOST: secrets.services.rabbitmq.vhost ?? "/"
|
|
217
|
-
},
|
|
218
211
|
...secrets.services.minio && {
|
|
219
212
|
STORAGE_ACCESS_KEY_ID: secrets.services.minio.username,
|
|
220
213
|
STORAGE_SECRET_ACCESS_KEY: secrets.services.minio.password,
|
|
@@ -301,4 +294,4 @@ function validateEnvironmentVariables(requiredVars, secrets) {
|
|
|
301
294
|
//#endregion
|
|
302
295
|
export { storage_exports as a, getKeyPath as c, setCustomSecret as i, readStageSecrets as n, toEmbeddableSecrets as o, secretsExist as r, writeStageSecrets as s, maskPassword as t };
|
|
303
296
|
|
|
304
|
-
//# sourceMappingURL=storage-
|
|
297
|
+
//# sourceMappingURL=storage-BjTLjDDp.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-TP0x118M.mjs","names":[],"sources":["../src/secrets/keystore.ts","../src/secrets/storage.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, join } from 'node:path';\n\n/** Key length for AES-256 encryption */\nconst KEY_LENGTH = 32; // 256 bits\n\n/**\n * Get the keystore directory for a project.\n * Keys are stored at ~/.gkm/{project-name}/\n *\n * @param projectName - Name of the project (defaults to current directory name)\n * @returns Path to the keystore directory\n */\nexport function getKeystoreDir(projectName?: string): string {\n\tconst name = projectName ?? basename(process.cwd());\n\treturn join(homedir(), '.gkm', name);\n}\n\n/**\n * Get the path to a stage's encryption key.\n *\n * @param stage - Stage name (e.g., 'development', 'production')\n * @param projectName - Name of the project (defaults to current directory name)\n * @returns Path to the key file\n */\nexport function getKeyPath(stage: string, projectName?: string): string {\n\treturn join(getKeystoreDir(projectName), `${stage}.key`);\n}\n\n/**\n * Check if a key exists for a stage.\n */\nexport function keyExists(stage: string, projectName?: string): boolean {\n\treturn existsSync(getKeyPath(stage, projectName));\n}\n\n/**\n * Generate a new encryption key for a stage.\n * The key is stored at ~/.gkm/{project-name}/{stage}.key with restricted permissions.\n *\n * @param stage - Stage name\n * @param projectName - Project name (defaults to current directory name)\n * @returns The generated key as a hex string\n */\nexport async function generateKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string> {\n\tconst keyDir = getKeystoreDir(projectName);\n\tconst keyPath = getKeyPath(stage, projectName);\n\n\t// Ensure keystore directory exists with restricted permissions\n\tawait mkdir(keyDir, { recursive: true, mode: 0o700 });\n\n\t// Generate random key\n\tconst key = randomBytes(KEY_LENGTH).toString('hex');\n\n\t// Write key with restricted permissions (owner read/write only)\n\tawait writeFile(keyPath, key, { mode: 0o600, encoding: 'utf-8' });\n\n\t// Ensure permissions are set correctly (in case file existed)\n\tawait chmod(keyPath, 0o600);\n\n\treturn key;\n}\n\n/**\n * Read an encryption key for a stage.\n *\n * @param stage - Stage name\n * @param projectName - Project name (defaults to current directory name)\n * @returns The key as a hex string, or null if not found\n */\nexport async function readKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string | null> {\n\tconst keyPath = getKeyPath(stage, projectName);\n\n\tif (!existsSync(keyPath)) {\n\t\treturn null;\n\t}\n\n\tconst key = await readFile(keyPath, 'utf-8');\n\treturn key.trim();\n}\n\n/**\n * Read an encryption key for a stage, throwing if not found.\n */\nexport async function requireKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string> {\n\tconst key = await readKey(stage, projectName);\n\n\tif (!key) {\n\t\tconst name = projectName ?? basename(process.cwd());\n\t\tthrow new Error(\n\t\t\t`Encryption key not found for stage \"${stage}\" in project \"${name}\". ` +\n\t\t\t\t`Expected key at: ${getKeyPath(stage, projectName)}`,\n\t\t);\n\t}\n\n\treturn key;\n}\n\n/**\n * Delete a key for a stage.\n */\nexport async function deleteKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<void> {\n\tconst keyPath = getKeyPath(stage, projectName);\n\n\tif (existsSync(keyPath)) {\n\t\tawait rm(keyPath);\n\t}\n}\n\n/**\n * Get or create a key for a stage.\n * If the key already exists, it is returned. Otherwise, a new key is generated.\n *\n * @param stage - Stage name\n * @param projectName - Project name (defaults to current directory name)\n * @returns The key as a hex string\n */\nexport async function getOrCreateKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string> {\n\tconst existingKey = await readKey(stage, projectName);\n\n\tif (existingKey) {\n\t\treturn existingKey;\n\t}\n\n\treturn generateKey(stage, projectName);\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { getOrCreateKey, readKey } from './keystore';\nimport type { EmbeddableSecrets, StageSecrets } from './types';\n\n/** Default secrets directory relative to project root */\nconst SECRETS_DIR = '.gkm/secrets';\n\n/** AES-256-GCM configuration */\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_LENGTH = 12; // 96 bits for GCM\nconst AUTH_TAG_LENGTH = 16; // 128 bits\n\n/** Encrypted secrets file structure */\ninterface EncryptedSecretsFile {\n\t/** Version for future format changes */\n\tversion: 1;\n\t/** Base64 encoded encrypted data (ciphertext + auth tag) */\n\tencrypted: string;\n\t/** Hex encoded IV */\n\tiv: string;\n}\n\n/**\n * Get the secrets directory path.\n */\nexport function getSecretsDir(cwd = process.cwd()): string {\n\treturn join(cwd, SECRETS_DIR);\n}\n\n/**\n * Get the secrets file path for a stage.\n */\nexport function getSecretsPath(stage: string, cwd = process.cwd()): string {\n\treturn join(getSecretsDir(cwd), `${stage}.json`);\n}\n\n/**\n * Check if secrets exist for a stage.\n */\nexport function secretsExist(stage: string, cwd = process.cwd()): boolean {\n\treturn existsSync(getSecretsPath(stage, cwd));\n}\n\n/**\n * Initialize an empty StageSecrets object for a stage.\n */\nexport function initStageSecrets(stage: string): StageSecrets {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\tstage,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tservices: {},\n\t\turls: {},\n\t\tcustom: {},\n\t};\n}\n\n/**\n * Encrypt secrets using a key.\n */\nfunction encryptSecretsData(\n\tsecrets: StageSecrets,\n\tkeyHex: string,\n): EncryptedSecretsFile {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst iv = randomBytes(IV_LENGTH);\n\n\t// Serialize secrets to JSON\n\tconst plaintext = JSON.stringify(secrets);\n\n\t// Encrypt\n\tconst cipher = createCipheriv(ALGORITHM, key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(plaintext, 'utf-8'),\n\t\tcipher.final(),\n\t]);\n\n\t// Get auth tag\n\tconst authTag = cipher.getAuthTag();\n\n\t// Combine ciphertext + auth tag\n\tconst combined = Buffer.concat([ciphertext, authTag]);\n\n\treturn {\n\t\tversion: 1,\n\t\tencrypted: combined.toString('base64'),\n\t\tiv: iv.toString('hex'),\n\t};\n}\n\n/**\n * Decrypt secrets using a key.\n */\nfunction decryptSecretsData(\n\tdata: EncryptedSecretsFile,\n\tkeyHex: string,\n): StageSecrets {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst ivBuffer = Buffer.from(data.iv, 'hex');\n\tconst combined = Buffer.from(data.encrypted, 'base64');\n\n\t// Split ciphertext and auth tag\n\tconst ciphertext = combined.subarray(0, -AUTH_TAG_LENGTH);\n\tconst authTag = combined.subarray(-AUTH_TAG_LENGTH);\n\n\t// Decrypt\n\tconst decipher = createDecipheriv(ALGORITHM, key, ivBuffer);\n\tdecipher.setAuthTag(authTag);\n\n\tconst plaintext = Buffer.concat([\n\t\tdecipher.update(ciphertext),\n\t\tdecipher.final(),\n\t]);\n\n\treturn JSON.parse(plaintext.toString('utf-8')) as StageSecrets;\n}\n\n/**\n * Read secrets for a stage (encrypted).\n * Requires the decryption key to be present at ~/.gkm/{project}/{stage}.key\n *\n * @returns StageSecrets or null if not found\n */\nexport async function readStageSecrets(\n\tstage: string,\n\tcwd = process.cwd(),\n): Promise<StageSecrets | null> {\n\tconst path = getSecretsPath(stage, cwd);\n\n\tif (!existsSync(path)) {\n\t\treturn null;\n\t}\n\n\tconst content = await readFile(path, 'utf-8');\n\tconst data = JSON.parse(content);\n\n\t// Check if this is an encrypted file (has version field)\n\tif (data.version === 1 && data.encrypted && data.iv) {\n\t\tconst projectName = basename(cwd);\n\t\tconst key = await readKey(stage, projectName);\n\n\t\tif (!key) {\n\t\t\tthrow new Error(\n\t\t\t\t`Decryption key not found for stage \"${stage}\". ` +\n\t\t\t\t\t`Expected key at: ~/.gkm/${projectName}/${stage}.key`,\n\t\t\t);\n\t\t}\n\n\t\treturn decryptSecretsData(data as EncryptedSecretsFile, key);\n\t}\n\n\t// Legacy: unencrypted format (for backwards compatibility)\n\treturn data as StageSecrets;\n}\n\n/**\n * Write secrets for a stage (encrypted).\n * Creates or uses existing encryption key at ~/.gkm/{project}/{stage}.key\n */\nexport async function writeStageSecrets(\n\tsecrets: StageSecrets,\n\tcwd = process.cwd(),\n): Promise<void> {\n\tconst dir = getSecretsDir(cwd);\n\tconst path = getSecretsPath(secrets.stage, cwd);\n\tconst projectName = basename(cwd);\n\n\t// Ensure directory exists\n\tawait mkdir(dir, { recursive: true });\n\n\t// Get or create encryption key\n\tconst key = await getOrCreateKey(secrets.stage, projectName);\n\n\t// Encrypt and write\n\tconst encrypted = encryptSecretsData(secrets, key);\n\tawait writeFile(path, JSON.stringify(encrypted, null, 2), 'utf-8');\n}\n\n/**\n * Convert StageSecrets to embeddable format (flat key-value pairs).\n * This is what gets encrypted and embedded in the bundle.\n */\nexport function toEmbeddableSecrets(secrets: StageSecrets): EmbeddableSecrets {\n\treturn {\n\t\t...secrets.urls,\n\t\t...secrets.custom,\n\t\t// Also include individual service credentials if needed\n\t\t...(secrets.services.postgres && {\n\t\t\tPOSTGRES_USER: secrets.services.postgres.username,\n\t\t\tPOSTGRES_PASSWORD: secrets.services.postgres.password,\n\t\t\tPOSTGRES_DB: secrets.services.postgres.database ?? 'app',\n\t\t\tPOSTGRES_HOST: secrets.services.postgres.host,\n\t\t\tPOSTGRES_PORT: String(secrets.services.postgres.port),\n\t\t}),\n\t\t...(secrets.services.redis && {\n\t\t\tREDIS_PASSWORD: secrets.services.redis.password,\n\t\t\tREDIS_HOST: secrets.services.redis.host,\n\t\t\tREDIS_PORT: String(secrets.services.redis.port),\n\t\t}),\n\t\t...(secrets.services.rabbitmq && {\n\t\t\tRABBITMQ_USER: secrets.services.rabbitmq.username,\n\t\t\tRABBITMQ_PASSWORD: secrets.services.rabbitmq.password,\n\t\t\tRABBITMQ_HOST: secrets.services.rabbitmq.host,\n\t\t\tRABBITMQ_PORT: String(secrets.services.rabbitmq.port),\n\t\t\tRABBITMQ_VHOST: secrets.services.rabbitmq.vhost ?? '/',\n\t\t}),\n\t\t...(secrets.services.minio && {\n\t\t\tSTORAGE_ACCESS_KEY_ID: secrets.services.minio.username,\n\t\t\tSTORAGE_SECRET_ACCESS_KEY: secrets.services.minio.password,\n\t\t\tSTORAGE_BUCKET: secrets.services.minio.bucket ?? 'app',\n\t\t\tSTORAGE_REGION: 'eu-west-1',\n\t\t\tSTORAGE_FORCE_PATH_STYLE: 'true',\n\t\t}),\n\t\t...(secrets.services.mailpit && {\n\t\t\tSMTP_HOST: secrets.services.mailpit.host,\n\t\t\tSMTP_PORT: String(secrets.services.mailpit.port),\n\t\t\tSMTP_USER: secrets.services.mailpit.username,\n\t\t\tSMTP_PASS: secrets.services.mailpit.password,\n\t\t\tSMTP_SECURE: 'false',\n\t\t\tMAIL_FROM: 'noreply@localhost',\n\t\t}),\n\t\t...(secrets.services.localstack && {\n\t\t\tAWS_ACCESS_KEY_ID:\n\t\t\t\tsecrets.services.localstack.accessKeyId ??\n\t\t\t\tsecrets.services.localstack.username,\n\t\t\tAWS_SECRET_ACCESS_KEY: secrets.services.localstack.password,\n\t\t\tAWS_REGION: secrets.services.localstack.region ?? 'us-east-1',\n\t\t\tAWS_ENDPOINT_URL: `http://${secrets.services.localstack.host}:${secrets.services.localstack.port}`,\n\t\t}),\n\t\t...(secrets.services.pgboss && {\n\t\t\tPGBOSS_DB_USER: secrets.services.pgboss.username,\n\t\t\tPGBOSS_DB_PASSWORD: secrets.services.pgboss.password,\n\t\t}),\n\t};\n}\n\n/**\n * Update a custom secret in the secrets file.\n */\nexport async function setCustomSecret(\n\tstage: string,\n\tkey: string,\n\tvalue: string,\n\tcwd = process.cwd(),\n): Promise<StageSecrets> {\n\tconst secrets = await readStageSecrets(stage, cwd);\n\n\tif (!secrets) {\n\t\tthrow new Error(\n\t\t\t`Secrets not found for stage \"${stage}\". Run \"gkm secrets:init --stage ${stage}\" first.`,\n\t\t);\n\t}\n\n\tconst updated: StageSecrets = {\n\t\t...secrets,\n\t\tupdatedAt: new Date().toISOString(),\n\t\tcustom: {\n\t\t\t...secrets.custom,\n\t\t\t[key]: value,\n\t\t},\n\t};\n\n\tawait writeStageSecrets(updated, cwd);\n\treturn updated;\n}\n\n/**\n * Mask a password for display (show first 4 and last 2 chars).\n */\nexport function maskPassword(password: string): string {\n\tif (password.length <= 8) {\n\t\treturn '********';\n\t}\n\treturn `${password.slice(0, 4)}${'*'.repeat(password.length - 6)}${password.slice(-2)}`;\n}\n\n/**\n * Result of environment variable validation.\n */\nexport interface EnvValidationResult {\n\t/** Whether all required environment variables are present */\n\tvalid: boolean;\n\t/** List of missing environment variable names */\n\tmissing: string[];\n\t/** List of environment variables that are provided */\n\tprovided: string[];\n\t/** List of environment variables that were required */\n\trequired: string[];\n}\n\n/**\n * Validate that all required environment variables are present in secrets.\n *\n * @param requiredVars - Array of environment variable names required by the application\n * @param secrets - Stage secrets to validate against\n * @returns Validation result with missing and provided variables\n *\n * @example\n * ```typescript\n * const required = ['DATABASE_URL', 'API_KEY', 'JWT_SECRET'];\n * const secrets = await readStageSecrets('production');\n * const result = validateEnvironmentVariables(required, secrets);\n *\n * if (!result.valid) {\n * console.error(`Missing environment variables: ${result.missing.join(', ')}`);\n * }\n * ```\n */\nexport function validateEnvironmentVariables(\n\trequiredVars: string[],\n\tsecrets: StageSecrets,\n): EnvValidationResult {\n\tconst embeddable = toEmbeddableSecrets(secrets);\n\tconst availableVars = new Set(Object.keys(embeddable));\n\n\tconst missing: string[] = [];\n\tconst provided: string[] = [];\n\n\tfor (const varName of requiredVars) {\n\t\tif (availableVars.has(varName)) {\n\t\t\tprovided.push(varName);\n\t\t} else {\n\t\t\tmissing.push(varName);\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: missing.length === 0,\n\t\tmissing: missing.sort(),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EACH,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;EAClC,QAAQ;GACP,GAAG,QAAQ;IACV,MAAM;EACR;CACD;CAEA,MAAM,kBAAkB,SAAS,GAAG;CACpC,OAAO;AACR;;;;AAKA,SAAgB,aAAa,UAA0B;CACtD,IAAI,SAAS,UAAU,GACtB,OAAO;CAER,OAAO,GAAG,SAAS,MAAM,GAAG,CAAC,IAAI,IAAI,OAAO,SAAS,SAAS,CAAC,IAAI,SAAS,MAAM,EAAE;AACrF;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,6BACf,cACA,SACsB;CACtB,MAAM,aAAa,oBAAoB,OAAO;CAC9C,MAAM,gBAAgB,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC;CAErD,MAAM,UAAoB,CAAC;CAC3B,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,WAAW,cACrB,IAAI,cAAc,IAAI,OAAO,GAC5B,SAAS,KAAK,OAAO;MAErB,QAAQ,KAAK,OAAO;CAItB,OAAO;EACN,OAAO,QAAQ,WAAW;EAC1B,SAAS,QAAQ,KAAK;EACtB,UAAU,SAAS,KAAK;EACxB,UAAU,CAAC,GAAG,YAAY,CAAC,CAAC,KAAK;CAClC;AACD"}
|
|
1
|
+
{"version":3,"file":"storage-BjTLjDDp.mjs","names":[],"sources":["../src/secrets/keystore.ts","../src/secrets/storage.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, join } from 'node:path';\n\n/** Key length for AES-256 encryption */\nconst KEY_LENGTH = 32; // 256 bits\n\n/**\n * Get the keystore directory for a project.\n * Keys are stored at ~/.gkm/{project-name}/\n *\n * @param projectName - Name of the project (defaults to current directory name)\n * @returns Path to the keystore directory\n */\nexport function getKeystoreDir(projectName?: string): string {\n\tconst name = projectName ?? basename(process.cwd());\n\treturn join(homedir(), '.gkm', name);\n}\n\n/**\n * Get the path to a stage's encryption key.\n *\n * @param stage - Stage name (e.g., 'development', 'production')\n * @param projectName - Name of the project (defaults to current directory name)\n * @returns Path to the key file\n */\nexport function getKeyPath(stage: string, projectName?: string): string {\n\treturn join(getKeystoreDir(projectName), `${stage}.key`);\n}\n\n/**\n * Check if a key exists for a stage.\n */\nexport function keyExists(stage: string, projectName?: string): boolean {\n\treturn existsSync(getKeyPath(stage, projectName));\n}\n\n/**\n * Generate a new encryption key for a stage.\n * The key is stored at ~/.gkm/{project-name}/{stage}.key with restricted permissions.\n *\n * @param stage - Stage name\n * @param projectName - Project name (defaults to current directory name)\n * @returns The generated key as a hex string\n */\nexport async function generateKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string> {\n\tconst keyDir = getKeystoreDir(projectName);\n\tconst keyPath = getKeyPath(stage, projectName);\n\n\t// Ensure keystore directory exists with restricted permissions\n\tawait mkdir(keyDir, { recursive: true, mode: 0o700 });\n\n\t// Generate random key\n\tconst key = randomBytes(KEY_LENGTH).toString('hex');\n\n\t// Write key with restricted permissions (owner read/write only)\n\tawait writeFile(keyPath, key, { mode: 0o600, encoding: 'utf-8' });\n\n\t// Ensure permissions are set correctly (in case file existed)\n\tawait chmod(keyPath, 0o600);\n\n\treturn key;\n}\n\n/**\n * Read an encryption key for a stage.\n *\n * @param stage - Stage name\n * @param projectName - Project name (defaults to current directory name)\n * @returns The key as a hex string, or null if not found\n */\nexport async function readKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string | null> {\n\tconst keyPath = getKeyPath(stage, projectName);\n\n\tif (!existsSync(keyPath)) {\n\t\treturn null;\n\t}\n\n\tconst key = await readFile(keyPath, 'utf-8');\n\treturn key.trim();\n}\n\n/**\n * Read an encryption key for a stage, throwing if not found.\n */\nexport async function requireKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string> {\n\tconst key = await readKey(stage, projectName);\n\n\tif (!key) {\n\t\tconst name = projectName ?? basename(process.cwd());\n\t\tthrow new Error(\n\t\t\t`Encryption key not found for stage \"${stage}\" in project \"${name}\". ` +\n\t\t\t\t`Expected key at: ${getKeyPath(stage, projectName)}`,\n\t\t);\n\t}\n\n\treturn key;\n}\n\n/**\n * Delete a key for a stage.\n */\nexport async function deleteKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<void> {\n\tconst keyPath = getKeyPath(stage, projectName);\n\n\tif (existsSync(keyPath)) {\n\t\tawait rm(keyPath);\n\t}\n}\n\n/**\n * Get or create a key for a stage.\n * If the key already exists, it is returned. Otherwise, a new key is generated.\n *\n * @param stage - Stage name\n * @param projectName - Project name (defaults to current directory name)\n * @returns The key as a hex string\n */\nexport async function getOrCreateKey(\n\tstage: string,\n\tprojectName?: string,\n): Promise<string> {\n\tconst existingKey = await readKey(stage, projectName);\n\n\tif (existingKey) {\n\t\treturn existingKey;\n\t}\n\n\treturn generateKey(stage, projectName);\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { getOrCreateKey, readKey } from './keystore';\nimport type { EmbeddableSecrets, StageSecrets } from './types';\n\n/** Default secrets directory relative to project root */\nconst SECRETS_DIR = '.gkm/secrets';\n\n/** AES-256-GCM configuration */\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_LENGTH = 12; // 96 bits for GCM\nconst AUTH_TAG_LENGTH = 16; // 128 bits\n\n/** Encrypted secrets file structure */\ninterface EncryptedSecretsFile {\n\t/** Version for future format changes */\n\tversion: 1;\n\t/** Base64 encoded encrypted data (ciphertext + auth tag) */\n\tencrypted: string;\n\t/** Hex encoded IV */\n\tiv: string;\n}\n\n/**\n * Get the secrets directory path.\n */\nexport function getSecretsDir(cwd = process.cwd()): string {\n\treturn join(cwd, SECRETS_DIR);\n}\n\n/**\n * Get the secrets file path for a stage.\n */\nexport function getSecretsPath(stage: string, cwd = process.cwd()): string {\n\treturn join(getSecretsDir(cwd), `${stage}.json`);\n}\n\n/**\n * Check if secrets exist for a stage.\n */\nexport function secretsExist(stage: string, cwd = process.cwd()): boolean {\n\treturn existsSync(getSecretsPath(stage, cwd));\n}\n\n/**\n * Initialize an empty StageSecrets object for a stage.\n */\nexport function initStageSecrets(stage: string): StageSecrets {\n\tconst now = new Date().toISOString();\n\treturn {\n\t\tstage,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tservices: {},\n\t\turls: {},\n\t\tcustom: {},\n\t};\n}\n\n/**\n * Encrypt secrets using a key.\n */\nfunction encryptSecretsData(\n\tsecrets: StageSecrets,\n\tkeyHex: string,\n): EncryptedSecretsFile {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst iv = randomBytes(IV_LENGTH);\n\n\t// Serialize secrets to JSON\n\tconst plaintext = JSON.stringify(secrets);\n\n\t// Encrypt\n\tconst cipher = createCipheriv(ALGORITHM, key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(plaintext, 'utf-8'),\n\t\tcipher.final(),\n\t]);\n\n\t// Get auth tag\n\tconst authTag = cipher.getAuthTag();\n\n\t// Combine ciphertext + auth tag\n\tconst combined = Buffer.concat([ciphertext, authTag]);\n\n\treturn {\n\t\tversion: 1,\n\t\tencrypted: combined.toString('base64'),\n\t\tiv: iv.toString('hex'),\n\t};\n}\n\n/**\n * Decrypt secrets using a key.\n */\nfunction decryptSecretsData(\n\tdata: EncryptedSecretsFile,\n\tkeyHex: string,\n): StageSecrets {\n\tconst key = Buffer.from(keyHex, 'hex');\n\tconst ivBuffer = Buffer.from(data.iv, 'hex');\n\tconst combined = Buffer.from(data.encrypted, 'base64');\n\n\t// Split ciphertext and auth tag\n\tconst ciphertext = combined.subarray(0, -AUTH_TAG_LENGTH);\n\tconst authTag = combined.subarray(-AUTH_TAG_LENGTH);\n\n\t// Decrypt\n\tconst decipher = createDecipheriv(ALGORITHM, key, ivBuffer);\n\tdecipher.setAuthTag(authTag);\n\n\tconst plaintext = Buffer.concat([\n\t\tdecipher.update(ciphertext),\n\t\tdecipher.final(),\n\t]);\n\n\treturn JSON.parse(plaintext.toString('utf-8')) as StageSecrets;\n}\n\n/**\n * Read secrets for a stage (encrypted).\n * Requires the decryption key to be present at ~/.gkm/{project}/{stage}.key\n *\n * @returns StageSecrets or null if not found\n */\nexport async function readStageSecrets(\n\tstage: string,\n\tcwd = process.cwd(),\n): Promise<StageSecrets | null> {\n\tconst path = getSecretsPath(stage, cwd);\n\n\tif (!existsSync(path)) {\n\t\treturn null;\n\t}\n\n\tconst content = await readFile(path, 'utf-8');\n\tconst data = JSON.parse(content);\n\n\t// Check if this is an encrypted file (has version field)\n\tif (data.version === 1 && data.encrypted && data.iv) {\n\t\tconst projectName = basename(cwd);\n\t\tconst key = await readKey(stage, projectName);\n\n\t\tif (!key) {\n\t\t\tthrow new Error(\n\t\t\t\t`Decryption key not found for stage \"${stage}\". ` +\n\t\t\t\t\t`Expected key at: ~/.gkm/${projectName}/${stage}.key`,\n\t\t\t);\n\t\t}\n\n\t\treturn decryptSecretsData(data as EncryptedSecretsFile, key);\n\t}\n\n\t// Legacy: unencrypted format (for backwards compatibility)\n\treturn data as StageSecrets;\n}\n\n/**\n * Write secrets for a stage (encrypted).\n * Creates or uses existing encryption key at ~/.gkm/{project}/{stage}.key\n */\nexport async function writeStageSecrets(\n\tsecrets: StageSecrets,\n\tcwd = process.cwd(),\n): Promise<void> {\n\tconst dir = getSecretsDir(cwd);\n\tconst path = getSecretsPath(secrets.stage, cwd);\n\tconst projectName = basename(cwd);\n\n\t// Ensure directory exists\n\tawait mkdir(dir, { recursive: true });\n\n\t// Get or create encryption key\n\tconst key = await getOrCreateKey(secrets.stage, projectName);\n\n\t// Encrypt and write\n\tconst encrypted = encryptSecretsData(secrets, key);\n\tawait writeFile(path, JSON.stringify(encrypted, null, 2), 'utf-8');\n}\n\n/**\n * Convert StageSecrets to embeddable format (flat key-value pairs).\n * This is what gets encrypted and embedded in the bundle.\n */\nexport function toEmbeddableSecrets(secrets: StageSecrets): EmbeddableSecrets {\n\treturn {\n\t\t...secrets.urls,\n\t\t...secrets.custom,\n\t\t// Also include individual service credentials if needed\n\t\t...(secrets.services.postgres && {\n\t\t\tPOSTGRES_USER: secrets.services.postgres.username,\n\t\t\tPOSTGRES_PASSWORD: secrets.services.postgres.password,\n\t\t\tPOSTGRES_DB: secrets.services.postgres.database ?? 'app',\n\t\t\tPOSTGRES_HOST: secrets.services.postgres.host,\n\t\t\tPOSTGRES_PORT: String(secrets.services.postgres.port),\n\t\t}),\n\t\t...(secrets.services.redis && {\n\t\t\tREDIS_PASSWORD: secrets.services.redis.password,\n\t\t\tREDIS_HOST: secrets.services.redis.host,\n\t\t\tREDIS_PORT: String(secrets.services.redis.port),\n\t\t}),\n\t\t...(secrets.services.minio && {\n\t\t\tSTORAGE_ACCESS_KEY_ID: secrets.services.minio.username,\n\t\t\tSTORAGE_SECRET_ACCESS_KEY: secrets.services.minio.password,\n\t\t\tSTORAGE_BUCKET: secrets.services.minio.bucket ?? 'app',\n\t\t\tSTORAGE_REGION: 'eu-west-1',\n\t\t\tSTORAGE_FORCE_PATH_STYLE: 'true',\n\t\t}),\n\t\t...(secrets.services.mailpit && {\n\t\t\tSMTP_HOST: secrets.services.mailpit.host,\n\t\t\tSMTP_PORT: String(secrets.services.mailpit.port),\n\t\t\tSMTP_USER: secrets.services.mailpit.username,\n\t\t\tSMTP_PASS: secrets.services.mailpit.password,\n\t\t\tSMTP_SECURE: 'false',\n\t\t\tMAIL_FROM: 'noreply@localhost',\n\t\t}),\n\t\t...(secrets.services.localstack && {\n\t\t\tAWS_ACCESS_KEY_ID:\n\t\t\t\tsecrets.services.localstack.accessKeyId ??\n\t\t\t\tsecrets.services.localstack.username,\n\t\t\tAWS_SECRET_ACCESS_KEY: secrets.services.localstack.password,\n\t\t\tAWS_REGION: secrets.services.localstack.region ?? 'us-east-1',\n\t\t\tAWS_ENDPOINT_URL: `http://${secrets.services.localstack.host}:${secrets.services.localstack.port}`,\n\t\t}),\n\t\t...(secrets.services.pgboss && {\n\t\t\tPGBOSS_DB_USER: secrets.services.pgboss.username,\n\t\t\tPGBOSS_DB_PASSWORD: secrets.services.pgboss.password,\n\t\t}),\n\t};\n}\n\n/**\n * Update a custom secret in the secrets file.\n */\nexport async function setCustomSecret(\n\tstage: string,\n\tkey: string,\n\tvalue: string,\n\tcwd = process.cwd(),\n): Promise<StageSecrets> {\n\tconst secrets = await readStageSecrets(stage, cwd);\n\n\tif (!secrets) {\n\t\tthrow new Error(\n\t\t\t`Secrets not found for stage \"${stage}\". Run \"gkm secrets:init --stage ${stage}\" first.`,\n\t\t);\n\t}\n\n\tconst updated: StageSecrets = {\n\t\t...secrets,\n\t\tupdatedAt: new Date().toISOString(),\n\t\tcustom: {\n\t\t\t...secrets.custom,\n\t\t\t[key]: value,\n\t\t},\n\t};\n\n\tawait writeStageSecrets(updated, cwd);\n\treturn updated;\n}\n\n/**\n * Mask a password for display (show first 4 and last 2 chars).\n */\nexport function maskPassword(password: string): string {\n\tif (password.length <= 8) {\n\t\treturn '********';\n\t}\n\treturn `${password.slice(0, 4)}${'*'.repeat(password.length - 6)}${password.slice(-2)}`;\n}\n\n/**\n * Result of environment variable validation.\n */\nexport interface EnvValidationResult {\n\t/** Whether all required environment variables are present */\n\tvalid: boolean;\n\t/** List of missing environment variable names */\n\tmissing: string[];\n\t/** List of environment variables that are provided */\n\tprovided: string[];\n\t/** List of environment variables that were required */\n\trequired: string[];\n}\n\n/**\n * Validate that all required environment variables are present in secrets.\n *\n * @param requiredVars - Array of environment variable names required by the application\n * @param secrets - Stage secrets to validate against\n * @returns Validation result with missing and provided variables\n *\n * @example\n * ```typescript\n * const required = ['DATABASE_URL', 'API_KEY', 'JWT_SECRET'];\n * const secrets = await readStageSecrets('production');\n * const result = validateEnvironmentVariables(required, secrets);\n *\n * if (!result.valid) {\n * console.error(`Missing environment variables: ${result.missing.join(', ')}`);\n * }\n * ```\n */\nexport function validateEnvironmentVariables(\n\trequiredVars: string[],\n\tsecrets: StageSecrets,\n): EnvValidationResult {\n\tconst embeddable = toEmbeddableSecrets(secrets);\n\tconst availableVars = new Set(Object.keys(embeddable));\n\n\tconst missing: string[] = [];\n\tconst provided: string[] = [];\n\n\tfor (const varName of requiredVars) {\n\t\tif (availableVars.has(varName)) {\n\t\t\tprovided.push(varName);\n\t\t} else {\n\t\t\tmissing.push(varName);\n\t\t}\n\t}\n\n\treturn {\n\t\tvalid: missing.length === 0,\n\t\tmissing: missing.sort(),\n\t\tprovided: provided.sort(),\n\t\trequired: [...requiredVars].sort(),\n\t};\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,aAAa;;;;;;;;AASnB,SAAgB,eAAe,aAA8B;CAC5D,MAAM,OAAO,eAAe,SAAS,QAAQ,IAAI,CAAC;CAClD,OAAO,KAAK,QAAQ,GAAG,QAAQ,IAAI;AACpC;;;;;;;;AASA,SAAgB,WAAW,OAAe,aAA8B;CACvE,OAAO,KAAK,eAAe,WAAW,GAAG,GAAG,MAAM,KAAK;AACxD;;;;;;;;;AAiBA,eAAsB,YACrB,OACA,aACkB;CAClB,MAAM,SAAS,eAAe,WAAW;CACzC,MAAM,UAAU,WAAW,OAAO,WAAW;CAG7C,MAAM,MAAM,QAAQ;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CAGpD,MAAM,MAAM,YAAY,UAAU,CAAC,CAAC,SAAS,KAAK;CAGlD,MAAM,UAAU,SAAS,KAAK;EAAE,MAAM;EAAO,UAAU;CAAQ,CAAC;CAGhE,MAAM,MAAM,SAAS,GAAK;CAE1B,OAAO;AACR;;;;;;;;AASA,eAAsB,QACrB,OACA,aACyB;CACzB,MAAM,UAAU,WAAW,OAAO,WAAW;CAE7C,IAAI,CAAC,WAAW,OAAO,GACtB,OAAO;CAIR,QAAO,MADW,SAAS,SAAS,OAAO,EAAA,CAChC,KAAK;AACjB;;;;;;;;;AA4CA,eAAsB,eACrB,OACA,aACkB;CAClB,MAAM,cAAc,MAAM,QAAQ,OAA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