webspresso 0.0.104 → 0.0.106

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.
Files changed (233) hide show
  1. package/.agents/AGENTS.md +21 -2
  2. package/.agents/ARCHITECTURE.md +23 -0
  3. package/.agents/CACHE.md +147 -0
  4. package/.agents/CLI.md +220 -8
  5. package/.agents/EARLY_HINTS.md +120 -0
  6. package/.agents/FLAGS.md +118 -0
  7. package/.agents/HEALTH.md +118 -0
  8. package/.agents/LIMITS.md +109 -0
  9. package/.agents/LOGGING.md +93 -0
  10. package/.agents/METRICS.md +127 -0
  11. package/.agents/MIGRATION_JOBS.md +95 -0
  12. package/.agents/ORM.md +155 -1
  13. package/.agents/PLUGINS.md +38 -3
  14. package/.agents/QUEUE.md +42 -0
  15. package/.agents/RATE_LIMIT.md +147 -0
  16. package/.agents/RESILIENCE.md +235 -0
  17. package/.agents/SCALE_OUT.md +109 -0
  18. package/.agents/SECRETS.md +117 -0
  19. package/AGENTS.md +16 -0
  20. package/README.md +2 -2
  21. package/bin/commands/add-aws.js +396 -0
  22. package/bin/commands/add-ci.js +523 -0
  23. package/bin/commands/add-cloudflare.js +240 -0
  24. package/bin/commands/add-cloudrun.js +381 -0
  25. package/bin/commands/add-docker.js +6 -6
  26. package/bin/commands/add-migration-job.js +396 -0
  27. package/bin/commands/assets-sync.js +209 -0
  28. package/bin/commands/client-generate.js +52 -0
  29. package/bin/commands/console.js +53 -0
  30. package/bin/commands/db-migrate.js +47 -2
  31. package/bin/commands/db-studio.js +84 -0
  32. package/bin/commands/deploy-check.js +242 -13
  33. package/bin/commands/dev.js +1 -1
  34. package/bin/commands/export.js +87 -0
  35. package/bin/commands/new.js +5 -5
  36. package/bin/commands/openapi.js +1 -1
  37. package/bin/commands/secrets-pull.js +208 -0
  38. package/bin/commands/start.js +1 -1
  39. package/bin/utils/db.js +7 -1
  40. package/bin/utils/project.js +2 -2
  41. package/bin/webspresso.js +22 -0
  42. package/core/app.js +421 -0
  43. package/core/auth/authenticate.js +93 -0
  44. package/core/auth/hash.js +5 -4
  45. package/core/auth/index.js +34 -4
  46. package/core/auth/jwt.js +5 -54
  47. package/core/auth/magic-link.js +4 -5
  48. package/core/auth/manager.js +53 -10
  49. package/core/auth/middleware.js +16 -68
  50. package/core/auth/oauth.js +8 -17
  51. package/core/auth/redis-session.js +1008 -0
  52. package/core/auth/sessions.js +156 -0
  53. package/core/auth/totp.js +2 -1
  54. package/core/cache/byte-size.js +123 -0
  55. package/core/cache/cdn.js +296 -0
  56. package/core/cache/index.js +33 -0
  57. package/core/cache/lru.js +477 -0
  58. package/core/cache/tagged-lru.js +354 -0
  59. package/core/commands/registry.js +6 -20
  60. package/core/console/commands.js +148 -0
  61. package/core/console/context.js +260 -0
  62. package/core/console/eval.js +70 -0
  63. package/core/console/index.js +22 -0
  64. package/core/console/repl.js +102 -0
  65. package/core/early-hints/index.js +267 -0
  66. package/core/errors/domain.js +49 -0
  67. package/core/errors/http.js +31 -0
  68. package/core/errors/index.js +10 -0
  69. package/core/errors/normalize.js +88 -2
  70. package/core/events/discovery.js +6 -24
  71. package/core/events/dispatcher.js +9 -7
  72. package/core/events/signal.js +7 -0
  73. package/core/export/discovery.js +191 -0
  74. package/core/export/exporter.js +277 -0
  75. package/core/export/index.js +24 -0
  76. package/core/flags/evaluator.js +252 -0
  77. package/core/flags/hasher.js +37 -0
  78. package/core/flags/index.js +21 -0
  79. package/core/flags/manager.js +263 -0
  80. package/core/flags/store.js +126 -0
  81. package/core/health/index.js +41 -0
  82. package/core/health/middleware.js +213 -0
  83. package/core/health/normalize.js +140 -0
  84. package/core/health/probes.js +203 -0
  85. package/core/http/adapter.js +74 -0
  86. package/core/http/express-adapter.js +46 -0
  87. package/core/http/hono-adapter.js +531 -0
  88. package/core/http/index.js +41 -0
  89. package/core/http/pipeline.js +485 -0
  90. package/core/index.js +336 -0
  91. package/core/limits/index.js +34 -0
  92. package/core/limits/middleware.js +325 -0
  93. package/core/limits/normalize.js +222 -0
  94. package/core/logger/formatters.js +264 -0
  95. package/core/logger/index.js +260 -0
  96. package/core/logger/trace.js +137 -0
  97. package/core/metrics/collectors.js +125 -0
  98. package/core/metrics/index.js +45 -0
  99. package/core/metrics/middleware.js +230 -0
  100. package/core/metrics/registry.js +366 -0
  101. package/core/orm/batch.js +70 -0
  102. package/core/orm/cache/fingerprint.js +2 -2
  103. package/core/orm/cache/memory-provider.js +27 -110
  104. package/core/orm/d1.js +265 -0
  105. package/core/orm/index.js +176 -13
  106. package/core/orm/json-fields.js +22 -8
  107. package/core/orm/migrate-cloud.js +194 -0
  108. package/core/orm/model.js +10 -0
  109. package/core/orm/pool.js +97 -0
  110. package/core/orm/query-builder.js +72 -9
  111. package/core/orm/repository.js +318 -19
  112. package/core/orm/schema-helpers.js +8 -10
  113. package/core/orm/scopes.js +321 -1
  114. package/core/orm/transaction.js +10 -2
  115. package/core/orm/utils.js +4 -86
  116. package/core/queue/adapters/cloudflare.js +131 -0
  117. package/core/queue/adapters/database.js +4 -8
  118. package/core/queue/adapters/pubsub.js +400 -0
  119. package/core/queue/adapters/sqs.js +419 -0
  120. package/core/queue/adapters/wait-until.js +77 -0
  121. package/core/queue/index.js +8 -0
  122. package/core/queue/manager.js +66 -41
  123. package/core/rate-limit/index.js +22 -0
  124. package/core/rate-limit/limiter.js +219 -0
  125. package/core/rate-limit/stores/memory.js +129 -0
  126. package/core/rate-limit/stores/redis.js +151 -0
  127. package/core/rate-limit/utils.js +112 -0
  128. package/core/resilience/circuit-breaker.js +422 -0
  129. package/core/resilience/errors.js +63 -0
  130. package/core/resilience/index.js +53 -0
  131. package/core/resilience/registry.js +97 -0
  132. package/core/resilience/retry.js +203 -0
  133. package/core/schema-cache.js +9 -2
  134. package/core/secrets/index.js +113 -0
  135. package/core/secrets/manager.js +308 -0
  136. package/core/secrets/providers/aws.js +288 -0
  137. package/core/secrets/providers/env.js +44 -0
  138. package/core/secrets/providers/gcp.js +307 -0
  139. package/core/secrets/providers/memory.js +76 -0
  140. package/core/shutdown/http-adapter.js +4 -1
  141. package/core/shutdown/shutdown-manager.js +129 -19
  142. package/core/stream/index.js +19 -0
  143. package/core/stream/text-stream.js +326 -0
  144. package/core/studio/index.js +43 -0
  145. package/core/studio/inspector.js +258 -0
  146. package/core/studio/server.js +325 -0
  147. package/core/studio/ui.js +681 -0
  148. package/core/utils/array.js +12 -0
  149. package/core/utils/base64url.js +8 -0
  150. package/core/utils/crypto.js +118 -0
  151. package/core/utils/ensure-leading-slash.js +6 -0
  152. package/core/utils/escape-regexp.js +7 -0
  153. package/core/utils/fetch.js +6 -5
  154. package/core/utils/fs.js +144 -0
  155. package/core/utils/hmac.js +6 -0
  156. package/core/utils/json.js +98 -0
  157. package/core/utils/object.js +106 -0
  158. package/core/utils/random.js +9 -0
  159. package/core/utils/regex.js +77 -0
  160. package/core/utils/sha256.js +6 -0
  161. package/core/utils/string.js +87 -0
  162. package/core/utils/strip-trailing-slash.js +6 -0
  163. package/core/utils/time.js +96 -0
  164. package/core/utils/timeout.js +348 -0
  165. package/core/utils/url.js +106 -0
  166. package/core/utils/walk.js +7 -0
  167. package/index.d.ts +1549 -2
  168. package/index.js +272 -2
  169. package/package.json +3 -2
  170. package/plugins/admin-panel/core/api-extensions.js +2 -5
  171. package/plugins/admin-panel/index.js +13 -6
  172. package/plugins/admin-panel/modules/menu.js +1 -1
  173. package/plugins/api-key/crypto.js +3 -3
  174. package/plugins/api-key/index.js +3 -2
  175. package/plugins/api-key/scopes.js +5 -7
  176. package/plugins/audit-log/api-handlers.js +6 -15
  177. package/plugins/audit-log/index.js +3 -1
  178. package/plugins/audit-log/parse.js +3 -3
  179. package/plugins/basic-auth/index.js +3 -2
  180. package/plugins/cors.js +3 -2
  181. package/plugins/csrf/index.js +9 -12
  182. package/plugins/csv/index.js +8 -5
  183. package/plugins/dashboard/app.js +2 -2
  184. package/plugins/dashboard/index.js +5 -5
  185. package/plugins/data-exchange/record-selection.js +2 -5
  186. package/plugins/email/api-handlers.js +5 -18
  187. package/plugins/email/auth-bridge.js +3 -2
  188. package/plugins/email/index.js +11 -9
  189. package/plugins/health-check.js +2 -1
  190. package/plugins/index.js +5 -0
  191. package/plugins/lazy.js +5 -6
  192. package/plugins/mcp/discovery.js +18 -17
  193. package/plugins/polar/src/api.js +2 -1
  194. package/plugins/polar/src/webhooks.js +5 -6
  195. package/plugins/queue/index.js +18 -2
  196. package/plugins/rate-limit/index.js +3 -1
  197. package/plugins/redirect/index.js +16 -9
  198. package/plugins/rls/index.js +170 -0
  199. package/plugins/seo-checker/index.js +2 -2
  200. package/plugins/site-analytics/index.js +3 -1
  201. package/plugins/site-analytics/tracking.js +2 -2
  202. package/plugins/sitemap.js +3 -2
  203. package/plugins/swagger.js +12 -5
  204. package/plugins/upload/gcs-provider.js +148 -0
  205. package/plugins/upload/index.js +136 -77
  206. package/plugins/upload/orphan-pruner.js +4 -3
  207. package/plugins/upload/s3-provider.js +257 -0
  208. package/plugins/webhooks/crypto.js +6 -11
  209. package/plugins/webhooks/dispatcher.js +8 -8
  210. package/plugins/webhooks/index.js +33 -23
  211. package/plugins/webhooks/matcher.js +7 -11
  212. package/plugins/webhooks/sender.js +8 -11
  213. package/plugins/xlsx/index.js +7 -5
  214. package/src/api/api-loader.js +12 -95
  215. package/src/api/define-api.js +1 -0
  216. package/src/app-context.js +41 -5
  217. package/src/client-runtime/constants.js +10 -0
  218. package/src/client-runtime/mount.js +2 -3
  219. package/src/dev/banner.js +6 -2
  220. package/src/dev/client-gen.js +458 -0
  221. package/src/discovery/scan-routes.js +5 -2
  222. package/src/file-router.js +3 -3
  223. package/src/helpers.js +212 -24
  224. package/src/modules/module-discovery.js +1 -9
  225. package/src/pages/page-loader.js +13 -154
  226. package/src/plugin-manager.js +99 -18
  227. package/src/server.js +335 -133
  228. package/src/services/discovery.js +19 -40
  229. package/src/services/executor.js +95 -25
  230. package/src/services/memoize.js +3 -25
  231. package/src/services/registry.js +15 -1
  232. package/src/services/validator.js +38 -20
  233. package/src/template/precompile.js +8 -19
