@getstrata/bootstrap 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,549 @@
1
+ // @bun
2
+ // ../../src/core/jobs/dispatchWebhookJob.ts
3
+ import { createHmac } from "crypto";
4
+
5
+ // ../../src/config/app.ts
6
+ var appConfig = {
7
+ name: "WorkHub",
8
+ env: process.env.APP_ENV ?? "local",
9
+ debug: (process.env.APP_DEBUG ?? "true") !== "false",
10
+ url: process.env.APP_URL ?? "http://localhost:3000",
11
+ apiPrefix: process.env.API_PREFIX ?? "/api/v1"
12
+ };
13
+
14
+ // ../../src/core/database/boundConnection.ts
15
+ var boundConnectionHolder = {
16
+ connection: null
17
+ };
18
+ function getBoundDatabaseConnection() {
19
+ return boundConnectionHolder.connection;
20
+ }
21
+
22
+ // ../../src/core/database/connectionContext.ts
23
+ import { AsyncLocalStorage } from "async_hooks";
24
+ var activeConnection = new AsyncLocalStorage;
25
+ function getActiveDatabaseConnection(fallback) {
26
+ return activeConnection.getStore() ?? fallback;
27
+ }
28
+
29
+ // ../../src/core/database/queryProxy.ts
30
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
31
+ function createDatabaseQueryProxy(pool) {
32
+ function resolveDatabase() {
33
+ return getActiveDatabaseConnection(pool);
34
+ }
35
+ function resolveDatabaseForProperty(property) {
36
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
37
+ return pool;
38
+ }
39
+ return resolveDatabase();
40
+ }
41
+ return new Proxy(function database() {}, {
42
+ apply(_target, _thisArg, args) {
43
+ return resolveDatabase()(...args);
44
+ },
45
+ get(_target, property) {
46
+ const connection = resolveDatabaseForProperty(property);
47
+ const value = connection[property];
48
+ return typeof value === "function" ? value.bind(connection) : value;
49
+ }
50
+ });
51
+ }
52
+
53
+ // ../../src/core/database/defaultConnection.ts
54
+ var defaultPool = {
55
+ connection: null
56
+ };
57
+ var defaultQuery = {
58
+ connection: null
59
+ };
60
+ function registerDefaultDatabasePool(connection) {
61
+ defaultPool.connection = connection;
62
+ defaultQuery.connection = createDatabaseQueryProxy(connection);
63
+ }
64
+ function getDefaultDatabaseQuery() {
65
+ if (!defaultQuery.connection) {
66
+ throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
67
+ }
68
+ return defaultQuery.connection;
69
+ }
70
+
71
+ // ../../src/core/database/repositoryConnection.ts
72
+ function resolveRepositoryConnection() {
73
+ return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
74
+ }
75
+ var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
76
+ apply(_target, _thisArg, args) {
77
+ return resolveRepositoryConnection()(...args);
78
+ },
79
+ get(_target, property) {
80
+ const connection = resolveRepositoryConnection();
81
+ const value = connection[property];
82
+ return typeof value === "function" ? value.bind(connection) : value;
83
+ }
84
+ });
85
+
86
+ // ../../src/core/queue/index.ts
87
+ class Job {
88
+ maxAttempts;
89
+ backoffMs;
90
+ priority;
91
+ }
92
+
93
+ // ../../src/core/security/safeUrl.ts
94
+ import { lookup as dnsLookupImpl } from "dns/promises";
95
+
96
+ // ../../src/core/errors/http.ts
97
+ class HttpError extends Error {
98
+ status;
99
+ details;
100
+ constructor(status, message, details) {
101
+ super(message);
102
+ this.name = new.target.name;
103
+ this.status = status;
104
+ this.details = details;
105
+ }
106
+ }
107
+
108
+ class BadRequestError extends HttpError {
109
+ constructor(message = "Bad Request", details) {
110
+ super(400, message, details);
111
+ }
112
+ }
113
+ class ConflictError extends HttpError {
114
+ constructor(message = "Conflict", details) {
115
+ super(409, message, details);
116
+ }
117
+ }
118
+
119
+ class UnprocessableEntityError extends HttpError {
120
+ constructor(message = "Unprocessable Entity", details) {
121
+ super(422, message, details);
122
+ }
123
+ }
124
+ class ForbiddenError extends HttpError {
125
+ constructor(message = "Forbidden", details) {
126
+ super(403, message, details);
127
+ }
128
+ }
129
+
130
+ class UnauthorizedError extends HttpError {
131
+ constructor(message = "Unauthorized", details) {
132
+ super(401, message, details);
133
+ }
134
+ }
135
+ class PreconditionFailedError extends HttpError {
136
+ constructor(message = "Precondition Failed", details) {
137
+ super(412, message, details);
138
+ }
139
+ }
140
+
141
+ // ../../src/core/security/safeUrl.ts
142
+ var dnsLookup = dnsLookupImpl;
143
+ var BLOCKED_HOSTNAMES = new Set([
144
+ "localhost",
145
+ "127.0.0.1",
146
+ "0.0.0.0",
147
+ "::1",
148
+ "metadata.google.internal"
149
+ ]);
150
+ function isPrivateIpv4(hostname) {
151
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
152
+ if (!match) {
153
+ return false;
154
+ }
155
+ const octets = match.slice(1, 5).map((part) => Number.parseInt(part, 10));
156
+ if (octets.some((octet) => octet < 0 || octet > 255)) {
157
+ return true;
158
+ }
159
+ const [a = 0, b = 0] = octets;
160
+ if (a === 10) {
161
+ return true;
162
+ }
163
+ if (a === 127) {
164
+ return true;
165
+ }
166
+ if (a === 0) {
167
+ return true;
168
+ }
169
+ if (a === 169 && b === 254) {
170
+ return true;
171
+ }
172
+ if (a === 172 && b >= 16 && b <= 31) {
173
+ return true;
174
+ }
175
+ if (a === 192 && b === 168) {
176
+ return true;
177
+ }
178
+ return false;
179
+ }
180
+ function isBlockedHostname(hostname) {
181
+ const normalized = hostname.trim().toLowerCase();
182
+ if (normalized.length === 0) {
183
+ return true;
184
+ }
185
+ if (BLOCKED_HOSTNAMES.has(normalized)) {
186
+ return true;
187
+ }
188
+ if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
189
+ return true;
190
+ }
191
+ if (normalized.includes(":")) {
192
+ return true;
193
+ }
194
+ return isPrivateIpv4(normalized);
195
+ }
196
+ function assertSafeOutboundUrl(rawUrl, options = {}) {
197
+ let parsed;
198
+ try {
199
+ parsed = new URL(rawUrl);
200
+ } catch {
201
+ throw new BadRequestError("Webhook URL is invalid.");
202
+ }
203
+ if (parsed.protocol !== "https:" && !(options.allowHttp && parsed.protocol === "http:")) {
204
+ throw new BadRequestError("Webhook URL must use HTTPS.");
205
+ }
206
+ if (parsed.username || parsed.password) {
207
+ throw new BadRequestError("Webhook URL must not include credentials.");
208
+ }
209
+ if (isBlockedHostname(parsed.hostname)) {
210
+ throw new BadRequestError("Webhook URL targets a blocked host.");
211
+ }
212
+ return parsed;
213
+ }
214
+ function isBlockedIpAddress(address) {
215
+ return isBlockedHostname(address.trim().toLowerCase());
216
+ }
217
+ async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
218
+ const parsed = assertSafeOutboundUrl(rawUrl, options);
219
+ if (options.resolveDns === false) {
220
+ return parsed;
221
+ }
222
+ const hostname = parsed.hostname.trim().toLowerCase();
223
+ const results = await dnsLookup(hostname, { all: true, verbatim: true });
224
+ if (results.some((result) => isBlockedIpAddress(result.address))) {
225
+ throw new BadRequestError("Webhook URL targets a blocked host.");
226
+ }
227
+ return parsed;
228
+ }
229
+
230
+ // ../../src/core/security/safeFetch.ts
231
+ var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
232
+ async function safeFetch(input, init = {}, options = {}) {
233
+ const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
234
+ const maxRedirects = options.maxRedirects ?? 0;
235
+ const resolveDns = options.resolveDns ?? appConfig.env === "production";
236
+ const urlOptions = { allowHttp: options.allowHttp, resolveDns };
237
+ const controller = new AbortController;
238
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
239
+ try {
240
+ let currentUrl = (await assertSafeOutboundUrlResolved(input, urlOptions)).toString();
241
+ let redirectCount = 0;
242
+ while (true) {
243
+ const response = await fetch(currentUrl, {
244
+ ...init,
245
+ signal: controller.signal,
246
+ redirect: "manual"
247
+ });
248
+ if (response.status >= 300 && response.status < 400) {
249
+ const location = response.headers.get("location");
250
+ if (!location || redirectCount >= maxRedirects) {
251
+ return response;
252
+ }
253
+ currentUrl = (await assertSafeOutboundUrlResolved(new URL(location, currentUrl).toString(), urlOptions)).toString();
254
+ redirectCount += 1;
255
+ continue;
256
+ }
257
+ return response;
258
+ }
259
+ } finally {
260
+ clearTimeout(timeout);
261
+ }
262
+ }
263
+
264
+ // ../../src/core/jobs/dispatchWebhookJob.ts
265
+ class DispatchWebhookJob extends Job {
266
+ maxAttempts = 3;
267
+ backoffMs = 2000;
268
+ async handle(payload) {
269
+ const rows = await repositoryConnection`
270
+ SELECT id, url, secret
271
+ FROM webhook
272
+ WHERE id = ${payload.webhookId} AND active = TRUE
273
+ LIMIT 1
274
+ `;
275
+ const webhook = rows[0];
276
+ if (!webhook) {
277
+ return;
278
+ }
279
+ const body = JSON.stringify({ event: payload.event, payload: payload.payload });
280
+ const signature = createHmac("sha256", webhook.secret).update(body).digest("hex");
281
+ assertSafeOutboundUrl(webhook.url, { allowHttp: appConfig.env !== "production" });
282
+ let responseStatus = null;
283
+ let errorMessage = null;
284
+ try {
285
+ const response = await safeFetch(webhook.url, {
286
+ method: "POST",
287
+ headers: {
288
+ "content-type": "application/json",
289
+ "x-workhub-signature": signature
290
+ },
291
+ body
292
+ }, { allowHttp: appConfig.env !== "production" });
293
+ responseStatus = response.status;
294
+ if (!response.ok) {
295
+ throw new Error(`Webhook delivery failed with status ${response.status}.`);
296
+ }
297
+ } catch (error) {
298
+ errorMessage = error instanceof Error ? error.message : String(error);
299
+ await repositoryConnection`
300
+ INSERT INTO webhook_delivery (webhook_id, event, payload, response_status, error)
301
+ VALUES (
302
+ ${webhook.id},
303
+ ${payload.event},
304
+ ${JSON.stringify(payload.payload)}::jsonb,
305
+ ${responseStatus},
306
+ ${errorMessage}
307
+ )
308
+ `;
309
+ throw error instanceof Error ? error : new Error(errorMessage);
310
+ }
311
+ await repositoryConnection`
312
+ INSERT INTO webhook_delivery (webhook_id, event, payload, response_status)
313
+ VALUES (
314
+ ${webhook.id},
315
+ ${payload.event},
316
+ ${JSON.stringify(payload.payload)}::jsonb,
317
+ ${responseStatus}
318
+ )
319
+ `;
320
+ }
321
+ }
322
+ var dispatchWebhookJob_default = DispatchWebhookJob;
323
+
324
+ // ../../src/core/jobs/invalidateCacheTagsJob.ts
325
+ class InvalidateCacheTagsJob extends Job {
326
+ cache;
327
+ constructor(cache) {
328
+ super();
329
+ this.cache = cache;
330
+ }
331
+ async handle(payload) {
332
+ await this.cache.tags(...payload.tags).flush();
333
+ }
334
+ }
335
+ var invalidateCacheTagsJob_default = InvalidateCacheTagsJob;
336
+
337
+ // ../../src/core/queue/jobRegistry.ts
338
+ class JobRegistry {
339
+ constructor() {}
340
+ factories = new Map;
341
+ instances = new WeakMap;
342
+ register(name, factory) {
343
+ this.factories.set(name, factory);
344
+ }
345
+ resolveName(job) {
346
+ return this.instances.get(job);
347
+ }
348
+ track(name, job) {
349
+ this.instances.set(job, name);
350
+ return job;
351
+ }
352
+ create(name) {
353
+ const factory = this.factories.get(name);
354
+ if (!factory) {
355
+ return;
356
+ }
357
+ return factory();
358
+ }
359
+ names() {
360
+ return [...this.factories.keys()];
361
+ }
362
+ }
363
+ var jobRegistry = new JobRegistry;
364
+
365
+ // ../../src/core/logging/logger.ts
366
+ class Logger {
367
+ channel;
368
+ constructor(channel = "app") {
369
+ this.channel = channel;
370
+ }
371
+ write(level, message, context = {}) {
372
+ const entry = {
373
+ level,
374
+ channel: this.channel,
375
+ message,
376
+ timestamp: new Date().toISOString(),
377
+ ...context
378
+ };
379
+ const line = JSON.stringify(entry);
380
+ if (level === "error") {
381
+ console.error(line);
382
+ return;
383
+ }
384
+ console.log(line);
385
+ }
386
+ debug(message, context) {
387
+ this.write("debug", message, context);
388
+ }
389
+ info(message, context) {
390
+ this.write("info", message, context);
391
+ }
392
+ warn(message, context) {
393
+ this.write("warn", message, context);
394
+ }
395
+ error(message, context) {
396
+ this.write("error", message, context);
397
+ }
398
+ }
399
+ var appLogger = new Logger("app");
400
+
401
+ // ../../src/bootstrap/config.ts
402
+ var APP_PORT_CONFIG_KEY = "app.port";
403
+ var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
404
+ var CACHE_MAX_ENTRIES_CONFIG_KEY = "cache.maxEntries";
405
+ var CACHE_DRIVER_CONFIG_KEY = "cache.driver";
406
+ var REDIS_URL_CONFIG_KEY = "cache.redisUrl";
407
+ var DATABASE_URL_CONFIG_KEY = "database.url";
408
+ var CORE_CONFIG_TOKEN = "core.config";
409
+ var CORE_CACHE_TOKEN = "core.cache";
410
+ var CORE_QUEUE_TOKEN = "core.queue";
411
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
412
+ var CORE_AUTH_TOKEN = "core.auth";
413
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
414
+ var AUTH_DEV_HEADERS_CONFIG_KEY = "auth.allowDevHeaders";
415
+ var DEFAULT_APP_PORT = 3000;
416
+ var DEFAULT_CACHE_TTL_MS = 3600000;
417
+ var DEFAULT_CACHE_MAX_ENTRIES = 100;
418
+ var DEFAULT_CACHE_DRIVER = "array";
419
+ var DEFAULT_API_TOKEN = "";
420
+ var DEFAULT_QUEUE_DRIVER = "sync";
421
+
422
+ // ../../src/bootstrap/contracts.ts
423
+ class ServiceContainer {
424
+ services = new Map;
425
+ singletonFactories = new Map;
426
+ bindings = new Map;
427
+ set(key, value) {
428
+ this.singletonFactories.delete(key);
429
+ this.bindings.delete(key);
430
+ this.services.set(key, value);
431
+ return value;
432
+ }
433
+ singleton(key, factory) {
434
+ this.bindings.delete(key);
435
+ this.services.delete(key);
436
+ this.singletonFactories.set(key, factory);
437
+ }
438
+ bind(key, factory) {
439
+ this.singletonFactories.delete(key);
440
+ this.services.delete(key);
441
+ this.bindings.set(key, factory);
442
+ }
443
+ get(key) {
444
+ if (this.services.has(key)) {
445
+ return this.services.get(key);
446
+ }
447
+ const singletonFactory = this.singletonFactories.get(key);
448
+ if (singletonFactory) {
449
+ const value = singletonFactory(this);
450
+ this.services.set(key, value);
451
+ return value;
452
+ }
453
+ const binding = this.bindings.get(key);
454
+ if (binding) {
455
+ return binding(this);
456
+ }
457
+ throw new Error(`Service "${key}" is not registered.`);
458
+ }
459
+ resolve(key) {
460
+ return this.get(key);
461
+ }
462
+ has(key) {
463
+ return this.services.has(key) || this.singletonFactories.has(key) || this.bindings.has(key);
464
+ }
465
+ }
466
+
467
+ class ConfigStore {
468
+ values = new Map;
469
+ set(key, value) {
470
+ this.values.set(key, value);
471
+ return value;
472
+ }
473
+ get(key) {
474
+ return this.values.get(key);
475
+ }
476
+ require(key) {
477
+ if (!this.values.has(key)) {
478
+ throw new Error(`Config key "${key}" is not defined.`);
479
+ }
480
+ return this.values.get(key);
481
+ }
482
+ has(key) {
483
+ return this.values.has(key);
484
+ }
485
+ }
486
+ var requiredDependencyKeys = [
487
+ "container",
488
+ "cache",
489
+ "storage"
490
+ ];
491
+ function getRequiredDependency(dependencies, key) {
492
+ const dependency = dependencies[key];
493
+ if (dependency === undefined) {
494
+ throw new Error(`Required dependency "${key}" is not registered.`);
495
+ }
496
+ return dependency;
497
+ }
498
+ function assertAppDependenciesComplete(dependencies) {
499
+ for (const key of requiredDependencyKeys) {
500
+ getRequiredDependency(dependencies, key);
501
+ }
502
+ }
503
+ function resolveService(dependencies, token) {
504
+ return dependencies.container.resolve(token);
505
+ }
506
+
507
+ // ../../src/bootstrap/applicationRegistry.ts
508
+ var activeContext;
509
+ function setActiveApplicationContext(context) {
510
+ activeContext = context;
511
+ }
512
+ function requireActiveApplicationContext() {
513
+ if (!activeContext) {
514
+ throw new Error("The application context has not been bootstrapped.");
515
+ }
516
+ return activeContext;
517
+ }
518
+ function resolveApplicationCache() {
519
+ return getRequiredDependency(requireActiveApplicationContext().dependencies, "cache");
520
+ }
521
+ function resolveApplicationQueue() {
522
+ return requireActiveApplicationContext().container.resolve(CORE_QUEUE_TOKEN);
523
+ }
524
+ function resolveApplicationAuth() {
525
+ return requireActiveApplicationContext().container.resolve(CORE_AUTH_TOKEN);
526
+ }
527
+ function resolveApplicationPolicyGate() {
528
+ return requireActiveApplicationContext().container.resolve(CORE_POLICY_GATE_TOKEN);
529
+ }
530
+ function resolveApplicationConfig() {
531
+ return requireActiveApplicationContext().config;
532
+ }
533
+ function resolveApplicationLogger() {
534
+ return appLogger;
535
+ }
536
+ function resolveApplicationDependencies() {
537
+ return requireActiveApplicationContext().dependencies;
538
+ }
539
+
540
+ // ../../src/bootstrap/queue/defaultJobs.ts
541
+ function registerDefaultJobs() {
542
+ jobRegistry.register("cache.invalidate-tags", () => {
543
+ return new invalidateCacheTagsJob_default(resolveApplicationCache());
544
+ });
545
+ jobRegistry.register("webhook.dispatch", () => new dispatchWebhookJob_default);
546
+ }
547
+ export {
548
+ registerDefaultJobs
549
+ };
@@ -19,6 +19,7 @@ export { appendOrganizationScope, appendProjectScope, assertOrganizationReadable
19
19
  export { default as MembershipService, resolveMembershipService, } from "../core/auth/membershipService.ts";
20
20
  export { Policy, PolicyGate } from "../core/auth/policy.ts";
21
21
  export { createScimAuthMiddleware } from "../core/auth/scimAuthMiddleware.ts";
22
+ export { type CacheDriver, type CreateCacheStoreOptions, createCacheStore, } from "../core/cache/createCacheStore.ts";
22
23
  export { default as CacheRepository } from "../core/cache/repository.ts";
23
24
  export { CACHE_TAGS } from "../core/cache/tags.ts";
24
25
  export type { DatabaseConnection } from "../core/database/baseRepository.ts";