@getstrata/core 0.5.41 → 0.5.43

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 (46) hide show
  1. package/dist/core/database/baseRepository.d.ts +1 -0
  2. package/dist/core/queue/failedJobRepository.d.ts +1 -0
  3. package/dist/entries/admin/formatValue.js +32 -0
  4. package/dist/entries/admin/registry.js +32 -0
  5. package/dist/entries/audit/exportAuditLogs.js +18 -0
  6. package/dist/entries/audit/siemFormatter.js +37 -0
  7. package/dist/entries/auth/scimAuthMiddleware.js +241 -0
  8. package/dist/entries/auth/sessionGuard.js +501 -0
  9. package/dist/entries/database/baseRepository.js +1388 -0
  10. package/dist/entries/database/bindConnection.js +22 -0
  11. package/dist/entries/database/boundConnection.js +19 -0
  12. package/dist/entries/database/connection.js +12 -0
  13. package/dist/entries/database/errors.js +128 -0
  14. package/dist/entries/database/model.js +948 -0
  15. package/dist/entries/database/query.js +436 -0
  16. package/dist/entries/database/relationships.js +162 -0
  17. package/dist/entries/database/schema.js +1054 -0
  18. package/dist/entries/database/table.js +8 -0
  19. package/dist/entries/database/transaction.js +129 -0
  20. package/dist/entries/http/authMiddleware.js +47 -0
  21. package/dist/entries/http/authorizeMiddleware.js +104 -0
  22. package/dist/entries/http/metricsMiddleware.js +91 -0
  23. package/dist/entries/http/parseMultipartUpload.js +144 -0
  24. package/dist/entries/http/securedRouteModelBinding.js +6 -0
  25. package/dist/entries/http/webErrorResponse.js +501 -0
  26. package/dist/entries/http/webFormRequest.js +6 -0
  27. package/dist/entries/jobs/dispatchWebhookJob.js +18 -0
  28. package/dist/entries/mail/mailer.js +208 -0
  29. package/dist/entries/mail/markdownMail.js +63 -0
  30. package/dist/entries/mail/markdownMailable.js +78 -0
  31. package/dist/entries/notifications.js +152 -0
  32. package/dist/entries/openapi/generator.js +178 -0
  33. package/dist/entries/openapi/validate.js +28 -0
  34. package/dist/entries/queue/createAppQueue.js +507 -0
  35. package/dist/entries/queue/failedJobRepository.js +2364 -0
  36. package/dist/entries/queue/publicQueue.js +507 -0
  37. package/dist/entries/queue/queueMetrics.js +507 -0
  38. package/dist/entries/queue/redisQueue.js +232 -0
  39. package/dist/entries/runtime/asyncContextStore.js +17 -0
  40. package/dist/entries/security/safeFetch.js +211 -0
  41. package/dist/entries/security/scimTenantTokens.js +51 -0
  42. package/dist/entries/security/timingSafeCompare.js +14 -0
  43. package/dist/entries/tenant/databaseTenantContext.js +116 -0
  44. package/dist/entries/tenant/tenantDatabaseScope.js +113 -0
  45. package/dist/entries/view.js +501 -0
  46. package/package.json +167 -2
@@ -63,5 +63,6 @@ declare class BaseRepository<TEntity extends object, PrimaryKey extends keyof TE
63
63
  loadMorphOneForParents<TParent extends object, LocalKey extends keyof TParent & string, MorphTypeKey extends keyof TEntity & string, MorphIdKey extends keyof TEntity & string>(parents: readonly TParent[], relation: MorphOneRelation<TParent, TEntity, LocalKey, MorphTypeKey, MorphIdKey>, options?: Omit<QueryOptions<TEntity>, "where">): Promise<Map<TParent[LocalKey], TEntity | undefined>>;