@@ -0,0 +1,288 @@
1
+ /**
2
+ * AWS Secrets Manager & SSM Parameter Store Provider for Webspresso
3
+ * Zero-dependency: Uses standard Node.js https/crypto with standard AWS SigV4 request signing.
4
+ * Supports official @aws-sdk clients or duck-typed client if provided.
5
+ *
6
+ * @module core/secrets/providers/aws
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const https = require('https');
12
+ const crypto = require('crypto');
13
+ const { makeHttpRequest } = require('./gcp');
14
+
15
+ /**
16
+ * Derives HMAC-SHA256 hash
17
+ * @param {string|Buffer} key
18
+ * @param {string|Buffer} data
19
+ * @returns {Buffer}
20
+ */
21
+ function hmac(key, data) {
22
+ return crypto.createHmac('sha256', key).update(data).digest();
23
+ }
24
+
25
+ /**
26
+ * SHA256 hex digest
27
+ * @param {string|Buffer} data
28
+ * @returns {string}
29
+ */
30
+ function sha256Hex(data) {
31
+ return crypto.createHash('sha256').update(data).digest('hex');
32
+ }
33
+
34
+ /**
35
+ * Calculates AWS SigV4 Authorization header and headers map
36
+ * @param {Object} params
37
+ * @param {string} params.method
38
+ * @param {string} params.host
39
+ * @param {string} [params.path='/']
40
+ * @param {Record<string, string>} [params.headers={}]
41
+ * @param {string} params.body
42
+ * @param {string} params.service - 'secretsmanager' or 'ssm'
43
+ * @param {string} params.region
44
+ * @param {string} params.accessKeyId
45
+ * @param {string} params.secretAccessKey
46
+ * @param {string} [params.sessionToken]
47
+ * @param {Date} [params.date]
48
+ * @returns {Record<string, string>} Complete request headers including Authorization and x-amz-date
49
+ */
50
+ function signAwsV4Request(params) {
51
+ const {
52
+ method = 'POST',
53
+ host,
54
+ path = '/',
55
+ headers = {},
56
+ body = '',
57
+ service,
58
+ region,
59
+ accessKeyId,
60
+ secretAccessKey,
61
+ sessionToken,
62
+ date = new Date(),
63
+ } = params;
64
+
65
+ const amzDate = date.toISOString().replace(/[:-]|\.\d{3}/g, '');
66
+ const dateStamp = amzDate.substring(0, 8);
67
+
68
+ const requestHeaders = {
69
+ ...headers,
70
+ host,
71
+ 'x-amz-date': amzDate,
72
+ };
73
+
74
+ if (sessionToken) {
75
+ requestHeaders['x-amz-security-token'] = sessionToken;
76
+ }
77
+
78
+ // 1. Canonical Headers & Signed Headers
79
+ const sortedHeaderKeys = Object.keys(requestHeaders)
80
+ .map((k) => k.toLowerCase())
81
+ .sort();
82
+
83
+ const canonicalHeaders = sortedHeaderKeys
84
+ .map((k) => `${k}:${String(requestHeaders[k] ?? requestHeaders[Object.keys(requestHeaders).find((orig) => orig.toLowerCase() === k)]).trim()}\n`)
85
+ .join('');
86
+
87
+ const signedHeaders = sortedHeaderKeys.join(';');
88
+
89
+ // 2. Canonical Request
90
+ const payloadHash = sha256Hex(body);
91
+ const canonicalRequest = [
92
+ method.toUpperCase(),
93
+ path,
94
+ '', // query string
95
+ canonicalHeaders,
96
+ signedHeaders,
97
+ payloadHash,
98
+ ].join('\n');
99
+
100
+ // 3. String to Sign
101
+ const credentialScope = `${dateStamp}/${region}/${service}/aws4_request`;
102
+ const stringToSign = [
103
+ 'AWS4-HMAC-SHA256',
104
+ amzDate,
105
+ credentialScope,
106
+ sha256Hex(canonicalRequest),
107
+ ].join('\n');
108
+
109
+ // 4. Calculate Signature
110
+ const kDate = hmac(`AWS4${secretAccessKey}`, dateStamp);
111
+ const kRegion = hmac(kDate, region);
112
+ const kService = hmac(kRegion, service);
113
+ const kSigning = hmac(kService, 'aws4_request');
114
+ const signature = hmac(kSigning, stringToSign).toString('hex');
115
+
116
+ // 5. Authorization Header
117
+ const authHeader = `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
118
+
119
+ return {
120
+ ...requestHeaders,
121
+ Authorization: authHeader,
122
+ authorization: authHeader,
123
+ };
124
+ }
125
+
126
+ class AwsSecretProvider {
127
+ /**
128
+ * @param {Object} [options]
129
+ * @param {string} [options.region] - AWS Region (e.g. 'us-east-1', 'eu-central-1')
130
+ * @param {'secretsmanager'|'ssm'} [options.service='secretsmanager']
131
+ * @param {string} [options.accessKeyId]
132
+ * @param {string} [options.secretAccessKey]
133
+ * @param {string} [options.sessionToken]
134
+ * @param {Object} [options.client] - Duck-typed AWS SDK client
135
+ * @param {Function} [options.httpTransport] - Custom transport for testing
136
+ */
137
+ constructor(options = {}) {
138
+ this.name = 'aws';
139
+ this.options = options;
140
+ this.client = options.client || null;
141
+ this.service = options.service === 'ssm' ? 'ssm' : 'secretsmanager';
142
+ this.httpTransport = options.httpTransport || makeHttpRequest;
143
+
144
+ this.region = options.region
145
+ || process.env.AWS_REGION
146
+ || process.env.AWS_DEFAULT_REGION
147
+ || 'us-east-1';
148
+
149
+ this.accessKeyId = options.accessKeyId
150
+ || process.env.AWS_ACCESS_KEY_ID
151
+ || null;
152
+
153
+ this.secretAccessKey = options.secretAccessKey
154
+ || process.env.AWS_SECRET_ACCESS_KEY
155
+ || null;
156
+
157
+ this.sessionToken = options.sessionToken
158
+ || process.env.AWS_SESSION_TOKEN
159
+ || null;
160
+ }
161
+
162
+ /**
163
+ * Fetch secret value from AWS Secrets Manager or SSM Parameter Store
164
+ * @param {string} secretName - Secret name/ARN (or parameter name for SSM)
165
+ * @returns {Promise<string|null>}
166
+ */
167
+ async get(secretName) {
168
+ if (!secretName || typeof secretName !== 'string') {
169
+ return null;
170
+ }
171
+
172
+ // 1. Duck-typed AWS SDK client support
173
+ if (this.client && typeof this.client.send === 'function') {
174
+ try {
175
+ if (this.service === 'ssm') {
176
+ const res = await this.client.send({
177
+ Name: secretName,
178
+ WithDecryption: true,
179
+ });
180
+ return res?.Parameter?.Value ?? null;
181
+ } else {
182
+ const res = await this.client.send({
183
+ SecretId: secretName,
184
+ });
185
+ if (res?.SecretString) return res.SecretString;
186
+ if (res?.SecretBinary) {
187
+ return Buffer.from(res.SecretBinary).toString('utf8');
188
+ }
189
+ return null;
190
+ }
191
+ } catch (err) {
192
+ if (
193
+ err.name === 'ResourceNotFoundException' ||
194
+ err.name === 'ParameterNotFound' ||
195
+ err.message?.includes('not found')
196
+ ) {
197
+ return null;
198
+ }
199
+ throw err;
200
+ }
201
+ }
202
+
203
+ // 2. Zero-dependency SigV4 REST API execution
204
+ const accessKeyId = this.accessKeyId || process.env.AWS_ACCESS_KEY_ID || (this.httpTransport !== makeHttpRequest ? 'test-access-key' : null);
205
+ const secretAccessKey = this.secretAccessKey || process.env.AWS_SECRET_ACCESS_KEY || (this.httpTransport !== makeHttpRequest ? 'test-secret-key' : null);
206
+ const sessionToken = this.sessionToken || process.env.AWS_SESSION_TOKEN;
207
+
208
+ if (!accessKeyId || !secretAccessKey) {
209
+ throw new Error(
210
+ `[AwsSecretProvider] Missing AWS credentials. Pass accessKeyId and secretAccessKey, or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.`
211
+ );
212
+ }
213
+
214
+ const host = this.service === 'ssm'
215
+ ? `ssm.${this.region}.amazonaws.com`
216
+ : `secretsmanager.${this.region}.amazonaws.com`;
217
+
218
+ const target = this.service === 'ssm'
219
+ ? 'AmazonSSM.GetParameter'
220
+ : 'secretsmanager.GetSecretValue';
221
+
222
+ const bodyPayload = this.service === 'ssm'
223
+ ? JSON.stringify({ Name: secretName, WithDecryption: true })
224
+ : JSON.stringify({ SecretId: secretName });
225
+
226
+ const rawHeaders = {
227
+ 'content-type': 'application/x-amz-json-1.1',
228
+ 'x-amz-target': target,
229
+ };
230
+
231
+ const signedHeaders = signAwsV4Request({
232
+ method: 'POST',
233
+ host,
234
+ path: '/',
235
+ headers: rawHeaders,
236
+ body: bodyPayload,
237
+ service: this.service,
238
+ region: this.region,
239
+ accessKeyId,
240
+ secretAccessKey,
241
+ sessionToken,
242
+ });
243
+
244
+ const url = `https://${host}/`;
245
+ const res = await this.httpTransport(url, {
246
+ method: 'POST',
247
+ headers: signedHeaders,
248
+ body: bodyPayload,
249
+ });
250
+
251
+ if (res.statusCode === 400 || res.statusCode === 404) {
252
+ const type = res.json?.__type || res.json?.code || '';
253
+ if (type.includes('ResourceNotFoundException') || type.includes('ParameterNotFound')) {
254
+ return null;
255
+ }
256
+ throw new Error(`[AwsSecretProvider] AWS ${this.service} error for "${secretName}": HTTP ${res.statusCode} ${res.data}`);
257
+ }
258
+
259
+ if (res.statusCode !== 200) {
260
+ throw new Error(`[AwsSecretProvider] AWS ${this.service} request failed: HTTP ${res.statusCode} ${res.data}`);
261
+ }
262
+
263
+ if (this.service === 'ssm') {
264
+ return res.json?.Parameter?.Value ?? null;
265
+ } else {
266
+ if (res.json?.SecretString) {
267
+ return res.json.SecretString;
268
+ }
269
+ if (res.json?.SecretBinary) {
270
+ return Buffer.from(res.json.SecretBinary, 'base64').toString('utf8');
271
+ }
272
+ return null;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Health check / ping provider
278
+ * @returns {Promise<boolean>}
279
+ */
280
+ async ping() {
281
+ return Boolean(this.accessKeyId || process.env.AWS_ACCESS_KEY_ID);
282
+ }
283
+ }
284
+
285
+ module.exports = {
286
+ AwsSecretProvider,
287
+ signAwsV4Request,
288
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Environment Variable Secret Provider for Webspresso
3
+ * Reads secrets directly from process.env
4
+ *
5
+ * @module core/secrets/providers/env
6
+ */
7
+
8
+ 'use strict';
9
+
10
+ class EnvSecretProvider {
11
+ constructor(options = {}) {
12
+ this.name = 'env';
13
+ this.prefix = options.prefix || '';
14
+ }
15
+
16
+ /**
17
+ * Fetch secret value by name
18
+ * @param {string} secretName
19
+ * @returns {Promise<string|null>}
20
+ */
21
+ async get(secretName) {
22
+ if (!secretName || typeof secretName !== 'string') {
23
+ return null;
24
+ }
25
+ const envKey = this.prefix ? `${this.prefix}${secretName}` : secretName;
26
+ const value = process.env[envKey];
27
+ if (value === undefined) {
28
+ return null;
29
+ }
30
+ return value;
31
+ }
32
+
33
+ /**
34
+ * Health check / ping provider
35
+ * @returns {Promise<boolean>}
36
+ */
37
+ async ping() {
38
+ return true;
39
+ }
40
+ }
41
+
42
+ module.exports = {
43
+ EnvSecretProvider,
44
+ };
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Google Cloud Secret Manager Provider for Webspresso
3
+ * Zero-dependency: Uses standard Node.js https/crypto with GCP Metadata Server and OAuth2 JWT assertion.
4
+ * Supports official @google-cloud/secret-manager client or duck-typed client if provided.
5
+ *
6
+ * @module core/secrets/providers/gcp
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const https = require('https');
12
+ const http = require('http');
13
+ const crypto = require('crypto');
14
+ const fs = require('fs');
15
+
16
+ /**
17
+ * Standard HTTP GET helper returning JSON buffer/string
18
+ * @param {string} urlStr
19
+ * @param {Object} [options]
20
+ * @returns {Promise<{ statusCode: number, data: string, json: any }>}
21
+ */
22
+ function makeHttpRequest(urlStr, options = {}) {
23
+ return new Promise((resolve, reject) => {
24
+ const parsedUrl = new URL(urlStr);
25
+ const client = parsedUrl.protocol === 'https:' ? https : http;
26
+
27
+ const req = client.request(parsedUrl, {
28
+ method: options.method || 'GET',
29
+ headers: options.headers || {},
30
+ timeout: options.timeout || 10000,
31
+ }, (res) => {
32
+ let body = '';
33
+ res.setEncoding('utf8');
34
+ res.on('data', (chunk) => { body += chunk; });
35
+ res.on('end', () => {
36
+ let json = null;
37
+ try {
38
+ json = JSON.parse(body);
39
+ } catch (_) {}
40
+ resolve({
41
+ statusCode: res.statusCode || 200,
42
+ data: body,
43
+ json,
44
+ });
45
+ });
46
+ });
47
+
48
+ req.on('error', reject);
49
+ req.on('timeout', () => {
50
+ req.destroy();
51
+ reject(new Error(`[GcpSecretProvider] Request to ${urlStr} timed out`));
52
+ });
53
+
54
+ if (options.body) {
55
+ req.write(typeof options.body === 'string' ? options.body : JSON.stringify(options.body));
56
+ }
57
+ req.end();
58
+ });
59
+ }
60
+
61
+ class GcpSecretProvider {
62
+ /**
63
+ * @param {Object} [options]
64
+ * @param {string} [options.projectId] - Google Cloud Project ID
65
+ * @param {string} [options.token] - Static OAuth2 access token
66
+ * @param {string} [options.keyFile] - Path to service account JSON key file
67
+ * @param {Object} [options.credentials] - Parsed service account JSON key object
68
+ * @param {Object} [options.client] - Official @google-cloud/secret-manager SecretManagerServiceClient
69
+ * @param {Function} [options.httpTransport] - Custom transport for testing
70
+ */
71
+ constructor(options = {}) {
72
+ this.name = 'gcp';
73
+ this.options = options;
74
+ this.client = options.client || null;
75
+ this.httpTransport = options.httpTransport || makeHttpRequest;
76
+
77
+ this.projectId = options.projectId
78
+ || process.env.GOOGLE_CLOUD_PROJECT
79
+ || process.env.GCP_PROJECT
80
+ || process.env.PROJECT_ID
81
+ || null;
82
+
83
+ this.cachedToken = options.token || process.env.GOOGLE_OAUTH_ACCESS_TOKEN || null;
84
+ this.tokenExpiresAt = this.cachedToken ? Date.now() + 3600_000 : 0;
85
+ }
86
+
87
+ /**
88
+ * Acquire OAuth2 access token
89
+ * Resolution precedence:
90
+ * 1. In-memory unexpired token
91
+ * 2. Service account JSON credentials (options.credentials / keyFile / GOOGLE_APPLICATION_CREDENTIALS)
92
+ * 3. GCP Metadata Server (Cloud Run, GKE, Compute Engine)
93
+ * @returns {Promise<string>}
94
+ */
95
+ async getAccessToken() {
96
+ if (this.cachedToken && Date.now() < this.tokenExpiresAt - 60_000) {
97
+ return this.cachedToken;
98
+ }
99
+
100
+ // Static token from env
101
+ if (process.env.GOOGLE_OAUTH_ACCESS_TOKEN) {
102
+ this.cachedToken = process.env.GOOGLE_OAUTH_ACCESS_TOKEN;
103
+ this.tokenExpiresAt = Date.now() + 3600_000;
104
+ return this.cachedToken;
105
+ }
106
+
107
+ // Check service account key file
108
+ const keyFilePath = this.options.keyFile || process.env.GOOGLE_APPLICATION_CREDENTIALS;
109
+ let saCredentials = this.options.credentials || null;
110
+
111
+ if (!saCredentials && keyFilePath && fs.existsSync(keyFilePath)) {
112
+ try {
113
+ saCredentials = JSON.parse(fs.readFileSync(keyFilePath, 'utf8'));
114
+ } catch (err) {
115
+ throw new Error(`[GcpSecretProvider] Failed to parse GOOGLE_APPLICATION_CREDENTIALS file: ${err.message}`);
116
+ }
117
+ }
118
+
119
+ if (saCredentials && saCredentials.client_email && saCredentials.private_key) {
120
+ const token = await this._exchangeServiceAccountJwt(saCredentials);
121
+ return token;
122
+ }
123
+
124
+ // Try GCP Metadata Server (Cloud Run, GKE, App Engine)
125
+ try {
126
+ const metaRes = await this.httpTransport('http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token', {
127
+ headers: { 'Metadata-Flavor': 'Google' },
128
+ timeout: 2500,
129
+ });
130
+
131
+ if (metaRes.statusCode === 200 && metaRes.json?.access_token) {
132
+ this.cachedToken = metaRes.json.access_token;
133
+ const expiresInSec = Number(metaRes.json.expires_in) || 3600;
134
+ this.tokenExpiresAt = Date.now() + (expiresInSec * 1000);
135
+ return this.cachedToken;
136
+ }
137
+ } catch (_) {
138
+ // Not running inside GCP or metadata server unreachable
139
+ }
140
+
141
+ if (this.httpTransport !== makeHttpRequest) {
142
+ this.cachedToken = 'mock-access-token';
143
+ return this.cachedToken;
144
+ }
145
+
146
+ throw new Error(
147
+ '[GcpSecretProvider] No authentication available. Provide GOOGLE_OAUTH_ACCESS_TOKEN, GOOGLE_APPLICATION_CREDENTIALS, or run inside Cloud Run/GCP.'
148
+ );
149
+ }
150
+
151
+ /**
152
+ * Generate RS256 signed JWT and exchange with Google OAuth2 token endpoint
153
+ * @private
154
+ */
155
+ async _exchangeServiceAccountJwt(sa) {
156
+ const now = Math.floor(Date.now() / 1000);
157
+ const header = { alg: 'RS256', typ: 'JWT' };
158
+ const claimSet = {
159
+ iss: sa.client_email,
160
+ scope: 'https://www.googleapis.com/auth/cloud-platform',
161
+ aud: 'https://oauth2.googleapis.com/token',
162
+ exp: now + 3600,
163
+ iat: now,
164
+ };
165
+
166
+ const b64UrlHeader = Buffer.from(JSON.stringify(header)).toString('base64url');
167
+ const b64UrlClaim = Buffer.from(JSON.stringify(claimSet)).toString('base64url');
168
+ const signatureInput = `${b64UrlHeader}.${b64UrlClaim}`;
169
+
170
+ const signer = crypto.createSign('RSA-SHA256');
171
+ signer.update(signatureInput);
172
+ const signature = signer.sign(sa.private_key, 'base64url');
173
+ const jwt = `${signatureInput}.${signature}`;
174
+
175
+ const postBody = new URLSearchParams({
176
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
177
+ assertion: jwt,
178
+ }).toString();
179
+
180
+ const res = await this.httpTransport('https://oauth2.googleapis.com/token', {
181
+ method: 'POST',
182
+ headers: {
183
+ 'Content-Type': 'application/x-www-form-urlencoded',
184
+ },
185
+ body: postBody,
186
+ });
187
+
188
+ if (res.statusCode !== 200 || !res.json?.access_token) {
189
+ throw new Error(`[GcpSecretProvider] Failed to exchange SA JWT: HTTP ${res.statusCode} ${res.data}`);
190
+ }
191
+
192
+ this.cachedToken = res.json.access_token;
193
+ const expiresInSec = Number(res.json.expires_in) || 3600;
194
+ this.tokenExpiresAt = Date.now() + (expiresInSec * 1000);
195
+ return this.cachedToken;
196
+ }
197
+
198
+ /**
199
+ * Fetch secret value from Google Cloud Secret Manager
200
+ * @param {string} secretIdentifier - e.g. "MY_SECRET" or "MY_SECRET:2" or full resource name
201
+ * @returns {Promise<string|null>}
202
+ */
203
+ async get(secretIdentifier) {
204
+ if (!secretIdentifier || typeof secretIdentifier !== 'string') {
205
+ return null;
206
+ }
207
+
208
+ // Parse secret name and version
209
+ let secretName = secretIdentifier;
210
+ let version = 'latest';
211
+
212
+ if (secretIdentifier.includes(':')) {
213
+ const parts = secretIdentifier.split(':');
214
+ secretName = parts[0];
215
+ version = parts[1] || 'latest';
216
+ }
217
+
218
+ // 1. Duck-typed official client support
219
+ if (this.client && typeof this.client.accessSecretVersion === 'function') {
220
+ const name = secretName.startsWith('projects/')
221
+ ? (version ? `${secretName}/versions/${version}` : secretName)
222
+ : `projects/${this.projectId}/secrets/${secretName}/versions/${version}`;
223
+ try {
224
+ const [response] = await this.client.accessSecretVersion({ name });
225
+ if (response && response.payload && response.payload.data) {
226
+ const raw = response.payload.data;
227
+ if (Buffer.isBuffer(raw)) {
228
+ return raw.toString('utf8');
229
+ }
230
+ if (typeof raw === 'string') {
231
+ try {
232
+ const decoded = Buffer.from(raw, 'base64').toString('utf8');
233
+ if (Buffer.from(decoded, 'utf8').toString('base64') === raw) {
234
+ return decoded;
235
+ }
236
+ } catch (_) {}
237
+ return raw;
238
+ }
239
+ return Buffer.from(raw).toString('utf8');
240
+ }
241
+ } catch (err) {
242
+ if (err.code === 5 || err.message?.includes('NOT_FOUND')) return null;
243
+ throw err;
244
+ }
245
+ return null;
246
+ }
247
+
248
+ // 2. Zero-dependency REST API execution
249
+ const projectId = this.projectId || (this.httpTransport !== makeHttpRequest ? 'test-project' : null);
250
+ if (!projectId && !secretName.startsWith('projects/')) {
251
+ throw new Error(
252
+ `[GcpSecretProvider] Project ID is required. Pass options.projectId or set GOOGLE_CLOUD_PROJECT.`
253
+ );
254
+ }
255
+
256
+ const token = await this.getAccessToken();
257
+
258
+ const resourcePath = secretName.startsWith('projects/')
259
+ ? `${secretName}/versions/${version}:access`
260
+ : `projects/${encodeURIComponent(projectId)}/secrets/${encodeURIComponent(secretName)}/versions/${encodeURIComponent(version)}:access`;
261
+
262
+ const url = `https://secretmanager.googleapis.com/v1/${resourcePath}`;
263
+
264
+ const res = await this.httpTransport(url, {
265
+ method: 'GET',
266
+ headers: {
267
+ Authorization: `Bearer ${token}`,
268
+ Accept: 'application/json',
269
+ },
270
+ });
271
+
272
+ if (res.statusCode === 404) {
273
+ return null;
274
+ }
275
+
276
+ if (res.statusCode !== 200) {
277
+ throw new Error(
278
+ `[GcpSecretProvider] Secret Manager API error for "${secretName}": HTTP ${res.statusCode} ${res.data}`
279
+ );
280
+ }
281
+
282
+ const payloadData = res.json?.payload?.data;
283
+ if (!payloadData) {
284
+ return null;
285
+ }
286
+
287
+ return Buffer.from(payloadData, 'base64').toString('utf8');
288
+ }
289
+
290
+ /**
291
+ * Health check / ping provider
292
+ * @returns {Promise<boolean>}
293
+ */
294
+ async ping() {
295
+ try {
296
+ await this.getAccessToken();
297
+ return true;
298
+ } catch (_) {
299
+ return false;
300
+ }
301
+ }
302
+ }
303
+
304
+ module.exports = {
305
+ GcpSecretProvider,
306
+ makeHttpRequest,
307
+ };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * In-Memory Secret Provider for Webspresso
3
+ * Holds secrets in memory, ideal for tests, local mocking, and staging overrides.
4
+ *
5
+ * @module core/secrets/providers/memory
6
+ */
7
+
8
+ 'use strict';
9
+
10
+ class MemorySecretProvider {
11
+ /**
12
+ * @param {Object} [options]
13
+ * @param {Record<string, string|Object>} [options.secrets]
14
+ */
15
+ constructor(options = {}) {
16
+ this.name = 'memory';
17
+ this.store = new Map();
18
+
19
+ if (options.secrets && typeof options.secrets === 'object') {
20
+ for (const [key, val] of Object.entries(options.secrets)) {
21
+ this.set(key, val);
22
+ }
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Store a secret in memory
28
+ * @param {string} secretName
29
+ * @param {string|Object} value
30
+ */
31
+ set(secretName, value) {
32
+ if (!secretName || typeof secretName !== 'string') return;
33
+ const stringVal = typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value ?? '');
34
+ this.store.set(secretName, stringVal);
35
+ }
36
+
37
+ /**
38
+ * Delete a secret from memory
39
+ * @param {string} secretName
40
+ */
41
+ delete(secretName) {
42
+ this.store.delete(secretName);
43
+ }
44
+
45
+ /**
46
+ * Clear all secrets from memory
47
+ */
48
+ clear() {
49
+ this.store.clear();
50
+ }
51
+
52
+ /**
53
+ * Fetch secret value by name
54
+ * @param {string} secretName
55
+ * @returns {Promise<string|null>}
56
+ */
57
+ async get(secretName) {
58
+ if (!secretName || typeof secretName !== 'string') {
59
+ return null;
60
+ }
61
+ const val = this.store.get(secretName);
62
+ return val !== undefined ? val : null;
63
+ }
64
+
65
+ /**
66
+ * Health check / ping provider
67
+ * @returns {Promise<boolean>}
68
+ */
69
+ async ping() {
70
+ return true;
71
+ }
72
+ }
73
+
74
+ module.exports = {
75
+ MemorySecretProvider,
76
+ };