@getstrata/core 0.5.43 → 0.5.44

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 (33) hide show
  1. package/dist/entries/auth/abilityChecker.js +1 -0
  2. package/dist/entries/auth/membershipMiddleware.js +298 -0
  3. package/dist/entries/auth/scimAuthMiddleware.js +10 -0
  4. package/dist/entries/auth/sessionGuard.js +14 -0
  5. package/dist/entries/database/migrations/types.js +1 -0
  6. package/dist/entries/database/migrations.js +127 -0
  7. package/dist/entries/database/seeders/types.js +1 -0
  8. package/dist/entries/http/conditionalResponse.js +192 -0
  9. package/dist/entries/http/corsMiddleware.js +54 -0
  10. package/dist/entries/http/csrfMiddleware.js +236 -0
  11. package/dist/entries/http/csrfToken.js +3 -0
  12. package/dist/entries/http/flashMiddleware.js +143 -0
  13. package/dist/entries/http/formRequest.js +152 -0
  14. package/dist/entries/http/loginThrottleMiddleware.js +46 -0
  15. package/dist/entries/http/memoryThrottleMiddleware.js +30 -0
  16. package/dist/entries/http/requireAbilityMiddleware.js +110 -0
  17. package/dist/entries/http/requireAuthMiddleware.js +80 -0
  18. package/dist/entries/http/requireGlobalAdminMiddleware.js +147 -0
  19. package/dist/entries/http/requireWebAuthMiddleware.js +107 -0
  20. package/dist/entries/http/route.js +8 -0
  21. package/dist/entries/http/routeMiddleware.js +32 -0
  22. package/dist/entries/http/routeModelBinding.js +141 -0
  23. package/dist/entries/http/scimThrottleMiddleware.js +23 -0
  24. package/dist/entries/http/securedRouteModelBinding.js +10 -0
  25. package/dist/entries/http/securityHeadersMiddleware.js +77 -0
  26. package/dist/entries/http/throttleMiddleware.js +87 -0
  27. package/dist/entries/http/webErrorResponse.js +14 -0
  28. package/dist/entries/http/webFormRequest.js +10 -0
  29. package/dist/entries/logging/requestLoggingMiddleware.js +89 -0
  30. package/dist/entries/tenant/tenantDatabaseScope.js +10 -0
  31. package/dist/entries/tracing/tracingMiddleware.js +103 -0
  32. package/dist/entries/view.js +14 -0
  33. package/package.json +127 -7
