@getstrata/core 2.2.48 → 2.2.49

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.
@@ -913,9 +913,6 @@ var init_databaseTenantContext = __esm(() => {
913
913
  init_tenancyConfig();
914
914
  });
915
915
 
916
- // ../../src/core/audit/exportAuditLogs.ts
917
- import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
918
-
919
916
  // ../../src/core/runtime/appEnv.ts
920
917
  var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
921
918
  function normalizeEnvValue(value) {
@@ -1338,8 +1335,39 @@ function assertSafeOutboundUrl(rawUrl, options = {}) {
1338
1335
  return parsed;
1339
1336
  }
1340
1337
 
1341
- // ../../src/core/audit/exportAuditLogs.ts
1338
+ // ../../src/core/audit/exportStore.ts
1342
1339
  init_databaseTenantContext();
1340
+ import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
1341
+ async function readPendingAuditLogs(batchSize) {
1342
+ return await runWithMigrationBypass(async () => {
1343
+ return await db`
1344
+ SELECT
1345
+ id,
1346
+ user_id,
1347
+ action,
1348
+ subject_type,
1349
+ subject_id,
1350
+ payload,
1351
+ ip_address,
1352
+ user_agent,
1353
+ checksum,
1354
+ tenant_id,
1355
+ trace_id,
1356
+ created_at
1357
+ FROM audit_log
1358
+ WHERE exported_at IS NULL
1359
+ ORDER BY id
1360
+ LIMIT ${batchSize}
1361
+ `;
1362
+ });
1363
+ }
1364
+ async function acknowledgeAuditLogs(ids) {
1365
+ await runWithMigrationBypass(async () => {
1366
+ for (const id of ids) {
1367
+ await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1368
+ }
1369
+ });
1370
+ }
1343
1371
 
1344
1372
  // ../../src/core/audit/siemFormatter.ts
1345
1373
  function formatSiemAuditEvent(input) {
@@ -1393,61 +1421,38 @@ async function exportPendingAuditLogs() {
1393
1421
  if (!config) {
1394
1422
  return 0;
1395
1423
  }
1396
- return await runWithMigrationBypass(async () => {
1397
- const rows = await db`
1398
- SELECT
1399
- id,
1400
- user_id,
1401
- action,
1402
- subject_type,
1403
- subject_id,
1404
- payload,
1405
- ip_address,
1406
- user_agent,
1407
- checksum,
1408
- tenant_id,
1409
- trace_id,
1410
- created_at
1411
- FROM audit_log
1412
- WHERE exported_at IS NULL
1413
- ORDER BY id
1414
- LIMIT ${config.batchSize}
1415
- `;
1416
- if (rows.length === 0) {
1417
- return 0;
1418
- }
1419
- const events = rows.map((row) => formatSiemAuditEvent({
1420
- action: row.action,
1421
- subject_type: row.subject_type,
1422
- subject_id: row.subject_id,
1423
- user_id: row.user_id,
1424
- tenant_id: row.tenant_id,
1425
- trace_id: row.trace_id,
1426
- ip_address: row.ip_address,
1427
- user_agent: row.user_agent,
1428
- checksum: row.checksum,
1429
- payload: row.payload,
1430
- created_at: row.created_at
1431
- }));
1432
- const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1424
+ const rows = await readPendingAuditLogs(config.batchSize);
1425
+ if (rows.length === 0) {
1426
+ return 0;
1427
+ }
1428
+ const events = rows.map((row) => formatSiemAuditEvent({
1429
+ action: row.action,
1430
+ subject_type: row.subject_type,
1431
+ subject_id: row.subject_id,
1432
+ user_id: row.user_id,
1433
+ tenant_id: row.tenant_id,
1434
+ trace_id: row.trace_id,
1435
+ ip_address: row.ip_address,
1436
+ user_agent: row.user_agent,
1437
+ checksum: row.checksum,
1438
+ payload: row.payload,
1439
+ created_at: row.created_at
1440
+ }));
1441
+ const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1433
1442
  `) : JSON.stringify({ events });
1434
- const response = await safeFetch(config.endpoint, {
1435
- method: "POST",
1436
- headers: {
1437
- "content-type": config.format === "cef" ? "text/plain" : "application/json",
1438
- ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1439
- },
1440
- body
1441
- }, { allowHttp: appEnv() !== "production" });
1442
- if (!response.ok) {
1443
- throw new Error(`SIEM export failed with status ${response.status}.`);
1444
- }
1445
- const ids = rows.map((row) => row.id);
1446
- for (const id of ids) {
1447
- await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1448
- }
1449
- return rows.length;
1450
- });
1443
+ const response = await safeFetch(config.endpoint, {
1444
+ method: "POST",
1445
+ headers: {
1446
+ "content-type": config.format === "cef" ? "text/plain" : "application/json",
1447
+ ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1448
+ },
1449
+ body
1450
+ }, { allowHttp: appEnv() !== "production" });
1451
+ if (!response.ok) {
1452
+ throw new Error(`SIEM export failed with status ${response.status}.`);
1453
+ }
1454
+ await acknowledgeAuditLogs(rows.map((row) => row.id));
1455
+ return rows.length;
1451
1456
  }
1452
1457
  export {
1453
1458
  exportPendingAuditLogs,
@@ -1782,6 +1782,33 @@ function buildConditionalWriteQuery(table, operation, changes, options, returnin
1782
1782
  };
1783
1783
  }
1784
1784
 
1785
+ // ../../src/core/database/relationQueries.ts
1786
+ init_dialect();
1787
+ function buildThroughWhere(table, options, parentIds) {
1788
+ const parameters = [...parentIds];
1789
+ const { clause } = buildQueryWhereClause(table, options, options.whereNodes, parameters);
1790
+ return {
1791
+ text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
1792
+ params: parameters.slice(parentIds.length)
1793
+ };
1794
+ }
1795
+ function buildHasManyThroughQuery(table, relation, parentIds, options) {
1796
+ const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
1797
+ const farTable = table.name;
1798
+ const columns = table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
1799
+ const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
1800
+ const { text: extraWhere, params: extraParams } = buildThroughWhere(table, options, parentIds);
1801
+ const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
1802
+ return { text: sql, params: [...parentIds, ...extraParams] };
1803
+ }
1804
+ function buildPivotLookupQuery(relation, parentIds) {
1805
+ const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
1806
+ return {
1807
+ text: `SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`,
1808
+ params: parentIds
1809
+ };
1810
+ }
1811
+
1785
1812
  // ../../src/core/database/relationships.ts
1786
1813
  function hasMany(definition) {
1787
1814
  return {
@@ -3088,26 +3115,10 @@ class BaseRepository {
3088
3115
  throw new Error("A related model scope joins the through table twice; use an explicitly aliased correlated predicate instead.");
3089
3116
  }
3090
3117
  const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
3091
- const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
3092
- const farTable = this.table.name;
3093
- const columns = this.table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
3094
- const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
3095
- const { text: extraWhere, params: extraParams } = this.buildThroughWhere(options, parentIds);
3096
- const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
3097
- const children = await this.connection.unsafe(sql, [
3098
- ...parentIds,
3099
- ...extraParams
3100
- ]);
3118
+ const { text, params } = buildHasManyThroughQuery(this.table, relation, parentIds, options);
3119
+ const children = await this.connection.unsafe(text, params);
3101
3120
  return indexHasManyThroughRelation(parents, children, relation);
3102
3121
  }
3103
- buildThroughWhere(options, parentIds) {
3104
- const parameters = [...parentIds];
3105
- const { clause } = buildQueryWhereClause(this.table, options, options.whereNodes, parameters);
3106
- return {
3107
- text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
3108
- params: parameters.slice(parentIds.length)
3109
- };
3110
- }
3111
3122
  async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
3112
3123
  if (children.length === 0) {
3113
3124
  return new Map;
@@ -3173,8 +3184,8 @@ class BaseRepository {
3173
3184
  return indexBelongsToManyRelation(parents, [], [], relation);
3174
3185
  }
3175
3186
  const parentIds = [...new Set(parents.map((parent) => parent[relation.parentKey]))];
3176
- const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
3177
- const pivotRows = await this.connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`, parentIds);
3187
+ const { text, params } = buildPivotLookupQuery(relation, parentIds);
3188
+ const pivotRows = await this.connection.unsafe(text, params);
3178
3189
  if (pivotRows.length === 0) {
3179
3190
  return indexBelongsToManyRelation(parents, [], [], relation);
3180
3191
  }
@@ -88,7 +88,7 @@ function sdkClientClassName() {
88
88
  return fromName ? `${fromName}Client` : "AppClient";
89
89
  }
90
90
 
91
- // ../../src/core/cache/redisCacheStore.ts
91
+ // ../../src/core/cache/redisCacheScript.ts
92
92
  var CACHE_SCRIPT = `
93
93
  local expected = {'hash', 'zset', 'zset', 'hash', 'zset'}
94
94
  for i, key in ipairs(KEYS) do
@@ -288,6 +288,7 @@ end
288
288
  return redis.error_reply('Unknown cache operation')
289
289
  `;
290
290
 
291
+ // ../../src/core/cache/redisCacheStore.ts
291
292
  class RedisCacheStore {
292
293
  redisUrl;
293
294
  ttlMs;
@@ -97,30 +97,7 @@ function sdkClientClassName() {
97
97
  return fromName ? `${fromName}Client` : "AppClient";
98
98
  }
99
99
 
100
- // ../../src/core/mail/mailer.ts
101
- function resolveSmtpConfig() {
102
- const host = process.env.MAIL_HOST?.trim();
103
- if (!host) {
104
- throw new Error('MAIL_DRIVER="smtp" requires MAIL_HOST to be set.');
105
- }
106
- const from = process.env.MAIL_FROM?.trim();
107
- if (!from) {
108
- throw new Error('MAIL_DRIVER="smtp" requires MAIL_FROM to be set.');
109
- }
110
- const port = Number(process.env.MAIL_PORT ?? "587");
111
- if (!Number.isInteger(port) || port <= 0 || port > 65535) {
112
- throw new Error('Environment variable "MAIL_PORT" must be a positive integer.');
113
- }
114
- return {
115
- host,
116
- port,
117
- from,
118
- secure: (process.env.MAIL_SECURE ?? "false") === "true",
119
- ...process.env.MAIL_TIMEOUT_MS !== undefined ? { timeoutMs: smtpTimeout(Number(process.env.MAIL_TIMEOUT_MS)) } : {},
120
- ...process.env.MAIL_USERNAME?.trim() ? { username: process.env.MAIL_USERNAME.trim() } : {},
121
- ...process.env.MAIL_PASSWORD?.trim() ? { password: process.env.MAIL_PASSWORD.trim() } : {}
122
- };
123
- }
100
+ // ../../src/core/mail/smtpMessage.ts
124
101
  var EMAIL_SHAPE = /^[^\s@\r\n]+@[^\s@\r\n]+\.[^\s@\r\n]+$/u;
125
102
  function assertSafeSmtpField(value, field) {
126
103
  if (/[\r\n]/u.test(value)) {
@@ -146,12 +123,111 @@ function assertSafeSmtpAddress(value, field) {
146
123
  smtpEnvelopeAddress(value, field);
147
124
  return assertSafeSmtpField(value, field).trim();
148
125
  }
149
- function redactMailBody(body) {
150
- return body.replace(/https?:\/\/[^\s]+/giu, "[redacted-url]").replace(/[?&](token|signature|expires|code)=[^&\s]+/giu, "[redacted-query]");
151
- }
152
126
  function encodeBase64(value) {
153
127
  return Buffer.from(value, "utf8").toString("base64");
154
128
  }
129
+ function encodeSmtpHeader(value) {
130
+ if (/^[\x20-\x7e]{0,60}$/u.test(value))
131
+ return value;
132
+ const words = [];
133
+ let part = "";
134
+ for (const character of value) {
135
+ if (Buffer.byteLength(part + character, "utf8") > 45) {
136
+ words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
137
+ part = "";
138
+ }
139
+ part += character;
140
+ }
141
+ if (part)
142
+ words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
143
+ return words.join(`\r
144
+ `);
145
+ }
146
+ function smtpAddressHeader(value) {
147
+ if (!value.includes("<"))
148
+ return value;
149
+ const name = value.slice(0, value.lastIndexOf("<")).trim();
150
+ const address = smtpEnvelopeAddress(value, "address");
151
+ if (!name)
152
+ return address;
153
+ const encoded = encodeSmtpHeader(name);
154
+ const display = encoded.startsWith("=?UTF-8?B?") ? encoded : `"${encoded.replace(/[\\"]/gu, "\\$&")}"`;
155
+ return `${display} <${address}>`;
156
+ }
157
+ function smtpMimePart(type, value) {
158
+ const normalized = value.replace(/\r\n|\r|\n/gu, `\r
159
+ `);
160
+ const base64 = /[^\t\r\n\x20-\x7e]/u.test(normalized) || normalized.split(`\r
161
+ `).some((line) => line.length > 998);
162
+ return [
163
+ `Content-Type: ${type}; charset=utf-8`,
164
+ `Content-Transfer-Encoding: ${base64 ? "base64" : "7bit"}`,
165
+ "",
166
+ base64 ? (encodeBase64(normalized).match(/.{1,76}/gu) ?? []).join(`\r
167
+ `) : normalized
168
+ ];
169
+ }
170
+ function buildSmtpPayload(from, message) {
171
+ const headers = [
172
+ `From: ${smtpAddressHeader(assertSafeSmtpAddress(from, "from"))}`,
173
+ `To: ${smtpAddressHeader(assertSafeSmtpAddress(message.to, "to"))}`,
174
+ `Subject: ${encodeSmtpHeader(assertSafeSmtpField(message.subject, "subject"))}`,
175
+ "MIME-Version: 1.0"
176
+ ];
177
+ let lines;
178
+ if (message.html) {
179
+ let boundary;
180
+ do {
181
+ boundary = `strata-${crypto.randomUUID()}`;
182
+ } while (message.body.includes(boundary) || message.html.includes(boundary));
183
+ lines = [
184
+ ...headers,
185
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
186
+ "",
187
+ `--${boundary}`,
188
+ ...smtpMimePart("text/plain", message.body),
189
+ `--${boundary}`,
190
+ ...smtpMimePart("text/html", message.html),
191
+ `--${boundary}--`,
192
+ ""
193
+ ];
194
+ } else
195
+ lines = [...headers, ...smtpMimePart("text/plain", message.body)];
196
+ const content = lines.join(`\r
197
+ `).replace(/(^|\r\n)\./gu, "$1..");
198
+ return `${content}${content.endsWith(`\r
199
+ `) ? "" : `\r
200
+ `}.\r
201
+ `;
202
+ }
203
+
204
+ // ../../src/core/mail/mailer.ts
205
+ function resolveSmtpConfig() {
206
+ const host = process.env.MAIL_HOST?.trim();
207
+ if (!host) {
208
+ throw new Error('MAIL_DRIVER="smtp" requires MAIL_HOST to be set.');
209
+ }
210
+ const from = process.env.MAIL_FROM?.trim();
211
+ if (!from) {
212
+ throw new Error('MAIL_DRIVER="smtp" requires MAIL_FROM to be set.');
213
+ }
214
+ const port = Number(process.env.MAIL_PORT ?? "587");
215
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
216
+ throw new Error('Environment variable "MAIL_PORT" must be a positive integer.');
217
+ }
218
+ return {
219
+ host,
220
+ port,
221
+ from,
222
+ secure: (process.env.MAIL_SECURE ?? "false") === "true",
223
+ ...process.env.MAIL_TIMEOUT_MS !== undefined ? { timeoutMs: smtpTimeout(Number(process.env.MAIL_TIMEOUT_MS)) } : {},
224
+ ...process.env.MAIL_USERNAME?.trim() ? { username: process.env.MAIL_USERNAME.trim() } : {},
225
+ ...process.env.MAIL_PASSWORD?.trim() ? { password: process.env.MAIL_PASSWORD.trim() } : {}
226
+ };
227
+ }
228
+ function redactMailBody(body) {
229
+ return body.replace(/https?:\/\/[^\s]+/giu, "[redacted-url]").replace(/[?&](token|signature|expires|code)=[^&\s]+/giu, "[redacted-query]");
230
+ }
155
231
  function smtpTimeout(value = 1e4) {
156
232
  if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) {
157
233
  throw new RangeError("SMTP timeoutMs must be a positive integer within the timer range.");
@@ -380,80 +456,6 @@ async function defaultSmtpTransport(config, message) {
380
456
  socket?.end();
381
457
  }
382
458
  }
383
- function encodeSmtpHeader(value) {
384
- if (/^[\x20-\x7e]{0,60}$/u.test(value))
385
- return value;
386
- const words = [];
387
- let part = "";
388
- for (const character of value) {
389
- if (Buffer.byteLength(part + character, "utf8") > 45) {
390
- words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
391
- part = "";
392
- }
393
- part += character;
394
- }
395
- if (part)
396
- words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
397
- return words.join(`\r
398
- `);
399
- }
400
- function smtpAddressHeader(value) {
401
- if (!value.includes("<"))
402
- return value;
403
- const name = value.slice(0, value.lastIndexOf("<")).trim();
404
- const address = smtpEnvelopeAddress(value, "address");
405
- if (!name)
406
- return address;
407
- const encoded = encodeSmtpHeader(name);
408
- const display = encoded.startsWith("=?UTF-8?B?") ? encoded : `"${encoded.replace(/[\\"]/gu, "\\$&")}"`;
409
- return `${display} <${address}>`;
410
- }
411
- function smtpMimePart(type, value) {
412
- const normalized = value.replace(/\r\n|\r|\n/gu, `\r
413
- `);
414
- const base64 = /[^\t\r\n\x20-\x7e]/u.test(normalized) || normalized.split(`\r
415
- `).some((line) => line.length > 998);
416
- return [
417
- `Content-Type: ${type}; charset=utf-8`,
418
- `Content-Transfer-Encoding: ${base64 ? "base64" : "7bit"}`,
419
- "",
420
- base64 ? (encodeBase64(normalized).match(/.{1,76}/gu) ?? []).join(`\r
421
- `) : normalized
422
- ];
423
- }
424
- function buildSmtpPayload(from, message) {
425
- const headers = [
426
- `From: ${smtpAddressHeader(assertSafeSmtpAddress(from, "from"))}`,
427
- `To: ${smtpAddressHeader(assertSafeSmtpAddress(message.to, "to"))}`,
428
- `Subject: ${encodeSmtpHeader(assertSafeSmtpField(message.subject, "subject"))}`,
429
- "MIME-Version: 1.0"
430
- ];
431
- let lines;
432
- if (message.html) {
433
- let boundary;
434
- do {
435
- boundary = `strata-${crypto.randomUUID()}`;
436
- } while (message.body.includes(boundary) || message.html.includes(boundary));
437
- lines = [
438
- ...headers,
439
- `Content-Type: multipart/alternative; boundary="${boundary}"`,
440
- "",
441
- `--${boundary}`,
442
- ...smtpMimePart("text/plain", message.body),
443
- `--${boundary}`,
444
- ...smtpMimePart("text/html", message.html),
445
- `--${boundary}--`,
446
- ""
447
- ];
448
- } else
449
- lines = [...headers, ...smtpMimePart("text/plain", message.body)];
450
- const content = lines.join(`\r
451
- `).replace(/(^|\r\n)\./gu, "$1..");
452
- return `${content}${content.endsWith(`\r
453
- `) ? "" : `\r
454
- `}.\r
455
- `;
456
- }
457
459
 
458
460
  class LogMailDriver {
459
461
  async send(message) {
@@ -42,16 +42,16 @@ function currentRequestMeta() {
42
42
  // ../../src/core/http/middleware.ts
43
43
  function composeMiddleware(...middleware) {
44
44
  return (handler) => {
45
- return async (request) => {
45
+ return async (request, ...arguments_) => {
46
46
  let index = 0;
47
47
  const dispatch = async () => {
48
48
  if (index >= middleware.length) {
49
- return await handler(request);
49
+ return await handler(request, ...arguments_);
50
50
  }
51
51
  const current = middleware[index];
52
52
  index += 1;
53
53
  if (!current) {
54
- return await handler(request);
54
+ return await handler(request, ...arguments_);
55
55
  }
56
56
  return await current(request, dispatch);
57
57
  };
@@ -913,9 +913,6 @@ var init_databaseTenantContext = __esm(() => {
913
913
  init_tenancyConfig();
914
914
  });
915
915
 
916
- // ../../src/core/audit/exportAuditLogs.ts
917
- import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
918
-
919
916
  // ../../src/core/runtime/appEnv.ts
920
917
  var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
921
918
  function normalizeEnvValue(value) {
@@ -1338,8 +1335,39 @@ function assertSafeOutboundUrl(rawUrl, options = {}) {
1338
1335
  return parsed;
1339
1336
  }
1340
1337
 
1341
- // ../../src/core/audit/exportAuditLogs.ts
1338
+ // ../../src/core/audit/exportStore.ts
1342
1339
  init_databaseTenantContext();
1340
+ import { repositoryConnection as db } from "@getstrata/core/database/repositoryConnection";
1341
+ async function readPendingAuditLogs(batchSize) {
1342
+ return await runWithMigrationBypass(async () => {
1343
+ return await db`
1344
+ SELECT
1345
+ id,
1346
+ user_id,
1347
+ action,
1348
+ subject_type,
1349
+ subject_id,
1350
+ payload,
1351
+ ip_address,
1352
+ user_agent,
1353
+ checksum,
1354
+ tenant_id,
1355
+ trace_id,
1356
+ created_at
1357
+ FROM audit_log
1358
+ WHERE exported_at IS NULL
1359
+ ORDER BY id
1360
+ LIMIT ${batchSize}
1361
+ `;
1362
+ });
1363
+ }
1364
+ async function acknowledgeAuditLogs(ids) {
1365
+ await runWithMigrationBypass(async () => {
1366
+ for (const id of ids) {
1367
+ await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1368
+ }
1369
+ });
1370
+ }
1343
1371
 
1344
1372
  // ../../src/core/audit/siemFormatter.ts
1345
1373
  function formatSiemAuditEvent(input) {
@@ -1393,61 +1421,38 @@ async function exportPendingAuditLogs() {
1393
1421
  if (!config) {
1394
1422
  return 0;
1395
1423
  }
1396
- return await runWithMigrationBypass(async () => {
1397
- const rows = await db`
1398
- SELECT
1399
- id,
1400
- user_id,
1401
- action,
1402
- subject_type,
1403
- subject_id,
1404
- payload,
1405
- ip_address,
1406
- user_agent,
1407
- checksum,
1408
- tenant_id,
1409
- trace_id,
1410
- created_at
1411
- FROM audit_log
1412
- WHERE exported_at IS NULL
1413
- ORDER BY id
1414
- LIMIT ${config.batchSize}
1415
- `;
1416
- if (rows.length === 0) {
1417
- return 0;
1418
- }
1419
- const events = rows.map((row) => formatSiemAuditEvent({
1420
- action: row.action,
1421
- subject_type: row.subject_type,
1422
- subject_id: row.subject_id,
1423
- user_id: row.user_id,
1424
- tenant_id: row.tenant_id,
1425
- trace_id: row.trace_id,
1426
- ip_address: row.ip_address,
1427
- user_agent: row.user_agent,
1428
- checksum: row.checksum,
1429
- payload: row.payload,
1430
- created_at: row.created_at
1431
- }));
1432
- const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1424
+ const rows = await readPendingAuditLogs(config.batchSize);
1425
+ if (rows.length === 0) {
1426
+ return 0;
1427
+ }
1428
+ const events = rows.map((row) => formatSiemAuditEvent({
1429
+ action: row.action,
1430
+ subject_type: row.subject_type,
1431
+ subject_id: row.subject_id,
1432
+ user_id: row.user_id,
1433
+ tenant_id: row.tenant_id,
1434
+ trace_id: row.trace_id,
1435
+ ip_address: row.ip_address,
1436
+ user_agent: row.user_agent,
1437
+ checksum: row.checksum,
1438
+ payload: row.payload,
1439
+ created_at: row.created_at
1440
+ }));
1441
+ const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
1433
1442
  `) : JSON.stringify({ events });
1434
- const response = await safeFetch(config.endpoint, {
1435
- method: "POST",
1436
- headers: {
1437
- "content-type": config.format === "cef" ? "text/plain" : "application/json",
1438
- ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1439
- },
1440
- body
1441
- }, { allowHttp: appEnv() !== "production" });
1442
- if (!response.ok) {
1443
- throw new Error(`SIEM export failed with status ${response.status}.`);
1444
- }
1445
- const ids = rows.map((row) => row.id);
1446
- for (const id of ids) {
1447
- await db`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
1448
- }
1449
- return rows.length;
1450
- });
1443
+ const response = await safeFetch(config.endpoint, {
1444
+ method: "POST",
1445
+ headers: {
1446
+ "content-type": config.format === "cef" ? "text/plain" : "application/json",
1447
+ ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
1448
+ },
1449
+ body
1450
+ }, { allowHttp: appEnv() !== "production" });
1451
+ if (!response.ok) {
1452
+ throw new Error(`SIEM export failed with status ${response.status}.`);
1453
+ }
1454
+ await acknowledgeAuditLogs(rows.map((row) => row.id));
1455
+ return rows.length;
1451
1456
  }
1452
1457
 
1453
1458
  // ../../src/core/logging/logger.ts