@getstrata/core 0.5.53 → 0.5.55
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/README.md +18 -14
- package/dist/core/http/index.d.ts +5 -10
- package/dist/core/http/response.d.ts +6 -0
- package/dist/core/queue/failedJobRepository.d.ts +1 -1
- package/dist/core/queue/failedJobTable.d.ts +1 -1
- package/dist/entries/auth/sessionGuard.js +8 -7
- package/dist/entries/http/response.js +880 -0
- package/dist/entries/http/webErrorResponse.js +8 -7
- package/dist/entries/queue/createAppQueue.js +2 -2
- package/dist/entries/queue/failedJobRepository.js +2 -2
- package/dist/entries/queue/publicQueue.js +2 -2
- package/dist/entries/queue/queueMetrics.js +2 -2
- package/dist/entries/view.js +8 -7
- package/dist/framework/public-api.d.ts +2 -1
- package/dist/index.js +2472 -2470
- package/dist/modules/user/apiTokenRepository.d.ts +1 -1
- package/dist/modules/user/apiTokenTable.d.ts +1 -1
- package/dist/modules/user/notificationRepository.d.ts +1 -1
- package/dist/modules/user/notificationTable.d.ts +1 -1
- package/dist/modules/user/oauthIdentityRepository.d.ts +2 -2
- package/dist/modules/user/repository.d.ts +1 -1
- package/dist/modules/user/table.d.ts +1 -1
- package/package.json +7 -2
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../src/core/http/response.ts
|
|
3
|
+
import { HttpError as HttpError3 } from "@getstrata/core/errors/http";
|
|
4
|
+
|
|
5
|
+
// ../../src/core/database/errors.ts
|
|
6
|
+
import {
|
|
7
|
+
BadRequestError,
|
|
8
|
+
ConflictError,
|
|
9
|
+
HttpError,
|
|
10
|
+
UnprocessableEntityError
|
|
11
|
+
} from "@getstrata/core/errors/http";
|
|
12
|
+
function isPostgresError(error) {
|
|
13
|
+
return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
|
|
14
|
+
}
|
|
15
|
+
function getPostgresSqlState(error) {
|
|
16
|
+
if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
|
|
17
|
+
return error.errno;
|
|
18
|
+
}
|
|
19
|
+
if (typeof error.errno === "number") {
|
|
20
|
+
return String(error.errno).padStart(5, "0");
|
|
21
|
+
}
|
|
22
|
+
if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
|
|
23
|
+
return error.code;
|
|
24
|
+
}
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
function mapDatabaseError(error) {
|
|
28
|
+
if (error instanceof HttpError) {
|
|
29
|
+
return error;
|
|
30
|
+
}
|
|
31
|
+
if (!isPostgresError(error)) {
|
|
32
|
+
const message = error instanceof Error ? error.message : "Database operation failed.";
|
|
33
|
+
return new BadRequestError(message);
|
|
34
|
+
}
|
|
35
|
+
const sqlState = getPostgresSqlState(error);
|
|
36
|
+
switch (sqlState) {
|
|
37
|
+
case "23505":
|
|
38
|
+
return new ConflictError(error.detail ?? "A record with these values already exists.", {
|
|
39
|
+
constraint: error.constraint
|
|
40
|
+
});
|
|
41
|
+
case "23503":
|
|
42
|
+
return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
|
|
43
|
+
constraint: error.constraint
|
|
44
|
+
});
|
|
45
|
+
case "23502":
|
|
46
|
+
return new BadRequestError(error.detail ?? "Required field is missing.", {
|
|
47
|
+
constraint: error.constraint
|
|
48
|
+
});
|
|
49
|
+
case "23514":
|
|
50
|
+
return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
|
|
51
|
+
constraint: error.constraint
|
|
52
|
+
});
|
|
53
|
+
default:
|
|
54
|
+
return new BadRequestError(error.message ?? "Database operation failed.", {
|
|
55
|
+
code: error.code,
|
|
56
|
+
sqlState
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function withDatabaseErrorHandling(operation) {
|
|
61
|
+
try {
|
|
62
|
+
return await operation();
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw mapDatabaseError(error);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ../../src/core/http/webErrorResponse.ts
|
|
69
|
+
import { HttpError as HttpError2, UnauthorizedError as UnauthorizedError2, ValidationError } from "@getstrata/core/errors/http";
|
|
70
|
+
|
|
71
|
+
// ../../src/config/frontend.ts
|
|
72
|
+
function readFrontendMode() {
|
|
73
|
+
const mode = (process.env.FRONTEND_MODE ?? "api").trim();
|
|
74
|
+
if (mode === "server-htmx") {
|
|
75
|
+
return "server-htmx";
|
|
76
|
+
}
|
|
77
|
+
if (mode === "spa-react") {
|
|
78
|
+
return "spa-react";
|
|
79
|
+
}
|
|
80
|
+
return "api";
|
|
81
|
+
}
|
|
82
|
+
function isViewsEnabled() {
|
|
83
|
+
return readFrontendMode() === "server-htmx";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ../../src/core/view/etaViewEngine.ts
|
|
87
|
+
import { join } from "path";
|
|
88
|
+
import { Eta } from "eta";
|
|
89
|
+
var DEFAULT_VIEWS_DIRECTORY = join(process.cwd(), "resources/views");
|
|
90
|
+
var DEFAULT_LAYOUT = "layouts/app.eta";
|
|
91
|
+
|
|
92
|
+
class EtaViewEngine {
|
|
93
|
+
eta;
|
|
94
|
+
resolveLayoutData;
|
|
95
|
+
constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
|
|
96
|
+
this.eta = new Eta({
|
|
97
|
+
views: viewsDirectory,
|
|
98
|
+
autoTrim: false
|
|
99
|
+
});
|
|
100
|
+
this.resolveLayoutData = resolveLayoutData;
|
|
101
|
+
}
|
|
102
|
+
async render(name, data = {}, options = {}) {
|
|
103
|
+
const template = name.endsWith(".eta") ? name : `${name}.eta`;
|
|
104
|
+
const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
|
|
105
|
+
const mergedData = { ...layoutData, ...data };
|
|
106
|
+
const body = await this.eta.renderAsync(template, mergedData);
|
|
107
|
+
const layout = options.layout ?? DEFAULT_LAYOUT;
|
|
108
|
+
if (layout === false) {
|
|
109
|
+
return body;
|
|
110
|
+
}
|
|
111
|
+
const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
|
|
112
|
+
return await this.eta.renderAsync(layoutTemplate, {
|
|
113
|
+
...mergedData,
|
|
114
|
+
body
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// ../../src/core/view/htmlResponse.ts
|
|
119
|
+
function htmlResponse(html, init = {}) {
|
|
120
|
+
return new Response(html, {
|
|
121
|
+
status: init.status ?? 200,
|
|
122
|
+
statusText: init.statusText,
|
|
123
|
+
headers: {
|
|
124
|
+
"Content-Type": "text/html; charset=utf-8"
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
function isHtmxRequest(request) {
|
|
129
|
+
return request.headers.get("HX-Request") === "true";
|
|
130
|
+
}
|
|
131
|
+
// ../../src/core/view/webLayoutData.ts
|
|
132
|
+
import { currentAuthUser } from "@getstrata/core/auth/authContext";
|
|
133
|
+
import { currentRequestMeta as currentRequestMeta2 } from "@getstrata/core/http/requestMetaContext";
|
|
134
|
+
|
|
135
|
+
// ../../src/bootstrap/config.ts
|
|
136
|
+
import {
|
|
137
|
+
CORE_AUTH_TOKEN,
|
|
138
|
+
CORE_CACHE_TOKEN,
|
|
139
|
+
CORE_CONFIG_TOKEN,
|
|
140
|
+
CORE_EVENT_BUS_TOKEN,
|
|
141
|
+
CORE_POLICY_GATE_TOKEN,
|
|
142
|
+
CORE_QUEUE_TOKEN,
|
|
143
|
+
CORE_TOKEN_SERVICE_TOKEN
|
|
144
|
+
} from "@getstrata/core/contracts/serviceTokens";
|
|
145
|
+
var DEFAULT_QUEUE_DRIVER = "sync";
|
|
146
|
+
|
|
147
|
+
// ../../src/modules/user/provider.ts
|
|
148
|
+
import { OidcProvider } from "@getstrata/core/auth/oauth/oidcProvider";
|
|
149
|
+
import { GitHubOAuthProvider, MockOAuthProvider } from "@getstrata/core/auth/oauth/providers";
|
|
150
|
+
import { SamlProvider } from "@getstrata/core/auth/oauth/samlProvider";
|
|
151
|
+
|
|
152
|
+
// ../../src/config/features.ts
|
|
153
|
+
function readFeatureFlags() {
|
|
154
|
+
return {
|
|
155
|
+
webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
|
|
156
|
+
fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
|
|
157
|
+
auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
|
|
158
|
+
oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
|
|
159
|
+
samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
|
|
160
|
+
scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
|
|
161
|
+
billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
|
|
162
|
+
siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
|
|
163
|
+
publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
|
|
164
|
+
emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
|
|
165
|
+
mfa: (process.env.FEATURE_MFA ?? "false") === "true"
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
var featureFlags = readFeatureFlags();
|
|
169
|
+
function isFeatureEnabled(feature) {
|
|
170
|
+
return readFeatureFlags()[feature];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ../../src/modules/user/apiTokenRepository.ts
|
|
174
|
+
import { BaseRepository } from "@getstrata/core/database/baseRepository";
|
|
175
|
+
|
|
176
|
+
// ../../src/config/database.ts
|
|
177
|
+
function readInteger(name, fallback) {
|
|
178
|
+
const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
|
|
179
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
|
180
|
+
}
|
|
181
|
+
var databaseConfig = {
|
|
182
|
+
url: process.env.DATABASE_URL ?? "",
|
|
183
|
+
poolMax: readInteger("DB_POOL_MAX", 10),
|
|
184
|
+
idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
|
|
185
|
+
maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
|
|
186
|
+
connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// ../../src/core/runtime/asyncContextStore.ts
|
|
190
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
191
|
+
function createAsyncContextStore(key) {
|
|
192
|
+
const symbol = Symbol.for(key);
|
|
193
|
+
const globalRecord = globalThis;
|
|
194
|
+
const existing = globalRecord[symbol];
|
|
195
|
+
if (existing) {
|
|
196
|
+
return existing;
|
|
197
|
+
}
|
|
198
|
+
const store = new AsyncLocalStorage;
|
|
199
|
+
globalRecord[symbol] = store;
|
|
200
|
+
return store;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ../../src/core/database/connectionContext.ts
|
|
204
|
+
var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
|
|
205
|
+
function runWithDatabaseConnection(connection, callback) {
|
|
206
|
+
return activeConnection.run(connection, callback);
|
|
207
|
+
}
|
|
208
|
+
function getActiveDatabaseConnection(fallback) {
|
|
209
|
+
return activeConnection.getStore() ?? fallback;
|
|
210
|
+
}
|
|
211
|
+
function hasActiveDatabaseConnection() {
|
|
212
|
+
return activeConnection.getStore() !== undefined;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ../../src/core/database/queryProxy.ts
|
|
216
|
+
var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
|
|
217
|
+
function createDatabaseQueryProxy(pool) {
|
|
218
|
+
function resolveDatabase() {
|
|
219
|
+
return getActiveDatabaseConnection(pool);
|
|
220
|
+
}
|
|
221
|
+
function resolveDatabaseForProperty(property) {
|
|
222
|
+
if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
|
|
223
|
+
return pool;
|
|
224
|
+
}
|
|
225
|
+
return resolveDatabase();
|
|
226
|
+
}
|
|
227
|
+
return new Proxy(function database() {}, {
|
|
228
|
+
apply(_target, _thisArg, args) {
|
|
229
|
+
return resolveDatabase()(...args);
|
|
230
|
+
},
|
|
231
|
+
get(_target, property) {
|
|
232
|
+
const connection = resolveDatabaseForProperty(property);
|
|
233
|
+
const value = connection[property];
|
|
234
|
+
return typeof value === "function" ? value.bind(connection) : value;
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ../../src/core/database/defaultConnection.ts
|
|
240
|
+
var defaultPool = {
|
|
241
|
+
connection: null
|
|
242
|
+
};
|
|
243
|
+
var defaultQuery = {
|
|
244
|
+
connection: null
|
|
245
|
+
};
|
|
246
|
+
function registerDefaultDatabasePool(connection) {
|
|
247
|
+
defaultPool.connection = connection;
|
|
248
|
+
defaultQuery.connection = createDatabaseQueryProxy(connection);
|
|
249
|
+
}
|
|
250
|
+
function getDefaultDatabaseQuery() {
|
|
251
|
+
if (!defaultQuery.connection) {
|
|
252
|
+
throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
|
|
253
|
+
}
|
|
254
|
+
return defaultQuery.connection;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ../../src/db/connection/createConnection.ts
|
|
258
|
+
var {SQL } = globalThis.Bun;
|
|
259
|
+
function createDatabaseConnection(config) {
|
|
260
|
+
if (!config.url) {
|
|
261
|
+
throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
|
|
262
|
+
}
|
|
263
|
+
return new SQL({
|
|
264
|
+
url: config.url,
|
|
265
|
+
max: config.poolMax,
|
|
266
|
+
idleTimeout: config.idleTimeoutSeconds,
|
|
267
|
+
maxLifetime: config.maxLifetimeSeconds,
|
|
268
|
+
connectionTimeout: config.connectionTimeoutSeconds
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ../../src/db/connection/index.ts
|
|
273
|
+
var connectionHolder = {
|
|
274
|
+
connection: null
|
|
275
|
+
};
|
|
276
|
+
function getDatabase() {
|
|
277
|
+
if (!connectionHolder.connection) {
|
|
278
|
+
connectionHolder.connection = createDatabaseConnection(databaseConfig);
|
|
279
|
+
registerDefaultDatabasePool(connectionHolder.connection);
|
|
280
|
+
}
|
|
281
|
+
return connectionHolder.connection;
|
|
282
|
+
}
|
|
283
|
+
function getDb() {
|
|
284
|
+
getDatabase();
|
|
285
|
+
return getDefaultDatabaseQuery();
|
|
286
|
+
}
|
|
287
|
+
var db = new Proxy(function database() {}, {
|
|
288
|
+
apply(_target, _thisArg, args) {
|
|
289
|
+
return getDb()(...args);
|
|
290
|
+
},
|
|
291
|
+
get(_target, property) {
|
|
292
|
+
const connection = getDb();
|
|
293
|
+
const value = connection[property];
|
|
294
|
+
return typeof value === "function" ? value.bind(connection) : value;
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
var connection_default = db;
|
|
298
|
+
|
|
299
|
+
// ../../src/modules/user/apiTokenTable.ts
|
|
300
|
+
import { defineTable } from "@getstrata/core/database/table";
|
|
301
|
+
var apiTokenTable = defineTable({
|
|
302
|
+
name: "api_token",
|
|
303
|
+
primaryKey: "id",
|
|
304
|
+
columns: [
|
|
305
|
+
"id",
|
|
306
|
+
"user_id",
|
|
307
|
+
"name",
|
|
308
|
+
"token_hash",
|
|
309
|
+
"abilities",
|
|
310
|
+
"last_used_at",
|
|
311
|
+
"expires_at",
|
|
312
|
+
"created_at"
|
|
313
|
+
],
|
|
314
|
+
defaultOrderBy: { column: "id", direction: "ASC" }
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// ../../src/modules/user/authService.ts
|
|
318
|
+
import { verifyPassword } from "@getstrata/core/auth/password";
|
|
319
|
+
import { revealMfaSecret } from "@getstrata/core/crypto/mfaSecret";
|
|
320
|
+
import { UnauthorizedError } from "@getstrata/core/errors/http";
|
|
321
|
+
import { logSecurityEvent } from "@getstrata/core/security/securityEvents";
|
|
322
|
+
import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
|
|
323
|
+
import { verifyTotp } from "@getstrata/core/security/totp";
|
|
324
|
+
import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
|
|
325
|
+
|
|
326
|
+
// ../../src/domain/abilities.ts
|
|
327
|
+
var MEMBER_ABILITIES = [
|
|
328
|
+
"organizations:read",
|
|
329
|
+
"projects:read",
|
|
330
|
+
"projects:create",
|
|
331
|
+
"tasks:read",
|
|
332
|
+
"tasks:create",
|
|
333
|
+
"comments:read",
|
|
334
|
+
"comments:create",
|
|
335
|
+
"attachments:read",
|
|
336
|
+
"attachments:create",
|
|
337
|
+
"auth:tokens:read",
|
|
338
|
+
"auth:tokens:write"
|
|
339
|
+
];
|
|
340
|
+
var ADMIN_ABILITIES = [
|
|
341
|
+
...MEMBER_ABILITIES,
|
|
342
|
+
"organizations:create",
|
|
343
|
+
"organizations:update",
|
|
344
|
+
"organizations:delete",
|
|
345
|
+
"projects:update",
|
|
346
|
+
"projects:delete",
|
|
347
|
+
"tasks:update",
|
|
348
|
+
"tasks:delete",
|
|
349
|
+
"comments:update",
|
|
350
|
+
"comments:delete",
|
|
351
|
+
"attachments:delete",
|
|
352
|
+
"webhooks:read",
|
|
353
|
+
"webhooks:write",
|
|
354
|
+
"audit:read"
|
|
355
|
+
];
|
|
356
|
+
var PLATFORM_ADMIN_ABILITIES = ["*"];
|
|
357
|
+
function resolveAbilitiesForRole(role) {
|
|
358
|
+
if (role === "admin") {
|
|
359
|
+
return [...PLATFORM_ADMIN_ABILITIES];
|
|
360
|
+
}
|
|
361
|
+
return [...MEMBER_ABILITIES];
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ../../src/modules/user/authService.ts
|
|
365
|
+
class AuthService {
|
|
366
|
+
users;
|
|
367
|
+
tokens;
|
|
368
|
+
oauthIdentities;
|
|
369
|
+
oauthProviders = new Map;
|
|
370
|
+
constructor(users, tokens, oauthIdentities) {
|
|
371
|
+
this.users = users;
|
|
372
|
+
this.tokens = tokens;
|
|
373
|
+
this.oauthIdentities = oauthIdentities;
|
|
374
|
+
}
|
|
375
|
+
registerOAuthProvider(provider) {
|
|
376
|
+
this.oauthProviders.set(provider.name, provider);
|
|
377
|
+
}
|
|
378
|
+
getOAuthProvider(name) {
|
|
379
|
+
return this.oauthProviders.get(name);
|
|
380
|
+
}
|
|
381
|
+
async loginWithPassword(email, password, options = {}) {
|
|
382
|
+
const user = await this.users.findByEmail(email);
|
|
383
|
+
if (!user?.password_hash) {
|
|
384
|
+
logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
|
|
385
|
+
throw new UnauthorizedError("Invalid credentials.");
|
|
386
|
+
}
|
|
387
|
+
const valid = await verifyPassword(password, user.password_hash);
|
|
388
|
+
if (!valid) {
|
|
389
|
+
logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
|
|
390
|
+
throw new UnauthorizedError("Invalid credentials.");
|
|
391
|
+
}
|
|
392
|
+
if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
|
|
393
|
+
logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
|
|
394
|
+
throw new UnauthorizedError("Email address is not verified.");
|
|
395
|
+
}
|
|
396
|
+
if (isFeatureEnabled("mfa") && user.mfa_enabled) {
|
|
397
|
+
const mfaSecret = revealMfaSecret(user.mfa_secret);
|
|
398
|
+
if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
|
|
399
|
+
logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
|
|
400
|
+
throw new UnauthorizedError("Invalid MFA code.");
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
|
|
404
|
+
return await this.tokens.createToken(user.id, {
|
|
405
|
+
name: "password-login",
|
|
406
|
+
abilities: resolveAbilitiesForRole(user.role),
|
|
407
|
+
expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
async loginWithOAuth(providerName, code) {
|
|
411
|
+
const provider = this.oauthProviders.get(providerName);
|
|
412
|
+
if (!provider) {
|
|
413
|
+
throw new UnauthorizedError("Unsupported OAuth provider.");
|
|
414
|
+
}
|
|
415
|
+
const profile = await provider.exchangeCode(code);
|
|
416
|
+
const user = await this.findOrCreateOAuthUser(providerName, profile);
|
|
417
|
+
logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
|
|
418
|
+
return await this.tokens.createToken(user.id, {
|
|
419
|
+
name: `${providerName}-oauth`,
|
|
420
|
+
abilities: resolveAbilitiesForRole(user.role),
|
|
421
|
+
expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
buildOAuthAuthorizationUrl(providerName, state) {
|
|
425
|
+
const provider = this.oauthProviders.get(providerName);
|
|
426
|
+
if (!provider) {
|
|
427
|
+
throw new UnauthorizedError("Unsupported OAuth provider.");
|
|
428
|
+
}
|
|
429
|
+
return provider.getAuthorizationUrl(state);
|
|
430
|
+
}
|
|
431
|
+
async findOrCreateOAuthUser(providerName, profile) {
|
|
432
|
+
const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
|
|
433
|
+
if (existingIdentity) {
|
|
434
|
+
return await this.users.findByIdOrThrow(existingIdentity.user_id);
|
|
435
|
+
}
|
|
436
|
+
const existingUser = await this.users.findByEmail(profile.email);
|
|
437
|
+
const user = existingUser ?? await this.users.create({
|
|
438
|
+
name: profile.name,
|
|
439
|
+
email: profile.email,
|
|
440
|
+
role: "member",
|
|
441
|
+
tenant_id: currentTenantId(),
|
|
442
|
+
email_verified_at: new Date,
|
|
443
|
+
created_at: new Date,
|
|
444
|
+
updated_at: new Date
|
|
445
|
+
});
|
|
446
|
+
await this.oauthIdentities.create({
|
|
447
|
+
user_id: user.id,
|
|
448
|
+
provider: providerName,
|
|
449
|
+
provider_user_id: profile.providerUserId,
|
|
450
|
+
email: profile.email,
|
|
451
|
+
created_at: new Date
|
|
452
|
+
});
|
|
453
|
+
return user;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// ../../src/modules/user/notificationRepository.ts
|
|
458
|
+
import { BaseRepository as BaseRepository2 } from "@getstrata/core/database/baseRepository";
|
|
459
|
+
|
|
460
|
+
// ../../src/modules/user/notificationTable.ts
|
|
461
|
+
import { defineTable as defineTable2 } from "@getstrata/core/database/table";
|
|
462
|
+
var notificationTable = defineTable2({
|
|
463
|
+
name: "notification",
|
|
464
|
+
primaryKey: "id",
|
|
465
|
+
columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
|
|
466
|
+
defaultOrderBy: { column: "created_at", direction: "DESC" }
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
// ../../src/modules/user/notificationService.ts
|
|
470
|
+
import { NotFoundError } from "@getstrata/core/errors/http";
|
|
471
|
+
|
|
472
|
+
// ../../src/modules/user/oauthIdentityRepository.ts
|
|
473
|
+
import { BaseRepository as BaseRepository3 } from "@getstrata/core/database/baseRepository";
|
|
474
|
+
import { defineTable as defineTable3 } from "@getstrata/core/database/table";
|
|
475
|
+
var oauthIdentityTable = defineTable3({
|
|
476
|
+
name: "oauth_identity",
|
|
477
|
+
primaryKey: "id",
|
|
478
|
+
columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
// ../../src/modules/user/repository.ts
|
|
482
|
+
import {
|
|
483
|
+
emailLookupForQuery,
|
|
484
|
+
protectEmail,
|
|
485
|
+
revealEmail
|
|
486
|
+
} from "@getstrata/core/crypto/fieldEncryption";
|
|
487
|
+
import { revealMfaSecret as revealMfaSecret2 } from "@getstrata/core/crypto/mfaSecret";
|
|
488
|
+
import { BaseRepository as BaseRepository4 } from "@getstrata/core/database/baseRepository";
|
|
489
|
+
import { currentTenantId as currentTenantId2 } from "@getstrata/core/tenant/tenantContext";
|
|
490
|
+
|
|
491
|
+
// ../../src/modules/user/table.ts
|
|
492
|
+
import { defineTable as defineTable4 } from "@getstrata/core/database/table";
|
|
493
|
+
var userTable = defineTable4({
|
|
494
|
+
name: "users",
|
|
495
|
+
primaryKey: "id",
|
|
496
|
+
columns: [
|
|
497
|
+
"id",
|
|
498
|
+
"name",
|
|
499
|
+
"email",
|
|
500
|
+
"email_lookup",
|
|
501
|
+
"role",
|
|
502
|
+
"tenant_id",
|
|
503
|
+
"password_hash",
|
|
504
|
+
"email_verified_at",
|
|
505
|
+
"mfa_secret",
|
|
506
|
+
"mfa_enabled",
|
|
507
|
+
"created_at",
|
|
508
|
+
"updated_at"
|
|
509
|
+
],
|
|
510
|
+
defaultOrderBy: { column: "id", direction: "ASC" }
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
// ../../src/modules/user/tokenService.ts
|
|
514
|
+
import { hashApiToken } from "@getstrata/core/auth/tokenHash";
|
|
515
|
+
import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core/errors/http";
|
|
516
|
+
import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
|
|
517
|
+
|
|
518
|
+
// ../../src/modules/user/provider.ts
|
|
519
|
+
var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
|
|
520
|
+
|
|
521
|
+
// ../../src/core/http/csrfToken.ts
|
|
522
|
+
import { timingSafeEqual } from "crypto";
|
|
523
|
+
|
|
524
|
+
// ../../src/core/http/cookies.ts
|
|
525
|
+
function readRequestCookie(request, name) {
|
|
526
|
+
const cookies = request.cookies;
|
|
527
|
+
if (cookies && typeof cookies.get === "function") {
|
|
528
|
+
const value = cookies.get(name);
|
|
529
|
+
if (value) {
|
|
530
|
+
return value;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const header = request.headers.get("cookie");
|
|
534
|
+
if (!header) {
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
for (const part of header.split(";")) {
|
|
538
|
+
const idx = part.indexOf("=");
|
|
539
|
+
if (idx === -1)
|
|
540
|
+
continue;
|
|
541
|
+
const cookieName = part.slice(0, idx).trim();
|
|
542
|
+
if (cookieName !== name)
|
|
543
|
+
continue;
|
|
544
|
+
return decodeURIComponent(part.slice(idx + 1).trim());
|
|
545
|
+
}
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
function readBunRequestCookie(request, name) {
|
|
549
|
+
return request.cookies.get(name) ?? readRequestCookie(request, name);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// ../../src/core/http/requestMetaContext.ts
|
|
553
|
+
var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
|
|
554
|
+
function runWithRequestMeta(meta, callback) {
|
|
555
|
+
return requestMetaContext.run(meta, callback);
|
|
556
|
+
}
|
|
557
|
+
function currentRequestMeta() {
|
|
558
|
+
return requestMetaContext.getStore() ?? {
|
|
559
|
+
ipAddress: null,
|
|
560
|
+
userAgent: null
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// ../../src/core/http/csrfToken.ts
|
|
565
|
+
var CSRF_COOKIE = "workhub_csrf";
|
|
566
|
+
var CSRF_TTL_MS = 60 * 60 * 1000;
|
|
567
|
+
function resolveCsrfSecret() {
|
|
568
|
+
return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
|
|
569
|
+
}
|
|
570
|
+
function csrfVerifyOptions() {
|
|
571
|
+
return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
|
|
572
|
+
}
|
|
573
|
+
function tokensMatch(left, right) {
|
|
574
|
+
const leftBuffer = Buffer.from(left);
|
|
575
|
+
const rightBuffer = Buffer.from(right);
|
|
576
|
+
if (leftBuffer.length !== rightBuffer.length) {
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
return timingSafeEqual(leftBuffer, rightBuffer);
|
|
580
|
+
}
|
|
581
|
+
function createCsrfTokenCookie() {
|
|
582
|
+
const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
|
|
583
|
+
return {
|
|
584
|
+
token,
|
|
585
|
+
cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
function resolveCsrfToken(request) {
|
|
589
|
+
const cookieValue = readRequestCookie(request, CSRF_COOKIE);
|
|
590
|
+
if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
|
|
591
|
+
return { token: cookieValue };
|
|
592
|
+
}
|
|
593
|
+
return createCsrfTokenCookie();
|
|
594
|
+
}
|
|
595
|
+
function readSubmittedCsrfToken(request) {
|
|
596
|
+
const headerToken = request.headers.get("x-csrf-token")?.trim();
|
|
597
|
+
if (headerToken) {
|
|
598
|
+
return headerToken;
|
|
599
|
+
}
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
async function readSubmittedCsrfTokenFromBody(request) {
|
|
603
|
+
const headerToken = readSubmittedCsrfToken(request);
|
|
604
|
+
if (headerToken) {
|
|
605
|
+
return headerToken;
|
|
606
|
+
}
|
|
607
|
+
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
|
608
|
+
if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
|
|
609
|
+
const formData = await request.clone().formData();
|
|
610
|
+
const field = formData.get("_token");
|
|
611
|
+
if (typeof field === "string" && field.trim().length > 0) {
|
|
612
|
+
return field.trim();
|
|
613
|
+
}
|
|
614
|
+
const legacyField = formData.get("_csrf");
|
|
615
|
+
if (typeof legacyField === "string" && legacyField.trim().length > 0) {
|
|
616
|
+
return legacyField.trim();
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
function verifyCsrfToken(request, submittedToken) {
|
|
622
|
+
if (!submittedToken) {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
const cookieValue = readRequestCookie(request, CSRF_COOKIE);
|
|
626
|
+
if (!cookieValue) {
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
if (!tokensMatch(submittedToken, cookieValue)) {
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
return Bun.CSRF.verify(submittedToken, csrfVerifyOptions());
|
|
633
|
+
}
|
|
634
|
+
function resolveCsrfTokenForRequest(request) {
|
|
635
|
+
const metaToken = currentRequestMeta().csrfToken;
|
|
636
|
+
if (metaToken) {
|
|
637
|
+
return metaToken;
|
|
638
|
+
}
|
|
639
|
+
return resolveCsrfToken(request).token;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// ../../src/core/http/flashSession.ts
|
|
643
|
+
import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
644
|
+
var FLASH_COOKIE = "workhub_flash";
|
|
645
|
+
var FLASH_TTL_MS = 60 * 1000;
|
|
646
|
+
function resolveFlashSecret() {
|
|
647
|
+
return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
|
|
648
|
+
}
|
|
649
|
+
function signFlashPayload(payload, issuedAt) {
|
|
650
|
+
const signature = createHmac("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
|
|
651
|
+
return `${payload}.${issuedAt}.${signature}`;
|
|
652
|
+
}
|
|
653
|
+
function readFlashCookie(request) {
|
|
654
|
+
const cookieHeader = request.headers.get("cookie");
|
|
655
|
+
if (!cookieHeader) {
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
for (const part of cookieHeader.split(";")) {
|
|
659
|
+
const [name, ...rest] = part.trim().split("=");
|
|
660
|
+
if (name === FLASH_COOKIE) {
|
|
661
|
+
return decodeURIComponent(rest.join("="));
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
return null;
|
|
665
|
+
}
|
|
666
|
+
function parseFlashCookie(cookieValue) {
|
|
667
|
+
const parts = cookieValue.split(".");
|
|
668
|
+
if (parts.length < 3) {
|
|
669
|
+
return null;
|
|
670
|
+
}
|
|
671
|
+
const signature = parts.pop();
|
|
672
|
+
const issuedAtRaw = parts.pop();
|
|
673
|
+
const payload = parts.join(".");
|
|
674
|
+
if (!signature || !issuedAtRaw || !payload) {
|
|
675
|
+
return null;
|
|
676
|
+
}
|
|
677
|
+
const issuedAt = Number.parseInt(issuedAtRaw, 10);
|
|
678
|
+
if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
|
|
682
|
+
if (!expectedSignature) {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
const expectedBuffer = Buffer.from(expectedSignature);
|
|
686
|
+
const actualBuffer = Buffer.from(signature);
|
|
687
|
+
if (expectedBuffer.length !== actualBuffer.length) {
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
|
|
691
|
+
return null;
|
|
692
|
+
}
|
|
693
|
+
try {
|
|
694
|
+
const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
695
|
+
if (!parsed?.message || typeof parsed.message !== "string") {
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
|
|
699
|
+
return null;
|
|
700
|
+
}
|
|
701
|
+
return parsed;
|
|
702
|
+
} catch {
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
function createFlashCookie(message) {
|
|
707
|
+
const payload = Buffer.from(JSON.stringify(message), "utf8").toString("base64url");
|
|
708
|
+
const issuedAt = Date.now();
|
|
709
|
+
const value = signFlashPayload(payload, issuedAt);
|
|
710
|
+
return `${FLASH_COOKIE}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=60`;
|
|
711
|
+
}
|
|
712
|
+
function clearFlashCookie() {
|
|
713
|
+
return `${FLASH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
|
|
714
|
+
}
|
|
715
|
+
function pullFlash(request) {
|
|
716
|
+
const cookieValue = readFlashCookie(request);
|
|
717
|
+
if (!cookieValue) {
|
|
718
|
+
return null;
|
|
719
|
+
}
|
|
720
|
+
return parseFlashCookie(cookieValue);
|
|
721
|
+
}
|
|
722
|
+
function flashResponse(response, message) {
|
|
723
|
+
const headers = new Headers(response.headers);
|
|
724
|
+
headers.append("set-cookie", createFlashCookie(message));
|
|
725
|
+
return new Response(response.body, {
|
|
726
|
+
status: response.status,
|
|
727
|
+
statusText: response.statusText,
|
|
728
|
+
headers
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
function withFlashClear(response) {
|
|
732
|
+
const headers = new Headers(response.headers);
|
|
733
|
+
headers.append("set-cookie", clearFlashCookie());
|
|
734
|
+
return new Response(response.body, {
|
|
735
|
+
status: response.status,
|
|
736
|
+
statusText: response.statusText,
|
|
737
|
+
headers
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// ../../src/core/view/webLayoutData.ts
|
|
742
|
+
async function resolveWebLayoutData(container, request) {
|
|
743
|
+
const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
|
|
744
|
+
const flash = request ? currentRequestMeta2().flash ?? pullFlash(request) : null;
|
|
745
|
+
const authUser = currentAuthUser();
|
|
746
|
+
if (!authUser) {
|
|
747
|
+
return { authUser: null, csrfToken, flash };
|
|
748
|
+
}
|
|
749
|
+
const userId = Number(authUser.id);
|
|
750
|
+
if (!Number.isInteger(userId) || userId <= 0) {
|
|
751
|
+
return { authUser: null, csrfToken, flash };
|
|
752
|
+
}
|
|
753
|
+
if (!container.has(tokenServiceToken)) {
|
|
754
|
+
return {
|
|
755
|
+
authUser: {
|
|
756
|
+
id: userId,
|
|
757
|
+
email: "",
|
|
758
|
+
role: authUser.role ?? "member"
|
|
759
|
+
},
|
|
760
|
+
csrfToken,
|
|
761
|
+
flash
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
const tokenService = container.resolve(tokenServiceToken);
|
|
765
|
+
try {
|
|
766
|
+
const user = await tokenService.findByIdOrThrow(userId);
|
|
767
|
+
return {
|
|
768
|
+
authUser: {
|
|
769
|
+
id: userId,
|
|
770
|
+
email: user.email ?? "",
|
|
771
|
+
role: authUser.role ?? user.role ?? "member"
|
|
772
|
+
},
|
|
773
|
+
csrfToken,
|
|
774
|
+
flash
|
|
775
|
+
};
|
|
776
|
+
} catch {
|
|
777
|
+
return { authUser: null, csrfToken, flash };
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
// ../../src/core/http/contentNegotiation.ts
|
|
781
|
+
function requestPrefersJson(request) {
|
|
782
|
+
if (!request) {
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
if (request.headers.get("HX-Request") === "true") {
|
|
786
|
+
return false;
|
|
787
|
+
}
|
|
788
|
+
const accept = request.headers.get("accept")?.toLowerCase() ?? "";
|
|
789
|
+
if (accept.includes("text/html")) {
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
if (accept.includes("application/json")) {
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
795
|
+
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
|
796
|
+
if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
|
|
797
|
+
return false;
|
|
798
|
+
}
|
|
799
|
+
const pathname = new URL(request.url).pathname;
|
|
800
|
+
return pathname.startsWith("/api/");
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// ../../src/core/http/webErrorResponse.ts
|
|
804
|
+
function normalizeFieldErrors(details) {
|
|
805
|
+
if (!details || typeof details !== "object" || Array.isArray(details)) {
|
|
806
|
+
return {};
|
|
807
|
+
}
|
|
808
|
+
const errors = {};
|
|
809
|
+
for (const [field, messages] of Object.entries(details)) {
|
|
810
|
+
if (Array.isArray(messages)) {
|
|
811
|
+
errors[field] = messages.map(String);
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if (typeof messages === "string") {
|
|
815
|
+
errors[field] = [messages];
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return errors;
|
|
819
|
+
}
|
|
820
|
+
function webErrorResponse(error, request) {
|
|
821
|
+
if (!request || !isViewsEnabled() || requestPrefersJson(request)) {
|
|
822
|
+
return null;
|
|
823
|
+
}
|
|
824
|
+
const mappedError = error instanceof HttpError2 ? error : mapDatabaseError(error);
|
|
825
|
+
if (mappedError instanceof UnauthorizedError2) {
|
|
826
|
+
const redirectTarget = encodeURIComponent(new URL(request.url).pathname);
|
|
827
|
+
return Response.redirect(`/login?redirect=${redirectTarget}`, 302);
|
|
828
|
+
}
|
|
829
|
+
if (mappedError instanceof ValidationError) {
|
|
830
|
+
const errors = normalizeFieldErrors(mappedError.details);
|
|
831
|
+
const fieldSummary = Object.entries(errors).flatMap(([field, messages]) => messages.map((message) => `${field}: ${message}`)).join(`
|
|
832
|
+
`);
|
|
833
|
+
return htmlResponse(`<section class="page-header"><h1>Validation failed</h1><pre>${fieldSummary || mappedError.message}</pre><p><a href="javascript:history.back()">Go back</a></p></section>`, { status: mappedError.status });
|
|
834
|
+
}
|
|
835
|
+
return htmlResponse(`<section class="page-header"><h1>${mappedError.message}</h1></section>`, {
|
|
836
|
+
status: mappedError.status
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// ../../src/core/http/response.ts
|
|
841
|
+
function jsonResponse(data, init = {}) {
|
|
842
|
+
return Response.json(data, {
|
|
843
|
+
status: init.status ?? 200,
|
|
844
|
+
headers: init.headers
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
function createdResponse(data, init = {}) {
|
|
848
|
+
return jsonResponse(data, { ...init, status: init.status ?? 201 });
|
|
849
|
+
}
|
|
850
|
+
function noContentResponse() {
|
|
851
|
+
return new Response(null, { status: 204 });
|
|
852
|
+
}
|
|
853
|
+
function errorResponse(error) {
|
|
854
|
+
const mappedError = error instanceof HttpError3 ? error : mapDatabaseError(error);
|
|
855
|
+
return Response.json({
|
|
856
|
+
error: mappedError.message,
|
|
857
|
+
...mappedError.details === undefined ? {} : { details: mappedError.details }
|
|
858
|
+
}, { status: mappedError.status });
|
|
859
|
+
}
|
|
860
|
+
function withErrorHandling(handler) {
|
|
861
|
+
return async (...args) => {
|
|
862
|
+
try {
|
|
863
|
+
return await handler(...args);
|
|
864
|
+
} catch (error) {
|
|
865
|
+
const request = args.find((arg) => arg instanceof Request);
|
|
866
|
+
const webResponse = webErrorResponse(error, request);
|
|
867
|
+
if (webResponse) {
|
|
868
|
+
return webResponse;
|
|
869
|
+
}
|
|
870
|
+
return errorResponse(error);
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
export {
|
|
875
|
+
withErrorHandling,
|
|
876
|
+
noContentResponse,
|
|
877
|
+
jsonResponse,
|
|
878
|
+
errorResponse,
|
|
879
|
+
createdResponse
|
|
880
|
+
};
|