@getstrata/core 0.5.42 → 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.
- package/dist/entries/admin/formatValue.js +32 -0
- package/dist/entries/admin/registry.js +32 -0
- package/dist/entries/audit/siemFormatter.js +37 -0
- package/dist/entries/auth/abilityChecker.js +1 -0
- package/dist/entries/auth/membershipMiddleware.js +298 -0
- package/dist/entries/auth/scimAuthMiddleware.js +251 -0
- package/dist/entries/auth/sessionGuard.js +72 -0
- package/dist/entries/database/migrations/types.js +1 -0
- package/dist/entries/database/migrations.js +127 -0
- package/dist/entries/database/schema.js +1054 -0
- package/dist/entries/database/seeders/types.js +1 -0
- package/dist/entries/http/conditionalResponse.js +192 -0
- package/dist/entries/http/corsMiddleware.js +54 -0
- package/dist/entries/http/csrfMiddleware.js +236 -0
- package/dist/entries/http/csrfToken.js +3 -0
- package/dist/entries/http/flashMiddleware.js +143 -0
- package/dist/entries/http/formRequest.js +152 -0
- package/dist/entries/http/loginThrottleMiddleware.js +46 -0
- package/dist/entries/http/memoryThrottleMiddleware.js +30 -0
- package/dist/entries/http/requireAbilityMiddleware.js +110 -0
- package/dist/entries/http/requireAuthMiddleware.js +80 -0
- package/dist/entries/http/requireGlobalAdminMiddleware.js +147 -0
- package/dist/entries/http/requireWebAuthMiddleware.js +107 -0
- package/dist/entries/http/route.js +8 -0
- package/dist/entries/http/routeMiddleware.js +32 -0
- package/dist/entries/http/routeModelBinding.js +141 -0
- package/dist/entries/http/scimThrottleMiddleware.js +23 -0
- package/dist/entries/http/securedRouteModelBinding.js +10 -0
- package/dist/entries/http/securityHeadersMiddleware.js +77 -0
- package/dist/entries/http/throttleMiddleware.js +87 -0
- package/dist/entries/http/webErrorResponse.js +72 -0
- package/dist/entries/http/webFormRequest.js +10 -0
- package/dist/entries/logging/requestLoggingMiddleware.js +89 -0
- package/dist/entries/mail/mailer.js +208 -0
- package/dist/entries/mail/markdownMail.js +63 -0
- package/dist/entries/mail/markdownMailable.js +78 -0
- package/dist/entries/notifications.js +152 -0
- package/dist/entries/openapi/generator.js +178 -0
- package/dist/entries/openapi/validate.js +28 -0
- package/dist/entries/queue/createAppQueue.js +58 -0
- package/dist/entries/queue/failedJobRepository.js +58 -0
- package/dist/entries/queue/publicQueue.js +58 -0
- package/dist/entries/queue/queueMetrics.js +58 -0
- package/dist/entries/runtime/asyncContextStore.js +17 -0
- package/dist/entries/security/safeFetch.js +211 -0
- package/dist/entries/security/timingSafeCompare.js +14 -0
- package/dist/entries/tenant/databaseTenantContext.js +116 -0
- package/dist/entries/tenant/tenantDatabaseScope.js +10 -0
- package/dist/entries/tracing/tracingMiddleware.js +103 -0
- package/dist/entries/view.js +72 -0
- package/package.json +202 -7
|
@@ -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
|
+
};
|
|
@@ -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 @@
|
|
|
1
|
+
// @bun
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../src/config/database.ts
|
|
3
|
+
function readInteger(name, fallback) {
|
|
4
|
+
const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
|
|
5
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
|
6
|
+
}
|
|
7
|
+
var databaseConfig = {
|
|
8
|
+
url: process.env.DATABASE_URL ?? "",
|
|
9
|
+
poolMax: readInteger("DB_POOL_MAX", 10),
|
|
10
|
+
idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
|
|
11
|
+
maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
|
|
12
|
+
connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// ../../src/core/runtime/asyncContextStore.ts
|
|
16
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
17
|
+
function createAsyncContextStore(key) {
|
|
18
|
+
const symbol = Symbol.for(key);
|
|
19
|
+
const globalRecord = globalThis;
|
|
20
|
+
const existing = globalRecord[symbol];
|
|
21
|
+
if (existing) {
|
|
22
|
+
return existing;
|
|
23
|
+
}
|
|
24
|
+
const store = new AsyncLocalStorage;
|
|
25
|
+
globalRecord[symbol] = store;
|
|
26
|
+
return store;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ../../src/core/database/connectionContext.ts
|
|
30
|
+
var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
|
|
31
|
+
function runWithDatabaseConnection(connection, callback) {
|
|
32
|
+
return activeConnection.run(connection, callback);
|
|
33
|
+
}
|
|
34
|
+
function getActiveDatabaseConnection(fallback) {
|
|
35
|
+
return activeConnection.getStore() ?? fallback;
|
|
36
|
+
}
|
|
37
|
+
function hasActiveDatabaseConnection() {
|
|
38
|
+
return activeConnection.getStore() !== undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ../../src/core/database/queryProxy.ts
|
|
42
|
+
var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
|
|
43
|
+
function createDatabaseQueryProxy(pool) {
|
|
44
|
+
function resolveDatabase() {
|
|
45
|
+
return getActiveDatabaseConnection(pool);
|
|
46
|
+
}
|
|
47
|
+
function resolveDatabaseForProperty(property) {
|
|
48
|
+
if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
|
|
49
|
+
return pool;
|
|
50
|
+
}
|
|
51
|
+
return resolveDatabase();
|
|
52
|
+
}
|
|
53
|
+
return new Proxy(function database() {}, {
|
|
54
|
+
apply(_target, _thisArg, args) {
|
|
55
|
+
return resolveDatabase()(...args);
|
|
56
|
+
},
|
|
57
|
+
get(_target, property) {
|
|
58
|
+
const connection = resolveDatabaseForProperty(property);
|
|
59
|
+
const value = connection[property];
|
|
60
|
+
return typeof value === "function" ? value.bind(connection) : value;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ../../src/core/database/defaultConnection.ts
|
|
66
|
+
var defaultPool = {
|
|
67
|
+
connection: null
|
|
68
|
+
};
|
|
69
|
+
var defaultQuery = {
|
|
70
|
+
connection: null
|
|
71
|
+
};
|
|
72
|
+
function registerDefaultDatabasePool(connection) {
|
|
73
|
+
defaultPool.connection = connection;
|
|
74
|
+
defaultQuery.connection = createDatabaseQueryProxy(connection);
|
|
75
|
+
}
|
|
76
|
+
function getDefaultDatabasePool() {
|
|
77
|
+
if (!defaultPool.connection) {
|
|
78
|
+
throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
79
|
+
}
|
|
80
|
+
return defaultPool.connection;
|
|
81
|
+
}
|
|
82
|
+
function getDefaultDatabaseQuery() {
|
|
83
|
+
if (!defaultQuery.connection) {
|
|
84
|
+
throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
85
|
+
}
|
|
86
|
+
return defaultQuery.connection;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ../../src/db/connection/createConnection.ts
|
|
90
|
+
var {SQL } = globalThis.Bun;
|
|
91
|
+
function createDatabaseConnection(config) {
|
|
92
|
+
if (!config.url) {
|
|
93
|
+
throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
|
|
94
|
+
}
|
|
95
|
+
return new SQL({
|
|
96
|
+
url: config.url,
|
|
97
|
+
max: config.poolMax,
|
|
98
|
+
idleTimeout: config.idleTimeoutSeconds,
|
|
99
|
+
maxLifetime: config.maxLifetimeSeconds,
|
|
100
|
+
connectionTimeout: config.connectionTimeoutSeconds
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ../../src/db/connection/index.ts
|
|
105
|
+
var connectionHolder = {
|
|
106
|
+
connection: null
|
|
107
|
+
};
|
|
108
|
+
function getDatabase() {
|
|
109
|
+
if (!connectionHolder.connection) {
|
|
110
|
+
connectionHolder.connection = createDatabaseConnection(databaseConfig);
|
|
111
|
+
registerDefaultDatabasePool(connectionHolder.connection);
|
|
112
|
+
}
|
|
113
|
+
return connectionHolder.connection;
|
|
114
|
+
}
|
|
115
|
+
function getDb() {
|
|
116
|
+
getDatabase();
|
|
117
|
+
return getDefaultDatabaseQuery();
|
|
118
|
+
}
|
|
119
|
+
var db = new Proxy(function database() {}, {
|
|
120
|
+
apply(_target, _thisArg, args) {
|
|
121
|
+
return getDb()(...args);
|
|
122
|
+
},
|
|
123
|
+
get(_target, property) {
|
|
124
|
+
const connection = getDb();
|
|
125
|
+
const value = connection[property];
|
|
126
|
+
return typeof value === "function" ? value.bind(connection) : value;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
var connection_default = db;
|
|
130
|
+
|
|
131
|
+
// ../../src/modules/organization/memberRepository.ts
|
|
132
|
+
class OrganizationMemberRepository {
|
|
133
|
+
constructor() {}
|
|
134
|
+
async findMembership(userId, organizationId) {
|
|
135
|
+
const rows = await connection_default`
|
|
136
|
+
SELECT id, organization_id, user_id, role, created_at
|
|
137
|
+
FROM organization_member
|
|
138
|
+
WHERE user_id = ${userId} AND organization_id = ${organizationId}
|
|
139
|
+
LIMIT 1
|
|
140
|
+
`;
|
|
141
|
+
return rows[0] ?? null;
|
|
142
|
+
}
|
|
143
|
+
async listForUser(userId) {
|
|
144
|
+
return await connection_default`
|
|
145
|
+
SELECT id, organization_id, user_id, role, created_at
|
|
146
|
+
FROM organization_member
|
|
147
|
+
WHERE user_id = ${userId}
|
|
148
|
+
ORDER BY organization_id
|
|
149
|
+
`;
|
|
150
|
+
}
|
|
151
|
+
async listForOrganization(organizationId) {
|
|
152
|
+
return await connection_default`
|
|
153
|
+
SELECT id, organization_id, user_id, role, created_at
|
|
154
|
+
FROM organization_member
|
|
155
|
+
WHERE organization_id = ${organizationId}
|
|
156
|
+
ORDER BY id
|
|
157
|
+
`;
|
|
158
|
+
}
|
|
159
|
+
async addMember(input) {
|
|
160
|
+
const rows = await connection_default`
|
|
161
|
+
INSERT INTO organization_member (organization_id, user_id, role)
|
|
162
|
+
VALUES (${input.organizationId}, ${input.userId}, ${input.role ?? "member"})
|
|
163
|
+
RETURNING id, organization_id, user_id, role, created_at
|
|
164
|
+
`;
|
|
165
|
+
const row = rows[0];
|
|
166
|
+
if (!row) {
|
|
167
|
+
throw new Error("Organization member insert did not return a row.");
|
|
168
|
+
}
|
|
169
|
+
return row;
|
|
170
|
+
}
|
|
171
|
+
async removeMember(organizationId, userId) {
|
|
172
|
+
const rows = await connection_default`
|
|
173
|
+
DELETE FROM organization_member
|
|
174
|
+
WHERE organization_id = ${organizationId} AND user_id = ${userId}
|
|
175
|
+
RETURNING id
|
|
176
|
+
`;
|
|
177
|
+
return rows.length > 0;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
var memberRepository_default = OrganizationMemberRepository;
|
|
181
|
+
|
|
182
|
+
// ../../src/core/errors/http.ts
|
|
183
|
+
class HttpError extends Error {
|
|
184
|
+
status;
|
|
185
|
+
details;
|
|
186
|
+
constructor(status, message, details) {
|
|
187
|
+
super(message);
|
|
188
|
+
this.name = new.target.name;
|
|
189
|
+
this.status = status;
|
|
190
|
+
this.details = details;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
class BadRequestError extends HttpError {
|
|
195
|
+
constructor(message = "Bad Request", details) {
|
|
196
|
+
super(400, message, details);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
class NotFoundError extends HttpError {
|
|
201
|
+
constructor(message = "Not Found", details) {
|
|
202
|
+
super(404, message, details);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
class ConflictError extends HttpError {
|
|
207
|
+
constructor(message = "Conflict", details) {
|
|
208
|
+
super(409, message, details);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
class UnprocessableEntityError extends HttpError {
|
|
213
|
+
constructor(message = "Unprocessable Entity", details) {
|
|
214
|
+
super(422, message, details);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
class ValidationError extends HttpError {
|
|
219
|
+
constructor(message = "Validation failed", details) {
|
|
220
|
+
super(422, message, details);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
class ForbiddenError extends HttpError {
|
|
225
|
+
constructor(message = "Forbidden", details) {
|
|
226
|
+
super(403, message, details);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
class UnauthorizedError extends HttpError {
|
|
231
|
+
constructor(message = "Unauthorized", details) {
|
|
232
|
+
super(401, message, details);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
class PayloadTooLargeError extends HttpError {
|
|
237
|
+
constructor(message = "Payload Too Large", details) {
|
|
238
|
+
super(413, message, details);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
class PreconditionFailedError extends HttpError {
|
|
243
|
+
constructor(message = "Precondition Failed", details) {
|
|
244
|
+
super(412, message, details);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ../../src/core/auth/authContext.ts
|
|
249
|
+
var authContext = createAsyncContextStore("@getstrata/authContext");
|
|
250
|
+
function runWithAuthUser(user, callback) {
|
|
251
|
+
return authContext.run(user, callback);
|
|
252
|
+
}
|
|
253
|
+
function currentAuthUser() {
|
|
254
|
+
return authContext.getStore() ?? null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ../../src/core/auth/accessControl.ts
|
|
258
|
+
function isGlobalAdmin(user) {
|
|
259
|
+
return user?.role === "admin";
|
|
260
|
+
}
|
|
261
|
+
function resolveUserId(user) {
|
|
262
|
+
const userId = typeof user.id === "number" ? user.id : Number(user.id);
|
|
263
|
+
if (!Number.isInteger(userId) || userId <= 0) {
|
|
264
|
+
throw new ForbiddenError("Invalid authenticated user.");
|
|
265
|
+
}
|
|
266
|
+
return userId;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ../../src/core/auth/membershipContext.ts
|
|
270
|
+
var membershipContext = createAsyncContextStore("@getstrata/membershipContext");
|
|
271
|
+
var membershipRepository = new memberRepository_default;
|
|
272
|
+
async function runWithMembershipContext(callback) {
|
|
273
|
+
const user = currentAuthUser();
|
|
274
|
+
if (!user || isGlobalAdmin(user)) {
|
|
275
|
+
return await callback();
|
|
276
|
+
}
|
|
277
|
+
const memberships = await membershipRepository.listForUser(resolveUserId(user));
|
|
278
|
+
const context = {
|
|
279
|
+
organizationIds: memberships.map((membership) => membership.organization_id),
|
|
280
|
+
rolesByOrganizationId: new Map(memberships.map((membership) => [membership.organization_id, membership.role]))
|
|
281
|
+
};
|
|
282
|
+
return await membershipContext.run(context, callback);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ../../src/core/auth/membershipContextMiddleware.ts
|
|
286
|
+
function createMembershipContextMiddleware() {
|
|
287
|
+
return async (_request, next) => {
|
|
288
|
+
return await runWithMembershipContext(async () => await next());
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ../../src/core/auth/membershipMiddleware.ts
|
|
293
|
+
function createMembershipMiddleware() {
|
|
294
|
+
return createMembershipContextMiddleware();
|
|
295
|
+
}
|
|
296
|
+
export {
|
|
297
|
+
createMembershipMiddleware
|
|
298
|
+
};
|
|
@@ -0,0 +1,251 @@
|
|
|
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
|
+
function rateLimitMultiplierForPlan(plan) {
|
|
181
|
+
switch (plan) {
|
|
182
|
+
case "enterprise":
|
|
183
|
+
return 4;
|
|
184
|
+
case "pro":
|
|
185
|
+
return 2;
|
|
186
|
+
default:
|
|
187
|
+
return 1;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ../../src/core/tenant/tenantDatabaseScope.ts
|
|
192
|
+
async function applyTenantContextToTransaction(transaction, tenantId) {
|
|
193
|
+
await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
|
|
194
|
+
await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
|
|
195
|
+
}
|
|
196
|
+
async function runWithTenantDatabase(tenant, callback) {
|
|
197
|
+
if (hasActiveDatabaseConnection()) {
|
|
198
|
+
const activeConnection2 = getActiveDatabaseConnection(getDefaultDatabasePool());
|
|
199
|
+
await applyTenantContextToTransaction(activeConnection2, tenant.id);
|
|
200
|
+
return await runWithTenant(tenant, callback);
|
|
201
|
+
}
|
|
202
|
+
return await getDefaultDatabasePool().begin(async (transaction) => {
|
|
203
|
+
await applyTenantContextToTransaction(transaction, tenant.id);
|
|
204
|
+
return await runWithDatabaseConnection(transaction, async () => {
|
|
205
|
+
return await runWithTenant(tenant, callback);
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
|
|
210
|
+
return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ../../src/core/auth/scimAuthMiddleware.ts
|
|
214
|
+
function createScimAuthMiddleware() {
|
|
215
|
+
return async (request, next) => {
|
|
216
|
+
const authorization = request.headers.get("authorization");
|
|
217
|
+
if (!authorization?.startsWith("Bearer ")) {
|
|
218
|
+
return jsonScimError("SCIM bearer token required.", 401);
|
|
219
|
+
}
|
|
220
|
+
const token = authorization.slice("Bearer ".length).trim();
|
|
221
|
+
const tenantId = resolveScimTenantFromToken(token);
|
|
222
|
+
if (tenantId === null) {
|
|
223
|
+
return jsonScimError("Invalid SCIM bearer token.", 401);
|
|
224
|
+
}
|
|
225
|
+
const tenant = await resolveTenant(tenantId);
|
|
226
|
+
if (!tenant) {
|
|
227
|
+
return jsonScimError("SCIM tenant not found.", 401);
|
|
228
|
+
}
|
|
229
|
+
return await runWithTenantDatabase(tenant, async () => {
|
|
230
|
+
bindDatabaseConnection2(getActiveDatabaseConnection(getDefaultDatabasePool()));
|
|
231
|
+
try {
|
|
232
|
+
return await next();
|
|
233
|
+
} finally {
|
|
234
|
+
resetBoundDatabaseConnection();
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function jsonScimError(detail, status) {
|
|
240
|
+
return Response.json({
|
|
241
|
+
schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
|
|
242
|
+
detail,
|
|
243
|
+
status: String(status)
|
|
244
|
+
}, {
|
|
245
|
+
status,
|
|
246
|
+
headers: { "content-type": "application/scim+json" }
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
export {
|
|
250
|
+
createScimAuthMiddleware
|
|
251
|
+
};
|