@@ -0,0 +1,77 @@
1
+ // @bun
2
+ // ../../src/config/app.ts
3
+ var appConfig = {
4
+ name: "WorkHub",
5
+ env: process.env.APP_ENV ?? "local",
6
+ debug: (process.env.APP_DEBUG ?? "true") !== "false",
7
+ url: process.env.APP_URL ?? "http://localhost:3000",
8
+ apiPrefix: process.env.API_PREFIX ?? "/api/v1"
9
+ };
10
+
11
+ // ../../src/config/contentSecurityPolicy.ts
12
+ function strictApiContentSecurityPolicy() {
13
+ return "default-src 'none'; frame-ancestors 'none'; base-uri 'none'";
14
+ }
15
+ function serverHtmxContentSecurityPolicy() {
16
+ return [
17
+ "default-src 'self'",
18
+ "script-src 'self' https://unpkg.com",
19
+ "style-src 'self'",
20
+ "connect-src 'self'",
21
+ "img-src 'self'",
22
+ "font-src 'self'",
23
+ "form-action 'self'",
24
+ "frame-ancestors 'none'",
25
+ "base-uri 'self'"
26
+ ].join("; ");
27
+ }
28
+ function spaContentSecurityPolicy() {
29
+ return [
30
+ "default-src 'self'",
31
+ "script-src 'self'",
32
+ "style-src 'self'",
33
+ "connect-src 'self'",
34
+ "img-src 'self'",
35
+ "font-src 'self'",
36
+ "frame-ancestors 'none'",
37
+ "base-uri 'self'"
38
+ ].join("; ");
39
+ }
40
+ function resolveContentSecurityPolicy(response) {
41
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
42
+ if (!contentType.includes("text/html")) {
43
+ return strictApiContentSecurityPolicy();
44
+ }
45
+ const frontendMode = (process.env.FRONTEND_MODE ?? "api").trim();
46
+ if (frontendMode === "server-htmx") {
47
+ return serverHtmxContentSecurityPolicy();
48
+ }
49
+ if (frontendMode === "spa-react") {
50
+ return spaContentSecurityPolicy();
51
+ }
52
+ return strictApiContentSecurityPolicy();
53
+ }
54
+
55
+ // ../../src/core/http/securityHeadersMiddleware.ts
56
+ function createSecurityHeadersMiddleware() {
57
+ return async (_request, next) => {
58
+ const response = await next();
59
+ const headers = new Headers(response.headers);
60
+ headers.set("X-Content-Type-Options", "nosniff");
61
+ headers.set("X-Frame-Options", "DENY");
62
+ headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
63
+ headers.set("X-XSS-Protection", "0");
64
+ headers.set("Content-Security-Policy", resolveContentSecurityPolicy(response));
65
+ if (appConfig.env === "production") {
66
+ headers.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
67
+ }
68
+ return new Response(response.body, {
69
+ status: response.status,
70
+ statusText: response.statusText,
71
+ headers
72
+ });
73
+ };
74
+ }
75
+ export {
76
+ createSecurityHeadersMiddleware
77
+ };
@@ -0,0 +1,87 @@
1
+ // @bun
2
+ // ../../src/core/http/throttleMiddleware.ts
3
+ var {RedisClient } = globalThis.Bun;
4
+
5
+ // ../../src/core/runtime/asyncContextStore.ts
6
+ import { AsyncLocalStorage } from "async_hooks";
7
+ function createAsyncContextStore(key) {
8
+ const symbol = Symbol.for(key);
9
+ const globalRecord = globalThis;
10
+ const existing = globalRecord[symbol];
11
+ if (existing) {
12
+ return existing;
13
+ }
14
+ const store = new AsyncLocalStorage;
15
+ globalRecord[symbol] = store;
16
+ return store;
17
+ }
18
+
19
+ // ../../src/core/auth/authContext.ts
20
+ var authContext = createAsyncContextStore("@getstrata/authContext");
21
+ function runWithAuthUser(user, callback) {
22
+ return authContext.run(user, callback);
23
+ }
24
+ function currentAuthUser() {
25
+ return authContext.getStore() ?? null;
26
+ }
27
+
28
+ // ../../src/core/tenant/tenantContext.ts
29
+ var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
30
+ function runWithTenant(tenant, callback) {
31
+ return tenantContext.run(tenant, callback);
32
+ }
33
+ function currentTenant() {
34
+ return tenantContext.getStore() ?? null;
35
+ }
36
+ function currentTenantId() {
37
+ return currentTenant()?.id ?? 1;
38
+ }
39
+ function rateLimitMultiplierForPlan(plan) {
40
+ switch (plan) {
41
+ case "enterprise":
42
+ return 4;
43
+ case "pro":
44
+ return 2;
45
+ default:
46
+ return 1;
47
+ }
48
+ }
49
+
50
+ // ../../src/core/http/throttleMiddleware.ts
51
+ function resolveThrottleIdentity(request) {
52
+ const user = currentAuthUser();
53
+ if (user?.tokenId !== undefined) {
54
+ return `token:${user.tokenId}`;
55
+ }
56
+ if (user) {
57
+ return `user:${user.id}`;
58
+ }
59
+ return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
60
+ }
61
+ function createThrottleMiddleware(options) {
62
+ const client = new RedisClient(options.redisUrl);
63
+ const prefix = options.keyPrefix ?? "workhub:throttle:";
64
+ return async (request, next) => {
65
+ const identity = resolveThrottleIdentity(request);
66
+ const path = new URL(request.url).pathname;
67
+ const throttleKey = `${prefix}${identity}:${path}`;
68
+ const attempts = Number(await client.incr(throttleKey));
69
+ if (attempts === 1) {
70
+ await client.expire(throttleKey, options.decaySeconds);
71
+ }
72
+ const maxAttempts = options.maxAttempts * rateLimitMultiplierForPlan(currentTenant()?.plan ?? "free");
73
+ if (attempts > maxAttempts) {
74
+ return Response.json({ error: "Too many requests." }, {
75
+ status: 429,
76
+ headers: {
77
+ "retry-after": String(options.decaySeconds)
78
+ }
79
+ });
80
+ }
81
+ return await next();
82
+ };
83
+ }
84
+ export {
85
+ resolveThrottleIdentity,
86
+ createThrottleMiddleware
87
+ };
@@ -2625,6 +2625,7 @@ var db = new Proxy(function database() {}, {
2625
2625
  return typeof value === "function" ? value.bind(connection) : value;
2626
2626
  }
2627
2627
  });
