@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,110 @@
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/auth/authContext.ts
17
+ var authContext = createAsyncContextStore("@getstrata/authContext");
18
+ function runWithAuthUser(user, callback) {
19
+ return authContext.run(user, callback);
20
+ }
21
+ function currentAuthUser() {
22
+ return authContext.getStore() ?? null;
23
+ }
24
+
25
+ // ../../src/core/errors/http.ts
26
+ class HttpError extends Error {
27
+ status;
28
+ details;
29
+ constructor(status, message, details) {
30
+ super(message);
31
+ this.name = new.target.name;
32
+ this.status = status;
33
+ this.details = details;
34
+ }
35
+ }
36
+
37
+ class BadRequestError extends HttpError {
38
+ constructor(message = "Bad Request", details) {
39
+ super(400, message, details);
40
+ }
41
+ }
42
+
43
+ class NotFoundError extends HttpError {
44
+ constructor(message = "Not Found", details) {
45
+ super(404, message, details);
46
+ }
47
+ }
48
+
49
+ class ConflictError extends HttpError {
50
+ constructor(message = "Conflict", details) {
51
+ super(409, message, details);
52
+ }
53
+ }
54
+
55
+ class UnprocessableEntityError extends HttpError {
56
+ constructor(message = "Unprocessable Entity", details) {
57
+ super(422, message, details);
58
+ }
59
+ }
60
+
61
+ class ValidationError extends HttpError {
62
+ constructor(message = "Validation failed", details) {
63
+ super(422, message, details);
64
+ }
65
+ }
66
+
67
+ class ForbiddenError extends HttpError {
68
+ constructor(message = "Forbidden", details) {
69
+ super(403, message, details);
70
+ }
71
+ }
72
+
73
+ class UnauthorizedError extends HttpError {
74
+ constructor(message = "Unauthorized", details) {
75
+ super(401, message, details);
76
+ }
77
+ }
78
+
79
+ class PayloadTooLargeError extends HttpError {
80
+ constructor(message = "Payload Too Large", details) {
81
+ super(413, message, details);
82
+ }
83
+ }
84
+
85
+ class PreconditionFailedError extends HttpError {
86
+ constructor(message = "Precondition Failed", details) {
87
+ super(412, message, details);
88
+ }
89
+ }
90
+
91
+ // ../../src/core/http/requireAbilityMiddleware.ts
92
+ function createRequireAbilityMiddleware(abilityChecker) {
93
+ return (ability) => {
94
+ return async (_request, next) => {
95
+ const user = currentAuthUser();
96
+ try {
97
+ abilityChecker.requireAbility(user, ability);
98
+ } catch (error) {
99
+ if (error instanceof ForbiddenError) {
100
+ return Response.json({ error: error.message }, { status: error.status });
101
+ }
102
+ throw error;
103
+ }
104
+ return await next();
105
+ };
106
+ };
107
+ }
108
+ export {
109
+ createRequireAbilityMiddleware
110
+ };
@@ -0,0 +1,80 @@
1
+ // @bun
2
+ // ../../src/core/errors/http.ts
3
+ class HttpError extends Error {
4
+ status;
5
+ details;
6
+ constructor(status, message, details) {
7
+ super(message);
8
+ this.name = new.target.name;
9
+ this.status = status;
10
+ this.details = details;
11
+ }
12
+ }
13
+
14
+ class BadRequestError extends HttpError {
15
+ constructor(message = "Bad Request", details) {
16
+ super(400, message, details);
17
+ }
18
+ }
19
+
20
+ class NotFoundError extends HttpError {
21
+ constructor(message = "Not Found", details) {
22
+ super(404, message, details);
23
+ }
24
+ }
25
+
26
+ class ConflictError extends HttpError {
27
+ constructor(message = "Conflict", details) {
28
+ super(409, message, details);
29
+ }
30
+ }
31
+
32
+ class UnprocessableEntityError extends HttpError {
33
+ constructor(message = "Unprocessable Entity", details) {
34
+ super(422, message, details);
35
+ }
36
+ }
37
+
38
+ class ValidationError extends HttpError {
39
+ constructor(message = "Validation failed", details) {
40
+ super(422, message, details);
41
+ }
42
+ }
43
+
44
+ class ForbiddenError extends HttpError {
45
+ constructor(message = "Forbidden", details) {
46
+ super(403, message, details);
47
+ }
48
+ }
49
+
50
+ class UnauthorizedError extends HttpError {
51
+ constructor(message = "Unauthorized", details) {
52
+ super(401, message, details);
53
+ }
54
+ }
55
+
56
+ class PayloadTooLargeError extends HttpError {
57
+ constructor(message = "Payload Too Large", details) {
58
+ super(413, message, details);
59
+ }
60
+ }
61
+
62
+ class PreconditionFailedError extends HttpError {
63
+ constructor(message = "Precondition Failed", details) {
64
+ super(412, message, details);
65
+ }
66
+ }
67
+
68
+ // ../../src/core/http/requireAuthMiddleware.ts
69
+ function createRequireAuthMiddleware(auth) {
70
+ return async (request, next) => {
71
+ if (!await auth.check(request)) {
72
+ const error = new UnauthorizedError;
73
+ return Response.json({ error: error.message }, { status: error.status });
74
+ }
75
+ return await next();
76
+ };
77
+ }
78
+ export {
79
+ createRequireAuthMiddleware
80
+ };
@@ -0,0 +1,147 @@
1
+ // @bun
2
+ // ../../src/core/errors/http.ts
3
+ class HttpError extends Error {
4
+ status;
5
+ details;
6
+ constructor(status, message, details) {
7
+ super(message);
8
+ this.name = new.target.name;
9
+ this.status = status;
10
+ this.details = details;
11
+ }
12
+ }
13
+
14
+ class BadRequestError extends HttpError {
15
+ constructor(message = "Bad Request", details) {
16
+ super(400, message, details);
17
+ }
18
+ }
19
+
20
+ class NotFoundError extends HttpError {
21
+ constructor(message = "Not Found", details) {
22
+ super(404, message, details);
23
+ }
24
+ }
25
+
26
+ class ConflictError extends HttpError {
27
+ constructor(message = "Conflict", details) {
28
+ super(409, message, details);
29
+ }
30
+ }
31
+
32
+ class UnprocessableEntityError extends HttpError {
33
+ constructor(message = "Unprocessable Entity", details) {
34
+ super(422, message, details);
35
+ }
36
+ }
37
+
38
+ class ValidationError extends HttpError {
39
+ constructor(message = "Validation failed", details) {
40
+ super(422, message, details);
41
+ }
42
+ }
43
+
44
+ class ForbiddenError extends HttpError {
45
+ constructor(message = "Forbidden", details) {
46
+ super(403, message, details);
47
+ }
48
+ }
49
+
50
+ class UnauthorizedError extends HttpError {
51
+ constructor(message = "Unauthorized", details) {
52
+ super(401, message, details);
53
+ }
54
+ }
55
+
56
+ class PayloadTooLargeError extends HttpError {
57
+ constructor(message = "Payload Too Large", details) {
58
+ super(413, message, details);
59
+ }
60
+ }
61
+
62
+ class PreconditionFailedError extends HttpError {
63
+ constructor(message = "Precondition Failed", details) {
64
+ super(412, message, details);
65
+ }
66
+ }
67
+
68
+ // ../../src/core/runtime/asyncContextStore.ts
69
+ import { AsyncLocalStorage } from "async_hooks";
70
+ function createAsyncContextStore(key) {
71
+ const symbol = Symbol.for(key);
72
+ const globalRecord = globalThis;
73
+ const existing = globalRecord[symbol];
74
+ if (existing) {
75
+ return existing;
76
+ }
77
+ const store = new AsyncLocalStorage;
78
+ globalRecord[symbol] = store;
79
+ return store;
80
+ }
81
+
82
+ // ../../src/core/auth/authContext.ts
83
+ var authContext = createAsyncContextStore("@getstrata/authContext");
84
+ function runWithAuthUser(user, callback) {
85
+ return authContext.run(user, callback);
86
+ }
87
+ function currentAuthUser() {
88
+ return authContext.getStore() ?? null;
89
+ }
90
+
91
+ // ../../src/core/auth/accessControl.ts
92
+ function isGlobalAdmin(user) {
93
+ return user?.role === "admin";
94
+ }
95
+ function resolveUserId(user) {
96
+ const userId = typeof user.id === "number" ? user.id : Number(user.id);
97
+ if (!Number.isInteger(userId) || userId <= 0) {
98
+ throw new ForbiddenError("Invalid authenticated user.");
99
+ }
100
+ return userId;
101
+ }
102
+
103
+ // ../../src/core/http/requestMetaContext.ts
104
+ var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
105
+ function runWithRequestMeta(meta, callback) {
106
+ return requestMetaContext.run(meta, callback);
107
+ }
108
+ function currentRequestMeta() {
109
+ return requestMetaContext.getStore() ?? {
110
+ ipAddress: null,
111
+ userAgent: null
112
+ };
113
+ }
114
+
115
+ // ../../src/core/security/securityEvents.ts
116
+ function logSecurityEvent(event, details = {}) {
117
+ const meta = currentRequestMeta();
118
+ const user = currentAuthUser();
119
+ console.log(JSON.stringify({
120
+ level: "security",
121
+ event,
122
+ timestamp: new Date().toISOString(),
123
+ ip_address: meta.ipAddress ?? null,
124
+ user_agent: meta.userAgent ?? null,
125
+ user_id: user?.id ?? null,
126
+ ...details
127
+ }));
128
+ }
129
+
130
+ // ../../src/core/http/requireGlobalAdminMiddleware.ts
131
+ function createRequireGlobalAdminMiddleware() {
132
+ return async (_request, next) => {
133
+ const user = currentAuthUser();
134
+ if (!isGlobalAdmin(user)) {
135
+ logSecurityEvent("privilege_escalation_blocked", {
136
+ required_role: "platform_admin",
137
+ path: new URL(_request.url).pathname
138
+ });
139
+ const error = new ForbiddenError("Platform admin access required.");
140
+ return Response.json({ error: error.message }, { status: error.status });
141
+ }
142
+ return await next();
143
+ };
144
+ }
145
+ export {
146
+ createRequireGlobalAdminMiddleware
147
+ };
@@ -0,0 +1,107 @@
1
+ // @bun
2
+ // ../../src/core/errors/http.ts
3
+ class HttpError extends Error {
4
+ status;
5
+ details;
6
+ constructor(status, message, details) {
7
+ super(message);
8
+ this.name = new.target.name;
9
+ this.status = status;
10
+ this.details = details;
11
+ }
12
+ }
13
+
14
+ class BadRequestError extends HttpError {
15
+ constructor(message = "Bad Request", details) {
16
+ super(400, message, details);
17
+ }
18
+ }
19
+
20
+ class NotFoundError extends HttpError {
21
+ constructor(message = "Not Found", details) {
22
+ super(404, message, details);
23
+ }
24
+ }
25
+
26
+ class ConflictError extends HttpError {
27
+ constructor(message = "Conflict", details) {
28
+ super(409, message, details);
29
+ }
30
+ }
31
+
32
+ class UnprocessableEntityError extends HttpError {
33
+ constructor(message = "Unprocessable Entity", details) {
34
+ super(422, message, details);
35
+ }
36
+ }
37
+
38
+ class ValidationError extends HttpError {
39
+ constructor(message = "Validation failed", details) {
40
+ super(422, message, details);
41
+ }
42
+ }
43
+
44
+ class ForbiddenError extends HttpError {
45
+ constructor(message = "Forbidden", details) {
46
+ super(403, message, details);
47
+ }
48
+ }
49
+
50
+ class UnauthorizedError extends HttpError {
51
+ constructor(message = "Unauthorized", details) {
52
+ super(401, message, details);
53
+ }
54
+ }
55
+
56
+ class PayloadTooLargeError extends HttpError {
57
+ constructor(message = "Payload Too Large", details) {
58
+ super(413, message, details);
59
+ }
60
+ }
61
+
62
+ class PreconditionFailedError extends HttpError {
63
+ constructor(message = "Precondition Failed", details) {
64
+ super(412, message, details);
65
+ }
66
+ }
67
+
68
+ // ../../src/core/http/contentNegotiation.ts
69
+ function requestPrefersJson(request) {
70
+ if (!request) {
71
+ return true;
72
+ }
73
+ if (request.headers.get("HX-Request") === "true") {
74
+ return false;
75
+ }
76
+ const accept = request.headers.get("accept")?.toLowerCase() ?? "";
77
+ if (accept.includes("text/html")) {
78
+ return false;
79
+ }
80
+ if (accept.includes("application/json")) {
81
+ return true;
82
+ }
83
+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
84
+ if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
85
+ return false;
86
+ }
87
+ const pathname = new URL(request.url).pathname;
88
+ return pathname.startsWith("/api/");
89
+ }
90
+
91
+ // ../../src/core/http/requireWebAuthMiddleware.ts
92
+ function createRequireWebAuthMiddleware(auth) {
93
+ return async (request, next) => {
94
+ const user = await auth.resolve(request);
95
+ if (user) {
96
+ return await next();
97
+ }
98
+ if (requestPrefersJson(request)) {
99
+ throw new UnauthorizedError;
100
+ }
101
+ const redirectTarget = encodeURIComponent(new URL(request.url).pathname);
102
+ return Response.redirect(`/login?redirect=${redirectTarget}`, 302);
103
+ };
104
+ }
105
+ export {
106
+ createRequireWebAuthMiddleware
107
+ };
@@ -0,0 +1,8 @@
1
+ // @bun
2
+ // ../../src/core/http/route.ts
3
+ function getRouteParams(request) {
4
+ return request.params;
5
+ }
6
+ export {
7
+ getRouteParams
8
+ };
@@ -0,0 +1,32 @@
1
+ // @bun
2
+ // ../../src/core/http/middleware.ts
3
+ function composeMiddleware(...middleware) {
4
+ return (handler) => {
5
+ return async (request) => {
6
+ let index = 0;
7
+ const dispatch = async () => {
8
+ if (index >= middleware.length) {
9
+ return await handler(request);
10
+ }
11
+ const current = middleware[index];
12
+ index += 1;
13
+ if (!current) {
14
+ return await handler(request);
15
+ }
16
+ return await current(request, dispatch);
17
+ };
18
+ return await dispatch();
19
+ };
20
+ };
21
+ }
22
+
23
+ // ../../src/core/http/routeMiddleware.ts
24
+ function withMiddleware(...middleware) {
25
+ const wrap = composeMiddleware(...middleware);
26
+ return (handler) => {
27
+ return wrap(handler);
28
+ };
29
+ }
30
+ export {
31
+ withMiddleware
32
+ };
@@ -0,0 +1,141 @@
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/auth/authContext.ts
17
+ var authContext = createAsyncContextStore("@getstrata/authContext");
18
+ function runWithAuthUser(user, callback) {
19
+ return authContext.run(user, callback);
20
+ }
21
+ function currentAuthUser() {
22
+ return authContext.getStore() ?? null;
23
+ }
24
+
25
+ // ../../src/core/errors/http.ts
26
+ class HttpError extends Error {
27
+ status;
28
+ details;
29
+ constructor(status, message, details) {
30
+ super(message);
31
+ this.name = new.target.name;
32
+ this.status = status;
33
+ this.details = details;
34
+ }
35
+ }
36
+
37
+ class BadRequestError extends HttpError {
38
+ constructor(message = "Bad Request", details) {
39
+ super(400, message, details);
40
+ }
41
+ }
42
+
43
+ class NotFoundError extends HttpError {
44
+ constructor(message = "Not Found", details) {
45
+ super(404, message, details);
46
+ }
47
+ }
48
+
49
+ class ConflictError extends HttpError {
50
+ constructor(message = "Conflict", details) {
51
+ super(409, message, details);
52
+ }
53
+ }
54
+
55
+ class UnprocessableEntityError extends HttpError {
56
+ constructor(message = "Unprocessable Entity", details) {
57
+ super(422, message, details);
58
+ }
59
+ }
60
+
61
+ class ValidationError extends HttpError {
62
+ constructor(message = "Validation failed", details) {
63
+ super(422, message, details);
64
+ }
65
+ }
66
+
67
+ class ForbiddenError extends HttpError {
68
+ constructor(message = "Forbidden", details) {
69
+ super(403, message, details);
70
+ }
71
+ }
72
+
73
+ class UnauthorizedError extends HttpError {
74
+ constructor(message = "Unauthorized", details) {
75
+ super(401, message, details);
76
+ }
77
+ }
78
+
79
+ class PayloadTooLargeError extends HttpError {
80
+ constructor(message = "Payload Too Large", details) {
81
+ super(413, message, details);
82
+ }
83
+ }
84
+
85
+ class PreconditionFailedError extends HttpError {
86
+ constructor(message = "Precondition Failed", details) {
87
+ super(412, message, details);
88
+ }
89
+ }
90
+
91
+ // ../../src/core/tenant/tenantContext.ts
92
+ var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
93
+ function runWithTenant(tenant, callback) {
94
+ return tenantContext.run(tenant, callback);
95
+ }
96
+ function currentTenant() {
97
+ return tenantContext.getStore() ?? null;
98
+ }
99
+ function currentTenantId() {
100
+ return currentTenant()?.id ?? 1;
101
+ }
102
+ function rateLimitMultiplierForPlan(plan) {
103
+ switch (plan) {
104
+ case "enterprise":
105
+ return 4;
106
+ case "pro":
107
+ return 2;
108
+ default:
109
+ return 1;
110
+ }
111
+ }
112
+
113
+ // ../../src/core/http/validation.ts
114
+ async function parseJsonBody(request, validator) {
115
+ let payload;
116
+ try {
117
+ payload = await request.json();
118
+ } catch {
119
+ throw new BadRequestError("Request body must be valid JSON.");
120
+ }
121
+ return validator(payload);
122
+ }
123
+ function parsePositiveIntParam(value, name = "id") {
124
+ const parsed = Number.parseInt(value, 10);
125
+ if (!Number.isInteger(parsed) || parsed <= 0) {
126
+ throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
127
+ }
128
+ return parsed;
129
+ }
130
+
131
+ // ../../src/core/http/routeModelBinding.ts
132
+ function bindRouteModel(param, resolver, handler) {
133
+ return async (request) => {
134
+ const id = parsePositiveIntParam(String(request.params[param]), String(param));
135
+ const model = await resolver(id, request);
136
+ return await handler(request, model);
137
+ };
138
+ }
139
+ export {
140
+ bindRouteModel
141
+ };
@@ -0,0 +1,23 @@
1
+ // @bun
2
+ // ../../src/core/http/scimThrottleMiddleware.ts
3
+ var {RedisClient } = globalThis.Bun;
4
+ function createScimThrottleMiddleware(options) {
5
+ const client = options.redisUrl ? new RedisClient(options.redisUrl) : null;
6
+ return async (request, next) => {
7
+ const identity = request.headers.get("authorization")?.slice("Bearer ".length, "Bearer ".length + 16) ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
8
+ const key = `workhub:scim-throttle:${identity}`;
9
+ if (client) {
10
+ const attempts = Number(await client.incr(key));
11
+ if (attempts === 1) {
12
+ await client.expire(key, options.decaySeconds);
13
+ }
14
+ if (attempts > options.maxAttempts) {
15
+ return Response.json({ error: "Too many SCIM requests." }, { status: 429, headers: { "retry-after": String(options.decaySeconds) } });
16
+ }
17
+ }
18
+ return await next();
19
+ };
20
+ }
21
+ export {
22
+ createScimThrottleMiddleware
23
+ };
@@ -288,6 +288,16 @@ function currentTenant() {
288
288
  function currentTenantId() {
289
289
  return currentTenant()?.id ?? 1;
290
290
  }
291
+ function rateLimitMultiplierForPlan(plan) {
292
+ switch (plan) {
293
+ case "enterprise":
294
+ return 4;
295
+ case "pro":
296
+ return 2;
297
+ default:
298
+ return 1;
299
+ }
300
+ }
291
301
 
292
302
  // ../../src/core/http/validation.ts
293
303
  async function parseJsonBody(request, validator) {