@getstrata/core 0.5.43 → 0.5.45

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 (40) hide show
  1. package/dist/entries/admin/types.js +1 -0
  2. package/dist/entries/auth/abilityChecker.js +1 -0
  3. package/dist/entries/auth/membershipMiddleware.js +298 -0
  4. package/dist/entries/auth/scimAuthMiddleware.js +10 -0
  5. package/dist/entries/auth/sessionGuard.js +14 -0
  6. package/dist/entries/database/bindConnection.js +1 -22
  7. package/dist/entries/database/boundConnection.js +1 -19
  8. package/dist/entries/database/connection.js +1 -12
  9. package/dist/entries/database/defaultConnection.js +1 -0
  10. package/dist/entries/database/migrations/types.js +1 -0
  11. package/dist/entries/database/migrations.js +127 -0
  12. package/dist/entries/database/repositoryConnection.js +1 -0
  13. package/dist/entries/database/seeders/types.js +1 -0
  14. package/dist/entries/http/conditionalResponse.js +192 -0
  15. package/dist/entries/http/corsMiddleware.js +54 -0
  16. package/dist/entries/http/csrfMiddleware.js +236 -0
  17. package/dist/entries/http/csrfToken.js +3 -0
  18. package/dist/entries/http/flashMiddleware.js +143 -0
  19. package/dist/entries/http/formRequest.js +158 -0
  20. package/dist/entries/http/loginThrottleMiddleware.js +46 -0
  21. package/dist/entries/http/memoryThrottleMiddleware.js +30 -0
  22. package/dist/entries/http/pagination.js +185 -0
  23. package/dist/entries/http/requireAbilityMiddleware.js +110 -0
  24. package/dist/entries/http/requireAuthMiddleware.js +80 -0
  25. package/dist/entries/http/requireGlobalAdminMiddleware.js +147 -0
  26. package/dist/entries/http/requireWebAuthMiddleware.js +107 -0
  27. package/dist/entries/http/route.js +8 -0
  28. package/dist/entries/http/routeMiddleware.js +32 -0
  29. package/dist/entries/http/routeModelBinding.js +147 -0
  30. package/dist/entries/http/scimThrottleMiddleware.js +23 -0
  31. package/dist/entries/http/securedRouteModelBinding.js +16 -0
  32. package/dist/entries/http/securityHeadersMiddleware.js +77 -0
  33. package/dist/entries/http/throttleMiddleware.js +87 -0
  34. package/dist/entries/http/webErrorResponse.js +14 -0
  35. package/dist/entries/http/webFormRequest.js +16 -0
  36. package/dist/entries/logging/requestLoggingMiddleware.js +89 -0
  37. package/dist/entries/tenant/tenantDatabaseScope.js +10 -0
  38. package/dist/entries/tracing/tracingMiddleware.js +103 -0
  39. package/dist/entries/view.js +14 -0
  40. package/package.json +147 -7
