@open-mercato/core 0.6.8-develop.7067.1.82e9867ea1 → 0.6.8-develop.7068.1.c55b52e1a1

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.
@@ -2,7 +2,8 @@ import { sql } from "kysely";
2
2
  import { ActionLog } from "@open-mercato/core/modules/audit_logs/data/entities";
3
3
  import {
4
4
  actionLogCreateSchema,
5
- actionLogListSchema
5
+ actionLogListSchema,
6
+ uuid
6
7
  } from "@open-mercato/core/modules/audit_logs/data/validators";
7
8
  import { isRecord } from "@open-mercato/core/modules/audit_logs/lib/changeRows";
8
9
  import {
@@ -24,6 +25,39 @@ const SORT_FIELDS = {
24
25
  createdAt: "action_logs.created_at"
25
26
  };
26
27
  const UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
28
+ const SCHEMA_UUID_REGEX = /^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
29
+ const API_KEY_ACTOR_PREFIX = "api_key:";
30
+ const SYSTEM_ACTOR_PREFIX = "system:";
31
+ const SYSTEM_ACTOR_CONTEXT_KEY = "systemActor";
32
+ const SYSTEM_ACTOR_REFERENCE_MAX_LENGTH = 255;
33
+ function toNullableUuid(value) {
34
+ return typeof value === "string" && UUID_REGEX.test(value) ? value : null;
35
+ }
36
+ function isSchemaUuid(value) {
37
+ if (runtimeValidationAvailable === false) return SCHEMA_UUID_REGEX.test(value);
38
+ try {
39
+ return uuid.safeParse(value).success;
40
+ } catch (err) {
41
+ if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false;
42
+ return SCHEMA_UUID_REGEX.test(value);
43
+ }
44
+ }
45
+ function readActorCandidate(value) {
46
+ if (typeof value !== "string") return null;
47
+ const trimmed = value.trim();
48
+ return trimmed.length > 0 ? trimmed : null;
49
+ }
50
+ function normalizeActorUserId(value) {
51
+ const candidate = readActorCandidate(value);
52
+ if (!candidate) return null;
53
+ const unwrapped = candidate.startsWith(API_KEY_ACTOR_PREFIX) ? candidate.slice(API_KEY_ACTOR_PREFIX.length) : candidate;
54
+ return isSchemaUuid(unwrapped) ? unwrapped : null;
55
+ }
56
+ function toSystemActorReference(candidate) {
57
+ if (!candidate.startsWith(SYSTEM_ACTOR_PREFIX)) return null;
58
+ if (candidate.length === SYSTEM_ACTOR_PREFIX.length) return null;
59
+ return candidate.slice(0, SYSTEM_ACTOR_REFERENCE_MAX_LENGTH);
60
+ }
27
61
  function readString(record, ...keys) {
28
62
  for (const key of keys) {
29
63
  const value = record[key];
@@ -132,13 +166,14 @@ class ActionLogService {
132
166
  return log;
133
167
  }
134
168
  parseCreateInput(input) {
169
+ const sanitized = this.sanitizeActor(input);
135
170
  let data;
136
171
  const schema = actionLogCreateSchema;
137
172
  const canValidate = Boolean(schema && typeof schema.parse === "function");
138
173
  const shouldValidate = canValidate && runtimeValidationAvailable !== false;
139
174
  if (shouldValidate) {
140
175
  try {
141
- data = schema.parse(input);
176
+ data = schema.parse(sanitized);
142
177
  runtimeValidationAvailable = true;
143
178
  } catch (err) {
144
179
  if (!isZodRuntimeMissing(err) && !validationWarningLogged) {
@@ -146,13 +181,28 @@ class ActionLogService {
146
181
  logger.warn("Falling back to permissive action log payload parser", { err });
147
182
  }
148
183
  if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false;
149
- data = this.normalizeInput(input);
184
+ data = this.normalizeInput(sanitized);
150
185
  }
151
186
  } else {
152
- data = this.normalizeInput(input);
187
+ data = this.normalizeInput(sanitized);
153
188
  }
154
189
  return data;
155
190
  }
191
+ sanitizeActor(input) {
192
+ if (!input) return input;
193
+ const candidate = readActorCandidate(input.actorUserId);
194
+ const actorUserId = normalizeActorUserId(candidate);
195
+ const systemActorReference = candidate && !actorUserId ? toSystemActorReference(candidate) : null;
196
+ if (!systemActorReference) {
197
+ if (actorUserId === (input.actorUserId ?? null)) return input;
198
+ return { ...input, actorUserId };
199
+ }
200
+ const context = isRecord(input.context) ? { ...input.context } : {};
201
+ if (context[SYSTEM_ACTOR_CONTEXT_KEY] === void 0) {
202
+ context[SYSTEM_ACTOR_CONTEXT_KEY] = systemActorReference;
203
+ }
204
+ return { ...input, actorUserId, context };
205
+ }
156
206
  createLogEntity(fork, data) {
157
207
  const projection = deriveActionLogProjection({
158
208
  actorUserId: data.actorUserId ?? null,
@@ -210,12 +260,6 @@ class ActionLogService {
210
260
  context: void 0
211
261
  };
212
262
  }
213
- const UUID_REGEX2 = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
214
- const toNullableUuid = (value) => {
215
- if (typeof value !== "string" || value.length === 0) return null;
216
- const candidate = value.startsWith("api_key:") ? value.slice("api_key:".length) : value;
217
- return UUID_REGEX2.test(candidate) ? candidate : null;
218
- };
219
263
  const normalizeRecordLike = (value) => {
220
264
  if (value === null) return null;
221
265
  if (Array.isArray(value)) return value;
@@ -226,7 +270,7 @@ class ActionLogService {
226
270
  return {
227
271
  tenantId: toNullableUuid(input.tenantId),
228
272
  organizationId: toNullableUuid(input.organizationId),
229
- actorUserId: toNullableUuid(input.actorUserId),
273
+ actorUserId: normalizeActorUserId(input.actorUserId),
230
274
  commandId: typeof input.commandId === "string" && input.commandId.length > 0 ? input.commandId : "unknown",
231
275
  actionLabel: toOptionalString(input.actionLabel) ?? void 0,
232
276
  resourceKind: toOptionalString(input.resourceKind) ?? void 0,
@@ -551,6 +595,7 @@ class ActionLogService {
551
595
  }
552
596
  }
553
597
  export {
554
- ActionLogService
598
+ ActionLogService,
599
+ SCHEMA_UUID_REGEX
555
600
  };
556
601
  //# sourceMappingURL=actionLogService.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/audit_logs/services/actionLogService.ts"],
4
- "sourcesContent": ["import type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport { ActionLog } from '@open-mercato/core/modules/audit_logs/data/entities'\nimport {\n actionLogCreateSchema,\n actionLogListSchema,\n type ActionLogCreateInput,\n type ActionLogListQuery,\n} from '@open-mercato/core/modules/audit_logs/data/validators'\nimport { isRecord } from '@open-mercato/core/modules/audit_logs/lib/changeRows'\nimport {\n ACTION_LOG_FILTER_TYPES,\n type ActionLogFilterType,\n deriveActionLogProjection,\n} from '@open-mercato/core/modules/audit_logs/lib/projections'\nimport { decryptWithAesGcm } from '@open-mercato/shared/lib/encryption/aes'\nimport {\n TenantDataEncryptionService,\n parseDecryptedFieldValue,\n} from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { toOptionalString } from '@open-mercato/shared/lib/string/coerce'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('audit_logs').child({ component: 'action-log-service' })\n\nlet validationWarningLogged = false\nlet runtimeValidationAvailable: boolean | null = null\nlet decryptionWarningLogged = false\n\nconst isZodRuntimeMissing = (err: unknown) => err instanceof TypeError && typeof err.message === 'string' && err.message.includes('_zod')\n\nconst SORT_FIELDS = {\n createdAt: 'action_logs.created_at',\n} as const\nconst UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/\n\ntype ActionLogProjectionBackfillOptions = {\n batchSize?: number\n force?: boolean\n logger?: (message: string) => void\n organizationId?: string | null\n tenantId?: string | null\n}\n\nexport type ActionLogProjectionBackfillResult = {\n errors: number\n scanned: number\n skipped: number\n updated: number\n}\n\ntype BackfillRow = {\n action_label: string | null\n action_type: string | null\n actor_user_id: string | null\n changed_fields: string[] | null\n changes_json: Record<string, unknown> | null\n command_id: string\n context_json: Record<string, unknown> | null\n created_at: Date\n id: string\n organization_id: string | null\n primary_changed_field: string | null\n snapshot_before: unknown | null\n source_key: string | null\n tenant_id: string | null\n}\n\nfunction readString(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n\n return null\n}\n\nfunction readRecord(record: Record<string, unknown>, ...keys: string[]): Record<string, unknown> | null {\n for (const key of keys) {\n const value = record[key]\n if (isRecord(value)) return value\n }\n\n return null\n}\n\nfunction readValue(record: Record<string, unknown>, ...keys: string[]): unknown {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key)) return record[key]\n }\n\n return undefined\n}\n\nfunction readStringArray(record: Record<string, unknown>, ...keys: string[]): string[] | null {\n for (const key of keys) {\n const value = record[key]\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === 'string')\n }\n }\n\n return null\n}\n\nfunction stringArraysEqual(left: string[] | null, right: string[]): boolean {\n if (!Array.isArray(left)) return false\n if (left.length !== right.length) return false\n\n return left.every((value, index) => value === right[index])\n}\n\nexport class ActionLogService {\n constructor(\n private readonly em: EntityManager,\n private readonly tenantEncryptionService?: TenantDataEncryptionService,\n ) {}\n\n private async decryptEntryPayload<T extends Record<string, unknown>>(entry: T): Promise<T> {\n if (!this.tenantEncryptionService?.isEnabled()) return entry\n\n try {\n const tenantId = readString(entry, 'tenantId', 'tenant_id')\n const organizationId = readString(entry, 'organizationId', 'organization_id')\n const dek = await this.tenantEncryptionService.getDek(tenantId)\n const deepDecrypt = (value: unknown): unknown => {\n if (!dek) return value\n if (typeof value === 'string' && value.split(':').length === 4 && value.endsWith(':v1')) {\n const decrypted = decryptWithAesGcm(value, dek.key)\n if (decrypted === null) return value\n return parseDecryptedFieldValue(decrypted)\n }\n if (Array.isArray(value)) return value.map((item) => deepDecrypt(item))\n if (value && typeof value === 'object') {\n const copy: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n copy[key] = deepDecrypt(item)\n }\n return copy\n }\n return value\n }\n\n const decrypted = await this.tenantEncryptionService.decryptEntityPayload(\n 'audit_logs:action_log',\n entry,\n tenantId,\n organizationId,\n )\n\n const merged = {\n ...entry,\n ...decrypted,\n } as Record<string, unknown>\n\n // Audit log jsonb columns are encrypted as JSON-stringified payloads. After the\n // service-level `decryptEntityPayload` call (which now returns raw strings \u2014\n // see issue #1810 follow-up), reattach the structured shape via\n // `parseDecryptedFieldValue` before running the recursive `deepDecrypt` walk\n // so nested encrypted strings inside payload objects/arrays are handled.\n const restoreJson = (value: unknown): unknown =>\n typeof value === 'string' ? parseDecryptedFieldValue(value) : value\n\n merged.changesJson = deepDecrypt(restoreJson(merged.changesJson ?? merged.changes_json ?? entry.changesJson ?? entry.changes_json))\n merged.changes_json = merged.changesJson\n merged.snapshotBefore = deepDecrypt(restoreJson(merged.snapshotBefore ?? merged.snapshot_before ?? entry.snapshotBefore ?? entry.snapshot_before))\n merged.snapshot_before = merged.snapshotBefore\n merged.snapshotAfter = deepDecrypt(restoreJson(merged.snapshotAfter ?? merged.snapshot_after ?? entry.snapshotAfter ?? entry.snapshot_after))\n merged.snapshot_after = merged.snapshotAfter\n merged.commandPayload = deepDecrypt(restoreJson(merged.commandPayload ?? merged.command_payload ?? entry.commandPayload ?? entry.command_payload))\n merged.command_payload = merged.commandPayload\n merged.contextJson = deepDecrypt(restoreJson(merged.contextJson ?? merged.context_json ?? entry.contextJson ?? entry.context_json))\n merged.context_json = merged.contextJson\n\n return merged as T\n } catch (err) {\n if (!decryptionWarningLogged) {\n decryptionWarningLogged = true\n logger.warn('Failed to decrypt action log entry', { err })\n }\n return entry\n }\n }\n\n private async decryptEntries(entries: ActionLog | ActionLog[] | null | undefined): Promise<void> {\n if (!entries) return\n\n const list = Array.isArray(entries) ? entries : [entries]\n for (const entry of list) {\n Object.assign(entry as unknown as Record<string, unknown>, await this.decryptEntryPayload(entry as unknown as Record<string, unknown>))\n }\n }\n\n async log(input: ActionLogCreateInput): Promise<ActionLog | null> {\n const data = this.parseCreateInput(input)\n const fork = this.em.fork()\n const log = this.createLogEntity(fork, data)\n await fork.persist(log).flush()\n await this.decryptEntries(log)\n return log\n }\n\n private parseCreateInput(input: ActionLogCreateInput): ActionLogCreateInput {\n let data: ActionLogCreateInput\n const schema = actionLogCreateSchema as typeof actionLogCreateSchema & { _zod?: unknown }\n const canValidate = Boolean(schema && typeof schema.parse === 'function')\n const shouldValidate = canValidate && runtimeValidationAvailable !== false\n\n if (shouldValidate) {\n try {\n data = schema.parse(input)\n runtimeValidationAvailable = true\n } catch (err) {\n if (!isZodRuntimeMissing(err) && !validationWarningLogged) {\n validationWarningLogged = true\n logger.warn('Falling back to permissive action log payload parser', { err })\n }\n if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false\n data = this.normalizeInput(input)\n }\n } else {\n data = this.normalizeInput(input)\n }\n\n return data\n }\n\n private createLogEntity(fork: EntityManager, data: ActionLogCreateInput): ActionLog {\n const projection = deriveActionLogProjection({\n actorUserId: data.actorUserId ?? null,\n actionLabel: data.actionLabel ?? null,\n changes: isRecord(data.changes) ? data.changes : null,\n commandId: data.commandId,\n context: isRecord(data.context) ? data.context : null,\n snapshotBefore: data.snapshotBefore,\n })\n\n return fork.create(ActionLog, {\n tenantId: data.tenantId ?? null,\n organizationId: data.organizationId ?? null,\n actorUserId: data.actorUserId ?? null,\n commandId: data.commandId,\n actionLabel: data.actionLabel ?? null,\n actionType: projection.actionType,\n resourceKind: data.resourceKind ?? null,\n resourceId: data.resourceId ?? null,\n parentResourceKind: data.parentResourceKind ?? null,\n parentResourceId: data.parentResourceId ?? null,\n relatedResourceKind: toOptionalString(data.relatedResourceKind) ?? null,\n relatedResourceId: toOptionalString(data.relatedResourceId) ?? null,\n executionState: data.executionState ?? 'done',\n undoToken: data.undoToken ?? null,\n commandPayload: data.commandPayload ?? null,\n snapshotBefore: data.snapshotBefore ?? null,\n snapshotAfter: data.snapshotAfter ?? null,\n changesJson: isRecord(data.changes) ? data.changes : null,\n changedFields: projection.changedFields,\n primaryChangedField: projection.primaryChangedField,\n contextJson: isRecord(data.context) ? data.context : null,\n sourceKey: projection.sourceKey,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n }\n\n private normalizeInput(input: Partial<ActionLogCreateInput> | null | undefined): ActionLogCreateInput {\n if (!input) {\n return {\n tenantId: null,\n organizationId: null,\n actorUserId: null,\n commandId: 'unknown',\n actionLabel: undefined,\n resourceKind: undefined,\n resourceId: undefined,\n relatedResourceKind: null,\n relatedResourceId: null,\n executionState: 'done',\n undoToken: undefined,\n commandPayload: undefined,\n snapshotBefore: undefined,\n snapshotAfter: undefined,\n changes: undefined,\n context: undefined,\n }\n }\n\n const UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/\n const toNullableUuid = (value: unknown) => {\n if (typeof value !== 'string' || value.length === 0) return null\n const candidate = value.startsWith('api_key:') ? value.slice('api_key:'.length) : value\n return UUID_REGEX.test(candidate) ? candidate : null\n }\n\n const normalizeRecordLike = (value: unknown): ActionLogCreateInput['changes'] => {\n if (value === null) return null\n if (Array.isArray(value)) return value\n if (typeof value === 'object') return value as Record<string, unknown>\n return undefined\n }\n\n const normalizeContext = (value: unknown) => (\n typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n )\n\n return {\n tenantId: toNullableUuid(input.tenantId),\n organizationId: toNullableUuid(input.organizationId),\n actorUserId: toNullableUuid(input.actorUserId),\n commandId: typeof input.commandId === 'string' && input.commandId.length > 0 ? input.commandId : 'unknown',\n actionLabel: toOptionalString(input.actionLabel) ?? undefined,\n resourceKind: toOptionalString(input.resourceKind) ?? undefined,\n resourceId: toOptionalString(input.resourceId) ?? undefined,\n parentResourceKind: toOptionalString(input.parentResourceKind) ?? null,\n parentResourceId: toOptionalString(input.parentResourceId) ?? null,\n relatedResourceKind: toOptionalString(input.relatedResourceKind) ?? null,\n relatedResourceId: toOptionalString(input.relatedResourceId) ?? null,\n executionState: input.executionState === 'undone' || input.executionState === 'failed' ? input.executionState : 'done',\n undoToken: toOptionalString(input.undoToken) ?? undefined,\n commandPayload: input.commandPayload,\n snapshotBefore: input.snapshotBefore,\n snapshotAfter: input.snapshotAfter,\n changes: normalizeRecordLike(input.changes),\n context: normalizeContext(input.context),\n }\n }\n\n private parseListQuery(query: Partial<ActionLogListQuery>) {\n return actionLogListSchema.parse({\n ...query,\n })\n }\n\n private resolveActorUserIds(parsed: ActionLogListQuery): string[] {\n const values = [...(parsed.actorUserIds ?? [])]\n if (parsed.actorUserId) values.push(parsed.actorUserId)\n\n return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)))\n }\n\n private resolveFieldNames(parsed: ActionLogListQuery): string[] {\n const values = [...(parsed.fieldNames ?? [])]\n if (parsed.fieldName) values.push(parsed.fieldName)\n\n return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)))\n }\n\n private resolveActionTypes(parsed: ActionLogListQuery): ActionLogFilterType[] {\n const values = [...(parsed.actionTypes ?? [])]\n if (parsed.actionType) values.push(parsed.actionType)\n\n return Array.from(new Set(values))\n .filter((value): value is ActionLogFilterType => ACTION_LOG_FILTER_TYPES.includes(value as ActionLogFilterType))\n }\n\n private resolvePagination(parsed: ActionLogListQuery): { page: number; pageSize: number; offset: number; limit: number } {\n const pageSize =\n typeof parsed.pageSize === 'number' && parsed.pageSize > 0\n ? parsed.pageSize\n : typeof parsed.limit === 'number' && parsed.limit > 0\n ? parsed.limit\n : 50\n const page = typeof parsed.page === 'number' && parsed.page > 0 ? parsed.page : 1\n const offset =\n typeof parsed.offset === 'number' && parsed.offset >= 0\n ? parsed.offset\n : (page - 1) * pageSize\n return { page, pageSize, offset, limit: pageSize }\n }\n\n private async loadEntries(parsed: ActionLogListQuery, options?: { paginate?: boolean }) {\n let query = (this.buildListQuery(parsed) as any).select('action_logs.id as id')\n\n if (options?.paginate !== false) {\n const { limit, offset } = this.resolvePagination(parsed)\n query = query.limit(limit).offset(offset)\n }\n\n const rows = await query.execute()\n const ids = rows.map((row: any) => row.id).filter(Boolean)\n if (ids.length === 0) return []\n\n const results = await this.em.find(ActionLog, {\n id: { $in: ids } as any,\n deletedAt: null,\n })\n await this.decryptEntries(results)\n\n const byId = new Map(results.map((entry: any) => [entry.id, entry]))\n return ids\n .map((id: any) => byId.get(id))\n .filter((entry: any): entry is ActionLog => Boolean(entry))\n }\n\n private buildListQuery(parsed: ActionLogListQuery): any {\n let query = (this.em.getKysely<any>() as any)\n .selectFrom('action_logs')\n .selectAll()\n .where('action_logs.deleted_at', 'is', null) as any\n\n if (parsed.tenantId) query = query.where('action_logs.tenant_id', '=', parsed.tenantId)\n if (parsed.organizationId) query = query.where('action_logs.organization_id', '=', parsed.organizationId)\n\n const actorUserIds = this.resolveActorUserIds(parsed)\n if (actorUserIds.length === 1) query = query.where('action_logs.actor_user_id', '=', actorUserIds[0])\n if (actorUserIds.length > 1) query = query.where('action_logs.actor_user_id', 'in', actorUserIds)\n\n if (parsed.includeRelated && parsed.resourceKind && parsed.resourceId) {\n query = query.where((eb: any) =>\n eb.or([\n eb.and([\n eb('action_logs.resource_kind', '=', parsed.resourceKind),\n eb('action_logs.resource_id', '=', parsed.resourceId),\n ]),\n eb.and([\n eb('action_logs.parent_resource_kind', '=', parsed.resourceKind),\n eb('action_logs.parent_resource_id', '=', parsed.resourceId),\n ]),\n eb.and([\n eb('action_logs.related_resource_kind', '=', parsed.resourceKind),\n eb('action_logs.related_resource_id', '=', parsed.resourceId),\n ]),\n ])\n )\n } else {\n if (parsed.resourceKind) query = query.where('action_logs.resource_kind', '=', parsed.resourceKind)\n if (parsed.resourceId) query = query.where('action_logs.resource_id', '=', parsed.resourceId)\n }\n\n if (parsed.undoableOnly) query = query.where('action_logs.undo_token', 'is not', null)\n if (parsed.before) query = query.where('action_logs.created_at', '<', parsed.before)\n if (parsed.after) query = query.where('action_logs.created_at', '>', parsed.after)\n\n const fieldNames = this.resolveFieldNames(parsed)\n if (fieldNames.length === 1) query = query.where('action_logs.primary_changed_field', '=', fieldNames[0])\n if (fieldNames.length > 1) query = query.where('action_logs.primary_changed_field', 'in', fieldNames)\n\n const actionTypes = this.resolveActionTypes(parsed)\n if (actionTypes.length === 1) query = query.where('action_logs.action_type', '=', actionTypes[0])\n if (actionTypes.length > 1) query = query.where('action_logs.action_type', 'in', actionTypes)\n\n if (parsed.sortField === 'user') {\n query = query.leftJoin('users as audit_actor', 'audit_actor.id', 'action_logs.actor_user_id')\n }\n\n const sortDir = parsed.sortDir === 'asc' ? 'asc' : 'desc'\n switch (parsed.sortField) {\n case 'user':\n query = query.orderBy(sql`coalesce(nullif(audit_actor.name, ''), audit_actor.email, '')`, sortDir)\n break\n case 'action':\n query = query.orderBy(sql`coalesce(action_logs.action_type, '')`, sortDir)\n break\n case 'field':\n query = query.orderBy(sql`coalesce(action_logs.primary_changed_field, '')`, sortDir)\n break\n case 'source':\n query = query.orderBy(sql`coalesce(action_logs.source_key, '')`, sortDir)\n break\n case 'createdAt':\n default:\n query = query.orderBy(SORT_FIELDS.createdAt, sortDir)\n query = query.orderBy('action_logs.id', sortDir)\n return query\n }\n\n query = query.orderBy('action_logs.created_at', 'desc')\n query = query.orderBy('action_logs.id', 'desc')\n return query\n }\n\n async count(query: Partial<ActionLogListQuery>) {\n const parsed = this.parseListQuery(query)\n const row = await (this.buildListQuery(parsed) as any)\n .clearSelect()\n .clearOrderBy()\n .select(sql<string>`count(*)`.as('count'))\n .executeTakeFirst()\n\n if (!row) return 0\n const rawCount = row.count ?? 0\n return typeof rawCount === 'number' ? rawCount : Number.parseInt(rawCount, 10) || 0\n }\n\n async list(query: Partial<ActionLogListQuery>) {\n const parsed = this.parseListQuery(query)\n const { page, pageSize } = this.resolvePagination(parsed)\n const [items, total] = await Promise.all([\n this.loadEntries(parsed),\n this.count(parsed),\n ])\n const totalPages = Math.max(1, Math.ceil((total || 0) / (pageSize || 1)))\n return { items, total, page, pageSize, totalPages }\n }\n\n async latestUndoableForActor(actorUserId: string, scope: { tenantId?: string | null; organizationId?: string | null }) {\n const where: FilterQuery<ActionLog> = {\n actorUserId,\n undoToken: { $ne: null } as any,\n executionState: 'done',\n deletedAt: null,\n }\n if (scope.tenantId) where.tenantId = scope.tenantId\n if (scope.organizationId) where.organizationId = scope.organizationId\n\n const entry = await this.em.findOne(ActionLog, where, { orderBy: { createdAt: 'desc' } })\n await this.decryptEntries(entry)\n return entry\n }\n\n async claimForUndo(id: string): Promise<boolean> {\n const affected = await this.em.nativeUpdate(\n ActionLog,\n { id, executionState: 'done', deletedAt: null },\n { executionState: 'undoing' },\n )\n return affected === 1\n }\n\n async releaseUndoClaim(id: string): Promise<boolean> {\n const affected = await this.em.nativeUpdate(\n ActionLog,\n { id, executionState: 'undoing', deletedAt: null },\n { executionState: 'done' },\n )\n return affected === 1\n }\n\n async markUndone(id: string, traceInput?: ActionLogCreateInput) {\n const fork = this.em.fork()\n const log = await fork.findOne(ActionLog, { id, deletedAt: null })\n if (!log) return null\n\n log.executionState = 'undone'\n log.undoToken = null\n\n const traceLog = traceInput ? this.createLogEntity(fork, this.parseCreateInput(traceInput)) : null\n if (traceLog) {\n fork.persist(traceLog)\n }\n\n await fork.flush()\n await this.decryptEntries(log)\n if (traceLog) await this.decryptEntries(traceLog)\n\n return log\n }\n\n async findByUndoToken(undoToken: string) {\n const entry = await this.em.findOne(ActionLog, { undoToken, deletedAt: null })\n await this.decryptEntries(entry)\n return entry\n }\n\n async findById(id: string) {\n const entry = await this.em.findOne(ActionLog, { id, deletedAt: null })\n await this.decryptEntries(entry)\n return entry\n }\n\n async latestUndoableForResource(params: {\n actorUserId: string\n tenantId?: string | null\n organizationId?: string | null\n resourceKind?: string | null\n resourceId?: string | null\n }) {\n const where: FilterQuery<ActionLog> = {\n actorUserId: params.actorUserId,\n undoToken: { $ne: null } as any,\n executionState: 'done',\n deletedAt: null,\n }\n if (params.tenantId) where.tenantId = params.tenantId\n if (params.organizationId) where.organizationId = params.organizationId\n if (params.resourceKind) where.resourceKind = params.resourceKind\n if (params.resourceId) where.resourceId = params.resourceId\n\n const entry = await this.em.findOne(ActionLog, where, { orderBy: { createdAt: 'desc' } })\n await this.decryptEntries(entry)\n return entry\n }\n\n async latestUndoneForActor(actorUserId: string, scope: { tenantId?: string | null; organizationId?: string | null }) {\n const where: FilterQuery<ActionLog> = {\n actorUserId,\n executionState: 'undone',\n deletedAt: null,\n }\n if (scope.tenantId) where.tenantId = scope.tenantId\n if (scope.organizationId) where.organizationId = scope.organizationId\n\n const entry = await this.em.findOne(ActionLog, where, { orderBy: { updatedAt: 'desc' } })\n await this.decryptEntries(entry)\n return entry\n }\n\n async markRedone(id: string) {\n const log = await this.em.findOne(ActionLog, { id, deletedAt: null })\n if (!log) return null\n\n log.executionState = 'redone'\n log.undoToken = null\n await this.em.flush()\n return log\n }\n\n async backfillProjections(options: ActionLogProjectionBackfillOptions = {}): Promise<ActionLogProjectionBackfillResult> {\n const batchSize = Math.min(Math.max(Math.trunc(options.batchSize ?? 250), 1), 1000)\n const logger = options.logger ?? (() => {})\n const result: ActionLogProjectionBackfillResult = {\n errors: 0,\n scanned: 0,\n skipped: 0,\n updated: 0,\n }\n\n let cursorCreatedAt: Date | null = null\n let cursorId: string | null = null\n\n while (true) {\n const rowsQuery = (this.em.getKysely<any>() as any)\n .selectFrom('action_logs')\n .select([\n 'action_logs.id',\n 'action_logs.tenant_id',\n 'action_logs.organization_id',\n 'action_logs.actor_user_id',\n 'action_logs.command_id',\n 'action_logs.action_label',\n 'action_logs.snapshot_before',\n 'action_logs.changes_json',\n 'action_logs.context_json',\n 'action_logs.action_type',\n 'action_logs.source_key',\n 'action_logs.changed_fields',\n 'action_logs.primary_changed_field',\n 'action_logs.created_at',\n ])\n .where('action_logs.deleted_at', 'is', null) as any\n\n if (options.tenantId) rowsQuery.where('action_logs.tenant_id', '=', options.tenantId)\n if (options.organizationId) rowsQuery.where('action_logs.organization_id', '=', options.organizationId)\n\n if (!options.force) {\n rowsQuery.where((eb: any) =>\n eb.or([\n eb('action_logs.action_type', 'is', null),\n eb('action_logs.source_key', 'is', null),\n eb('action_logs.changed_fields', 'is', null),\n ])\n )\n }\n\n if (cursorCreatedAt && cursorId) {\n rowsQuery.where((eb: any) =>\n eb.or([\n eb('action_logs.created_at', '>', cursorCreatedAt),\n eb.and([\n eb('action_logs.created_at', '=', cursorCreatedAt),\n eb('action_logs.id', '>', cursorId),\n ]),\n ])\n )\n }\n\n const rows = await rowsQuery\n .orderBy('created_at', 'asc')\n .orderBy('id', 'asc')\n .limit(batchSize)\n\n if (rows.length === 0) break\n\n for (const row of rows) {\n result.scanned += 1\n\n try {\n const decrypted = await this.decryptEntryPayload(row as unknown as Record<string, unknown>)\n const projection = deriveActionLogProjection({\n actorUserId: readString(decrypted, 'actorUserId', 'actor_user_id'),\n actionLabel: readString(decrypted, 'actionLabel', 'action_label'),\n changes: readRecord(decrypted, 'changesJson', 'changes_json'),\n commandId: readString(decrypted, 'commandId', 'command_id') ?? 'unknown',\n context: readRecord(decrypted, 'contextJson', 'context_json'),\n snapshotBefore: readValue(decrypted, 'snapshotBefore', 'snapshot_before'),\n })\n\n const needsUpdate = options.force === true\n || row.action_type !== projection.actionType\n || row.source_key !== projection.sourceKey\n || row.primary_changed_field !== projection.primaryChangedField\n || !stringArraysEqual(row.changed_fields, projection.changedFields)\n\n if (!needsUpdate) {\n result.skipped += 1\n continue\n }\n\n await (this.em.getKysely<any>() as any)\n .updateTable('action_logs')\n .set({\n action_type: projection.actionType,\n changed_fields: projection.changedFields,\n primary_changed_field: projection.primaryChangedField,\n source_key: projection.sourceKey,\n })\n .where('id', '=', row.id)\n .execute()\n\n result.updated += 1\n } catch (err) {\n result.errors += 1\n logger(`[backfill] Failed for action log ${row.id}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n const lastRow = rows[rows.length - 1]\n cursorCreatedAt = lastRow.created_at\n cursorId = lastRow.id\n\n logger(\n `[backfill] Processed ${result.scanned} action logs (updated: ${result.updated}, skipped: ${result.skipped}, errors: ${result.errors})`,\n )\n\n if (rows.length < batchSize) break\n }\n\n return result\n }\n}\n"],
5
- "mappings": "AAEA,SAAS,WAAW;AACpB,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EAEA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC;AAAA,EAEE;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,YAAY,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAEnF,IAAI,0BAA0B;AAC9B,IAAI,6BAA6C;AACjD,IAAI,0BAA0B;AAE9B,MAAM,sBAAsB,CAAC,QAAiB,eAAe,aAAa,OAAO,IAAI,YAAY,YAAY,IAAI,QAAQ,SAAS,MAAM;AAExI,MAAM,cAAc;AAAA,EAClB,WAAW;AACb;AACA,MAAM,aAAa;AAkCnB,SAAS,WAAW,WAAoC,MAA+B;AACrF,aAAW,OAAO,MAAM;AACtB,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,OAAO,UAAU,YAAY,MAAM,SAAS,EAAG,QAAO;AAAA,EAC5D;AAEA,SAAO;AACT;AAEA,SAAS,WAAW,WAAoC,MAAgD;AACtG,aAAW,OAAO,MAAM;AACtB,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,SAAS,KAAK,EAAG,QAAO;AAAA,EAC9B;AAEA,SAAO;AACT;AAEA,SAAS,UAAU,WAAoC,MAAyB;AAC9E,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,UAAU,eAAe,KAAK,QAAQ,GAAG,EAAG,QAAO,OAAO,GAAG;AAAA,EAC1E;AAEA,SAAO;AACT;AAEA,SAAS,gBAAgB,WAAoC,MAAiC;AAC5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AO,WAAW;AAClB;AAAA,UACF;AAEA,gBAAO,KAAK,GAAG,UAAe,EAC3B,YAAY,aAAa,EACzB,IAAI;AAAA,YACH,aAAa,WAAW;AAAA,YACxB,gBAAgB,WAAW;AAAA,YAC3B,uBAAuB,WAAW;AAAA,YAClC,YAAY,WAAW;AAAA,UACzB,CAAC,EACA,MAAM,MAAM,KAAK,IAAI,EAAE,EACvB,QAAQ;AAEX,iBAAO,WAAW;AAAA,QACpB,SAAS,KAAK;AACZ,iBAAO,UAAU;AACjB,UAAAA,QAAO,oCAAoC,IAAI,EAAE,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAAA,QAC1G;AAAA,MACF;AAEA,YAAM,UAAU,KAAK,KAAK,SAAS,CAAC;AACpC,wBAAkB,QAAQ;AAC1B,iBAAW,QAAQ;AAEnB,MAAAA;AAAA,QACE,wBAAwB,OAAO,OAAO,0BAA0B,OAAO,OAAO,cAAc,OAAO,OAAO,aAAa,OAAO,MAAM;AAAA,MACtI;AAEA,UAAI,KAAK,SAAS,UAAW;AAAA,IAC/B;AAEA,WAAO;AAAA,EACT;AACF;",
6
- "names": ["decrypted", "UUID_REGEX", "logger"]
4
+ "sourcesContent": ["import type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport { ActionLog } from '@open-mercato/core/modules/audit_logs/data/entities'\nimport {\n actionLogCreateSchema,\n actionLogListSchema,\n uuid,\n type ActionLogCreateInput,\n type ActionLogListQuery,\n} from '@open-mercato/core/modules/audit_logs/data/validators'\nimport { isRecord } from '@open-mercato/core/modules/audit_logs/lib/changeRows'\nimport {\n ACTION_LOG_FILTER_TYPES,\n type ActionLogFilterType,\n deriveActionLogProjection,\n} from '@open-mercato/core/modules/audit_logs/lib/projections'\nimport { decryptWithAesGcm } from '@open-mercato/shared/lib/encryption/aes'\nimport {\n TenantDataEncryptionService,\n parseDecryptedFieldValue,\n} from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport { toOptionalString } from '@open-mercato/shared/lib/string/coerce'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('audit_logs').child({ component: 'action-log-service' })\n\nlet validationWarningLogged = false\nlet runtimeValidationAvailable: boolean | null = null\nlet decryptionWarningLogged = false\n\nconst isZodRuntimeMissing = (err: unknown) => err instanceof TypeError && typeof err.message === 'string' && err.message.includes('_zod')\n\nconst SORT_FIELDS = {\n createdAt: 'action_logs.created_at',\n} as const\nconst UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/\n// Mirrors what `uuid` (`data/validators.ts`) accepts \u2014 versions 1-8 plus the nil and\n// max UUIDs \u2014 and is used only when the zod runtime is unavailable, so the actor\n// sanitizer can never reject a value `actionLogCreateSchema` would have accepted.\nexport const SCHEMA_UUID_REGEX = /^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/\nconst API_KEY_ACTOR_PREFIX = 'api_key:'\nconst SYSTEM_ACTOR_PREFIX = 'system:'\n// `context.systemActor` names the automated principal behind an entry; `context.source`\n// (read by `deriveActionLogSource`) names the channel it arrived through. They are\n// siblings on purpose and never contradict each other: an entry carrying `systemActor`\n// has a null actor column, which already derives the `system` source.\nconst SYSTEM_ACTOR_CONTEXT_KEY = 'systemActor'\nconst SYSTEM_ACTOR_REFERENCE_MAX_LENGTH = 255\n\nfunction toNullableUuid(value: unknown): string | null {\n return typeof value === 'string' && UUID_REGEX.test(value) ? value : null\n}\n\nfunction isSchemaUuid(value: string): boolean {\n if (runtimeValidationAvailable === false) return SCHEMA_UUID_REGEX.test(value)\n\n try {\n return uuid.safeParse(value).success\n } catch (err) {\n if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false\n return SCHEMA_UUID_REGEX.test(value)\n }\n}\n\nfunction readActorCandidate(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction normalizeActorUserId(value: unknown): string | null {\n const candidate = readActorCandidate(value)\n if (!candidate) return null\n const unwrapped = candidate.startsWith(API_KEY_ACTOR_PREFIX)\n ? candidate.slice(API_KEY_ACTOR_PREFIX.length)\n : candidate\n\n return isSchemaUuid(unwrapped) ? unwrapped : null\n}\n\nfunction toSystemActorReference(candidate: string): string | null {\n if (!candidate.startsWith(SYSTEM_ACTOR_PREFIX)) return null\n if (candidate.length === SYSTEM_ACTOR_PREFIX.length) return null\n return candidate.slice(0, SYSTEM_ACTOR_REFERENCE_MAX_LENGTH)\n}\n\ntype ActionLogProjectionBackfillOptions = {\n batchSize?: number\n force?: boolean\n logger?: (message: string) => void\n organizationId?: string | null\n tenantId?: string | null\n}\n\nexport type ActionLogProjectionBackfillResult = {\n errors: number\n scanned: number\n skipped: number\n updated: number\n}\n\ntype BackfillRow = {\n action_label: string | null\n action_type: string | null\n actor_user_id: string | null\n changed_fields: string[] | null\n changes_json: Record<string, unknown> | null\n command_id: string\n context_json: Record<string, unknown> | null\n created_at: Date\n id: string\n organization_id: string | null\n primary_changed_field: string | null\n snapshot_before: unknown | null\n source_key: string | null\n tenant_id: string | null\n}\n\nfunction readString(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n\n return null\n}\n\nfunction readRecord(record: Record<string, unknown>, ...keys: string[]): Record<string, unknown> | null {\n for (const key of keys) {\n const value = record[key]\n if (isRecord(value)) return value\n }\n\n return null\n}\n\nfunction readValue(record: Record<string, unknown>, ...keys: string[]): unknown {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key)) return record[key]\n }\n\n return undefined\n}\n\nfunction readStringArray(record: Record<string, unknown>, ...keys: string[]): string[] | null {\n for (const key of keys) {\n const value = record[key]\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === 'string')\n }\n }\n\n return null\n}\n\nfunction stringArraysEqual(left: string[] | null, right: string[]): boolean {\n if (!Array.isArray(left)) return false\n if (left.length !== right.length) return false\n\n return left.every((value, index) => value === right[index])\n}\n\nexport class ActionLogService {\n constructor(\n private readonly em: EntityManager,\n private readonly tenantEncryptionService?: TenantDataEncryptionService,\n ) {}\n\n private async decryptEntryPayload<T extends Record<string, unknown>>(entry: T): Promise<T> {\n if (!this.tenantEncryptionService?.isEnabled()) return entry\n\n try {\n const tenantId = readString(entry, 'tenantId', 'tenant_id')\n const organizationId = readString(entry, 'organizationId', 'organization_id')\n const dek = await this.tenantEncryptionService.getDek(tenantId)\n const deepDecrypt = (value: unknown): unknown => {\n if (!dek) return value\n if (typeof value === 'string' && value.split(':').length === 4 && value.endsWith(':v1')) {\n const decrypted = decryptWithAesGcm(value, dek.key)\n if (decrypted === null) return value\n return parseDecryptedFieldValue(decrypted)\n }\n if (Array.isArray(value)) return value.map((item) => deepDecrypt(item))\n if (value && typeof value === 'object') {\n const copy: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n copy[key] = deepDecrypt(item)\n }\n return copy\n }\n return value\n }\n\n const decrypted = await this.tenantEncryptionService.decryptEntityPayload(\n 'audit_logs:action_log',\n entry,\n tenantId,\n organizationId,\n )\n\n const merged = {\n ...entry,\n ...decrypted,\n } as Record<string, unknown>\n\n // Audit log jsonb columns are encrypted as JSON-stringified payloads. After the\n // service-level `decryptEntityPayload` call (which now returns raw strings \u2014\n // see issue #1810 follow-up), reattach the structured shape via\n // `parseDecryptedFieldValue` before running the recursive `deepDecrypt` walk\n // so nested encrypted strings inside payload objects/arrays are handled.\n const restoreJson = (value: unknown): unknown =>\n typeof value === 'string' ? parseDecryptedFieldValue(value) : value\n\n merged.changesJson = deepDecrypt(restoreJson(merged.changesJson ?? merged.changes_json ?? entry.changesJson ?? entry.changes_json))\n merged.changes_json = merged.changesJson\n merged.snapshotBefore = deepDecrypt(restoreJson(merged.snapshotBefore ?? merged.snapshot_before ?? entry.snapshotBefore ?? entry.snapshot_before))\n merged.snapshot_before = merged.snapshotBefore\n merged.snapshotAfter = deepDecrypt(restoreJson(merged.snapshotAfter ?? merged.snapshot_after ?? entry.snapshotAfter ?? entry.snapshot_after))\n merged.snapshot_after = merged.snapshotAfter\n merged.commandPayload = deepDecrypt(restoreJson(merged.commandPayload ?? merged.command_payload ?? entry.commandPayload ?? entry.command_payload))\n merged.command_payload = merged.commandPayload\n merged.contextJson = deepDecrypt(restoreJson(merged.contextJson ?? merged.context_json ?? entry.contextJson ?? entry.context_json))\n merged.context_json = merged.contextJson\n\n return merged as T\n } catch (err) {\n if (!decryptionWarningLogged) {\n decryptionWarningLogged = true\n logger.warn('Failed to decrypt action log entry', { err })\n }\n return entry\n }\n }\n\n private async decryptEntries(entries: ActionLog | ActionLog[] | null | undefined): Promise<void> {\n if (!entries) return\n\n const list = Array.isArray(entries) ? entries : [entries]\n for (const entry of list) {\n Object.assign(entry as unknown as Record<string, unknown>, await this.decryptEntryPayload(entry as unknown as Record<string, unknown>))\n }\n }\n\n async log(input: ActionLogCreateInput): Promise<ActionLog | null> {\n const data = this.parseCreateInput(input)\n const fork = this.em.fork()\n const log = this.createLogEntity(fork, data)\n await fork.persist(log).flush()\n await this.decryptEntries(log)\n return log\n }\n\n private parseCreateInput(input: ActionLogCreateInput): ActionLogCreateInput {\n const sanitized = this.sanitizeActor(input)\n let data: ActionLogCreateInput\n const schema = actionLogCreateSchema as typeof actionLogCreateSchema & { _zod?: unknown }\n const canValidate = Boolean(schema && typeof schema.parse === 'function')\n const shouldValidate = canValidate && runtimeValidationAvailable !== false\n\n if (shouldValidate) {\n try {\n data = schema.parse(sanitized)\n runtimeValidationAvailable = true\n } catch (err) {\n if (!isZodRuntimeMissing(err) && !validationWarningLogged) {\n validationWarningLogged = true\n logger.warn('Falling back to permissive action log payload parser', { err })\n }\n if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false\n data = this.normalizeInput(sanitized)\n }\n } else {\n data = this.normalizeInput(sanitized)\n }\n\n return data\n }\n\n private sanitizeActor(input: ActionLogCreateInput): ActionLogCreateInput {\n if (!input) return input\n const candidate = readActorCandidate(input.actorUserId)\n const actorUserId = normalizeActorUserId(candidate)\n const systemActorReference = candidate && !actorUserId ? toSystemActorReference(candidate) : null\n\n if (!systemActorReference) {\n if (actorUserId === (input.actorUserId ?? null)) return input\n return { ...input, actorUserId }\n }\n\n const context = isRecord(input.context) ? { ...input.context } : {}\n if (context[SYSTEM_ACTOR_CONTEXT_KEY] === undefined) {\n context[SYSTEM_ACTOR_CONTEXT_KEY] = systemActorReference\n }\n\n return { ...input, actorUserId, context }\n }\n\n private createLogEntity(fork: EntityManager, data: ActionLogCreateInput): ActionLog {\n const projection = deriveActionLogProjection({\n actorUserId: data.actorUserId ?? null,\n actionLabel: data.actionLabel ?? null,\n changes: isRecord(data.changes) ? data.changes : null,\n commandId: data.commandId,\n context: isRecord(data.context) ? data.context : null,\n snapshotBefore: data.snapshotBefore,\n })\n\n return fork.create(ActionLog, {\n tenantId: data.tenantId ?? null,\n organizationId: data.organizationId ?? null,\n actorUserId: data.actorUserId ?? null,\n commandId: data.commandId,\n actionLabel: data.actionLabel ?? null,\n actionType: projection.actionType,\n resourceKind: data.resourceKind ?? null,\n resourceId: data.resourceId ?? null,\n parentResourceKind: data.parentResourceKind ?? null,\n parentResourceId: data.parentResourceId ?? null,\n relatedResourceKind: toOptionalString(data.relatedResourceKind) ?? null,\n relatedResourceId: toOptionalString(data.relatedResourceId) ?? null,\n executionState: data.executionState ?? 'done',\n undoToken: data.undoToken ?? null,\n commandPayload: data.commandPayload ?? null,\n snapshotBefore: data.snapshotBefore ?? null,\n snapshotAfter: data.snapshotAfter ?? null,\n changesJson: isRecord(data.changes) ? data.changes : null,\n changedFields: projection.changedFields,\n primaryChangedField: projection.primaryChangedField,\n contextJson: isRecord(data.context) ? data.context : null,\n sourceKey: projection.sourceKey,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n }\n\n private normalizeInput(input: Partial<ActionLogCreateInput> | null | undefined): ActionLogCreateInput {\n if (!input) {\n return {\n tenantId: null,\n organizationId: null,\n actorUserId: null,\n commandId: 'unknown',\n actionLabel: undefined,\n resourceKind: undefined,\n resourceId: undefined,\n relatedResourceKind: null,\n relatedResourceId: null,\n executionState: 'done',\n undoToken: undefined,\n commandPayload: undefined,\n snapshotBefore: undefined,\n snapshotAfter: undefined,\n changes: undefined,\n context: undefined,\n }\n }\n\n const normalizeRecordLike = (value: unknown): ActionLogCreateInput['changes'] => {\n if (value === null) return null\n if (Array.isArray(value)) return value\n if (typeof value === 'object') return value as Record<string, unknown>\n return undefined\n }\n\n const normalizeContext = (value: unknown) => (\n typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n )\n\n return {\n tenantId: toNullableUuid(input.tenantId),\n organizationId: toNullableUuid(input.organizationId),\n actorUserId: normalizeActorUserId(input.actorUserId),\n commandId: typeof input.commandId === 'string' && input.commandId.length > 0 ? input.commandId : 'unknown',\n actionLabel: toOptionalString(input.actionLabel) ?? undefined,\n resourceKind: toOptionalString(input.resourceKind) ?? undefined,\n resourceId: toOptionalString(input.resourceId) ?? undefined,\n parentResourceKind: toOptionalString(input.parentResourceKind) ?? null,\n parentResourceId: toOptionalString(input.parentResourceId) ?? null,\n relatedResourceKind: toOptionalString(input.relatedResourceKind) ?? null,\n relatedResourceId: toOptionalString(input.relatedResourceId) ?? null,\n executionState: input.executionState === 'undone' || input.executionState === 'failed' ? input.executionState : 'done',\n undoToken: toOptionalString(input.undoToken) ?? undefined,\n commandPayload: input.commandPayload,\n snapshotBefore: input.snapshotBefore,\n snapshotAfter: input.snapshotAfter,\n changes: normalizeRecordLike(input.changes),\n context: normalizeContext(input.context),\n }\n }\n\n private parseListQuery(query: Partial<ActionLogListQuery>) {\n return actionLogListSchema.parse({\n ...query,\n })\n }\n\n private resolveActorUserIds(parsed: ActionLogListQuery): string[] {\n const values = [...(parsed.actorUserIds ?? [])]\n if (parsed.actorUserId) values.push(parsed.actorUserId)\n\n return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)))\n }\n\n private resolveFieldNames(parsed: ActionLogListQuery): string[] {\n const values = [...(parsed.fieldNames ?? [])]\n if (parsed.fieldName) values.push(parsed.fieldName)\n\n return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)))\n }\n\n private resolveActionTypes(parsed: ActionLogListQuery): ActionLogFilterType[] {\n const values = [...(parsed.actionTypes ?? [])]\n if (parsed.actionType) values.push(parsed.actionType)\n\n return Array.from(new Set(values))\n .filter((value): value is ActionLogFilterType => ACTION_LOG_FILTER_TYPES.includes(value as ActionLogFilterType))\n }\n\n private resolvePagination(parsed: ActionLogListQuery): { page: number; pageSize: number; offset: number; limit: number } {\n const pageSize =\n typeof parsed.pageSize === 'number' && parsed.pageSize > 0\n ? parsed.pageSize\n : typeof parsed.limit === 'number' && parsed.limit > 0\n ? parsed.limit\n : 50\n const page = typeof parsed.page === 'number' && parsed.page > 0 ? parsed.page : 1\n const offset =\n typeof parsed.offset === 'number' && parsed.offset >= 0\n ? parsed.offset\n : (page - 1) * pageSize\n return { page, pageSize, offset, limit: pageSize }\n }\n\n private async loadEntries(parsed: ActionLogListQuery, options?: { paginate?: boolean }) {\n let query = (this.buildListQuery(parsed) as any).select('action_logs.id as id')\n\n if (options?.paginate !== false) {\n const { limit, offset } = this.resolvePagination(parsed)\n query = query.limit(limit).offset(offset)\n }\n\n const rows = await query.execute()\n const ids = rows.map((row: any) => row.id).filter(Boolean)\n if (ids.length === 0) return []\n\n const results = await this.em.find(ActionLog, {\n id: { $in: ids } as any,\n deletedAt: null,\n })\n await this.decryptEntries(results)\n\n const byId = new Map(results.map((entry: any) => [entry.id, entry]))\n return ids\n .map((id: any) => byId.get(id))\n .filter((entry: any): entry is ActionLog => Boolean(entry))\n }\n\n private buildListQuery(parsed: ActionLogListQuery): any {\n let query = (this.em.getKysely<any>() as any)\n .selectFrom('action_logs')\n .selectAll()\n .where('action_logs.deleted_at', 'is', null) as any\n\n if (parsed.tenantId) query = query.where('action_logs.tenant_id', '=', parsed.tenantId)\n if (parsed.organizationId) query = query.where('action_logs.organization_id', '=', parsed.organizationId)\n\n const actorUserIds = this.resolveActorUserIds(parsed)\n if (actorUserIds.length === 1) query = query.where('action_logs.actor_user_id', '=', actorUserIds[0])\n if (actorUserIds.length > 1) query = query.where('action_logs.actor_user_id', 'in', actorUserIds)\n\n if (parsed.includeRelated && parsed.resourceKind && parsed.resourceId) {\n query = query.where((eb: any) =>\n eb.or([\n eb.and([\n eb('action_logs.resource_kind', '=', parsed.resourceKind),\n eb('action_logs.resource_id', '=', parsed.resourceId),\n ]),\n eb.and([\n eb('action_logs.parent_resource_kind', '=', parsed.resourceKind),\n eb('action_logs.parent_resource_id', '=', parsed.resourceId),\n ]),\n eb.and([\n eb('action_logs.related_resource_kind', '=', parsed.resourceKind),\n eb('action_logs.related_resource_id', '=', parsed.resourceId),\n ]),\n ])\n )\n } else {\n if (parsed.resourceKind) query = query.where('action_logs.resource_kind', '=', parsed.resourceKind)\n if (parsed.resourceId) query = query.where('action_logs.resource_id', '=', parsed.resourceId)\n }\n\n if (parsed.undoableOnly) query = query.where('action_logs.undo_token', 'is not', null)\n if (parsed.before) query = query.where('action_logs.created_at', '<', parsed.before)\n if (parsed.after) query = query.where('action_logs.created_at', '>', parsed.after)\n\n const fieldNames = this.resolveFieldNames(parsed)\n if (fieldNames.length === 1) query = query.where('action_logs.primary_changed_field', '=', fieldNames[0])\n if (fieldNames.length > 1) query = query.where('action_logs.primary_changed_field', 'in', fieldNames)\n\n const actionTypes = this.resolveActionTypes(parsed)\n if (actionTypes.length === 1) query = query.where('action_logs.action_type', '=', actionTypes[0])\n if (actionTypes.length > 1) query = query.where('action_logs.action_type', 'in', actionTypes)\n\n if (parsed.sortField === 'user') {\n query = query.leftJoin('users as audit_actor', 'audit_actor.id', 'action_logs.actor_user_id')\n }\n\n const sortDir = parsed.sortDir === 'asc' ? 'asc' : 'desc'\n switch (parsed.sortField) {\n case 'user':\n query = query.orderBy(sql`coalesce(nullif(audit_actor.name, ''), audit_actor.email, '')`, sortDir)\n break\n case 'action':\n query = query.orderBy(sql`coalesce(action_logs.action_type, '')`, sortDir)\n break\n case 'field':\n query = query.orderBy(sql`coalesce(action_logs.primary_changed_field, '')`, sortDir)\n break\n case 'source':\n query = query.orderBy(sql`coalesce(action_logs.source_key, '')`, sortDir)\n break\n case 'createdAt':\n default:\n query = query.orderBy(SORT_FIELDS.createdAt, sortDir)\n query = query.orderBy('action_logs.id', sortDir)\n return query\n }\n\n query = query.orderBy('action_logs.created_at', 'desc')\n query = query.orderBy('action_logs.id', 'desc')\n return query\n }\n\n async count(query: Partial<ActionLogListQuery>) {\n const parsed = this.parseListQuery(query)\n const row = await (this.buildListQuery(parsed) as any)\n .clearSelect()\n .clearOrderBy()\n .select(sql<string>`count(*)`.as('count'))\n .executeTakeFirst()\n\n if (!row) return 0\n const rawCount = row.count ?? 0\n return typeof rawCount === 'number' ? rawCount : Number.parseInt(rawCount, 10) || 0\n }\n\n async list(query: Partial<ActionLogListQuery>) {\n const parsed = this.parseListQuery(query)\n const { page, pageSize } = this.resolvePagination(parsed)\n const [items, total] = await Promise.all([\n this.loadEntries(parsed),\n this.count(parsed),\n ])\n const totalPages = Math.max(1, Math.ceil((total || 0) / (pageSize || 1)))\n return { items, total, page, pageSize, totalPages }\n }\n\n async latestUndoableForActor(actorUserId: string, scope: { tenantId?: string | null; organizationId?: string | null }) {\n const where: FilterQuery<ActionLog> = {\n actorUserId,\n undoToken: { $ne: null } as any,\n executionState: 'done',\n deletedAt: null,\n }\n if (scope.tenantId) where.tenantId = scope.tenantId\n if (scope.organizationId) where.organizationId = scope.organizationId\n\n const entry = await this.em.findOne(ActionLog, where, { orderBy: { createdAt: 'desc' } })\n await this.decryptEntries(entry)\n return entry\n }\n\n async claimForUndo(id: string): Promise<boolean> {\n const affected = await this.em.nativeUpdate(\n ActionLog,\n { id, executionState: 'done', deletedAt: null },\n { executionState: 'undoing' },\n )\n return affected === 1\n }\n\n async releaseUndoClaim(id: string): Promise<boolean> {\n const affected = await this.em.nativeUpdate(\n ActionLog,\n { id, executionState: 'undoing', deletedAt: null },\n { executionState: 'done' },\n )\n return affected === 1\n }\n\n async markUndone(id: string, traceInput?: ActionLogCreateInput) {\n const fork = this.em.fork()\n const log = await fork.findOne(ActionLog, { id, deletedAt: null })\n if (!log) return null\n\n log.executionState = 'undone'\n log.undoToken = null\n\n const traceLog = traceInput ? this.createLogEntity(fork, this.parseCreateInput(traceInput)) : null\n if (traceLog) {\n fork.persist(traceLog)\n }\n\n await fork.flush()\n await this.decryptEntries(log)\n if (traceLog) await this.decryptEntries(traceLog)\n\n return log\n }\n\n async findByUndoToken(undoToken: string) {\n const entry = await this.em.findOne(ActionLog, { undoToken, deletedAt: null })\n await this.decryptEntries(entry)\n return entry\n }\n\n async findById(id: string) {\n const entry = await this.em.findOne(ActionLog, { id, deletedAt: null })\n await this.decryptEntries(entry)\n return entry\n }\n\n async latestUndoableForResource(params: {\n actorUserId: string\n tenantId?: string | null\n organizationId?: string | null\n resourceKind?: string | null\n resourceId?: string | null\n }) {\n const where: FilterQuery<ActionLog> = {\n actorUserId: params.actorUserId,\n undoToken: { $ne: null } as any,\n executionState: 'done',\n deletedAt: null,\n }\n if (params.tenantId) where.tenantId = params.tenantId\n if (params.organizationId) where.organizationId = params.organizationId\n if (params.resourceKind) where.resourceKind = params.resourceKind\n if (params.resourceId) where.resourceId = params.resourceId\n\n const entry = await this.em.findOne(ActionLog, where, { orderBy: { createdAt: 'desc' } })\n await this.decryptEntries(entry)\n return entry\n }\n\n async latestUndoneForActor(actorUserId: string, scope: { tenantId?: string | null; organizationId?: string | null }) {\n const where: FilterQuery<ActionLog> = {\n actorUserId,\n executionState: 'undone',\n deletedAt: null,\n }\n if (scope.tenantId) where.tenantId = scope.tenantId\n if (scope.organizationId) where.organizationId = scope.organizationId\n\n const entry = await this.em.findOne(ActionLog, where, { orderBy: { updatedAt: 'desc' } })\n await this.decryptEntries(entry)\n return entry\n }\n\n async markRedone(id: string) {\n const log = await this.em.findOne(ActionLog, { id, deletedAt: null })\n if (!log) return null\n\n log.executionState = 'redone'\n log.undoToken = null\n await this.em.flush()\n return log\n }\n\n async backfillProjections(options: ActionLogProjectionBackfillOptions = {}): Promise<ActionLogProjectionBackfillResult> {\n const batchSize = Math.min(Math.max(Math.trunc(options.batchSize ?? 250), 1), 1000)\n const logger = options.logger ?? (() => {})\n const result: ActionLogProjectionBackfillResult = {\n errors: 0,\n scanned: 0,\n skipped: 0,\n updated: 0,\n }\n\n let cursorCreatedAt: Date | null = null\n let cursorId: string | null = null\n\n while (true) {\n const rowsQuery = (this.em.getKysely<any>() as any)\n .selectFrom('action_logs')\n .select([\n 'action_logs.id',\n 'action_logs.tenant_id',\n 'action_logs.organization_id',\n 'action_logs.actor_user_id',\n 'action_logs.command_id',\n 'action_logs.action_label',\n 'action_logs.snapshot_before',\n 'action_logs.changes_json',\n 'action_logs.context_json',\n 'action_logs.action_type',\n 'action_logs.source_key',\n 'action_logs.changed_fields',\n 'action_logs.primary_changed_field',\n 'action_logs.created_at',\n ])\n .where('action_logs.deleted_at', 'is', null) as any\n\n if (options.tenantId) rowsQuery.where('action_logs.tenant_id', '=', options.tenantId)\n if (options.organizationId) rowsQuery.where('action_logs.organization_id', '=', options.organizationId)\n\n if (!options.force) {\n rowsQuery.where((eb: any) =>\n eb.or([\n eb('action_logs.action_type', 'is', null),\n eb('action_logs.source_key', 'is', null),\n eb('action_logs.changed_fields', 'is', null),\n ])\n )\n }\n\n if (cursorCreatedAt && cursorId) {\n rowsQuery.where((eb: any) =>\n eb.or([\n eb('action_logs.created_at', '>', cursorCreatedAt),\n eb.and([\n eb('action_logs.created_at', '=', cursorCreatedAt),\n eb('action_logs.id', '>', cursorId),\n ]),\n ])\n )\n }\n\n const rows = await rowsQuery\n .orderBy('created_at', 'asc')\n .orderBy('id', 'asc')\n .limit(batchSize)\n\n if (rows.length === 0) break\n\n for (const row of rows) {\n result.scanned += 1\n\n try {\n const decrypted = await this.decryptEntryPayload(row as unknown as Record<string, unknown>)\n const projection = deriveActionLogProjection({\n actorUserId: readString(decrypted, 'actorUserId', 'actor_user_id'),\n actionLabel: readString(decrypted, 'actionLabel', 'action_label'),\n changes: readRecord(decrypted, 'changesJson', 'changes_json'),\n commandId: readString(decrypted, 'commandId', 'command_id') ?? 'unknown',\n context: readRecord(decrypted, 'contextJson', 'context_json'),\n snapshotBefore: readValue(decrypted, 'snapshotBefore', 'snapshot_before'),\n })\n\n const needsUpdate = options.force === true\n || row.action_type !== projection.actionType\n || row.source_key !== projection.sourceKey\n || row.primary_changed_field !== projection.primaryChangedField\n || !stringArraysEqual(row.changed_fields, projection.changedFields)\n\n if (!needsUpdate) {\n result.skipped += 1\n continue\n }\n\n await (this.em.getKysely<any>() as any)\n .updateTable('action_logs')\n .set({\n action_type: projection.actionType,\n changed_fields: projection.changedFields,\n primary_changed_field: projection.primaryChangedField,\n source_key: projection.sourceKey,\n })\n .where('id', '=', row.id)\n .execute()\n\n result.updated += 1\n } catch (err) {\n result.errors += 1\n logger(`[backfill] Failed for action log ${row.id}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n const lastRow = rows[rows.length - 1]\n cursorCreatedAt = lastRow.created_at\n cursorId = lastRow.id\n\n logger(\n `[backfill] Processed ${result.scanned} action logs (updated: ${result.updated}, skipped: ${result.skipped}, errors: ${result.errors})`,\n )\n\n if (rows.length < batchSize) break\n }\n\n return result\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,WAAW;AACpB,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,gBAAgB;AACzB;AAAA,EACE;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EACvB,QAAQ;AAEX,iBAAO,WAAW;AAAA,QACpB,SAAS,KAAK;AACZ,iBAAO,UAAU;AACjB,UAAAA,QAAO,oCAAoC,IAAI,EAAE,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAAA,QAC1G;AAAA,MACF;AAEA,YAAM,UAAU,KAAK,KAAK,SAAS,CAAC;AACpC,wBAAkB,QAAQ;AAC1B,iBAAW,QAAQ;AAEnB,MAAAA;AAAA,QACE,wBAAwB,OAAO,OAAO,0BAA0B,OAAO,OAAO,cAAc,OAAO,OAAO,aAAa,OAAO,MAAM;AAAA,MACtI;AAEA,UAAI,KAAK,SAAS,UAAW;AAAA,IAC/B;AAEA,WAAO;AAAA,EACT;AACF;",
6
+ "names": ["decrypted", "logger"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.6.8-develop.7067.1.82e9867ea1",
3
+ "version": "0.6.8-develop.7068.1.c55b52e1a1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -252,16 +252,16 @@
252
252
  "zod": "^4.4.3"
253
253
  },
254
254
  "peerDependencies": {
255
- "@open-mercato/ai-assistant": "0.6.8-develop.7067.1.82e9867ea1",
256
- "@open-mercato/shared": "0.6.8-develop.7067.1.82e9867ea1",
257
- "@open-mercato/ui": "0.6.8-develop.7067.1.82e9867ea1",
255
+ "@open-mercato/ai-assistant": "0.6.8-develop.7068.1.c55b52e1a1",
256
+ "@open-mercato/shared": "0.6.8-develop.7068.1.c55b52e1a1",
257
+ "@open-mercato/ui": "0.6.8-develop.7068.1.c55b52e1a1",
258
258
  "react": "^19.0.0",
259
259
  "react-dom": "^19.0.0"
260
260
  },
261
261
  "devDependencies": {
262
- "@open-mercato/ai-assistant": "0.6.8-develop.7067.1.82e9867ea1",
263
- "@open-mercato/shared": "0.6.8-develop.7067.1.82e9867ea1",
264
- "@open-mercato/ui": "0.6.8-develop.7067.1.82e9867ea1",
262
+ "@open-mercato/ai-assistant": "0.6.8-develop.7068.1.c55b52e1a1",
263
+ "@open-mercato/shared": "0.6.8-develop.7068.1.c55b52e1a1",
264
+ "@open-mercato/ui": "0.6.8-develop.7068.1.c55b52e1a1",
265
265
  "@testing-library/dom": "^10.4.1",
266
266
  "@testing-library/jest-dom": "^7.0.0",
267
267
  "@testing-library/react": "^16.3.1",
@@ -5,6 +5,7 @@ import { ActionLog } from '@open-mercato/core/modules/audit_logs/data/entities'
5
5
  import {
6
6
  actionLogCreateSchema,
7
7
  actionLogListSchema,
8
+ uuid,
8
9
  type ActionLogCreateInput,
9
10
  type ActionLogListQuery,
10
11
  } from '@open-mercato/core/modules/audit_logs/data/validators'
@@ -34,6 +35,55 @@ const SORT_FIELDS = {
34
35
  createdAt: 'action_logs.created_at',
35
36
  } as const
36
37
  const UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/
38
+ // Mirrors what `uuid` (`data/validators.ts`) accepts — versions 1-8 plus the nil and
39
+ // max UUIDs — and is used only when the zod runtime is unavailable, so the actor
40
+ // sanitizer can never reject a value `actionLogCreateSchema` would have accepted.
41
+ export const SCHEMA_UUID_REGEX = /^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/
42
+ const API_KEY_ACTOR_PREFIX = 'api_key:'
43
+ const SYSTEM_ACTOR_PREFIX = 'system:'
44
+ // `context.systemActor` names the automated principal behind an entry; `context.source`
45
+ // (read by `deriveActionLogSource`) names the channel it arrived through. They are
46
+ // siblings on purpose and never contradict each other: an entry carrying `systemActor`
47
+ // has a null actor column, which already derives the `system` source.
48
+ const SYSTEM_ACTOR_CONTEXT_KEY = 'systemActor'
49
+ const SYSTEM_ACTOR_REFERENCE_MAX_LENGTH = 255
50
+
51
+ function toNullableUuid(value: unknown): string | null {
52
+ return typeof value === 'string' && UUID_REGEX.test(value) ? value : null
53
+ }
54
+
55
+ function isSchemaUuid(value: string): boolean {
56
+ if (runtimeValidationAvailable === false) return SCHEMA_UUID_REGEX.test(value)
57
+
58
+ try {
59
+ return uuid.safeParse(value).success
60
+ } catch (err) {
61
+ if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false
62
+ return SCHEMA_UUID_REGEX.test(value)
63
+ }
64
+ }
65
+
66
+ function readActorCandidate(value: unknown): string | null {
67
+ if (typeof value !== 'string') return null
68
+ const trimmed = value.trim()
69
+ return trimmed.length > 0 ? trimmed : null
70
+ }
71
+
72
+ function normalizeActorUserId(value: unknown): string | null {
73
+ const candidate = readActorCandidate(value)
74
+ if (!candidate) return null
75
+ const unwrapped = candidate.startsWith(API_KEY_ACTOR_PREFIX)
76
+ ? candidate.slice(API_KEY_ACTOR_PREFIX.length)
77
+ : candidate
78
+
79
+ return isSchemaUuid(unwrapped) ? unwrapped : null
80
+ }
81
+
82
+ function toSystemActorReference(candidate: string): string | null {
83
+ if (!candidate.startsWith(SYSTEM_ACTOR_PREFIX)) return null
84
+ if (candidate.length === SYSTEM_ACTOR_PREFIX.length) return null
85
+ return candidate.slice(0, SYSTEM_ACTOR_REFERENCE_MAX_LENGTH)
86
+ }
37
87
 
38
88
  type ActionLogProjectionBackfillOptions = {
39
89
  batchSize?: number
@@ -202,6 +252,7 @@ export class ActionLogService {
202
252
  }
203
253
 
204
254
  private parseCreateInput(input: ActionLogCreateInput): ActionLogCreateInput {
255
+ const sanitized = this.sanitizeActor(input)
205
256
  let data: ActionLogCreateInput
206
257
  const schema = actionLogCreateSchema as typeof actionLogCreateSchema & { _zod?: unknown }
207
258
  const canValidate = Boolean(schema && typeof schema.parse === 'function')
@@ -209,7 +260,7 @@ export class ActionLogService {
209
260
 
210
261
  if (shouldValidate) {
211
262
  try {
212
- data = schema.parse(input)
263
+ data = schema.parse(sanitized)
213
264
  runtimeValidationAvailable = true
214
265
  } catch (err) {
215
266
  if (!isZodRuntimeMissing(err) && !validationWarningLogged) {
@@ -217,15 +268,34 @@ export class ActionLogService {
217
268
  logger.warn('Falling back to permissive action log payload parser', { err })
218
269
  }
219
270
  if (isZodRuntimeMissing(err)) runtimeValidationAvailable = false
220
- data = this.normalizeInput(input)
271
+ data = this.normalizeInput(sanitized)
221
272
  }
222
273
  } else {
223
- data = this.normalizeInput(input)
274
+ data = this.normalizeInput(sanitized)
224
275
  }
225
276
 
226
277
  return data
227
278
  }
228
279
 
280
+ private sanitizeActor(input: ActionLogCreateInput): ActionLogCreateInput {
281
+ if (!input) return input
282
+ const candidate = readActorCandidate(input.actorUserId)
283
+ const actorUserId = normalizeActorUserId(candidate)
284
+ const systemActorReference = candidate && !actorUserId ? toSystemActorReference(candidate) : null
285
+
286
+ if (!systemActorReference) {
287
+ if (actorUserId === (input.actorUserId ?? null)) return input
288
+ return { ...input, actorUserId }
289
+ }
290
+
291
+ const context = isRecord(input.context) ? { ...input.context } : {}
292
+ if (context[SYSTEM_ACTOR_CONTEXT_KEY] === undefined) {
293
+ context[SYSTEM_ACTOR_CONTEXT_KEY] = systemActorReference
294
+ }
295
+
296
+ return { ...input, actorUserId, context }
297
+ }
298
+
229
299
  private createLogEntity(fork: EntityManager, data: ActionLogCreateInput): ActionLog {
230
300
  const projection = deriveActionLogProjection({
231
301
  actorUserId: data.actorUserId ?? null,
@@ -286,13 +356,6 @@ export class ActionLogService {
286
356
  }
287
357
  }
288
358
 
289
- const UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/
290
- const toNullableUuid = (value: unknown) => {
291
- if (typeof value !== 'string' || value.length === 0) return null
292
- const candidate = value.startsWith('api_key:') ? value.slice('api_key:'.length) : value
293
- return UUID_REGEX.test(candidate) ? candidate : null
294
- }
295
-
296
359
  const normalizeRecordLike = (value: unknown): ActionLogCreateInput['changes'] => {
297
360
  if (value === null) return null
298
361
  if (Array.isArray(value)) return value
@@ -309,7 +372,7 @@ export class ActionLogService {
309
372
  return {
310
373
  tenantId: toNullableUuid(input.tenantId),
311
374
  organizationId: toNullableUuid(input.organizationId),
312
- actorUserId: toNullableUuid(input.actorUserId),
375
+ actorUserId: normalizeActorUserId(input.actorUserId),
313
376
  commandId: typeof input.commandId === 'string' && input.commandId.length > 0 ? input.commandId : 'unknown',
314
377
  actionLabel: toOptionalString(input.actionLabel) ?? undefined,
315
378
  resourceKind: toOptionalString(input.resourceKind) ?? undefined,