@open-mercato/enterprise 0.10.1-develop.8287.1.7313a0fe67 → 0.10.1-develop.8291.1.6ec3aee41c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/agent_orchestrator/lib/eval/toolFixtures.js +7 -0
- package/dist/modules/agent_orchestrator/lib/eval/toolFixtures.js.map +2 -2
- package/dist/modules/security/lib/inAppNotifications.js +12 -0
- package/dist/modules/security/lib/inAppNotifications.js.map +7 -0
- package/dist/modules/security/subscribers/audit.js +2 -0
- package/dist/modules/security/subscribers/audit.js.map +2 -2
- package/dist/modules/security/subscribers/enforcement-deadline-notification.js +23 -20
- package/dist/modules/security/subscribers/enforcement-deadline-notification.js.map +2 -2
- package/dist/modules/security/subscribers/mfa-emergency-bypass-notification.js +2 -0
- package/dist/modules/security/subscribers/mfa-emergency-bypass-notification.js.map +2 -2
- package/dist/modules/security/subscribers/mfa-reset-notification.js +18 -16
- package/dist/modules/security/subscribers/mfa-reset-notification.js.map +2 -2
- package/dist/modules/security/subscribers/notification.js +18 -16
- package/dist/modules/security/subscribers/notification.js.map +2 -2
- package/package.json +9 -9
- package/src/modules/agent_orchestrator/lib/eval/toolFixtures.ts +6 -0
- package/src/modules/security/lib/inAppNotifications.ts +12 -0
- package/src/modules/security/subscribers/audit.ts +3 -0
- package/src/modules/security/subscribers/enforcement-deadline-notification.ts +23 -20
- package/src/modules/security/subscribers/mfa-emergency-bypass-notification.ts +3 -0
- package/src/modules/security/subscribers/mfa-reset-notification.ts +17 -15
- package/src/modules/security/subscribers/notification.ts +17 -15
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:enterprise] found
|
|
1
|
+
[build:enterprise] found 928 entry points
|
|
2
2
|
[build:enterprise] built successfully
|
|
@@ -14,6 +14,7 @@ const DEFAULT_EVAL_TOOL_FIXTURE_MAX_BYTES = 5 * 1024 * 1024;
|
|
|
14
14
|
const EVAL_TOOL_FIXTURE_FILE_SUFFIX = ".tools.json";
|
|
15
15
|
const TOOL_FIXTURE_MISSING = "tool_fixture_missing";
|
|
16
16
|
const TOOL_REPLAY_MUTATION_REFUSED = "tool_replay_mutation_refused";
|
|
17
|
+
const TOOL_REPLAY_FORBIDDEN = "tool_replay_forbidden";
|
|
17
18
|
const TOOL_FIXTURE_INVALID = "tool_fixture_invalid";
|
|
18
19
|
const TOOL_FIXTURE_RECORD_FAILED = "tool_fixture_record_failed";
|
|
19
20
|
const toolFixtureEntrySchema = z.object({
|
|
@@ -196,6 +197,11 @@ function createFileToolFixtureStore(options) {
|
|
|
196
197
|
};
|
|
197
198
|
}
|
|
198
199
|
function describeToolReplayMisses(misses) {
|
|
200
|
+
const forbidden = misses.filter((miss) => miss.reason === "forbidden");
|
|
201
|
+
if (forbidden.length) {
|
|
202
|
+
const names2 = Array.from(new Set(forbidden.map((miss) => miss.toolName))).join(", ");
|
|
203
|
+
return `[internal] ${TOOL_REPLAY_FORBIDDEN}: insufficient permissions for tool(s) ${names2}`;
|
|
204
|
+
}
|
|
199
205
|
const refused = misses.filter((miss) => miss.reason === "mutation_refused");
|
|
200
206
|
if (refused.length) {
|
|
201
207
|
const names2 = Array.from(new Set(refused.map((miss) => miss.toolName))).join(", ");
|
|
@@ -301,6 +307,7 @@ export {
|
|
|
301
307
|
TOOL_FIXTURE_INVALID,
|
|
302
308
|
TOOL_FIXTURE_MISSING,
|
|
303
309
|
TOOL_FIXTURE_RECORD_FAILED,
|
|
310
|
+
TOOL_REPLAY_FORBIDDEN,
|
|
304
311
|
TOOL_REPLAY_MUTATION_REFUSED,
|
|
305
312
|
aggregateEvalToolMode,
|
|
306
313
|
buildToolFixtureFile,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/agent_orchestrator/lib/eval/toolFixtures.ts"],
|
|
4
|
-
"sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { createHash } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n computeToolArgsKey,\n type ToolReplayFixture,\n type ToolReplayMiss,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/llm-adapters/tool-replay-context'\nimport { AgentEvalCase, AgentRun, AgentToolCall } from '../../data/entities'\n\nexport const EVAL_TOOL_FIXTURE_FORMAT = 'open-mercato.agent-eval-tool-fixtures'\nexport const EVAL_TOOL_FIXTURE_FORMAT_VERSION = 1\nexport const EVAL_TOOL_FIXTURE_MAX_ENTRIES = 1000\nexport const DEFAULT_EVAL_TOOL_FIXTURE_MAX_BYTES = 5 * 1024 * 1024\nexport const EVAL_TOOL_FIXTURE_FILE_SUFFIX = '.tools.json'\n\nexport const TOOL_FIXTURE_MISSING = 'tool_fixture_missing'\nexport const TOOL_REPLAY_MUTATION_REFUSED = 'tool_replay_mutation_refused'\nexport const TOOL_FIXTURE_INVALID = 'tool_fixture_invalid'\nexport const TOOL_FIXTURE_RECORD_FAILED = 'tool_fixture_record_failed'\n\nexport type EvalToolMode = 'live' | 'replay' | 'record' | 'mixed' | 'unsupported_runtime'\nexport type EvalToolFixtureFidelity = 'full' | 'summary'\n\nconst toolFixtureEntrySchema = z.object({\n toolName: z.string().min(1).max(200),\n argsKey: z.string().max(128).optional(),\n args: z.unknown(),\n output: z.unknown(),\n error: z.object({ message: z.string().max(4000) }).nullable().optional(),\n occurrence: z.number().int().min(0),\n toolCallId: z.string().max(200).nullable().optional(),\n})\n\nexport const evalToolFixtureFileSchema = z.object({\n format: z.literal(EVAL_TOOL_FIXTURE_FORMAT),\n formatVersion: z.literal(EVAL_TOOL_FIXTURE_FORMAT_VERSION),\n agentId: z.string().min(1).max(100),\n caseKey: z.string().min(1).max(200),\n containsTenantData: z.boolean(),\n fidelity: z.enum(['full', 'summary']),\n recordedAt: z.string().max(40),\n fixtures: z.array(toolFixtureEntrySchema).max(EVAL_TOOL_FIXTURE_MAX_ENTRIES),\n})\n\nexport type EvalToolFixtureFile = z.infer<typeof evalToolFixtureFileSchema>\n\nexport type EvalToolFixtureCaseRef = {\n agentId: string\n caseKey: string\n fixturePath: string | null\n trialIndex: number\n trialScoped?: boolean\n}\n\nexport type EvalToolFixtureLoad =\n | { ok: true; fixtures: ToolReplayFixture[]; fidelity: EvalToolFixtureFidelity }\n | { ok: false; reason: 'not_configured' | 'not_found' }\n | { ok: false; reason: 'invalid'; message: string }\n\nexport type EvalToolFixtureStore = {\n load: (ref: EvalToolFixtureCaseRef) => Promise<EvalToolFixtureLoad>\n save: (ref: EvalToolFixtureCaseRef, fixtures: ToolReplayFixture[]) => Promise<void>\n}\n\n/**\n * In-process tool fixture options for one eval suite replay. Only the CLI builds\n * them (fixtures live on the operator's disk); the HTTP API and the queue worker\n * never accept a fixture location, so a request can never make the server read\n * or write arbitrary paths.\n */\nexport type EvalToolFixtureOptions =\n | { mode: 'record'; store: EvalToolFixtureStore }\n | { mode: 'replay'; store: EvalToolFixtureStore; onMiss: 'error' | 'live' }\n\nexport type EvalCaseToolOutcome = {\n mode: EvalToolMode\n misses: number\n summaryFidelity: boolean\n}\n\nexport function resolveEvalToolFixtureMaxBytes(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env.OM_AGENT_EVAL_TOOL_FIXTURE_MAX_BYTES\n const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_EVAL_TOOL_FIXTURE_MAX_BYTES\n}\n\nconst SAFE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,150}$/\n\n/**\n * Maps an agent id or case key to one file-name segment. Keys that are already\n * safe are kept verbatim so recorded files stay readable; anything else (path\n * separators, `..`, unicode) becomes a stable hash-derived name.\n */\nexport function fixtureFileSegment(value: string): string {\n if (SAFE_SEGMENT.test(value) && !value.includes('..')) return value\n return `key-${createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 32)}`\n}\n\nexport function conventionalToolFixturePath(dir: string, agentId: string, caseKey: string): string {\n return path.join(path.resolve(dir), fixtureFileSegment(agentId), `${fixtureFileSegment(caseKey)}${EVAL_TOOL_FIXTURE_FILE_SUFFIX}`)\n}\n\nfunction isInside(baseDir: string, target: string): boolean {\n const relative = path.relative(baseDir, target)\n return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)\n}\n\n/**\n * Normalizes parsed entries into replay fixtures. `argsKey` is recomputed from\n * `args`, so a hand-edited fixture can never carry a stale key, and occurrences\n * must be unique per `(toolName, argsKey)` for strict matching to be unambiguous.\n */\nexport function normalizeToolFixtures(\n entries: ReadonlyArray<z.infer<typeof toolFixtureEntrySchema>>,\n): { ok: true; fixtures: ToolReplayFixture[] } | { ok: false; message: string } {\n const seen = new Set<string>()\n const fixtures: ToolReplayFixture[] = []\n for (const entry of entries) {\n const argsKey = computeToolArgsKey(entry.args ?? null)\n const identity = `${entry.toolName}\\u0000${argsKey}\\u0000${entry.occurrence}`\n if (seen.has(identity)) {\n return { ok: false, message: `duplicate fixture for tool \"${entry.toolName}\" occurrence ${entry.occurrence}` }\n }\n seen.add(identity)\n fixtures.push({\n toolName: entry.toolName,\n argsKey,\n args: entry.args ?? null,\n output: entry.output ?? null,\n error: entry.error ?? null,\n occurrence: entry.occurrence,\n toolCallId: entry.toolCallId ?? null,\n })\n }\n return { ok: true, fixtures }\n}\n\nexport function parseToolFixtureText(text: string): EvalToolFixtureLoad {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n return { ok: false, reason: 'invalid', message: 'not valid JSON' }\n }\n const parsed = evalToolFixtureFileSchema.safeParse(raw)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n return { ok: false, reason: 'invalid', message: `${issue?.path.join('.') || '.'}: ${issue?.message ?? 'invalid'}` }\n }\n const normalized = normalizeToolFixtures(parsed.data.fixtures)\n if (!normalized.ok) return { ok: false, reason: 'invalid', message: normalized.message }\n return { ok: true, fixtures: normalized.fixtures, fidelity: parsed.data.fidelity }\n}\n\nexport function buildToolFixtureFile(input: {\n agentId: string\n caseKey: string\n fixtures: ReadonlyArray<ToolReplayFixture>\n fidelity?: EvalToolFixtureFidelity\n now?: Date\n}): EvalToolFixtureFile {\n return {\n format: EVAL_TOOL_FIXTURE_FORMAT,\n formatVersion: EVAL_TOOL_FIXTURE_FORMAT_VERSION,\n agentId: input.agentId,\n caseKey: input.caseKey,\n containsTenantData: true,\n fidelity: input.fidelity ?? 'full',\n recordedAt: (input.now ?? new Date()).toISOString(),\n fixtures: input.fixtures.map((fixture) => ({\n toolName: fixture.toolName,\n argsKey: fixture.argsKey,\n args: fixture.args ?? null,\n output: fixture.output ?? null,\n error: fixture.error ?? null,\n occurrence: fixture.occurrence,\n toolCallId: fixture.toolCallId ?? null,\n })),\n }\n}\n\nexport class EvalToolFixtureTooLargeError extends Error {\n readonly code = TOOL_FIXTURE_RECORD_FAILED\n\n constructor(readonly bytes: number, readonly maxBytes: number) {\n super(\n `[internal] ${TOOL_FIXTURE_RECORD_FAILED}: fixture file is ${bytes} bytes, above the ${maxBytes}-byte limit (OM_AGENT_EVAL_TOOL_FIXTURE_MAX_BYTES)`,\n )\n this.name = 'EvalToolFixtureTooLargeError'\n }\n}\n\nexport function serializeToolFixtureFile(file: EvalToolFixtureFile, maxBytes = resolveEvalToolFixtureMaxBytes()): string {\n if (file.fixtures.length > EVAL_TOOL_FIXTURE_MAX_ENTRIES) {\n throw new Error(\n `[internal] ${TOOL_FIXTURE_RECORD_FAILED}: ${file.fixtures.length} tool calls exceed the ${EVAL_TOOL_FIXTURE_MAX_ENTRIES}-entry limit`,\n )\n }\n const text = `${JSON.stringify(file, null, 2)}\\n`\n const bytes = Buffer.byteLength(text, 'utf8')\n if (bytes > maxBytes) throw new EvalToolFixtureTooLargeError(bytes, maxBytes)\n return text\n}\n\nexport function writeToolFixtureFile(filePath: string, file: EvalToolFixtureFile, maxBytes?: number): void {\n const text = serializeToolFixtureFile(file, maxBytes)\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n fs.writeFileSync(filePath, text, { encoding: 'utf8', mode: 0o600 })\n}\n\nexport function readToolFixtureFile(filePath: string, maxBytes = resolveEvalToolFixtureMaxBytes()): EvalToolFixtureLoad {\n let fd: number | null = null\n try {\n fd = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0))\n const stats = fs.fstatSync(fd)\n if (!stats.isFile()) return { ok: false, reason: 'invalid', message: 'not a regular file' }\n if (stats.size > maxBytes) {\n return { ok: false, reason: 'invalid', message: `file is above the ${maxBytes}-byte limit (OM_AGENT_EVAL_TOOL_FIXTURE_MAX_BYTES)` }\n }\n const buffer = Buffer.alloc(stats.size)\n let total = 0\n while (total < buffer.length) {\n const read = fs.readSync(fd, buffer, total, buffer.length - total, null)\n if (read === 0) break\n total += read\n }\n return parseToolFixtureText(buffer.subarray(0, total).toString('utf8'))\n } catch (error) {\n const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : null\n if (code === 'ENOENT') return { ok: false, reason: 'not_found' }\n return { ok: false, reason: 'invalid', message: `cannot read file${code ? ` (${code})` : ''}` }\n } finally {\n if (fd !== null) fs.closeSync(fd)\n }\n}\n\n/**\n * File-system fixture store for the CLI. Replay resolution: an explicit\n * `--replay <dir>` wins (`<dir>/<agentId>/<caseKey>.tools.json`); otherwise a\n * case's own `fixtures.tools` path resolves against the eval-set file directory\n * and may not leave it. A case with neither runs live. Record always writes the\n * conventional path under `recordDir`.\n */\nexport function createFileToolFixtureStore(options: {\n replayDir?: string | null\n recordDir?: string | null\n evalSetDir?: string | null\n maxBytes?: number\n perTrial?: boolean\n}): EvalToolFixtureStore & { resolveReplayPath: (ref: EvalToolFixtureCaseRef) => string | null } {\n const maxBytes = options.maxBytes ?? resolveEvalToolFixtureMaxBytes()\n const trialPath = (directory: string, ref: EvalToolFixtureCaseRef): string => {\n const conventional = conventionalToolFixturePath(directory, ref.agentId, ref.caseKey)\n return (options.perTrial || ref.trialScoped) && ref.trialIndex > 0\n ? conventional.replace(/\\.tools\\.json$/, `.${ref.trialIndex}.tools.json`)\n : conventional\n }\n const resolveReplayPath = (ref: EvalToolFixtureCaseRef): string | null => {\n if (options.replayDir) return trialPath(options.replayDir, ref)\n if (ref.fixturePath && options.evalSetDir) {\n const baseDir = path.resolve(options.evalSetDir)\n const target = path.resolve(baseDir, ref.fixturePath)\n return isInside(baseDir, target) ? target : null\n }\n return null\n }\n return {\n resolveReplayPath,\n async load(ref) {\n const filePath = resolveReplayPath(ref)\n if (!filePath && ref.fixturePath && options.evalSetDir) {\n return { ok: false, reason: 'invalid', message: `fixtures.tools path \"${ref.fixturePath}\" leaves the eval set directory` }\n }\n if (!filePath) return { ok: false, reason: 'not_configured' }\n return readToolFixtureFile(filePath, maxBytes)\n },\n async save(ref, fixtures) {\n if (!options.recordDir) throw new Error(`[internal] ${TOOL_FIXTURE_RECORD_FAILED}: no record directory`)\n const file = buildToolFixtureFile({ agentId: ref.agentId, caseKey: ref.caseKey, fixtures })\n writeToolFixtureFile(trialPath(options.recordDir, ref), file, maxBytes)\n },\n }\n}\n\nexport function describeToolReplayMisses(misses: ReadonlyArray<ToolReplayMiss>): string | null {\n const refused = misses.filter((miss) => miss.reason === 'mutation_refused')\n if (refused.length) {\n const names = Array.from(new Set(refused.map((miss) => miss.toolName))).join(', ')\n return `[internal] ${TOOL_REPLAY_MUTATION_REFUSED}: mutation tool(s) ${names} cannot run under tool replay`\n }\n const failed = misses.filter((miss) => miss.reason === 'fixture_missing' && miss.resolution === 'error')\n if (!failed.length) return null\n const names = Array.from(new Set(failed.map((miss) => miss.toolName))).join(', ')\n return `[internal] ${TOOL_FIXTURE_MISSING}: no recorded result for ${failed.length} tool call(s) (${names})`\n}\n\n/**\n * Suite-level tool mode from the per-case modes: a single mode when every case\n * agrees, `mixed` when any case fell back to live tools or cases disagree.\n */\nexport function aggregateEvalToolMode(modes: ReadonlyArray<EvalToolMode>): EvalToolMode {\n if (!modes.length) return 'live'\n if (modes.includes('mixed')) return 'mixed'\n const distinct = new Set(modes)\n return distinct.size === 1 ? modes[0] : 'mixed'\n}\n\nexport type StoredRunFixtures = { agentId: string; fixtures: ToolReplayFixture[] }\n\n/**\n * Best-effort fixture export from a stored run (`--fixtures-from-run`). Stored\n * tool calls keep request/response SUMMARIES that ingestion may redact or\n * truncate, so the result is always `fidelity: 'summary'`; recording at\n * execution time is the faithful path.\n */\nexport async function buildToolFixturesFromRun(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n runId: string,\n): Promise<StoredRunFixtures | null> {\n const run = await findOneWithDecryption(em, AgentRun, { id: runId, ...scope }, undefined, scope)\n if (!run) return null\n const toolCalls = await findWithDecryption(\n em,\n AgentToolCall,\n { agentRunId: run.id, ...scope },\n { orderBy: { createdAt: 'ASC' } },\n scope,\n )\n const occurrences = new Map<string, number>()\n const fixtures = toolCalls.slice(0, EVAL_TOOL_FIXTURE_MAX_ENTRIES).map((call): ToolReplayFixture => {\n const args = call.requestSummary ?? null\n const argsKey = computeToolArgsKey(args)\n const counterKey = `${call.toolName}\\u0000${argsKey}`\n const occurrence = occurrences.get(counterKey) ?? 0\n occurrences.set(counterKey, occurrence + 1)\n const failed = call.status !== 'ok'\n return {\n toolName: call.toolName,\n argsKey,\n args,\n output: failed ? null : call.responseSummary ?? null,\n error: failed ? { message: call.errorMessage ?? String(call.status) } : null,\n occurrence,\n toolCallId: null,\n }\n })\n return { agentId: run.agentId, fixtures }\n}\n\n/** The DB case key of a run's eval case (cases created from a run keep it as `sourceId`). */\nexport async function findEvalCaseKeyForRun(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n runId: string,\n): Promise<string | null> {\n const evalCase = await em.findOne(AgentEvalCase, { ...scope, sourceId: runId, deletedAt: null })\n return evalCase?.id ?? null\n}\n\nexport type EvalCliToolFixtureFlags = {\n record?: string\n replay?: string\n onFixtureMiss?: string\n perTrial?: boolean\n fixturesFromRun?: string\n casesFile?: { cases: ReadonlyArray<{ fixtures?: { tools?: string } | null; mocks?: unknown }> } | null\n evalSetDir?: string | null\n}\n\nexport type EvalCliToolFixtureResult =\n | { ok: true; options: EvalToolFixtureOptions | null; recordDir: string | null; implicitReplay: boolean }\n | { ok: false; message: string }\n\n/**\n * Parses the eval CLI `--record`, `--replay`, `--on-fixture-miss` and\n * `--fixtures-from-run` flags. A `--cases` file whose cases reference\n * `fixtures.tools` or declare `mocks` replays them without `--replay`; cases\n * with neither then run live and the suite reports `mixed`.\n */\nexport function parseEvalCliToolFixtureFlags(flags: EvalCliToolFixtureFlags): EvalCliToolFixtureResult {\n if (flags.record !== undefined && flags.replay !== undefined) {\n return { ok: false, message: '--record and --replay are mutually exclusive' }\n }\n if (flags.onFixtureMiss !== undefined && flags.onFixtureMiss !== 'error' && flags.onFixtureMiss !== 'live') {\n return { ok: false, message: '--on-fixture-miss takes error or live' }\n }\n if (flags.fixturesFromRun !== undefined && flags.record === undefined) {\n return { ok: false, message: '--fixtures-from-run requires --record <dir>' }\n }\n if (flags.record !== undefined) {\n if (flags.onFixtureMiss !== undefined) return { ok: false, message: '--on-fixture-miss applies to replay only' }\n const recordDir = path.resolve(flags.record)\n return {\n ok: true,\n recordDir,\n implicitReplay: false,\n options: { mode: 'record', store: createFileToolFixtureStore({ recordDir, perTrial: flags.perTrial }) },\n }\n }\n const implicitReplay =\n flags.replay === undefined &&\n Boolean(flags.evalSetDir) &&\n Boolean(flags.casesFile?.cases.some((entry) => Boolean(entry.fixtures?.tools) || Boolean(entry.mocks)))\n if (flags.replay === undefined && !implicitReplay) {\n if (flags.onFixtureMiss !== undefined) {\n return { ok: false, message: '--on-fixture-miss requires --replay <dir> or a --cases file with fixtures.tools or mocks' }\n }\n return { ok: true, options: null, recordDir: null, implicitReplay: false }\n }\n const onMiss = flags.onFixtureMiss === 'live' ? 'live' : 'error'\n return {\n ok: true,\n recordDir: null,\n implicitReplay,\n options: {\n mode: 'replay',\n onMiss,\n store: createFileToolFixtureStore({\n perTrial: flags.perTrial,\n replayDir: flags.replay ? path.resolve(flags.replay) : null,\n evalSetDir: flags.evalSetDir ?? null,\n }),\n },\n }\n}\n\nexport const EVAL_TOOL_FIXTURE_TENANT_DATA_WARNING =\n 'Tool fixtures contain recorded tool outputs, which can include decrypted tenant data. Commit only fixtures built from synthetic or public data.'\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,OAGK;AACP,SAAS,eAAe,UAAU,qBAAqB;AAEhD,MAAM,2BAA2B;AACjC,MAAM,mCAAmC;AACzC,MAAM,gCAAgC;AACtC,MAAM,sCAAsC,IAAI,OAAO;AACvD,MAAM,gCAAgC;AAEtC,MAAM,uBAAuB;AAC7B,MAAM,+BAA+B;AACrC,MAAM,uBAAuB;AAC7B,MAAM,6BAA6B;AAK1C,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EACnC,SAAS,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,EACtC,MAAM,EAAE,QAAQ;AAAA,EAChB,QAAQ,EAAE,QAAQ;AAAA,EAClB,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,GAAI,EAAE,CAAC,EAAE,SAAS,EAAE,SAAS;AAAA,EACvE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,EAClC,YAAY,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,SAAS;AACtD,CAAC;AAEM,MAAM,4BAA4B,EAAE,OAAO;AAAA,EAChD,QAAQ,EAAE,QAAQ,wBAAwB;AAAA,EAC1C,eAAe,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C,UAAU,QAAQ,MAAM,UAAU,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC;AACxG,MAAI,MAAM,WAAW,UAAa,CAAC,gBAAgB;AACjD,QAAI,MAAM,kBAAkB,QAAW;AACrC,aAAO,EAAE,IAAI,OAAO,SAAS,2FAA2F;AAAA,IAC1H;AACA,WAAO,EAAE,IAAI,MAAM,SAAS,MAAM,WAAW,MAAM,gBAAgB,MAAM;AAAA,EAC3E;AACA,QAAM,SAAS,MAAM,kBAAkB,SAAS,SAAS;AACzD,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,WAAW;AAAA,IACX;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN;AAAA,MACA,OAAO,2BAA2B;AAAA,QAChC,UAAU,MAAM;AAAA,QAChB,WAAW,MAAM,SAAS,KAAK,QAAQ,MAAM,MAAM,IAAI;AAAA,QACvD,YAAY,MAAM,cAAc;AAAA,MAClC,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,MAAM,wCACX;",
|
|
4
|
+
"sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { createHash } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n computeToolArgsKey,\n type ToolReplayFixture,\n type ToolReplayMiss,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/llm-adapters/tool-replay-context'\nimport { AgentEvalCase, AgentRun, AgentToolCall } from '../../data/entities'\n\nexport const EVAL_TOOL_FIXTURE_FORMAT = 'open-mercato.agent-eval-tool-fixtures'\nexport const EVAL_TOOL_FIXTURE_FORMAT_VERSION = 1\nexport const EVAL_TOOL_FIXTURE_MAX_ENTRIES = 1000\nexport const DEFAULT_EVAL_TOOL_FIXTURE_MAX_BYTES = 5 * 1024 * 1024\nexport const EVAL_TOOL_FIXTURE_FILE_SUFFIX = '.tools.json'\n\nexport const TOOL_FIXTURE_MISSING = 'tool_fixture_missing'\nexport const TOOL_REPLAY_MUTATION_REFUSED = 'tool_replay_mutation_refused'\nexport const TOOL_REPLAY_FORBIDDEN = 'tool_replay_forbidden'\nexport const TOOL_FIXTURE_INVALID = 'tool_fixture_invalid'\nexport const TOOL_FIXTURE_RECORD_FAILED = 'tool_fixture_record_failed'\n\nexport type EvalToolMode = 'live' | 'replay' | 'record' | 'mixed' | 'unsupported_runtime'\nexport type EvalToolFixtureFidelity = 'full' | 'summary'\n\nconst toolFixtureEntrySchema = z.object({\n toolName: z.string().min(1).max(200),\n argsKey: z.string().max(128).optional(),\n args: z.unknown(),\n output: z.unknown(),\n error: z.object({ message: z.string().max(4000) }).nullable().optional(),\n occurrence: z.number().int().min(0),\n toolCallId: z.string().max(200).nullable().optional(),\n})\n\nexport const evalToolFixtureFileSchema = z.object({\n format: z.literal(EVAL_TOOL_FIXTURE_FORMAT),\n formatVersion: z.literal(EVAL_TOOL_FIXTURE_FORMAT_VERSION),\n agentId: z.string().min(1).max(100),\n caseKey: z.string().min(1).max(200),\n containsTenantData: z.boolean(),\n fidelity: z.enum(['full', 'summary']),\n recordedAt: z.string().max(40),\n fixtures: z.array(toolFixtureEntrySchema).max(EVAL_TOOL_FIXTURE_MAX_ENTRIES),\n})\n\nexport type EvalToolFixtureFile = z.infer<typeof evalToolFixtureFileSchema>\n\nexport type EvalToolFixtureCaseRef = {\n agentId: string\n caseKey: string\n fixturePath: string | null\n trialIndex: number\n trialScoped?: boolean\n}\n\nexport type EvalToolFixtureLoad =\n | { ok: true; fixtures: ToolReplayFixture[]; fidelity: EvalToolFixtureFidelity }\n | { ok: false; reason: 'not_configured' | 'not_found' }\n | { ok: false; reason: 'invalid'; message: string }\n\nexport type EvalToolFixtureStore = {\n load: (ref: EvalToolFixtureCaseRef) => Promise<EvalToolFixtureLoad>\n save: (ref: EvalToolFixtureCaseRef, fixtures: ToolReplayFixture[]) => Promise<void>\n}\n\n/**\n * In-process tool fixture options for one eval suite replay. Only the CLI builds\n * them (fixtures live on the operator's disk); the HTTP API and the queue worker\n * never accept a fixture location, so a request can never make the server read\n * or write arbitrary paths.\n */\nexport type EvalToolFixtureOptions =\n | { mode: 'record'; store: EvalToolFixtureStore }\n | { mode: 'replay'; store: EvalToolFixtureStore; onMiss: 'error' | 'live' }\n\nexport type EvalCaseToolOutcome = {\n mode: EvalToolMode\n misses: number\n summaryFidelity: boolean\n}\n\nexport function resolveEvalToolFixtureMaxBytes(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env.OM_AGENT_EVAL_TOOL_FIXTURE_MAX_BYTES\n const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_EVAL_TOOL_FIXTURE_MAX_BYTES\n}\n\nconst SAFE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,150}$/\n\n/**\n * Maps an agent id or case key to one file-name segment. Keys that are already\n * safe are kept verbatim so recorded files stay readable; anything else (path\n * separators, `..`, unicode) becomes a stable hash-derived name.\n */\nexport function fixtureFileSegment(value: string): string {\n if (SAFE_SEGMENT.test(value) && !value.includes('..')) return value\n return `key-${createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 32)}`\n}\n\nexport function conventionalToolFixturePath(dir: string, agentId: string, caseKey: string): string {\n return path.join(path.resolve(dir), fixtureFileSegment(agentId), `${fixtureFileSegment(caseKey)}${EVAL_TOOL_FIXTURE_FILE_SUFFIX}`)\n}\n\nfunction isInside(baseDir: string, target: string): boolean {\n const relative = path.relative(baseDir, target)\n return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)\n}\n\n/**\n * Normalizes parsed entries into replay fixtures. `argsKey` is recomputed from\n * `args`, so a hand-edited fixture can never carry a stale key, and occurrences\n * must be unique per `(toolName, argsKey)` for strict matching to be unambiguous.\n */\nexport function normalizeToolFixtures(\n entries: ReadonlyArray<z.infer<typeof toolFixtureEntrySchema>>,\n): { ok: true; fixtures: ToolReplayFixture[] } | { ok: false; message: string } {\n const seen = new Set<string>()\n const fixtures: ToolReplayFixture[] = []\n for (const entry of entries) {\n const argsKey = computeToolArgsKey(entry.args ?? null)\n const identity = `${entry.toolName}\\u0000${argsKey}\\u0000${entry.occurrence}`\n if (seen.has(identity)) {\n return { ok: false, message: `duplicate fixture for tool \"${entry.toolName}\" occurrence ${entry.occurrence}` }\n }\n seen.add(identity)\n fixtures.push({\n toolName: entry.toolName,\n argsKey,\n args: entry.args ?? null,\n output: entry.output ?? null,\n error: entry.error ?? null,\n occurrence: entry.occurrence,\n toolCallId: entry.toolCallId ?? null,\n })\n }\n return { ok: true, fixtures }\n}\n\nexport function parseToolFixtureText(text: string): EvalToolFixtureLoad {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n return { ok: false, reason: 'invalid', message: 'not valid JSON' }\n }\n const parsed = evalToolFixtureFileSchema.safeParse(raw)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n return { ok: false, reason: 'invalid', message: `${issue?.path.join('.') || '.'}: ${issue?.message ?? 'invalid'}` }\n }\n const normalized = normalizeToolFixtures(parsed.data.fixtures)\n if (!normalized.ok) return { ok: false, reason: 'invalid', message: normalized.message }\n return { ok: true, fixtures: normalized.fixtures, fidelity: parsed.data.fidelity }\n}\n\nexport function buildToolFixtureFile(input: {\n agentId: string\n caseKey: string\n fixtures: ReadonlyArray<ToolReplayFixture>\n fidelity?: EvalToolFixtureFidelity\n now?: Date\n}): EvalToolFixtureFile {\n return {\n format: EVAL_TOOL_FIXTURE_FORMAT,\n formatVersion: EVAL_TOOL_FIXTURE_FORMAT_VERSION,\n agentId: input.agentId,\n caseKey: input.caseKey,\n containsTenantData: true,\n fidelity: input.fidelity ?? 'full',\n recordedAt: (input.now ?? new Date()).toISOString(),\n fixtures: input.fixtures.map((fixture) => ({\n toolName: fixture.toolName,\n argsKey: fixture.argsKey,\n args: fixture.args ?? null,\n output: fixture.output ?? null,\n error: fixture.error ?? null,\n occurrence: fixture.occurrence,\n toolCallId: fixture.toolCallId ?? null,\n })),\n }\n}\n\nexport class EvalToolFixtureTooLargeError extends Error {\n readonly code = TOOL_FIXTURE_RECORD_FAILED\n\n constructor(readonly bytes: number, readonly maxBytes: number) {\n super(\n `[internal] ${TOOL_FIXTURE_RECORD_FAILED}: fixture file is ${bytes} bytes, above the ${maxBytes}-byte limit (OM_AGENT_EVAL_TOOL_FIXTURE_MAX_BYTES)`,\n )\n this.name = 'EvalToolFixtureTooLargeError'\n }\n}\n\nexport function serializeToolFixtureFile(file: EvalToolFixtureFile, maxBytes = resolveEvalToolFixtureMaxBytes()): string {\n if (file.fixtures.length > EVAL_TOOL_FIXTURE_MAX_ENTRIES) {\n throw new Error(\n `[internal] ${TOOL_FIXTURE_RECORD_FAILED}: ${file.fixtures.length} tool calls exceed the ${EVAL_TOOL_FIXTURE_MAX_ENTRIES}-entry limit`,\n )\n }\n const text = `${JSON.stringify(file, null, 2)}\\n`\n const bytes = Buffer.byteLength(text, 'utf8')\n if (bytes > maxBytes) throw new EvalToolFixtureTooLargeError(bytes, maxBytes)\n return text\n}\n\nexport function writeToolFixtureFile(filePath: string, file: EvalToolFixtureFile, maxBytes?: number): void {\n const text = serializeToolFixtureFile(file, maxBytes)\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n fs.writeFileSync(filePath, text, { encoding: 'utf8', mode: 0o600 })\n}\n\nexport function readToolFixtureFile(filePath: string, maxBytes = resolveEvalToolFixtureMaxBytes()): EvalToolFixtureLoad {\n let fd: number | null = null\n try {\n fd = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0))\n const stats = fs.fstatSync(fd)\n if (!stats.isFile()) return { ok: false, reason: 'invalid', message: 'not a regular file' }\n if (stats.size > maxBytes) {\n return { ok: false, reason: 'invalid', message: `file is above the ${maxBytes}-byte limit (OM_AGENT_EVAL_TOOL_FIXTURE_MAX_BYTES)` }\n }\n const buffer = Buffer.alloc(stats.size)\n let total = 0\n while (total < buffer.length) {\n const read = fs.readSync(fd, buffer, total, buffer.length - total, null)\n if (read === 0) break\n total += read\n }\n return parseToolFixtureText(buffer.subarray(0, total).toString('utf8'))\n } catch (error) {\n const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : null\n if (code === 'ENOENT') return { ok: false, reason: 'not_found' }\n return { ok: false, reason: 'invalid', message: `cannot read file${code ? ` (${code})` : ''}` }\n } finally {\n if (fd !== null) fs.closeSync(fd)\n }\n}\n\n/**\n * File-system fixture store for the CLI. Replay resolution: an explicit\n * `--replay <dir>` wins (`<dir>/<agentId>/<caseKey>.tools.json`); otherwise a\n * case's own `fixtures.tools` path resolves against the eval-set file directory\n * and may not leave it. A case with neither runs live. Record always writes the\n * conventional path under `recordDir`.\n */\nexport function createFileToolFixtureStore(options: {\n replayDir?: string | null\n recordDir?: string | null\n evalSetDir?: string | null\n maxBytes?: number\n perTrial?: boolean\n}): EvalToolFixtureStore & { resolveReplayPath: (ref: EvalToolFixtureCaseRef) => string | null } {\n const maxBytes = options.maxBytes ?? resolveEvalToolFixtureMaxBytes()\n const trialPath = (directory: string, ref: EvalToolFixtureCaseRef): string => {\n const conventional = conventionalToolFixturePath(directory, ref.agentId, ref.caseKey)\n return (options.perTrial || ref.trialScoped) && ref.trialIndex > 0\n ? conventional.replace(/\\.tools\\.json$/, `.${ref.trialIndex}.tools.json`)\n : conventional\n }\n const resolveReplayPath = (ref: EvalToolFixtureCaseRef): string | null => {\n if (options.replayDir) return trialPath(options.replayDir, ref)\n if (ref.fixturePath && options.evalSetDir) {\n const baseDir = path.resolve(options.evalSetDir)\n const target = path.resolve(baseDir, ref.fixturePath)\n return isInside(baseDir, target) ? target : null\n }\n return null\n }\n return {\n resolveReplayPath,\n async load(ref) {\n const filePath = resolveReplayPath(ref)\n if (!filePath && ref.fixturePath && options.evalSetDir) {\n return { ok: false, reason: 'invalid', message: `fixtures.tools path \"${ref.fixturePath}\" leaves the eval set directory` }\n }\n if (!filePath) return { ok: false, reason: 'not_configured' }\n return readToolFixtureFile(filePath, maxBytes)\n },\n async save(ref, fixtures) {\n if (!options.recordDir) throw new Error(`[internal] ${TOOL_FIXTURE_RECORD_FAILED}: no record directory`)\n const file = buildToolFixtureFile({ agentId: ref.agentId, caseKey: ref.caseKey, fixtures })\n writeToolFixtureFile(trialPath(options.recordDir, ref), file, maxBytes)\n },\n }\n}\n\nexport function describeToolReplayMisses(misses: ReadonlyArray<ToolReplayMiss>): string | null {\n const forbidden = misses.filter((miss) => miss.reason === 'forbidden')\n if (forbidden.length) {\n const names = Array.from(new Set(forbidden.map((miss) => miss.toolName))).join(', ')\n return `[internal] ${TOOL_REPLAY_FORBIDDEN}: insufficient permissions for tool(s) ${names}`\n }\n const refused = misses.filter((miss) => miss.reason === 'mutation_refused')\n if (refused.length) {\n const names = Array.from(new Set(refused.map((miss) => miss.toolName))).join(', ')\n return `[internal] ${TOOL_REPLAY_MUTATION_REFUSED}: mutation tool(s) ${names} cannot run under tool replay`\n }\n const failed = misses.filter((miss) => miss.reason === 'fixture_missing' && miss.resolution === 'error')\n if (!failed.length) return null\n const names = Array.from(new Set(failed.map((miss) => miss.toolName))).join(', ')\n return `[internal] ${TOOL_FIXTURE_MISSING}: no recorded result for ${failed.length} tool call(s) (${names})`\n}\n\n/**\n * Suite-level tool mode from the per-case modes: a single mode when every case\n * agrees, `mixed` when any case fell back to live tools or cases disagree.\n */\nexport function aggregateEvalToolMode(modes: ReadonlyArray<EvalToolMode>): EvalToolMode {\n if (!modes.length) return 'live'\n if (modes.includes('mixed')) return 'mixed'\n const distinct = new Set(modes)\n return distinct.size === 1 ? modes[0] : 'mixed'\n}\n\nexport type StoredRunFixtures = { agentId: string; fixtures: ToolReplayFixture[] }\n\n/**\n * Best-effort fixture export from a stored run (`--fixtures-from-run`). Stored\n * tool calls keep request/response SUMMARIES that ingestion may redact or\n * truncate, so the result is always `fidelity: 'summary'`; recording at\n * execution time is the faithful path.\n */\nexport async function buildToolFixturesFromRun(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n runId: string,\n): Promise<StoredRunFixtures | null> {\n const run = await findOneWithDecryption(em, AgentRun, { id: runId, ...scope }, undefined, scope)\n if (!run) return null\n const toolCalls = await findWithDecryption(\n em,\n AgentToolCall,\n { agentRunId: run.id, ...scope },\n { orderBy: { createdAt: 'ASC' } },\n scope,\n )\n const occurrences = new Map<string, number>()\n const fixtures = toolCalls.slice(0, EVAL_TOOL_FIXTURE_MAX_ENTRIES).map((call): ToolReplayFixture => {\n const args = call.requestSummary ?? null\n const argsKey = computeToolArgsKey(args)\n const counterKey = `${call.toolName}\\u0000${argsKey}`\n const occurrence = occurrences.get(counterKey) ?? 0\n occurrences.set(counterKey, occurrence + 1)\n const failed = call.status !== 'ok'\n return {\n toolName: call.toolName,\n argsKey,\n args,\n output: failed ? null : call.responseSummary ?? null,\n error: failed ? { message: call.errorMessage ?? String(call.status) } : null,\n occurrence,\n toolCallId: null,\n }\n })\n return { agentId: run.agentId, fixtures }\n}\n\n/** The DB case key of a run's eval case (cases created from a run keep it as `sourceId`). */\nexport async function findEvalCaseKeyForRun(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n runId: string,\n): Promise<string | null> {\n const evalCase = await em.findOne(AgentEvalCase, { ...scope, sourceId: runId, deletedAt: null })\n return evalCase?.id ?? null\n}\n\nexport type EvalCliToolFixtureFlags = {\n record?: string\n replay?: string\n onFixtureMiss?: string\n perTrial?: boolean\n fixturesFromRun?: string\n casesFile?: { cases: ReadonlyArray<{ fixtures?: { tools?: string } | null; mocks?: unknown }> } | null\n evalSetDir?: string | null\n}\n\nexport type EvalCliToolFixtureResult =\n | { ok: true; options: EvalToolFixtureOptions | null; recordDir: string | null; implicitReplay: boolean }\n | { ok: false; message: string }\n\n/**\n * Parses the eval CLI `--record`, `--replay`, `--on-fixture-miss` and\n * `--fixtures-from-run` flags. A `--cases` file whose cases reference\n * `fixtures.tools` or declare `mocks` replays them without `--replay`; cases\n * with neither then run live and the suite reports `mixed`.\n */\nexport function parseEvalCliToolFixtureFlags(flags: EvalCliToolFixtureFlags): EvalCliToolFixtureResult {\n if (flags.record !== undefined && flags.replay !== undefined) {\n return { ok: false, message: '--record and --replay are mutually exclusive' }\n }\n if (flags.onFixtureMiss !== undefined && flags.onFixtureMiss !== 'error' && flags.onFixtureMiss !== 'live') {\n return { ok: false, message: '--on-fixture-miss takes error or live' }\n }\n if (flags.fixturesFromRun !== undefined && flags.record === undefined) {\n return { ok: false, message: '--fixtures-from-run requires --record <dir>' }\n }\n if (flags.record !== undefined) {\n if (flags.onFixtureMiss !== undefined) return { ok: false, message: '--on-fixture-miss applies to replay only' }\n const recordDir = path.resolve(flags.record)\n return {\n ok: true,\n recordDir,\n implicitReplay: false,\n options: { mode: 'record', store: createFileToolFixtureStore({ recordDir, perTrial: flags.perTrial }) },\n }\n }\n const implicitReplay =\n flags.replay === undefined &&\n Boolean(flags.evalSetDir) &&\n Boolean(flags.casesFile?.cases.some((entry) => Boolean(entry.fixtures?.tools) || Boolean(entry.mocks)))\n if (flags.replay === undefined && !implicitReplay) {\n if (flags.onFixtureMiss !== undefined) {\n return { ok: false, message: '--on-fixture-miss requires --replay <dir> or a --cases file with fixtures.tools or mocks' }\n }\n return { ok: true, options: null, recordDir: null, implicitReplay: false }\n }\n const onMiss = flags.onFixtureMiss === 'live' ? 'live' : 'error'\n return {\n ok: true,\n recordDir: null,\n implicitReplay,\n options: {\n mode: 'replay',\n onMiss,\n store: createFileToolFixtureStore({\n perTrial: flags.perTrial,\n replayDir: flags.replay ? path.resolve(flags.replay) : null,\n evalSetDir: flags.evalSetDir ?? null,\n }),\n },\n }\n}\n\nexport const EVAL_TOOL_FIXTURE_TENANT_DATA_WARNING =\n 'Tool fixtures contain recorded tool outputs, which can include decrypted tenant data. Commit only fixtures built from synthetic or public data.'\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAC3B,SAAS,SA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UAAa,CAAC,gBAAgB;AACjD,QAAI,MAAM,kBAAkB,QAAW;AACrC,aAAO,EAAE,IAAI,OAAO,SAAS,2FAA2F;AAAA,IAC1H;AACA,WAAO,EAAE,IAAI,MAAM,SAAS,MAAM,WAAW,MAAM,gBAAgB,MAAM;AAAA,EAC3E;AACA,QAAM,SAAS,MAAM,kBAAkB,SAAS,SAAS;AACzD,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,WAAW;AAAA,IACX;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN;AAAA,MACA,OAAO,2BAA2B;AAAA,QAChC,UAAU,MAAM;AAAA,QAChB,WAAW,MAAM,SAAS,KAAK,QAAQ,MAAM,MAAM,IAAI;AAAA,QACvD,YAAY,MAAM,cAAc;AAAA,MAClC,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,MAAM,wCACX;",
|
|
6
6
|
"names": ["names"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
|
|
2
|
+
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
3
|
+
const logger = createLogger("security").child({ component: "in-app-notifications" });
|
|
4
|
+
function inAppNotificationsAvailable(ctx) {
|
|
5
|
+
if (ctx.resolve("em").getMetadata().has(Notification)) return true;
|
|
6
|
+
logger.warn("Skipping in-app security notification because notifications metadata is unavailable");
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
inAppNotificationsAvailable
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=inAppNotifications.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/security/lib/inAppNotifications.ts"],
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('security').child({ component: 'in-app-notifications' })\n\nexport function inAppNotificationsAvailable(ctx: { resolve: <T = unknown>(name: string) => T }): boolean {\n if (ctx.resolve<EntityManager>('em').getMetadata().has(Notification)) return true\n\n logger.warn('Skipping in-app security notification because notifications metadata is unavailable')\n return false\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAE5E,SAAS,4BAA4B,KAA6D;AACvG,MAAI,IAAI,QAAuB,IAAI,EAAE,YAAY,EAAE,IAAI,YAAY,EAAG,QAAO;AAE7E,SAAO,KAAK,qFAAqF;AACjG,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { buildNotificationFromType } from "@open-mercato/core/modules/notifications/lib/notificationBuilder";
|
|
2
2
|
import { resolveNotificationService } from "@open-mercato/core/modules/notifications/lib/notificationService";
|
|
3
|
+
import { inAppNotificationsAvailable } from "../lib/inAppNotifications.js";
|
|
3
4
|
import { notificationTypes } from "../notifications.js";
|
|
4
5
|
const metadata = {
|
|
5
6
|
event: "security.password.notification_requested",
|
|
@@ -10,6 +11,7 @@ async function auditSubscriber(payload, ctx) {
|
|
|
10
11
|
if (!payload.tenantId) return;
|
|
11
12
|
const typeDef = notificationTypes.find((type) => type.type === "security.password.changed");
|
|
12
13
|
if (!typeDef) return;
|
|
14
|
+
if (!inAppNotificationsAvailable(ctx)) return;
|
|
13
15
|
const notificationService = resolveNotificationService(ctx);
|
|
14
16
|
await notificationService.create(
|
|
15
17
|
buildNotificationFromType(typeDef, {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/subscribers/audit.ts"],
|
|
4
|
-
"sourcesContent": ["import { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { notificationTypes } from '../notifications'\n\nexport const metadata = {\n event: 'security.password.notification_requested',\n persistent: true,\n id: 'security:password-change-notification',\n}\n\ntype PasswordNotificationPayload = {\n userId: string\n tenantId?: string | null\n organizationId?: string | null\n changedAt?: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function auditSubscriber(\n payload: PasswordNotificationPayload,\n ctx: ResolverContext,\n) {\n if (!payload.tenantId) return\n\n const typeDef = notificationTypes.find((type) => type.type === 'security.password.changed')\n if (!typeDef) return\n\n const notificationService = resolveNotificationService(ctx)\n await notificationService.create(\n buildNotificationFromType(typeDef, {\n recipientUserId: payload.userId,\n sourceEntityType: 'security:profile_password',\n sourceEntityId: payload.userId,\n linkHref: '/backend/profile/security',\n }),\n {\n tenantId: payload.tenantId,\n organizationId: payload.organizationId ?? null,\n },\n )\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAE3B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAaA,eAAO,gBACL,SACA,KACA;AACA,MAAI,CAAC,QAAQ,SAAU;AAEvB,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,2BAA2B;AAC1F,MAAI,CAAC,QAAS;AAEd,QAAM,sBAAsB,2BAA2B,GAAG;AAC1D,QAAM,oBAAoB;AAAA,IACxB,0BAA0B,SAAS;AAAA,MACjC,iBAAiB,QAAQ;AAAA,MACzB,kBAAkB;AAAA,MAClB,gBAAgB,QAAQ;AAAA,MACxB,UAAU;AAAA,IACZ,CAAC;AAAA,IACD;AAAA,MACE,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ,kBAAkB;AAAA,IAC5C;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { inAppNotificationsAvailable } from '../lib/inAppNotifications'\nimport { notificationTypes } from '../notifications'\n\nexport const metadata = {\n event: 'security.password.notification_requested',\n persistent: true,\n id: 'security:password-change-notification',\n}\n\ntype PasswordNotificationPayload = {\n userId: string\n tenantId?: string | null\n organizationId?: string | null\n changedAt?: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function auditSubscriber(\n payload: PasswordNotificationPayload,\n ctx: ResolverContext,\n) {\n if (!payload.tenantId) return\n\n const typeDef = notificationTypes.find((type) => type.type === 'security.password.changed')\n if (!typeDef) return\n\n if (!inAppNotificationsAvailable(ctx)) return\n\n const notificationService = resolveNotificationService(ctx)\n await notificationService.create(\n buildNotificationFromType(typeDef, {\n recipientUserId: payload.userId,\n sourceEntityType: 'security:profile_password',\n sourceEntityId: payload.userId,\n linkHref: '/backend/profile/security',\n }),\n {\n tenantId: payload.tenantId,\n organizationId: payload.organizationId ?? null,\n },\n )\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB;AAE3B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAaA,eAAO,gBACL,SACA,KACA;AACA,MAAI,CAAC,QAAQ,SAAU;AAEvB,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,2BAA2B;AAC1F,MAAI,CAAC,QAAS;AAEd,MAAI,CAAC,4BAA4B,GAAG,EAAG;AAEvC,QAAM,sBAAsB,2BAA2B,GAAG;AAC1D,QAAM,oBAAoB;AAAA,IACxB,0BAA0B,SAAS;AAAA,MACjC,iBAAiB,QAAQ;AAAA,MACzB,kBAAkB;AAAA,MAClB,gBAAgB,QAAQ;AAAA,MACxB,UAAU;AAAA,IACZ,CAAC;AAAA,IACD;AAAA,MACE,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ,kBAAkB;AAAA,IAC5C;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,6 +5,7 @@ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find"
|
|
|
5
5
|
import { sendEmail } from "@open-mercato/shared/lib/email/send";
|
|
6
6
|
import EnforcementDeadlineEmail from "../emails/enforcement-deadline.js";
|
|
7
7
|
import { MfaEnforcementPolicy, UserMfaMethod } from "../data/entities.js";
|
|
8
|
+
import { inAppNotificationsAvailable } from "../lib/inAppNotifications.js";
|
|
8
9
|
import { notificationTypes } from "../notifications.js";
|
|
9
10
|
const DAY_MS = 24 * 60 * 60 * 1e3;
|
|
10
11
|
const ENFORCEMENT_BODY_KEYS = {
|
|
@@ -106,7 +107,7 @@ async function notifyEnforcementPolicyChange(payload, ctx) {
|
|
|
106
107
|
const typeDef = notificationTypes.find((type) => type.type === "security.mfa.enforcement_deadline");
|
|
107
108
|
if (!typeDef) return;
|
|
108
109
|
const em = ctx.resolve("em").fork();
|
|
109
|
-
const notificationService = resolveNotificationService(ctx);
|
|
110
|
+
const notificationService = inAppNotificationsAvailable(ctx) ? resolveNotificationService(ctx) : null;
|
|
110
111
|
const policy = await em.findOne(MfaEnforcementPolicy, {
|
|
111
112
|
id: payload.policyId,
|
|
112
113
|
deletedAt: null
|
|
@@ -125,25 +126,27 @@ async function notifyEnforcementPolicyChange(payload, ctx) {
|
|
|
125
126
|
const setupUrl = resolveSetupUrl();
|
|
126
127
|
for (const user of users) {
|
|
127
128
|
if (enrolledUserIds.has(user.id)) continue;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
129
|
+
if (notificationService) {
|
|
130
|
+
const notificationInput = buildNotificationFromType(typeDef, {
|
|
131
|
+
recipientUserId: user.id,
|
|
132
|
+
bodyVariables: message.bodyVariables,
|
|
133
|
+
sourceEntityType: "security:mfa_enforcement_policy",
|
|
134
|
+
sourceEntityId: policy.id,
|
|
135
|
+
linkHref: "/backend/profile/security/mfa",
|
|
136
|
+
groupKey: `security.mfa.enforcement_deadline:${policy.id}`
|
|
137
|
+
});
|
|
138
|
+
await notificationService.create(
|
|
139
|
+
{
|
|
140
|
+
...notificationInput,
|
|
141
|
+
bodyKey: message.bodyKey,
|
|
142
|
+
body: message.bodyKey
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
tenantId: user.tenantId,
|
|
146
|
+
organizationId: user.organizationId
|
|
147
|
+
}
|
|
148
|
+
);
|
|
149
|
+
}
|
|
147
150
|
if (user.email) {
|
|
148
151
|
await sendEmail({
|
|
149
152
|
to: user.email,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/subscribers/enforcement-deadline-notification.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport EnforcementDeadlineEmail from '../emails/enforcement-deadline'\nimport { MfaEnforcementPolicy, UserMfaMethod } from '../data/entities'\nimport { notificationTypes } from '../notifications'\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst ENFORCEMENT_BODY_KEYS = {\n withDeadline: 'security.notifications.enforcementDeadline.bodyWithDeadline',\n immediate: 'security.notifications.enforcementDeadline.bodyImmediate',\n overdue: 'security.notifications.enforcementDeadline.bodyOverdue',\n} as const\n\nexport const metadata = {\n event: 'security.enforcement.created',\n persistent: true,\n id: 'security:enforcement-deadline-notification',\n}\n\ntype EnforcementLifecyclePayload = {\n policyId: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\ntype ResolvedUser = {\n id: string\n email: string | null\n tenantId: string\n organizationId: string | null\n}\n\ntype EnforcementMessage = {\n bodyKey: string\n bodyVariables: Record<string, string> | undefined\n deadlineIsoDate: string | null\n daysRemaining: number | null\n emailMode: 'deadline' | 'immediate' | 'overdue'\n}\n\nfunction toIsoDate(value: Date): string {\n return value.toISOString().slice(0, 10)\n}\n\nfunction resolveSetupUrl(): string {\n const appUrl = process.env.APP_URL?.trim()\n if (!appUrl) return '/backend/profile/security/mfa'\n return `${appUrl.replace(/\\/$/, '')}/backend/profile/security/mfa`\n}\n\nasync function resolveScopedUsers(\n em: EntityManager,\n policy: MfaEnforcementPolicy,\n): Promise<ResolvedUser[]> {\n const users = await em.find(User, {\n deletedAt: null,\n ...(policy.tenantId ? { tenantId: policy.tenantId } : {}),\n ...(policy.organizationId ? { organizationId: policy.organizationId } : {}),\n })\n\n const resolvedUsers: ResolvedUser[] = []\n for (const user of users) {\n if (!user.tenantId) continue\n const decrypted = await findOneWithDecryption(\n em,\n User,\n {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n },\n )\n if (!decrypted?.tenantId) continue\n resolvedUsers.push({\n id: decrypted.id,\n email: typeof decrypted.email === 'string' ? decrypted.email : null,\n tenantId: decrypted.tenantId,\n organizationId: decrypted.organizationId ?? null,\n })\n }\n\n return resolvedUsers\n}\n\nfunction resolveEnforcementMessage(deadline?: Date | null): EnforcementMessage {\n if (!(deadline instanceof Date) || Number.isNaN(deadline.getTime())) {\n return {\n bodyKey: ENFORCEMENT_BODY_KEYS.immediate,\n bodyVariables: undefined,\n deadlineIsoDate: null,\n daysRemaining: null,\n emailMode: 'immediate',\n }\n }\n\n const daysRemaining = Math.ceil((deadline.getTime() - Date.now()) / DAY_MS)\n const deadlineIsoDate = toIsoDate(deadline)\n if (daysRemaining <= 0) {\n return {\n bodyKey: ENFORCEMENT_BODY_KEYS.overdue,\n bodyVariables: {\n deadline: deadlineIsoDate,\n },\n deadlineIsoDate,\n daysRemaining: null,\n emailMode: 'overdue',\n }\n }\n\n return {\n bodyKey: ENFORCEMENT_BODY_KEYS.withDeadline,\n bodyVariables: {\n days: String(daysRemaining),\n deadline: deadlineIsoDate,\n },\n deadlineIsoDate,\n daysRemaining,\n emailMode: 'deadline',\n }\n}\n\nfunction resolveEmailSubject(message: EnforcementMessage): string {\n if (message.emailMode === 'deadline' && message.daysRemaining !== null) {\n return `MFA enrollment required within ${message.daysRemaining} day${message.daysRemaining === 1 ? '' : 's'}`\n }\n if (message.emailMode === 'overdue') {\n return 'MFA enrollment deadline has passed'\n }\n return 'MFA enrollment required immediately'\n}\n\nexport async function notifyEnforcementPolicyChange(\n payload: EnforcementLifecyclePayload,\n ctx: ResolverContext,\n) {\n const typeDef = notificationTypes.find((type) => type.type === 'security.mfa.enforcement_deadline')\n if (!typeDef) return\n\n const em = ctx.resolve<EntityManager>('em').fork()\n const notificationService = resolveNotificationService(ctx)\n const policy = await em.findOne(MfaEnforcementPolicy, {\n id: payload.policyId,\n deletedAt: null,\n })\n if (!policy?.isEnforced) return\n\n const users = await resolveScopedUsers(em, policy)\n if (users.length === 0) return\n\n const methods = await em.find(UserMfaMethod, {\n userId: { $in: users.map((user) => user.id) },\n isActive: true,\n deletedAt: null,\n ...(policy.allowedMethods && policy.allowedMethods.length > 0\n ? { type: { $in: policy.allowedMethods } }\n : {}),\n })\n const enrolledUserIds = new Set(methods.map((method) => method.userId))\n\n const message = resolveEnforcementMessage(policy.enforcementDeadline)\n const setupUrl = resolveSetupUrl()\n for (const user of users) {\n if (enrolledUserIds.has(user.id)) continue\n\n const notificationInput = buildNotificationFromType(typeDef, {\n
|
|
5
|
-
"mappings": "AACA,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,iBAAiB;AAC1B,OAAO,8BAA8B;AACrC,SAAS,sBAAsB,qBAAqB;AACpD,SAAS,yBAAyB;AAElC,MAAM,SAAS,KAAK,KAAK,KAAK;AAC9B,MAAM,wBAAwB;AAAA,EAC5B,cAAc;AAAA,EACd,WAAW;AAAA,EACX,SAAS;AACX;AAEO,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAyBA,SAAS,UAAU,OAAqB;AACtC,SAAO,MAAM,YAAY,EAAE,MAAM,GAAG,EAAE;AACxC;AAEA,SAAS,kBAA0B;AACjC,QAAM,SAAS,QAAQ,IAAI,SAAS,KAAK;AACzC,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,GAAG,OAAO,QAAQ,OAAO,EAAE,CAAC;AACrC;AAEA,eAAe,mBACb,IACA,QACyB;AACzB,QAAM,QAAQ,MAAM,GAAG,KAAK,MAAM;AAAA,IAChC,WAAW;AAAA,IACX,GAAI,OAAO,WAAW,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;AAAA,IACvD,GAAI,OAAO,iBAAiB,EAAE,gBAAgB,OAAO,eAAe,IAAI,CAAC;AAAA,EAC3E,CAAC;AAED,QAAM,gBAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,KAAK,SAAU;AACpB,UAAM,YAAY,MAAM;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,QACE,IAAI,KAAK;AAAA,QACT,UAAU,KAAK;AAAA,QACf,gBAAgB,KAAK,kBAAkB;AAAA,QAC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,cAAc,WAAW;AACnC,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,eAAsB,8BACpB,SACA,KACA;AACA,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,mCAAmC;AAClG,MAAI,CAAC,QAAS;AAEd,QAAM,KAAK,IAAI,QAAuB,IAAI,EAAE,KAAK;AACjD,QAAM,sBAAsB,2BAA2B,GAAG;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport EnforcementDeadlineEmail from '../emails/enforcement-deadline'\nimport { MfaEnforcementPolicy, UserMfaMethod } from '../data/entities'\nimport { inAppNotificationsAvailable } from '../lib/inAppNotifications'\nimport { notificationTypes } from '../notifications'\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst ENFORCEMENT_BODY_KEYS = {\n withDeadline: 'security.notifications.enforcementDeadline.bodyWithDeadline',\n immediate: 'security.notifications.enforcementDeadline.bodyImmediate',\n overdue: 'security.notifications.enforcementDeadline.bodyOverdue',\n} as const\n\nexport const metadata = {\n event: 'security.enforcement.created',\n persistent: true,\n id: 'security:enforcement-deadline-notification',\n}\n\ntype EnforcementLifecyclePayload = {\n policyId: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\ntype ResolvedUser = {\n id: string\n email: string | null\n tenantId: string\n organizationId: string | null\n}\n\ntype EnforcementMessage = {\n bodyKey: string\n bodyVariables: Record<string, string> | undefined\n deadlineIsoDate: string | null\n daysRemaining: number | null\n emailMode: 'deadline' | 'immediate' | 'overdue'\n}\n\nfunction toIsoDate(value: Date): string {\n return value.toISOString().slice(0, 10)\n}\n\nfunction resolveSetupUrl(): string {\n const appUrl = process.env.APP_URL?.trim()\n if (!appUrl) return '/backend/profile/security/mfa'\n return `${appUrl.replace(/\\/$/, '')}/backend/profile/security/mfa`\n}\n\nasync function resolveScopedUsers(\n em: EntityManager,\n policy: MfaEnforcementPolicy,\n): Promise<ResolvedUser[]> {\n const users = await em.find(User, {\n deletedAt: null,\n ...(policy.tenantId ? { tenantId: policy.tenantId } : {}),\n ...(policy.organizationId ? { organizationId: policy.organizationId } : {}),\n })\n\n const resolvedUsers: ResolvedUser[] = []\n for (const user of users) {\n if (!user.tenantId) continue\n const decrypted = await findOneWithDecryption(\n em,\n User,\n {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n },\n )\n if (!decrypted?.tenantId) continue\n resolvedUsers.push({\n id: decrypted.id,\n email: typeof decrypted.email === 'string' ? decrypted.email : null,\n tenantId: decrypted.tenantId,\n organizationId: decrypted.organizationId ?? null,\n })\n }\n\n return resolvedUsers\n}\n\nfunction resolveEnforcementMessage(deadline?: Date | null): EnforcementMessage {\n if (!(deadline instanceof Date) || Number.isNaN(deadline.getTime())) {\n return {\n bodyKey: ENFORCEMENT_BODY_KEYS.immediate,\n bodyVariables: undefined,\n deadlineIsoDate: null,\n daysRemaining: null,\n emailMode: 'immediate',\n }\n }\n\n const daysRemaining = Math.ceil((deadline.getTime() - Date.now()) / DAY_MS)\n const deadlineIsoDate = toIsoDate(deadline)\n if (daysRemaining <= 0) {\n return {\n bodyKey: ENFORCEMENT_BODY_KEYS.overdue,\n bodyVariables: {\n deadline: deadlineIsoDate,\n },\n deadlineIsoDate,\n daysRemaining: null,\n emailMode: 'overdue',\n }\n }\n\n return {\n bodyKey: ENFORCEMENT_BODY_KEYS.withDeadline,\n bodyVariables: {\n days: String(daysRemaining),\n deadline: deadlineIsoDate,\n },\n deadlineIsoDate,\n daysRemaining,\n emailMode: 'deadline',\n }\n}\n\nfunction resolveEmailSubject(message: EnforcementMessage): string {\n if (message.emailMode === 'deadline' && message.daysRemaining !== null) {\n return `MFA enrollment required within ${message.daysRemaining} day${message.daysRemaining === 1 ? '' : 's'}`\n }\n if (message.emailMode === 'overdue') {\n return 'MFA enrollment deadline has passed'\n }\n return 'MFA enrollment required immediately'\n}\n\nexport async function notifyEnforcementPolicyChange(\n payload: EnforcementLifecyclePayload,\n ctx: ResolverContext,\n) {\n const typeDef = notificationTypes.find((type) => type.type === 'security.mfa.enforcement_deadline')\n if (!typeDef) return\n\n const em = ctx.resolve<EntityManager>('em').fork()\n const notificationService = inAppNotificationsAvailable(ctx) ? resolveNotificationService(ctx) : null\n const policy = await em.findOne(MfaEnforcementPolicy, {\n id: payload.policyId,\n deletedAt: null,\n })\n if (!policy?.isEnforced) return\n\n const users = await resolveScopedUsers(em, policy)\n if (users.length === 0) return\n\n const methods = await em.find(UserMfaMethod, {\n userId: { $in: users.map((user) => user.id) },\n isActive: true,\n deletedAt: null,\n ...(policy.allowedMethods && policy.allowedMethods.length > 0\n ? { type: { $in: policy.allowedMethods } }\n : {}),\n })\n const enrolledUserIds = new Set(methods.map((method) => method.userId))\n\n const message = resolveEnforcementMessage(policy.enforcementDeadline)\n const setupUrl = resolveSetupUrl()\n for (const user of users) {\n if (enrolledUserIds.has(user.id)) continue\n\n if (notificationService) {\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: user.id,\n bodyVariables: message.bodyVariables,\n sourceEntityType: 'security:mfa_enforcement_policy',\n sourceEntityId: policy.id,\n linkHref: '/backend/profile/security/mfa',\n groupKey: `security.mfa.enforcement_deadline:${policy.id}`,\n })\n\n await notificationService.create(\n {\n ...notificationInput,\n bodyKey: message.bodyKey,\n body: message.bodyKey,\n },\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n },\n )\n }\n\n if (user.email) {\n await sendEmail({\n to: user.email,\n subject: resolveEmailSubject(message),\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n react: EnforcementDeadlineEmail({\n daysRemaining: message.daysRemaining,\n deadlineIsoDate: message.deadlineIsoDate,\n setupUrl,\n }),\n })\n }\n }\n}\n\nexport default async function enforcementDeadlineNotificationSubscriber(\n payload: EnforcementLifecyclePayload,\n ctx: ResolverContext,\n) {\n await notifyEnforcementPolicyChange(payload, ctx)\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,iBAAiB;AAC1B,OAAO,8BAA8B;AACrC,SAAS,sBAAsB,qBAAqB;AACpD,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB;AAElC,MAAM,SAAS,KAAK,KAAK,KAAK;AAC9B,MAAM,wBAAwB;AAAA,EAC5B,cAAc;AAAA,EACd,WAAW;AAAA,EACX,SAAS;AACX;AAEO,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAyBA,SAAS,UAAU,OAAqB;AACtC,SAAO,MAAM,YAAY,EAAE,MAAM,GAAG,EAAE;AACxC;AAEA,SAAS,kBAA0B;AACjC,QAAM,SAAS,QAAQ,IAAI,SAAS,KAAK;AACzC,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,GAAG,OAAO,QAAQ,OAAO,EAAE,CAAC;AACrC;AAEA,eAAe,mBACb,IACA,QACyB;AACzB,QAAM,QAAQ,MAAM,GAAG,KAAK,MAAM;AAAA,IAChC,WAAW;AAAA,IACX,GAAI,OAAO,WAAW,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;AAAA,IACvD,GAAI,OAAO,iBAAiB,EAAE,gBAAgB,OAAO,eAAe,IAAI,CAAC;AAAA,EAC3E,CAAC;AAED,QAAM,gBAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,KAAK,SAAU;AACpB,UAAM,YAAY,MAAM;AAAA,MACtB;A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B,gBAAgB,OAAO;AAAA,QACvB,UAAU;AAAA,QACV,UAAU,qCAAqC,OAAO,EAAE;AAAA,MAC1D,CAAC;AAED,YAAM,oBAAoB;AAAA,QACxB;AAAA,UACE,GAAG;AAAA,UACH,SAAS,QAAQ;AAAA,UACjB,MAAM,QAAQ;AAAA,QAChB;AAAA,QACA;AAAA,UACE,UAAU,KAAK;AAAA,UACf,gBAAgB,KAAK;AAAA,QACvB;AAAA,MACF;AAAA,IACF;AAEA,QAAI,KAAK,OAAO;AACd,YAAM,UAAU;AAAA,QACd,IAAI,KAAK;AAAA,QACT,SAAS,oBAAoB,OAAO;AAAA,QACpC,UAAU,KAAK;AAAA,QACf,gBAAgB,KAAK;AAAA,QACrB,OAAO,yBAAyB;AAAA,UAC9B,eAAe,QAAQ;AAAA,UACvB,iBAAiB,QAAQ;AAAA,UACzB;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,eAAO,0CACL,SACA,KACA;AACA,QAAM,8BAA8B,SAAS,GAAG;AAClD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,6 +3,7 @@ import { buildBatchNotificationFromType } from "@open-mercato/core/modules/notif
|
|
|
3
3
|
import { getRecipientUserIdsForFeature, getScopedNotificationRecipientUserIds } from "@open-mercato/core/modules/notifications/lib/notificationRecipients";
|
|
4
4
|
import { resolveNotificationService } from "@open-mercato/core/modules/notifications/lib/notificationService";
|
|
5
5
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
6
|
+
import { inAppNotificationsAvailable } from "../lib/inAppNotifications.js";
|
|
6
7
|
import { notificationTypes } from "../notifications.js";
|
|
7
8
|
import { mfaEmergencyBypassEventSchema } from "../data/validators.js";
|
|
8
9
|
const metadata = {
|
|
@@ -17,6 +18,7 @@ async function mfaEmergencyBypassNotification(payload, ctx) {
|
|
|
17
18
|
if (ctx.tenantId !== tenantId || ctx.organizationId !== organizationId) return;
|
|
18
19
|
const typeDef = notificationTypes.find((type) => type.type === metadata.event);
|
|
19
20
|
if (!typeDef) return;
|
|
21
|
+
if (!inAppNotificationsAvailable(ctx)) return;
|
|
20
22
|
const scope = { tenantId, organizationId };
|
|
21
23
|
const groupKey = `${metadata.event}:${observedAt.slice(0, 10)}`;
|
|
22
24
|
const em = ctx.resolve("em").fork();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/subscribers/mfa-emergency-bypass-notification.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { buildBatchNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { getRecipientUserIdsForFeature, getScopedNotificationRecipientUserIds } from '@open-mercato/core/modules/notifications/lib/notificationRecipients'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { notificationTypes } from '../notifications'\nimport { mfaEmergencyBypassEventSchema } from '../data/validators'\n\nexport const metadata = {\n event: 'security.mfa.emergency_bypass_detected',\n persistent: true,\n id: 'security:mfa-emergency-bypass-notification',\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n tenantId?: string | null\n organizationId?: string | null\n}\n\ntype RbacServiceLike = {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string; organizationId: string },\n ) => Promise<boolean>\n}\n\nexport default async function mfaEmergencyBypassNotification(payload: unknown, ctx: ResolverContext) {\n const parsed = mfaEmergencyBypassEventSchema.safeParse(payload)\n if (!parsed.success) return\n const { tenantId, organizationId, observedAt } = parsed.data\n if (ctx.tenantId !== tenantId || ctx.organizationId !== organizationId) return\n\n const typeDef = notificationTypes.find((type) => type.type === metadata.event)\n if (!typeDef) return\n const scope = { tenantId, organizationId }\n const groupKey = `${metadata.event}:${observedAt.slice(0, 10)}`\n const em = ctx.resolve<EntityManager>('em').fork()\n\n const existing = await findOneWithDecryption(em, Notification, {\n ...scope,\n type: metadata.event,\n groupKey,\n }, undefined, scope)\n if (existing) return\n\n const candidates = await getRecipientUserIdsForFeature(em.getKysely(), tenantId, 'security.mfa.manage')\n if (candidates.length === 0) return\n const scopedCandidates = await getScopedNotificationRecipientUserIds(em.getKysely(), tenantId, organizationId, candidates)\n const rbac = ctx.resolve<RbacServiceLike>('rbacService')\n const recipientUserIds: string[] = []\n for (let offset = 0; offset < scopedCandidates.length; offset += 10) {\n const allowed = await Promise.all(scopedCandidates.slice(offset, offset + 10).map(async (userId) => ({\n userId,\n allowed: await rbac.userHasAllFeatures(userId, ['security.mfa.manage'], scope),\n })))\n recipientUserIds.push(...allowed.filter((candidate) => candidate.allowed).map((candidate) => candidate.userId))\n }\n if (recipientUserIds.length === 0) return\n\n await resolveNotificationService(ctx).createBatch(\n { ...buildBatchNotificationFromType(typeDef, { recipientUserIds, groupKey }), channels: ['in_app'] },\n scope,\n { skipExistingGroup: true },\n )\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,sCAAsC;AAC/C,SAAS,+BAA+B,6CAA6C;AACrF,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;AAEvC,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAgBA,eAAO,+BAAsD,SAAkB,KAAsB;AACnG,QAAM,SAAS,8BAA8B,UAAU,OAAO;AAC9D,MAAI,CAAC,OAAO,QAAS;AACrB,QAAM,EAAE,UAAU,gBAAgB,WAAW,IAAI,OAAO;AACxD,MAAI,IAAI,aAAa,YAAY,IAAI,mBAAmB,eAAgB;AAExE,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,SAAS,KAAK;AAC7E,MAAI,CAAC,QAAS;AACd,QAAM,QAAQ,EAAE,UAAU,eAAe;AACzC,QAAM,WAAW,GAAG,SAAS,KAAK,IAAI,WAAW,MAAM,GAAG,EAAE,CAAC;AAC7D,QAAM,KAAK,IAAI,QAAuB,IAAI,EAAE,KAAK;AAEjD,QAAM,WAAW,MAAM,sBAAsB,IAAI,cAAc;AAAA,IAC7D,GAAG;AAAA,IACH,MAAM,SAAS;AAAA,IACf;AAAA,EACF,GAAG,QAAW,KAAK;AACnB,MAAI,SAAU;AAEd,QAAM,aAAa,MAAM,8BAA8B,GAAG,UAAU,GAAG,UAAU,qBAAqB;AACtG,MAAI,WAAW,WAAW,EAAG;AAC7B,QAAM,mBAAmB,MAAM,sCAAsC,GAAG,UAAU,GAAG,UAAU,gBAAgB,UAAU;AACzH,QAAM,OAAO,IAAI,QAAyB,aAAa;AACvD,QAAM,mBAA6B,CAAC;AACpC,WAAS,SAAS,GAAG,SAAS,iBAAiB,QAAQ,UAAU,IAAI;AACnE,UAAM,UAAU,MAAM,QAAQ,IAAI,iBAAiB,MAAM,QAAQ,SAAS,EAAE,EAAE,IAAI,OAAO,YAAY;AAAA,MACnG;AAAA,MACA,SAAS,MAAM,KAAK,mBAAmB,QAAQ,CAAC,qBAAqB,GAAG,KAAK;AAAA,IAC/E,EAAE,CAAC;AACH,qBAAiB,KAAK,GAAG,QAAQ,OAAO,CAAC,cAAc,UAAU,OAAO,EAAE,IAAI,CAAC,cAAc,UAAU,MAAM,CAAC;AAAA,EAChH;AACA,MAAI,iBAAiB,WAAW,EAAG;AAEnC,QAAM,2BAA2B,GAAG,EAAE;AAAA,IACpC,EAAE,GAAG,+BAA+B,SAAS,EAAE,kBAAkB,SAAS,CAAC,GAAG,UAAU,CAAC,QAAQ,EAAE;AAAA,IACnG;AAAA,IACA,EAAE,mBAAmB,KAAK;AAAA,EAC5B;AACF;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { buildBatchNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { getRecipientUserIdsForFeature, getScopedNotificationRecipientUserIds } from '@open-mercato/core/modules/notifications/lib/notificationRecipients'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { inAppNotificationsAvailable } from '../lib/inAppNotifications'\nimport { notificationTypes } from '../notifications'\nimport { mfaEmergencyBypassEventSchema } from '../data/validators'\n\nexport const metadata = {\n event: 'security.mfa.emergency_bypass_detected',\n persistent: true,\n id: 'security:mfa-emergency-bypass-notification',\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n tenantId?: string | null\n organizationId?: string | null\n}\n\ntype RbacServiceLike = {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string; organizationId: string },\n ) => Promise<boolean>\n}\n\nexport default async function mfaEmergencyBypassNotification(payload: unknown, ctx: ResolverContext) {\n const parsed = mfaEmergencyBypassEventSchema.safeParse(payload)\n if (!parsed.success) return\n const { tenantId, organizationId, observedAt } = parsed.data\n if (ctx.tenantId !== tenantId || ctx.organizationId !== organizationId) return\n\n const typeDef = notificationTypes.find((type) => type.type === metadata.event)\n if (!typeDef) return\n if (!inAppNotificationsAvailable(ctx)) return\n\n const scope = { tenantId, organizationId }\n const groupKey = `${metadata.event}:${observedAt.slice(0, 10)}`\n const em = ctx.resolve<EntityManager>('em').fork()\n\n const existing = await findOneWithDecryption(em, Notification, {\n ...scope,\n type: metadata.event,\n groupKey,\n }, undefined, scope)\n if (existing) return\n\n const candidates = await getRecipientUserIdsForFeature(em.getKysely(), tenantId, 'security.mfa.manage')\n if (candidates.length === 0) return\n const scopedCandidates = await getScopedNotificationRecipientUserIds(em.getKysely(), tenantId, organizationId, candidates)\n const rbac = ctx.resolve<RbacServiceLike>('rbacService')\n const recipientUserIds: string[] = []\n for (let offset = 0; offset < scopedCandidates.length; offset += 10) {\n const allowed = await Promise.all(scopedCandidates.slice(offset, offset + 10).map(async (userId) => ({\n userId,\n allowed: await rbac.userHasAllFeatures(userId, ['security.mfa.manage'], scope),\n })))\n recipientUserIds.push(...allowed.filter((candidate) => candidate.allowed).map((candidate) => candidate.userId))\n }\n if (recipientUserIds.length === 0) return\n\n await resolveNotificationService(ctx).createBatch(\n { ...buildBatchNotificationFromType(typeDef, { recipientUserIds, groupKey }), channels: ['in_app'] },\n scope,\n { skipExistingGroup: true },\n )\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,sCAAsC;AAC/C,SAAS,+BAA+B,6CAA6C;AACrF,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;AAEvC,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAgBA,eAAO,+BAAsD,SAAkB,KAAsB;AACnG,QAAM,SAAS,8BAA8B,UAAU,OAAO;AAC9D,MAAI,CAAC,OAAO,QAAS;AACrB,QAAM,EAAE,UAAU,gBAAgB,WAAW,IAAI,OAAO;AACxD,MAAI,IAAI,aAAa,YAAY,IAAI,mBAAmB,eAAgB;AAExE,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,SAAS,KAAK;AAC7E,MAAI,CAAC,QAAS;AACd,MAAI,CAAC,4BAA4B,GAAG,EAAG;AAEvC,QAAM,QAAQ,EAAE,UAAU,eAAe;AACzC,QAAM,WAAW,GAAG,SAAS,KAAK,IAAI,WAAW,MAAM,GAAG,EAAE,CAAC;AAC7D,QAAM,KAAK,IAAI,QAAuB,IAAI,EAAE,KAAK;AAEjD,QAAM,WAAW,MAAM,sBAAsB,IAAI,cAAc;AAAA,IAC7D,GAAG;AAAA,IACH,MAAM,SAAS;AAAA,IACf;AAAA,EACF,GAAG,QAAW,KAAK;AACnB,MAAI,SAAU;AAEd,QAAM,aAAa,MAAM,8BAA8B,GAAG,UAAU,GAAG,UAAU,qBAAqB;AACtG,MAAI,WAAW,WAAW,EAAG;AAC7B,QAAM,mBAAmB,MAAM,sCAAsC,GAAG,UAAU,GAAG,UAAU,gBAAgB,UAAU;AACzH,QAAM,OAAO,IAAI,QAAyB,aAAa;AACvD,QAAM,mBAA6B,CAAC;AACpC,WAAS,SAAS,GAAG,SAAS,iBAAiB,QAAQ,UAAU,IAAI;AACnE,UAAM,UAAU,MAAM,QAAQ,IAAI,iBAAiB,MAAM,QAAQ,SAAS,EAAE,EAAE,IAAI,OAAO,YAAY;AAAA,MACnG;AAAA,MACA,SAAS,MAAM,KAAK,mBAAmB,QAAQ,CAAC,qBAAqB,GAAG,KAAK;AAAA,IAC/E,EAAE,CAAC;AACH,qBAAiB,KAAK,GAAG,QAAQ,OAAO,CAAC,cAAc,UAAU,OAAO,EAAE,IAAI,CAAC,cAAc,UAAU,MAAM,CAAC;AAAA,EAChH;AACA,MAAI,iBAAiB,WAAW,EAAG;AAEnC,QAAM,2BAA2B,GAAG,EAAE;AAAA,IACpC,EAAE,GAAG,+BAA+B,SAAS,EAAE,kBAAkB,SAAS,CAAC,GAAG,UAAU,CAAC,QAAQ,EAAE;AAAA,IACnG;AAAA,IACA,EAAE,mBAAmB,KAAK;AAAA,EAC5B;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,7 @@ import { resolveNotificationService } from "@open-mercato/core/modules/notificat
|
|
|
4
4
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
5
5
|
import { sendEmail } from "@open-mercato/shared/lib/email/send";
|
|
6
6
|
import MfaResetEmail from "../emails/mfa-reset.js";
|
|
7
|
+
import { inAppNotificationsAvailable } from "../lib/inAppNotifications.js";
|
|
7
8
|
import { notificationTypes } from "../notifications.js";
|
|
8
9
|
const metadata = {
|
|
9
10
|
event: "security.mfa.reset",
|
|
@@ -42,24 +43,25 @@ async function mfaResetNotificationSubscriber(payload, ctx) {
|
|
|
42
43
|
const em = ctx.resolve("em").fork();
|
|
43
44
|
const user = await resolveUserById(em, payload.targetUserId);
|
|
44
45
|
if (!user) return;
|
|
45
|
-
const notificationService = resolveNotificationService(ctx);
|
|
46
46
|
const resetAtIso = payload.resetAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
47
47
|
const reason = payload.reason.trim() || "No reason provided";
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
48
|
+
if (inAppNotificationsAvailable(ctx)) {
|
|
49
|
+
await resolveNotificationService(ctx).create(
|
|
50
|
+
buildNotificationFromType(typeDef, {
|
|
51
|
+
recipientUserId: user.id,
|
|
52
|
+
bodyVariables: {
|
|
53
|
+
reason
|
|
54
|
+
},
|
|
55
|
+
sourceEntityType: "security:mfa_reset",
|
|
56
|
+
sourceEntityId: user.id,
|
|
57
|
+
linkHref: "/backend/profile/security/mfa"
|
|
58
|
+
}),
|
|
59
|
+
{
|
|
60
|
+
tenantId: user.tenantId,
|
|
61
|
+
organizationId: user.organizationId
|
|
62
|
+
}
|
|
63
|
+
);
|
|
64
|
+
}
|
|
63
65
|
if (user.email) {
|
|
64
66
|
await sendEmail({
|
|
65
67
|
to: user.email,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/subscribers/mfa-reset-notification.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport MfaResetEmail from '../emails/mfa-reset'\nimport { notificationTypes } from '../notifications'\n\nexport const metadata = {\n event: 'security.mfa.reset',\n persistent: true,\n id: 'security:mfa-reset-notification',\n}\n\ntype MfaResetPayload = {\n targetUserId: string\n reason: string\n resetAt?: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\ntype ResolvedUser = {\n id: string\n email: string | null\n tenantId: string\n organizationId: string | null\n}\n\nasync function resolveUserById(em: EntityManager, userId: string): Promise<ResolvedUser | null> {\n const user = await em.findOne(User, { id: userId, deletedAt: null })\n if (!user?.tenantId) return null\n\n const decrypted = await findOneWithDecryption(\n em,\n User,\n {\n id: userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n },\n )\n if (!decrypted?.tenantId) return null\n\n return {\n id: decrypted.id,\n email: typeof decrypted.email === 'string' ? decrypted.email : null,\n tenantId: decrypted.tenantId,\n organizationId: decrypted.organizationId ?? null,\n }\n}\n\nexport default async function mfaResetNotificationSubscriber(\n payload: MfaResetPayload,\n ctx: ResolverContext,\n) {\n const typeDef = notificationTypes.find((type) => type.type === 'security.mfa.reset')\n if (!typeDef) return\n\n const em = ctx.resolve<EntityManager>('em').fork()\n const user = await resolveUserById(em, payload.targetUserId)\n if (!user) return\n\n const
|
|
5
|
-
"mappings": "AACA,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,iBAAiB;AAC1B,OAAO,mBAAmB;AAC1B,SAAS,yBAAyB;AAE3B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAmBA,eAAe,gBAAgB,IAAmB,QAA8C;AAC9F,QAAM,OAAO,MAAM,GAAG,QAAQ,MAAM,EAAE,IAAI,QAAQ,WAAW,KAAK,CAAC;AACnE,MAAI,CAAC,MAAM,SAAU,QAAO;AAE5B,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,MACE,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,IACzC;AAAA,EACF;AACA,MAAI,CAAC,WAAW,SAAU,QAAO;AAEjC,SAAO;AAAA,IACL,IAAI,UAAU;AAAA,IACd,OAAO,OAAO,UAAU,UAAU,WAAW,UAAU,QAAQ;AAAA,IAC/D,UAAU,UAAU;AAAA,IACpB,gBAAgB,UAAU,kBAAkB;AAAA,EAC9C;AACF;AAEA,eAAO,+BACL,SACA,KACA;AACA,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,oBAAoB;AACnF,MAAI,CAAC,QAAS;AAEd,QAAM,KAAK,IAAI,QAAuB,IAAI,EAAE,KAAK;AACjD,QAAM,OAAO,MAAM,gBAAgB,IAAI,QAAQ,YAAY;AAC3D,MAAI,CAAC,KAAM;AAEX,QAAM,
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport MfaResetEmail from '../emails/mfa-reset'\nimport { inAppNotificationsAvailable } from '../lib/inAppNotifications'\nimport { notificationTypes } from '../notifications'\n\nexport const metadata = {\n event: 'security.mfa.reset',\n persistent: true,\n id: 'security:mfa-reset-notification',\n}\n\ntype MfaResetPayload = {\n targetUserId: string\n reason: string\n resetAt?: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\ntype ResolvedUser = {\n id: string\n email: string | null\n tenantId: string\n organizationId: string | null\n}\n\nasync function resolveUserById(em: EntityManager, userId: string): Promise<ResolvedUser | null> {\n const user = await em.findOne(User, { id: userId, deletedAt: null })\n if (!user?.tenantId) return null\n\n const decrypted = await findOneWithDecryption(\n em,\n User,\n {\n id: userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n },\n )\n if (!decrypted?.tenantId) return null\n\n return {\n id: decrypted.id,\n email: typeof decrypted.email === 'string' ? decrypted.email : null,\n tenantId: decrypted.tenantId,\n organizationId: decrypted.organizationId ?? null,\n }\n}\n\nexport default async function mfaResetNotificationSubscriber(\n payload: MfaResetPayload,\n ctx: ResolverContext,\n) {\n const typeDef = notificationTypes.find((type) => type.type === 'security.mfa.reset')\n if (!typeDef) return\n\n const em = ctx.resolve<EntityManager>('em').fork()\n const user = await resolveUserById(em, payload.targetUserId)\n if (!user) return\n\n const resetAtIso = payload.resetAt ?? new Date().toISOString()\n const reason = payload.reason.trim() || 'No reason provided'\n\n if (inAppNotificationsAvailable(ctx)) {\n await resolveNotificationService(ctx).create(\n buildNotificationFromType(typeDef, {\n recipientUserId: user.id,\n bodyVariables: {\n reason,\n },\n sourceEntityType: 'security:mfa_reset',\n sourceEntityId: user.id,\n linkHref: '/backend/profile/security/mfa',\n }),\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n },\n )\n }\n\n if (user.email) {\n await sendEmail({\n to: user.email,\n subject: 'Your MFA methods were reset',\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n react: MfaResetEmail({\n reason,\n resetAtIso,\n }),\n })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,YAAY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AM,2BAA2B,GAAG,EAAE;AAAA,MACpC,0BAA0B,SAAS;AAAA,QACjC,iBAAiB,KAAK;AAAA,QACtB,eAAe;AAAA,UACb;AAAA,QACF;AAAA,QACA,kBAAkB;AAAA,QAClB,gBAAgB,KAAK;AAAA,QACrB,UAAU;AAAA,MACZ,CAAC;AAAA,MACD;AAAA,QACE,UAAU,KAAK;AAAA,QACf,gBAAgB,KAAK;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,KAAK,OAAO;AACd,UAAM,UAAU;AAAA,MACd,IAAI,KAAK;AAAA,MACT,SAAS;AAAA,MACT,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK;AAAA,MACrB,OAAO,cAAc;AAAA,QACnB;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,7 @@ import { resolveNotificationService } from "@open-mercato/core/modules/notificat
|
|
|
4
4
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
5
5
|
import { sendEmail } from "@open-mercato/shared/lib/email/send";
|
|
6
6
|
import MfaEnrolledEmail from "../emails/mfa-enrolled.js";
|
|
7
|
+
import { inAppNotificationsAvailable } from "../lib/inAppNotifications.js";
|
|
7
8
|
import { notificationTypes } from "../notifications.js";
|
|
8
9
|
const metadata = {
|
|
9
10
|
event: "security.mfa.enrolled",
|
|
@@ -50,24 +51,25 @@ async function notificationSubscriber(payload, ctx) {
|
|
|
50
51
|
const em = ctx.resolve("em").fork();
|
|
51
52
|
const user = await resolveUserById(em, payload.userId);
|
|
52
53
|
if (!user) return;
|
|
53
|
-
const notificationService = resolveNotificationService(ctx);
|
|
54
54
|
const methodLabel = resolveMethodLabel(payload.methodType);
|
|
55
55
|
const enrolledAtIso = payload.enrolledAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
56
|
+
if (inAppNotificationsAvailable(ctx)) {
|
|
57
|
+
await resolveNotificationService(ctx).create(
|
|
58
|
+
buildNotificationFromType(typeDef, {
|
|
59
|
+
recipientUserId: user.id,
|
|
60
|
+
bodyVariables: {
|
|
61
|
+
method: methodLabel
|
|
62
|
+
},
|
|
63
|
+
sourceEntityType: "security:mfa_method",
|
|
64
|
+
sourceEntityId: payload.methodId,
|
|
65
|
+
linkHref: "/backend/profile/security/mfa"
|
|
66
|
+
}),
|
|
67
|
+
{
|
|
68
|
+
tenantId: user.tenantId,
|
|
69
|
+
organizationId: user.organizationId
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
}
|
|
71
73
|
if (user.email) {
|
|
72
74
|
await sendEmail({
|
|
73
75
|
to: user.email,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/security/subscribers/notification.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport MfaEnrolledEmail from '../emails/mfa-enrolled'\nimport { notificationTypes } from '../notifications'\n\nexport const metadata = {\n event: 'security.mfa.enrolled',\n persistent: true,\n id: 'security:mfa-enrolled-notification',\n}\n\ntype MfaEnrolledPayload = {\n userId: string\n methodId: string\n methodType: string\n enrolledAt?: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\ntype ResolvedUser = {\n id: string\n email: string | null\n tenantId: string\n organizationId: string | null\n}\n\nconst METHOD_LABELS: Record<string, string> = {\n totp: 'Authenticator app',\n passkey: 'Passkey',\n otp_email: 'Email OTP',\n}\n\nfunction resolveMethodLabel(methodType: string): string {\n return METHOD_LABELS[methodType] ?? methodType\n}\n\nasync function resolveUserById(em: EntityManager, userId: string): Promise<ResolvedUser | null> {\n const user = await em.findOne(User, { id: userId, deletedAt: null })\n if (!user?.tenantId) return null\n\n const decrypted = await findOneWithDecryption(\n em,\n User,\n {\n id: userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n },\n )\n if (!decrypted?.tenantId) return null\n\n return {\n id: decrypted.id,\n email: typeof decrypted.email === 'string' ? decrypted.email : null,\n tenantId: decrypted.tenantId,\n organizationId: decrypted.organizationId ?? null,\n }\n}\n\nexport default async function notificationSubscriber(\n payload: MfaEnrolledPayload,\n ctx: ResolverContext,\n) {\n const typeDef = notificationTypes.find((type) => type.type === 'security.mfa.enrolled')\n if (!typeDef) return\n\n const em = ctx.resolve<EntityManager>('em').fork()\n const user = await resolveUserById(em, payload.userId)\n if (!user) return\n\n const
|
|
5
|
-
"mappings": "AACA,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,iBAAiB;AAC1B,OAAO,sBAAsB;AAC7B,SAAS,yBAAyB;AAE3B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAoBA,MAAM,gBAAwC;AAAA,EAC5C,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AACb;AAEA,SAAS,mBAAmB,YAA4B;AACtD,SAAO,cAAc,UAAU,KAAK;AACtC;AAEA,eAAe,gBAAgB,IAAmB,QAA8C;AAC9F,QAAM,OAAO,MAAM,GAAG,QAAQ,MAAM,EAAE,IAAI,QAAQ,WAAW,KAAK,CAAC;AACnE,MAAI,CAAC,MAAM,SAAU,QAAO;AAE5B,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,MACE,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,IACzC;AAAA,EACF;AACA,MAAI,CAAC,WAAW,SAAU,QAAO;AAEjC,SAAO;AAAA,IACL,IAAI,UAAU;AAAA,IACd,OAAO,OAAO,UAAU,UAAU,WAAW,UAAU,QAAQ;AAAA,IAC/D,UAAU,UAAU;AAAA,IACpB,gBAAgB,UAAU,kBAAkB;AAAA,EAC9C;AACF;AAEA,eAAO,uBACL,SACA,KACA;AACA,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,uBAAuB;AACtF,MAAI,CAAC,QAAS;AAEd,QAAM,KAAK,IAAI,QAAuB,IAAI,EAAE,KAAK;AACjD,QAAM,OAAO,MAAM,gBAAgB,IAAI,QAAQ,MAAM;AACrD,MAAI,CAAC,KAAM;AAEX,QAAM,
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport MfaEnrolledEmail from '../emails/mfa-enrolled'\nimport { inAppNotificationsAvailable } from '../lib/inAppNotifications'\nimport { notificationTypes } from '../notifications'\n\nexport const metadata = {\n event: 'security.mfa.enrolled',\n persistent: true,\n id: 'security:mfa-enrolled-notification',\n}\n\ntype MfaEnrolledPayload = {\n userId: string\n methodId: string\n methodType: string\n enrolledAt?: string\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n}\n\ntype ResolvedUser = {\n id: string\n email: string | null\n tenantId: string\n organizationId: string | null\n}\n\nconst METHOD_LABELS: Record<string, string> = {\n totp: 'Authenticator app',\n passkey: 'Passkey',\n otp_email: 'Email OTP',\n}\n\nfunction resolveMethodLabel(methodType: string): string {\n return METHOD_LABELS[methodType] ?? methodType\n}\n\nasync function resolveUserById(em: EntityManager, userId: string): Promise<ResolvedUser | null> {\n const user = await em.findOne(User, { id: userId, deletedAt: null })\n if (!user?.tenantId) return null\n\n const decrypted = await findOneWithDecryption(\n em,\n User,\n {\n id: userId,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n },\n )\n if (!decrypted?.tenantId) return null\n\n return {\n id: decrypted.id,\n email: typeof decrypted.email === 'string' ? decrypted.email : null,\n tenantId: decrypted.tenantId,\n organizationId: decrypted.organizationId ?? null,\n }\n}\n\nexport default async function notificationSubscriber(\n payload: MfaEnrolledPayload,\n ctx: ResolverContext,\n) {\n const typeDef = notificationTypes.find((type) => type.type === 'security.mfa.enrolled')\n if (!typeDef) return\n\n const em = ctx.resolve<EntityManager>('em').fork()\n const user = await resolveUserById(em, payload.userId)\n if (!user) return\n\n const methodLabel = resolveMethodLabel(payload.methodType)\n const enrolledAtIso = payload.enrolledAt ?? new Date().toISOString()\n\n if (inAppNotificationsAvailable(ctx)) {\n await resolveNotificationService(ctx).create(\n buildNotificationFromType(typeDef, {\n recipientUserId: user.id,\n bodyVariables: {\n method: methodLabel,\n },\n sourceEntityType: 'security:mfa_method',\n sourceEntityId: payload.methodId,\n linkHref: '/backend/profile/security/mfa',\n }),\n {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n },\n )\n }\n\n if (user.email) {\n await sendEmail({\n to: user.email,\n subject: 'Multi-factor authentication enabled',\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n react: MfaEnrolledEmail({\n methodLabel,\n enrolledAtIso,\n }),\n })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,iBAAiB;AAC1B,OAAO,sBAAsB;AAC7B,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB;AAE3B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAoBA,MAAM,gBAAwC;AAAA,EAC5C,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AACb;AAEA,SAAS,mBAAmB,YAA4B;AACtD,SAAO,cAAc,UAAU,KAAK;AACtC;AAEA,eAAe,gBAAgB,IAAmB,QAA8C;AAC9F,QAAM,OAAO,MAAM,GAAG,QAAQ,MAAM,EAAE,IAAI,QAAQ,WAAW,KAAK,CAAC;AACnE,MAAI,CAAC,MAAM,SAAU,QAAO;AAE5B,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,MACE,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK,kBAAkB;AAAA,IACzC;AAAA,EACF;AACA,MAAI,CAAC,WAAW,SAAU,QAAO;AAEjC,SAAO;AAAA,IACL,IAAI,UAAU;AAAA,IACd,OAAO,OAAO,UAAU,UAAU,WAAW,UAAU,QAAQ;AAAA,IAC/D,UAAU,UAAU;AAAA,IACpB,gBAAgB,UAAU,kBAAkB;AAAA,EAC9C;AACF;AAEA,eAAO,uBACL,SACA,KACA;AACA,QAAM,UAAU,kBAAkB,KAAK,CAAC,SAAS,KAAK,SAAS,uBAAuB;AACtF,MAAI,CAAC,QAAS;AAEd,QAAM,KAAK,IAAI,QAAuB,IAAI,EAAE,KAAK;AACjD,QAAM,OAAO,MAAM,gBAAgB,IAAI,QAAQ,MAAM;AACrD,MAAI,CAAC,KAAM;AAEX,QAAM,cAAc,mBAAmB,QAAQ,UAAU;AACzD,QAAM,gBAAgB,QAAQ,eAAc,oBAAI,KAAK,GAAE,YAAY;AAEnE,MAAI,4BAA4B,GAAG,GAAG;AACpC,UAAM,2BAA2B,GAAG,EAAE;AAAA,MACpC,0BAA0B,SAAS;AAAA,QACjC,iBAAiB,KAAK;AAAA,QACtB,eAAe;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,QACA,kBAAkB;AAAA,QAClB,gBAAgB,QAAQ;AAAA,QACxB,UAAU;AAAA,MACZ,CAAC;AAAA,MACD;AAAA,QACE,UAAU,KAAK;AAAA,QACf,gBAAgB,KAAK;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,KAAK,OAAO;AACd,UAAM,UAAU;AAAA,MACd,IAAI,KAAK;AAAA,MACT,SAAS;AAAA,MACT,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK;AAAA,MACrB,OAAO,iBAAiB;AAAA,QACtB;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/enterprise",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -70,12 +70,12 @@
|
|
|
70
70
|
"@dnd-kit/core": "^6.3.1",
|
|
71
71
|
"@dnd-kit/sortable": "^10.0.0",
|
|
72
72
|
"@dnd-kit/utilities": "^3.2.2",
|
|
73
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
74
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
75
|
-
"@open-mercato/queue": "0.10.1-develop.
|
|
76
|
-
"@open-mercato/scheduler": "0.10.1-develop.
|
|
77
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
78
|
-
"@open-mercato/web-research": "0.10.1-develop.
|
|
73
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
74
|
+
"@open-mercato/core": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
75
|
+
"@open-mercato/queue": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
76
|
+
"@open-mercato/scheduler": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
77
|
+
"@open-mercato/ui": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
78
|
+
"@open-mercato/web-research": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
79
79
|
"@simplewebauthn/browser": "^13.3.0",
|
|
80
80
|
"@simplewebauthn/server": "^13.3.2",
|
|
81
81
|
"@simplewebauthn/types": "^12.0.0",
|
|
@@ -88,14 +88,14 @@
|
|
|
88
88
|
},
|
|
89
89
|
"peerDependencies": {
|
|
90
90
|
"@mikro-orm/core": "^7.0.14",
|
|
91
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
91
|
+
"@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
92
92
|
"react": "^19.0.0",
|
|
93
93
|
"react-dom": "^19.0.0",
|
|
94
94
|
"react-is": ">=18.0.0",
|
|
95
95
|
"zod": ">=3.23.0"
|
|
96
96
|
},
|
|
97
97
|
"devDependencies": {
|
|
98
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
98
|
+
"@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
99
99
|
"@types/jest": "^30.0.0",
|
|
100
100
|
"@types/react": "^19.2.18",
|
|
101
101
|
"@types/react-dom": "^19.2.5",
|
|
@@ -19,6 +19,7 @@ export const EVAL_TOOL_FIXTURE_FILE_SUFFIX = '.tools.json'
|
|
|
19
19
|
|
|
20
20
|
export const TOOL_FIXTURE_MISSING = 'tool_fixture_missing'
|
|
21
21
|
export const TOOL_REPLAY_MUTATION_REFUSED = 'tool_replay_mutation_refused'
|
|
22
|
+
export const TOOL_REPLAY_FORBIDDEN = 'tool_replay_forbidden'
|
|
22
23
|
export const TOOL_FIXTURE_INVALID = 'tool_fixture_invalid'
|
|
23
24
|
export const TOOL_FIXTURE_RECORD_FAILED = 'tool_fixture_record_failed'
|
|
24
25
|
|
|
@@ -287,6 +288,11 @@ export function createFileToolFixtureStore(options: {
|
|
|
287
288
|
}
|
|
288
289
|
|
|
289
290
|
export function describeToolReplayMisses(misses: ReadonlyArray<ToolReplayMiss>): string | null {
|
|
291
|
+
const forbidden = misses.filter((miss) => miss.reason === 'forbidden')
|
|
292
|
+
if (forbidden.length) {
|
|
293
|
+
const names = Array.from(new Set(forbidden.map((miss) => miss.toolName))).join(', ')
|
|
294
|
+
return `[internal] ${TOOL_REPLAY_FORBIDDEN}: insufficient permissions for tool(s) ${names}`
|
|
295
|
+
}
|
|
290
296
|
const refused = misses.filter((miss) => miss.reason === 'mutation_refused')
|
|
291
297
|
if (refused.length) {
|
|
292
298
|
const names = Array.from(new Set(refused.map((miss) => miss.toolName))).join(', ')
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
2
|
+
import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
|
|
3
|
+
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
4
|
+
|
|
5
|
+
const logger = createLogger('security').child({ component: 'in-app-notifications' })
|
|
6
|
+
|
|
7
|
+
export function inAppNotificationsAvailable(ctx: { resolve: <T = unknown>(name: string) => T }): boolean {
|
|
8
|
+
if (ctx.resolve<EntityManager>('em').getMetadata().has(Notification)) return true
|
|
9
|
+
|
|
10
|
+
logger.warn('Skipping in-app security notification because notifications metadata is unavailable')
|
|
11
|
+
return false
|
|
12
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'
|
|
2
2
|
import { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'
|
|
3
|
+
import { inAppNotificationsAvailable } from '../lib/inAppNotifications'
|
|
3
4
|
import { notificationTypes } from '../notifications'
|
|
4
5
|
|
|
5
6
|
export const metadata = {
|
|
@@ -28,6 +29,8 @@ export default async function auditSubscriber(
|
|
|
28
29
|
const typeDef = notificationTypes.find((type) => type.type === 'security.password.changed')
|
|
29
30
|
if (!typeDef) return
|
|
30
31
|
|
|
32
|
+
if (!inAppNotificationsAvailable(ctx)) return
|
|
33
|
+
|
|
31
34
|
const notificationService = resolveNotificationService(ctx)
|
|
32
35
|
await notificationService.create(
|
|
33
36
|
buildNotificationFromType(typeDef, {
|
|
@@ -6,6 +6,7 @@ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
|
6
6
|
import { sendEmail } from '@open-mercato/shared/lib/email/send'
|
|
7
7
|
import EnforcementDeadlineEmail from '../emails/enforcement-deadline'
|
|
8
8
|
import { MfaEnforcementPolicy, UserMfaMethod } from '../data/entities'
|
|
9
|
+
import { inAppNotificationsAvailable } from '../lib/inAppNotifications'
|
|
9
10
|
import { notificationTypes } from '../notifications'
|
|
10
11
|
|
|
11
12
|
const DAY_MS = 24 * 60 * 60 * 1000
|
|
@@ -149,7 +150,7 @@ export async function notifyEnforcementPolicyChange(
|
|
|
149
150
|
if (!typeDef) return
|
|
150
151
|
|
|
151
152
|
const em = ctx.resolve<EntityManager>('em').fork()
|
|
152
|
-
const notificationService = resolveNotificationService(ctx)
|
|
153
|
+
const notificationService = inAppNotificationsAvailable(ctx) ? resolveNotificationService(ctx) : null
|
|
153
154
|
const policy = await em.findOne(MfaEnforcementPolicy, {
|
|
154
155
|
id: payload.policyId,
|
|
155
156
|
deletedAt: null,
|
|
@@ -174,26 +175,28 @@ export async function notifyEnforcementPolicyChange(
|
|
|
174
175
|
for (const user of users) {
|
|
175
176
|
if (enrolledUserIds.has(user.id)) continue
|
|
176
177
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
178
|
+
if (notificationService) {
|
|
179
|
+
const notificationInput = buildNotificationFromType(typeDef, {
|
|
180
|
+
recipientUserId: user.id,
|
|
181
|
+
bodyVariables: message.bodyVariables,
|
|
182
|
+
sourceEntityType: 'security:mfa_enforcement_policy',
|
|
183
|
+
sourceEntityId: policy.id,
|
|
184
|
+
linkHref: '/backend/profile/security/mfa',
|
|
185
|
+
groupKey: `security.mfa.enforcement_deadline:${policy.id}`,
|
|
186
|
+
})
|
|
185
187
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
188
|
+
await notificationService.create(
|
|
189
|
+
{
|
|
190
|
+
...notificationInput,
|
|
191
|
+
bodyKey: message.bodyKey,
|
|
192
|
+
body: message.bodyKey,
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
tenantId: user.tenantId,
|
|
196
|
+
organizationId: user.organizationId,
|
|
197
|
+
},
|
|
198
|
+
)
|
|
199
|
+
}
|
|
197
200
|
|
|
198
201
|
if (user.email) {
|
|
199
202
|
await sendEmail({
|
|
@@ -4,6 +4,7 @@ import { buildBatchNotificationFromType } from '@open-mercato/core/modules/notif
|
|
|
4
4
|
import { getRecipientUserIdsForFeature, getScopedNotificationRecipientUserIds } from '@open-mercato/core/modules/notifications/lib/notificationRecipients'
|
|
5
5
|
import { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'
|
|
6
6
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
7
|
+
import { inAppNotificationsAvailable } from '../lib/inAppNotifications'
|
|
7
8
|
import { notificationTypes } from '../notifications'
|
|
8
9
|
import { mfaEmergencyBypassEventSchema } from '../data/validators'
|
|
9
10
|
|
|
@@ -35,6 +36,8 @@ export default async function mfaEmergencyBypassNotification(payload: unknown, c
|
|
|
35
36
|
|
|
36
37
|
const typeDef = notificationTypes.find((type) => type.type === metadata.event)
|
|
37
38
|
if (!typeDef) return
|
|
39
|
+
if (!inAppNotificationsAvailable(ctx)) return
|
|
40
|
+
|
|
38
41
|
const scope = { tenantId, organizationId }
|
|
39
42
|
const groupKey = `${metadata.event}:${observedAt.slice(0, 10)}`
|
|
40
43
|
const em = ctx.resolve<EntityManager>('em').fork()
|
|
@@ -5,6 +5,7 @@ import { resolveNotificationService } from '@open-mercato/core/modules/notificat
|
|
|
5
5
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
6
6
|
import { sendEmail } from '@open-mercato/shared/lib/email/send'
|
|
7
7
|
import MfaResetEmail from '../emails/mfa-reset'
|
|
8
|
+
import { inAppNotificationsAvailable } from '../lib/inAppNotifications'
|
|
8
9
|
import { notificationTypes } from '../notifications'
|
|
9
10
|
|
|
10
11
|
export const metadata = {
|
|
@@ -70,25 +71,26 @@ export default async function mfaResetNotificationSubscriber(
|
|
|
70
71
|
const user = await resolveUserById(em, payload.targetUserId)
|
|
71
72
|
if (!user) return
|
|
72
73
|
|
|
73
|
-
const notificationService = resolveNotificationService(ctx)
|
|
74
74
|
const resetAtIso = payload.resetAt ?? new Date().toISOString()
|
|
75
75
|
const reason = payload.reason.trim() || 'No reason provided'
|
|
76
76
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
77
|
+
if (inAppNotificationsAvailable(ctx)) {
|
|
78
|
+
await resolveNotificationService(ctx).create(
|
|
79
|
+
buildNotificationFromType(typeDef, {
|
|
80
|
+
recipientUserId: user.id,
|
|
81
|
+
bodyVariables: {
|
|
82
|
+
reason,
|
|
83
|
+
},
|
|
84
|
+
sourceEntityType: 'security:mfa_reset',
|
|
85
|
+
sourceEntityId: user.id,
|
|
86
|
+
linkHref: '/backend/profile/security/mfa',
|
|
87
|
+
}),
|
|
88
|
+
{
|
|
89
|
+
tenantId: user.tenantId,
|
|
90
|
+
organizationId: user.organizationId,
|
|
82
91
|
},
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
linkHref: '/backend/profile/security/mfa',
|
|
86
|
-
}),
|
|
87
|
-
{
|
|
88
|
-
tenantId: user.tenantId,
|
|
89
|
-
organizationId: user.organizationId,
|
|
90
|
-
},
|
|
91
|
-
)
|
|
92
|
+
)
|
|
93
|
+
}
|
|
92
94
|
|
|
93
95
|
if (user.email) {
|
|
94
96
|
await sendEmail({
|
|
@@ -5,6 +5,7 @@ import { resolveNotificationService } from '@open-mercato/core/modules/notificat
|
|
|
5
5
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
6
6
|
import { sendEmail } from '@open-mercato/shared/lib/email/send'
|
|
7
7
|
import MfaEnrolledEmail from '../emails/mfa-enrolled'
|
|
8
|
+
import { inAppNotificationsAvailable } from '../lib/inAppNotifications'
|
|
8
9
|
import { notificationTypes } from '../notifications'
|
|
9
10
|
|
|
10
11
|
export const metadata = {
|
|
@@ -81,25 +82,26 @@ export default async function notificationSubscriber(
|
|
|
81
82
|
const user = await resolveUserById(em, payload.userId)
|
|
82
83
|
if (!user) return
|
|
83
84
|
|
|
84
|
-
const notificationService = resolveNotificationService(ctx)
|
|
85
85
|
const methodLabel = resolveMethodLabel(payload.methodType)
|
|
86
86
|
const enrolledAtIso = payload.enrolledAt ?? new Date().toISOString()
|
|
87
87
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
88
|
+
if (inAppNotificationsAvailable(ctx)) {
|
|
89
|
+
await resolveNotificationService(ctx).create(
|
|
90
|
+
buildNotificationFromType(typeDef, {
|
|
91
|
+
recipientUserId: user.id,
|
|
92
|
+
bodyVariables: {
|
|
93
|
+
method: methodLabel,
|
|
94
|
+
},
|
|
95
|
+
sourceEntityType: 'security:mfa_method',
|
|
96
|
+
sourceEntityId: payload.methodId,
|
|
97
|
+
linkHref: '/backend/profile/security/mfa',
|
|
98
|
+
}),
|
|
99
|
+
{
|
|
100
|
+
tenantId: user.tenantId,
|
|
101
|
+
organizationId: user.organizationId,
|
|
93
102
|
},
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
linkHref: '/backend/profile/security/mfa',
|
|
97
|
-
}),
|
|
98
|
-
{
|
|
99
|
-
tenantId: user.tenantId,
|
|
100
|
-
organizationId: user.organizationId,
|
|
101
|
-
},
|
|
102
|
-
)
|
|
103
|
+
)
|
|
104
|
+
}
|
|
103
105
|
|
|
104
106
|
if (user.email) {
|
|
105
107
|
await sendEmail({
|