@@ -0,0 +1,158 @@
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/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
+ function getQueryParams(request) {
115
+ if (!request) {
116
+ return new URLSearchParams;
117
+ }
118
+ return new URL(request.url).searchParams;
119
+ }
120
+ async function parseJsonBody(request, validator) {
121
+ let payload;
122
+ try {
123
+ payload = await request.json();
124
+ } catch {
125
+ throw new BadRequestError("Request body must be valid JSON.");
126
+ }
127
+ return validator(payload);
128
+ }
129
+ function parsePositiveIntParam(value, name = "id") {
130
+ const parsed = Number.parseInt(value, 10);
131
+ if (!Number.isInteger(parsed) || parsed <= 0) {
132
+ throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
133
+ }
134
+ return parsed;
135
+ }
136
+
137
+ // ../../src/core/http/formRequest.ts
138
+ class FormRequest {
139
+ authorize(_request) {
140
+ return true;
141
+ }
142
+ async validate(request) {
143
+ if (!await this.authorize(request)) {
144
+ throw new ForbiddenError;
145
+ }
146
+ return await parseJsonBody(request, (payload) => this.parse(payload));
147
+ }
148
+ }
149
+
150
+ class QueryFormRequest {
151
+ validate(request) {
152
+ return this.parseQuery(request);
153
+ }
154
+ }
155
+ export {
156
+ QueryFormRequest,
157
+ FormRequest
158
+ };
@@ -0,0 +1,46 @@
1
+ // @bun
2
+ // ../../src/core/http/loginThrottleMiddleware.ts
3
+ var {RedisClient } = globalThis.Bun;
4
+ function resolveLoginIdentity(request) {
5
+ return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
6
+ }
7
+ async function resolveLoginEmail(request) {
8
+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
9
+ try {
10
+ if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
11
+ const formData = await request.clone().formData();
12
+ const email = formData.get("email");
13
+ return typeof email === "string" ? email.trim().toLowerCase() : "unknown";
14
+ }
15
+ const payload = await request.clone().json();
16
+ return typeof payload.email === "string" ? payload.email.trim().toLowerCase() : "unknown";
17
+ } catch {
18
+ return "unknown";
19
+ }
20
+ }
21
+ function createLoginThrottleMiddleware(options) {
22
+ const client = new RedisClient(options.redisUrl);
23
+ const prefix = options.keyPrefix ?? "workhub:login-throttle:";
24
+ return async (request, next) => {
25
+ const identity = resolveLoginIdentity(request);
26
+ const email = await resolveLoginEmail(request);
27
+ const throttleKey = `${prefix}${identity}:${email}`;
28
+ const attempts = Number(await client.incr(throttleKey));
29
+ if (attempts === 1) {
30
+ await client.expire(throttleKey, options.decaySeconds);
31
+ }
32
+ if (attempts > options.maxAttempts) {
33
+ return Response.json({ error: "Too many login attempts. Try again later." }, {
34
+ status: 429,
35
+ headers: {
36
+ "retry-after": String(options.decaySeconds)
37
+ }
38
+ });
39
+ }
40
+ return await next();
41
+ };
42
+ }
43
+ export {
44
+ resolveLoginIdentity,
45
+ createLoginThrottleMiddleware
46
+ };
@@ -0,0 +1,30 @@
1
+ // @bun
2
+ // ../../src/core/http/memoryThrottleMiddleware.ts
3
+ var buckets = new Map;
4
+ function createMemoryThrottleMiddleware(options) {
5
+ const prefix = options.keyPrefix ?? "workhub:memory-throttle:";
6
+ return async (request, next) => {
7
+ const path = new URL(request.url).pathname;
8
+ const identity = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? request.headers.get("authorization")?.slice(0, 32) ?? "unknown";
9
+ const key = `${prefix}${identity}:${path}`;
10
+ const now = Date.now();
11
+ const existing = buckets.get(key);
12
+ if (!existing || existing.resetAt <= now) {
13
+ buckets.set(key, { count: 1, resetAt: now + options.decaySeconds * 1000 });
14
+ return await next();
15
+ }
16
+ existing.count += 1;
17
+ if (existing.count > options.maxAttempts) {
18
+ return Response.json({ error: "Too many requests." }, {
19
+ status: 429,
20
+ headers: {
21
+ "retry-after": String(options.decaySeconds)
22
+ }
23
+ });
24
+ }
25
+ return await next();
26
+ };
27
+ }
28
+ export {
29
+ createMemoryThrottleMiddleware
30
+ };
@@ -0,0 +1,185 @@
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/pagination/index.ts
69
+ function buildPaginationMeta(input) {
70
+ const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
71
+ return {
72
+ page: input.page,
73
+ per_page: input.perPage,
74
+ total: input.total,
75
+ last_page: lastPage
76
+ };
77
+ }
78
+
79
+ // ../../src/core/runtime/asyncContextStore.ts
80
+ import { AsyncLocalStorage } from "async_hooks";
81
+ function createAsyncContextStore(key) {
82
+ const symbol = Symbol.for(key);
83
+ const globalRecord = globalThis;
84
+ const existing = globalRecord[symbol];
85
+ if (existing) {
86
+ return existing;
87
+ }
88
+ const store = new AsyncLocalStorage;
89
+ globalRecord[symbol] = store;
90
+ return store;
91
+ }
92
+
93
+ // ../../src/core/auth/authContext.ts
94
+ var authContext = createAsyncContextStore("@getstrata/authContext");
95
+ function runWithAuthUser(user, callback) {
96
+ return authContext.run(user, callback);
97
+ }
98
+ function currentAuthUser() {
99
+ return authContext.getStore() ?? null;
100
+ }
101
+
102
+ // ../../src/core/tenant/tenantContext.ts
103
+ var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
104
+ function runWithTenant(tenant, callback) {
105
+ return tenantContext.run(tenant, callback);
106
+ }
107
+ function currentTenant() {
108
+ return tenantContext.getStore() ?? null;
109
+ }
110
+ function currentTenantId() {
111
+ return currentTenant()?.id ?? 1;
112
+ }
113
+ function rateLimitMultiplierForPlan(plan) {
114
+ switch (plan) {
115
+ case "enterprise":
116
+ return 4;
117
+ case "pro":
118
+ return 2;
119
+ default:
120
+ return 1;
121
+ }
122
+ }
123
+
124
+ // ../../src/core/http/validation.ts
125
+ function getQueryParams(request) {
126
+ if (!request) {
127
+ return new URLSearchParams;
128
+ }
129
+ return new URL(request.url).searchParams;
130
+ }
131
+ async function parseJsonBody(request, validator) {
132
+ let payload;
133
+ try {
134
+ payload = await request.json();
135
+ } catch {
136
+ throw new BadRequestError("Request body must be valid JSON.");
137
+ }
138
+ return validator(payload);
139
+ }
140
+ function parsePositiveIntParam(value, name = "id") {
141
+ const parsed = Number.parseInt(value, 10);
142
+ if (!Number.isInteger(parsed) || parsed <= 0) {
143
+ throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
144
+ }
145
+ return parsed;
146
+ }
147
+
148
+ // ../../src/core/http/pagination.ts
149
+ var DEFAULT_PER_PAGE = 15;
150
+ var MAX_PER_PAGE = 100;
151
+ function parseRequiredPositiveIntQueryParam(params, name) {
152
+ const value = params.get(name);
153
+ if (value === null || value.trim() === "") {
154
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
155
+ }
156
+ const parsed = Number.parseInt(value, 10);
157
+ if (!Number.isInteger(parsed) || parsed <= 0) {
158
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
159
+ }
160
+ return parsed;
161
+ }
162
+ function parsePaginationQuery(request) {
163
+ const params = getQueryParams(request);
164
+ const pageParam = params.get("page");
165
+ const perPageParam = params.get("per_page");
166
+ const page = pageParam === null || pageParam.trim() === "" ? 1 : parseRequiredPositiveIntQueryParam(params, "page");
167
+ if (perPageParam === null || perPageParam.trim() === "") {
168
+ return { page, perPage: DEFAULT_PER_PAGE };
169
+ }
170
+ const perPage = parseRequiredPositiveIntQueryParam(params, "per_page");
171
+ if (perPage > MAX_PER_PAGE) {
172
+ throw new BadRequestError(`Invalid query parameter "per_page". Maximum allowed value is ${MAX_PER_PAGE}.`);
173
+ }
174
+ return { page, perPage };
175
+ }
176
+ function paginatedResponse(data, meta, init = {}) {
177
+ return Response.json({ data, meta }, init);
178
+ }
179
+ export {
180
+ parsePaginationQuery,
181
+ paginatedResponse,
182
+ buildPaginationMeta,
183
+ MAX_PER_PAGE,
184
+ DEFAULT_PER_PAGE
185
+ };
@@ -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
+ };