2628
+ var connection_default = db;
2628
2629
 
2629
2630
  // ../../src/modules/user/apiTokenTable.ts
2630
2631
  var apiTokenTable = defineTable({
@@ -2766,6 +2767,9 @@ function currentAuthUser() {
2766
2767
 
2767
2768
  // ../../src/core/http/requestMetaContext.ts
2768
2769
  var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
2770
+ function runWithRequestMeta(meta, callback) {
2771
+ return requestMetaContext.run(meta, callback);
2772
+ }
2769
2773
  function currentRequestMeta() {
2770
2774
  return requestMetaContext.getStore() ?? {
2771
2775
  ipAddress: null,
@@ -2859,6 +2863,16 @@ function currentTenant() {
2859
2863
  function currentTenantId() {
2860
2864
  return currentTenant()?.id ?? 1;
2861
2865
  }
2866
+ function rateLimitMultiplierForPlan(plan) {
2867
+ switch (plan) {
2868
+ case "enterprise":
2869
+ return 4;
2870
+ case "pro":
2871
+ return 2;
2872
+ default:
2873
+ return 1;
2874
+ }
2875
+ }
2862
2876
 
2863
2877
  // ../../src/domain/abilities.ts
2864
2878
  var MEMBER_ABILITIES = [
@@ -140,6 +140,16 @@ function currentTenant() {
140
140
  function currentTenantId() {
141
141
  return currentTenant()?.id ?? 1;
142
142
  }
143
+ function rateLimitMultiplierForPlan(plan) {
144
+ switch (plan) {
145
+ case "enterprise":
146
+ return 4;
147
+ case "pro":
148
+ return 2;
149
+ default:
150
+ return 1;
151
+ }
152
+ }
143
153
 
144
154
  // ../../src/core/http/validation.ts
145
155
  async function parseJsonBody(request, validator) {
@@ -0,0 +1,89 @@
1
+ // @bun
2
+ // ../../src/core/runtime/asyncContextStore.ts
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ function createAsyncContextStore(key) {
5
+ const symbol = Symbol.for(key);
6
+ const globalRecord = globalThis;
7
+ const existing = globalRecord[symbol];
8
+ if (existing) {
9
+ return existing;
10
+ }
11
+ const store = new AsyncLocalStorage;
12
+ globalRecord[symbol] = store;
13
+ return store;
14
+ }
15
+
16
+ // ../../src/core/http/requestMetaContext.ts
17
+ var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
18
+ function runWithRequestMeta(meta, callback) {
19
+ return requestMetaContext.run(meta, callback);
20
+ }
21
+ function currentRequestMeta() {
22
+ return requestMetaContext.getStore() ?? {
23
+ ipAddress: null,
24
+ userAgent: null
25
+ };
26
+ }
27
+
28
+ // ../../src/core/logging/logger.ts
29
+ class Logger {
30
+ channel;
31
+ constructor(channel = "app") {
32
+ this.channel = channel;
33
+ }
34
+ write(level, message, context = {}) {
35
+ const entry = {
36
+ level,
37
+ channel: this.channel,
38
+ message,
39
+ timestamp: new Date().toISOString(),
40
+ ...context
41
+ };
42
+ const line = JSON.stringify(entry);
43
+ if (level === "error") {
44
+ console.error(line);
45
+ return;
46
+ }
47
+ console.log(line);
48
+ }
49
+ debug(message, context) {
50
+ this.write("debug", message, context);
51
+ }
52
+ info(message, context) {
53
+ this.write("info", message, context);
54
+ }
55
+ warn(message, context) {
56
+ this.write("warn", message, context);
57
+ }
58
+ error(message, context) {
59
+ this.write("error", message, context);
60
+ }
61
+ }
62
+ var appLogger = new Logger("app");
63
+
64
+ // ../../src/core/logging/requestLoggingMiddleware.ts
65
+ function createRequestLoggingMiddleware() {
66
+ return async (request, next) => {
67
+ return await runWithRequestMeta({
68
+ ipAddress: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("x-real-ip"),
69
+ userAgent: request.headers.get("user-agent"),
70
+ request
71
+ }, async () => {
72
+ const startedAt = performance.now();
73
+ const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
74
+ const response = await next();
75
+ const durationMs = Math.round(performance.now() - startedAt);
76
+ appLogger.info("HTTP request completed", {
77
+ requestId,
78
+ method: request.method,
79
+ path: new URL(request.url).pathname,
80
+ status: response.status,
81
+ durationMs
82
+ });
83
+ return response;
84
+ });
85
+ };
86
+ }
87
+ export {
88
+ createRequestLoggingMiddleware
89
+ };
@@ -84,6 +84,16 @@ function currentTenant() {
84
84
  function currentTenantId() {
85
85
  return currentTenant()?.id ?? 1;
86
86
  }
87
+ function rateLimitMultiplierForPlan(plan) {
88
+ switch (plan) {
89
+ case "enterprise":
90
+ return 4;
91
+ case "pro":
92
+ return 2;
93
+ default:
94
+ return 1;
95
+ }
96
+ }
87
97
 
88
98
  // ../../src/core/tenant/tenantDatabaseScope.ts
89
99
  async function applyTenantContextToTransaction(transaction, tenantId) {
@@ -0,0 +1,103 @@
1
+ // @bun
2
+ // ../../src/core/tracing/otel.ts
3
+ import { randomBytes } from "crypto";
4
+ function randomHex(bytes) {
5
+ return randomBytes(bytes).toString("hex");
6
+ }
7
+ function createSpan(input) {
8
+ const spanId = randomHex(8);
9
+ return {
10
+ traceId: input.traceId,
11
+ spanId,
12
+ name: input.name,
13
+ startTimeUnixNano: String(Math.floor(input.startedAt * 1e6)),
14
+ endTimeUnixNano: String(Math.floor(input.endedAt * 1e6)),
15
+ attributes: Object.entries(input.attributes ?? {}).map(([key, value]) => ({
16
+ key,
17
+ value: { stringValue: value }
18
+ })),
19
+ status: { code: 1 }
20
+ };
21
+ }
22
+ async function exportOtelSpan(span) {
23
+ const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();
24
+ if (!endpoint) {
25
+ return;
26
+ }
27
+ const serviceName = process.env.OTEL_SERVICE_NAME?.trim() ?? "workhub-api";
28
+ const url = endpoint.endsWith("/v1/traces") ? endpoint : `${endpoint.replace(/\/$/, "")}/v1/traces`;
29
+ await fetch(url, {
30
+ method: "POST",
31
+ headers: { "content-type": "application/json" },
32
+ body: JSON.stringify({
33
+ resourceSpans: [
34
+ {
35
+ resource: {
36
+ attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
37
+ },
38
+ scopeSpans: [{ spans: [span] }]
39
+ }
40
+ ]
41
+ })
42
+ });
43
+ }
44
+
45
+ // ../../src/core/runtime/asyncContextStore.ts
46
+ import { AsyncLocalStorage } from "async_hooks";
47
+ function createAsyncContextStore(key) {
48
+ const symbol = Symbol.for(key);
49
+ const globalRecord = globalThis;
50
+ const existing = globalRecord[symbol];
51
+ if (existing) {
52
+ return existing;
53
+ }
54
+ const store = new AsyncLocalStorage;
55
+ globalRecord[symbol] = store;
56
+ return store;
57
+ }
58
+
59
+ // ../../src/core/tracing/traceContext.ts
60
+ var traceContextStorage = createAsyncContextStore("@getstrata/traceContext");
61
+ function runWithTraceContext(context, callback) {
62
+ return traceContextStorage.run(context, callback);
63
+ }
64
+
65
+ // ../../src/core/tracing/tracingMiddleware.ts
66
+ function createTracingMiddleware() {
67
+ return async (request, next) => {
68
+ const traceId = (request.headers.get("x-trace-id") ?? crypto.randomUUID()).replace(/-/g, "");
69
+ const spanId = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
70
+ const startedAt = performance.now();
71
+ const path = new URL(request.url).pathname;
72
+ return await runWithTraceContext({ traceId, spanId }, async () => {
73
+ const response = await next();
74
+ const endedAt = performance.now();
75
+ const headers = new Headers(response.headers);
76
+ headers.set("x-trace-id", traceId);
77
+ headers.set("x-span-id", spanId);
78
+ headers.set("traceparent", `00-${traceId}-${spanId}-01`);
79
+ headers.set("server-timing", `app;dur=${(endedAt - startedAt).toFixed(2)}`);
80
+ exportOtelSpan(createSpan({
81
+ traceId,
82
+ name: `${request.method} ${path}`,
83
+ startedAt,
84
+ endedAt,
85
+ attributes: {
86
+ "http.method": request.method,
87
+ "http.route": path,
88
+ "http.status_code": String(response.status)
89
+ }
90
+ })).catch(() => {
91
+ return;
92
+ });
93
+ return new Response(response.body, {
94
+ status: response.status,
95
+ statusText: response.statusText,
96
+ headers
97
+ });
98
+ });
99
+ };
100
+ }
101
+ export {
102
+ createTracingMiddleware
103
+ };
@@ -2610,6 +2610,7 @@ var db = new Proxy(function database() {}, {
2610
2610
  return typeof value === "function" ? value.bind(connection) : value;
2611
2611
  }
2612
2612
  });
2613
+ var connection_default = db;
2613
2614
 
2614
2615
  // ../../src/modules/user/apiTokenTable.ts
2615
2616
  var apiTokenTable = defineTable({
@@ -2751,6 +2752,9 @@ function currentAuthUser() {
2751
2752
 
2752
2753
  // ../../src/core/http/requestMetaContext.ts
2753
2754
  var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
2755
+ function runWithRequestMeta(meta, callback) {
2756
+ return requestMetaContext.run(meta, callback);
2757
+ }
2754
2758
  function currentRequestMeta() {
2755
2759
  return requestMetaContext.getStore() ?? {
2756
2760
  ipAddress: null,
@@ -2844,6 +2848,16 @@ function currentTenant() {
2844
2848
  function currentTenantId() {
2845
2849
  return currentTenant()?.id ?? 1;
2846
2850
  }
2851
+ function rateLimitMultiplierForPlan(plan) {
2852
+ switch (plan) {
2853
+ case "enterprise":
2854
+ return 4;
2855
+ case "pro":
2856
+ return 2;
2857
+ default:
2858
+ return 1;
2859
+ }
2860
+ }
2847
2861
 
2848
2862
  // ../../src/domain/abilities.ts
2849
2863
  var MEMBER_ABILITIES = [