64
64
  loadMorphToForChildren<TChild extends object, TParent extends object, MorphTypeKey extends keyof TChild & string, MorphIdKey extends keyof TChild & string, OwnerKey extends keyof TParent & string>(children: readonly TChild[], relation: MorphToRelation<TChild, MorphTypeKey, MorphIdKey>, repositoriesByType: ReadonlyMap<string, BaseRepository<TParent, OwnerKey>>, options?: Omit<QueryOptions<TParent>, "where">): Promise<Map<TChild[MorphIdKey], TParent>>;
65
65
  }
66
+ export { BaseRepository };
66
67
  export default BaseRepository;
67
68
  export type { DatabaseConnection, SqlDatabaseConnection };
@@ -3,4 +3,5 @@ import type { FailedJobRecord } from "./types";
3
3
  declare class FailedJobRepository extends BaseRepository<FailedJobRecord, "id"> {
4
4
  constructor();
5
5
  }
6
+ export { FailedJobRepository };
6
7
  export default FailedJobRepository;
@@ -0,0 +1,32 @@
1
+ // @bun
2
+ // ../../src/core/admin/formatValue.ts
3
+ function formatAdminValue(value, type = "text") {
4
+ if (value === null || value === undefined) {
5
+ return "";
6
+ }
7
+ if (type === "boolean") {
8
+ return value ? "yes" : "no";
9
+ }
10
+ if (type === "number") {
11
+ return String(value);
12
+ }
13
+ if (type === "datetime") {
14
+ if (value instanceof Date) {
15
+ return value.toISOString();
16
+ }
17
+ return String(value);
18
+ }
19
+ if (type === "code") {
20
+ if (typeof value === "string") {
21
+ return value;
22
+ }
23
+ return JSON.stringify(value, null, 2);
24
+ }
25
+ if (typeof value === "object") {
26
+ return JSON.stringify(value);
27
+ }
28
+ return String(value);
29
+ }
30
+ export {
31
+ formatAdminValue
32
+ };
@@ -0,0 +1,32 @@
1
+ // @bun
2
+ // ../../src/core/admin/registry.ts
3
+ class AdminResourceRegistry {
4
+ resources = new Map;
5
+ constructor() {}
6
+ register(resource) {
7
+ if (this.resources.has(resource.name)) {
8
+ throw new Error(`Admin resource "${resource.name}" is already registered.`);
9
+ }
10
+ this.resources.set(resource.name, resource);
11
+ }
12
+ get(name) {
13
+ return this.resources.get(name);
14
+ }
15
+ list() {
16
+ const definitions = [];
17
+ for (const resource of this.resources.values()) {
18
+ const { handlers: _handlers, ...definition } = resource;
19
+ definitions.push(definition);
20
+ }
21
+ return definitions;
22
+ }
23
+ all() {
24
+ return [...this.resources.values()];
25
+ }
26
+ clear() {
27
+ this.resources.clear();
28
+ }
29
+ }
30
+ export {
31
+ AdminResourceRegistry
32
+ };
@@ -12,9 +12,15 @@ var appConfig = {
12
12
  var boundConnectionHolder = {
13
13
  connection: null
14
14
  };
15
+ function bindDatabaseConnection(connection) {
16
+ boundConnectionHolder.connection = connection;
17
+ }
15
18
  function getBoundDatabaseConnection() {
16
19
  return boundConnectionHolder.connection;
17
20
  }
21
+ function resetBoundDatabaseConnection() {
22
+ boundConnectionHolder.connection = null;
23
+ }
18
24
 
19
25
  // ../../src/core/runtime/asyncContextStore.ts
20
26
  import { AsyncLocalStorage } from "async_hooks";
@@ -32,9 +38,15 @@ function createAsyncContextStore(key) {
32
38
 
33
39
  // ../../src/core/database/connectionContext.ts
34
40
  var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
41
+ function runWithDatabaseConnection(connection, callback) {
42
+ return activeConnection.run(connection, callback);
43
+ }
35
44
  function getActiveDatabaseConnection(fallback) {
36
45
  return activeConnection.getStore() ?? fallback;
37
46
  }
47
+ function hasActiveDatabaseConnection() {
48
+ return activeConnection.getStore() !== undefined;
49
+ }
38
50
 
39
51
  // ../../src/core/database/queryProxy.ts
40
52
  var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
@@ -71,6 +83,12 @@ function registerDefaultDatabasePool(connection) {
71
83
  defaultPool.connection = connection;
72
84
  defaultQuery.connection = createDatabaseQueryProxy(connection);
73
85
  }
86
+ function getDefaultDatabasePool() {
87
+ if (!defaultPool.connection) {
88
+ throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
89
+ }
90
+ return defaultPool.connection;
91
+ }
74
92
  function getDefaultDatabaseQuery() {
75
93
  if (!defaultQuery.connection) {
76
94
  throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
@@ -0,0 +1,37 @@
1
+ // @bun
2
+ // ../../src/core/audit/siemFormatter.ts
3
+ function formatSiemAuditEvent(input) {
4
+ return {
5
+ timestamp: input.created_at.toISOString(),
6
+ event_type: "workhub.audit",
7
+ actor_user_id: input.user_id,
8
+ tenant_id: input.tenant_id ?? null,
9
+ trace_id: input.trace_id ?? null,
10
+ action: input.action,
11
+ subject_type: input.subject_type,
12
+ subject_id: input.subject_id,
13
+ ip_address: input.ip_address ?? null,
14
+ user_agent: input.user_agent ?? null,
15
+ checksum: input.checksum ?? null,
16
+ payload: input.payload ?? {}
17
+ };
18
+ }
19
+ function formatCefLine(event) {
20
+ const extension = [
21
+ `rt=${event.timestamp}`,
22
+ `suid=${event.actor_user_id ?? "unknown"}`,
23
+ `cs1=${event.action}`,
24
+ `cs1Label=Action`,
25
+ `cs2=${event.subject_type}`,
26
+ `cs2Label=SubjectType`,
27
+ `cs3=${event.subject_id ?? ""}`,
28
+ `cs3Label=SubjectId`,
29
+ `src=${event.ip_address ?? ""}`,
30
+ `request=${event.trace_id ?? ""}`
31
+ ].join(" ");
32
+ return `CEF:0|WorkHub|API|1.0|${event.action}|${event.subject_type}|5|${extension}`;
33
+ }
34
+ export {
35
+ formatSiemAuditEvent,
36
+ formatCefLine
37
+ };
@@ -0,0 +1,241 @@
1
+ // @bun
2
+ // ../../src/core/database/boundConnection.ts
3
+ var boundConnectionHolder = {
4
+ connection: null
5
+ };
6
+ function bindDatabaseConnection(connection) {
7
+ boundConnectionHolder.connection = connection;
8
+ }
9
+ function getBoundDatabaseConnection() {
10
+ return boundConnectionHolder.connection;
11
+ }
12
+ function resetBoundDatabaseConnection() {
13
+ boundConnectionHolder.connection = null;
14
+ }
15
+
16
+ // ../../src/core/database/bindConnection.ts
17
+ function bindDatabaseConnection2(connection) {
18
+ bindDatabaseConnection(connection);
19
+ }
20
+
21
+ // ../../src/core/runtime/asyncContextStore.ts
22
+ import { AsyncLocalStorage } from "async_hooks";
23
+ function createAsyncContextStore(key) {
24
+ const symbol = Symbol.for(key);
25
+ const globalRecord = globalThis;
26
+ const existing = globalRecord[symbol];
27
+ if (existing) {
28
+ return existing;
29
+ }
30
+ const store = new AsyncLocalStorage;
31
+ globalRecord[symbol] = store;
32
+ return store;
33
+ }
34
+
35
+ // ../../src/core/database/connectionContext.ts
36
+ var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
37
+ function runWithDatabaseConnection(connection, callback) {
38
+ return activeConnection.run(connection, callback);
39
+ }
40
+ function getActiveDatabaseConnection(fallback) {
41
+ return activeConnection.getStore() ?? fallback;
42
+ }
43
+ function hasActiveDatabaseConnection() {
44
+ return activeConnection.getStore() !== undefined;
45
+ }
46
+
47
+ // ../../src/core/database/queryProxy.ts
48
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
49
+ function createDatabaseQueryProxy(pool) {
50
+ function resolveDatabase() {
51
+ return getActiveDatabaseConnection(pool);
52
+ }
53
+ function resolveDatabaseForProperty(property) {
54
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
55
+ return pool;
56
+ }
57
+ return resolveDatabase();
58
+ }
59
+ return new Proxy(function database() {}, {
60
+ apply(_target, _thisArg, args) {
61
+ return resolveDatabase()(...args);
62
+ },
63
+ get(_target, property) {
64
+ const connection = resolveDatabaseForProperty(property);
65
+ const value = connection[property];
66
+ return typeof value === "function" ? value.bind(connection) : value;
67
+ }
68
+ });
69
+ }
70
+
71
+ // ../../src/core/database/defaultConnection.ts
72
+ var defaultPool = {
73
+ connection: null
74
+ };
75
+ var defaultQuery = {
76
+ connection: null
77
+ };
78
+ function registerDefaultDatabasePool(connection) {
79
+ defaultPool.connection = connection;
80
+ defaultQuery.connection = createDatabaseQueryProxy(connection);
81
+ }
82
+ function getDefaultDatabasePool() {
83
+ if (!defaultPool.connection) {
84
+ throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
85
+ }
86
+ return defaultPool.connection;
87
+ }
88
+ function getDefaultDatabaseQuery() {
89
+ if (!defaultQuery.connection) {
90
+ throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
91
+ }
92
+ return defaultQuery.connection;
93
+ }
94
+
95
+ // ../../src/domain/scim.ts
96
+ var TEST_SCIM_BEARER_TOKEN = "workhub-scim-test-token";
97
+
98
+ // ../../src/core/security/timingSafeCompare.ts
99
+ import { timingSafeEqual } from "crypto";
100
+ function timingSafeCompareString(left, right) {
101
+ const leftBuffer = Buffer.from(left);
102
+ const rightBuffer = Buffer.from(right);
103
+ if (leftBuffer.length !== rightBuffer.length) {
104
+ return false;
105
+ }
106
+ return timingSafeEqual(leftBuffer, rightBuffer);
107
+ }
108
+
109
+ // ../../src/core/security/scimTenantTokens.ts
110
+ function parseScimTenantTokens(raw) {
111
+ const tokens = new Map;
112
+ if (!raw?.trim()) {
113
+ return tokens;
114
+ }
115
+ for (const entry of raw.split(",")) {
116
+ const [tenantPart, tokenPart] = entry.split(":");
117
+ if (!tenantPart || !tokenPart) {
118
+ continue;
119
+ }
120
+ const tenantId = Number.parseInt(tenantPart.trim(), 10);
121
+ const token = tokenPart.trim();
122
+ if (Number.isInteger(tenantId) && tenantId > 0 && token.length > 0) {
123
+ tokens.set(tenantId, token);
124
+ }
125
+ }
126
+ return tokens;
127
+ }
128
+ function resolveScimTenantFromToken(token) {
129
+ const tenantTokens = parseScimTenantTokens(process.env.SCIM_TENANT_TOKENS);
130
+ for (const [tenantId, expectedToken] of tenantTokens) {
131
+ if (timingSafeCompareString(token, expectedToken)) {
132
+ return tenantId;
133
+ }
134
+ }
135
+ const fallbackToken = process.env.SCIM_BEARER_TOKEN ?? TEST_SCIM_BEARER_TOKEN;
136
+ if (timingSafeCompareString(token, fallbackToken)) {
137
+ return 1;
138
+ }
139
+ return null;
140
+ }
141
+
142
+ // ../../src/core/database/repositoryConnection.ts
143
+ function resolveRepositoryConnection() {
144
+ return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
145
+ }
146
+ var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
147
+ apply(_target, _thisArg, args) {
148
+ return resolveRepositoryConnection()(...args);
149
+ },
150
+ get(_target, property) {
151
+ const connection = resolveRepositoryConnection();
152
+ const value = connection[property];
153
+ return typeof value === "function" ? value.bind(connection) : value;
154
+ }
155
+ });
156
+
157
+ // ../../src/core/tenant/resolveTenant.ts
158
+ async function resolveTenant(tenantId) {
159
+ const rows = await repositoryConnection`
160
+ SELECT id, slug, plan, region
161
+ FROM tenant
162
+ WHERE id = ${tenantId}
163
+ LIMIT 1
164
+ `;
165
+ const row = rows[0];
166
+ return row ? { id: row.id, slug: row.slug, plan: row.plan, region: row.region ?? "eu" } : null;
167
+ }
168
+
169
+ // ../../src/core/tenant/tenantContext.ts
170
+ var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
171
+ function runWithTenant(tenant, callback) {
172
+ return tenantContext.run(tenant, callback);
173
+ }
174
+ function currentTenant() {
175
+ return tenantContext.getStore() ?? null;
176
+ }
177
+ function currentTenantId() {
178
+ return currentTenant()?.id ?? 1;
179
+ }
180
+
181
+ // ../../src/core/tenant/tenantDatabaseScope.ts
182
+ async function applyTenantContextToTransaction(transaction, tenantId) {
183
+ await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
184
+ await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
185
+ }
186
+ async function runWithTenantDatabase(tenant, callback) {
187
+ if (hasActiveDatabaseConnection()) {
188
+ const activeConnection2 = getActiveDatabaseConnection(getDefaultDatabasePool());
189
+ await applyTenantContextToTransaction(activeConnection2, tenant.id);
190
+ return await runWithTenant(tenant, callback);
191
+ }
192
+ return await getDefaultDatabasePool().begin(async (transaction) => {
193
+ await applyTenantContextToTransaction(transaction, tenant.id);
194
+ return await runWithDatabaseConnection(transaction, async () => {
195
+ return await runWithTenant(tenant, callback);
196
+ });
197
+ });
198
+ }
199
+ function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
200
+ return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
201
+ }
202
+
203
+ // ../../src/core/auth/scimAuthMiddleware.ts
204
+ function createScimAuthMiddleware() {
205
+ return async (request, next) => {
206
+ const authorization = request.headers.get("authorization");
207
+ if (!authorization?.startsWith("Bearer ")) {
208
+ return jsonScimError("SCIM bearer token required.", 401);
209
+ }
210
+ const token = authorization.slice("Bearer ".length).trim();
211
+ const tenantId = resolveScimTenantFromToken(token);
212
+ if (tenantId === null) {
213
+ return jsonScimError("Invalid SCIM bearer token.", 401);
214
+ }
215
+ const tenant = await resolveTenant(tenantId);
216
+ if (!tenant) {
217
+ return jsonScimError("SCIM tenant not found.", 401);
218
+ }
219
+ return await runWithTenantDatabase(tenant, async () => {
220
+ bindDatabaseConnection2(getActiveDatabaseConnection(getDefaultDatabasePool()));
221
+ try {
222
+ return await next();
223
+ } finally {
224
+ resetBoundDatabaseConnection();
225
+ }
226
+ });
227
+ };
228
+ }
229
+ function jsonScimError(detail, status) {
230
+ return Response.json({
231
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
232
+ detail,
233
+ status: String(status)
234
+ }, {
235
+ status,
236
+ headers: { "content-type": "application/scim+json" }
237
+ });
238
+ }
239
+ export {
240
+ createScimAuthMiddleware
241
+ };