@open-mercato/shared 0.10.1-develop.8279.1.7d4003fb64 → 0.10.1-develop.8289.1.9a25111d49

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.
Files changed (32) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/lib/ai/referenceResolver.js +9 -0
  3. package/dist/lib/ai/referenceResolver.js.map +7 -0
  4. package/dist/lib/ai/run-observation.js +78 -0
  5. package/dist/lib/ai/run-observation.js.map +7 -0
  6. package/dist/lib/commands/auditCorrelationScope.js +32 -0
  7. package/dist/lib/commands/auditCorrelationScope.js.map +7 -0
  8. package/dist/lib/commands/command-bus.js +23 -0
  9. package/dist/lib/commands/command-bus.js.map +2 -2
  10. package/dist/lib/commands/index.js +4 -1
  11. package/dist/lib/commands/index.js.map +2 -2
  12. package/dist/lib/commands/types.js.map +2 -2
  13. package/dist/lib/version.js +1 -1
  14. package/dist/lib/version.js.map +1 -1
  15. package/dist/modules/search.js.map +2 -2
  16. package/dist/security/features.js +23 -0
  17. package/dist/security/features.js.map +2 -2
  18. package/package.json +2 -2
  19. package/src/lib/ai/__tests__/referenceResolver.test.ts +12 -0
  20. package/src/lib/ai/__tests__/run-observation.test.ts +124 -0
  21. package/src/lib/ai/referenceResolver.ts +34 -0
  22. package/src/lib/ai/run-observation.ts +110 -0
  23. package/src/lib/commands/__tests__/auditCorrelationScope.test.ts +48 -0
  24. package/src/lib/commands/__tests__/command-bus.test.ts +104 -0
  25. package/src/lib/commands/auditCorrelationScope.ts +53 -0
  26. package/src/lib/commands/command-bus.ts +28 -0
  27. package/src/lib/commands/index.ts +1 -0
  28. package/src/lib/commands/types.ts +6 -0
  29. package/src/modules/search.ts +61 -0
  30. package/src/modules/widgets/injection.ts +2 -0
  31. package/src/security/__tests__/features.test.ts +58 -0
  32. package/src/security/features.ts +32 -0
@@ -5,6 +5,7 @@ import {
5
5
  registerCommandLoaders,
6
6
  CommandBus,
7
7
  isCommandInterceptorError,
8
+ withAuditCorrelation,
8
9
  } from '@open-mercato/shared/lib/commands'
9
10
  import { registerCommandInterceptors } from '@open-mercato/shared/lib/commands/command-interceptor-store'
10
11
  import type { CommandInterceptor, CommandInterceptorContext } from '@open-mercato/shared/lib/commands/command-interceptor'
@@ -561,6 +562,109 @@ describe('CommandBus', () => {
561
562
  )
562
563
  })
563
564
 
565
+ describe('auditCorrelation', () => {
566
+ async function runWithCorrelation(
567
+ commandId: string,
568
+ auditCorrelation: Record<string, unknown> | undefined,
569
+ metadataContext?: Record<string, unknown>,
570
+ ): Promise<Record<string, unknown>> {
571
+ const logMock = jest.fn(async () => ({ id: 'log-correlation' }))
572
+ registerCommand({
573
+ id: commandId,
574
+ execute: jest.fn(async () => ({ ok: true })),
575
+ buildLog: jest.fn(() => ({ actionLabel: 'Correlated', resourceKind: 'test', resourceId: '1' })),
576
+ })
577
+ const container = createContainer({ injectionMode: InjectionMode.CLASSIC })
578
+ container.register({ actionLogService: asValue({ log: logMock }) })
579
+ await new CommandBus().execute(commandId, {
580
+ input: {},
581
+ ctx: {
582
+ container,
583
+ auth: { sub: 'user-1', tenantId: 'tenant-1', orgId: 'org-1' },
584
+ organizationScope: null,
585
+ selectedOrganizationId: 'org-1',
586
+ organizationIds: ['org-1'],
587
+ auditCorrelation: auditCorrelation as Record<string, string> | undefined,
588
+ },
589
+ metadata: metadataContext ? { context: metadataContext } : undefined,
590
+ })
591
+ return logMock.mock.calls[0][0] as Record<string, unknown>
592
+ }
593
+
594
+ it('merges ctx.auditCorrelation into context.correlation', async () => {
595
+ const payload = await runWithCorrelation('test.correlation.merge', { agentRunId: 'run-1', proposalId: 'prop-1' })
596
+ expect(payload.context).toEqual({ correlation: { agentRunId: 'run-1', proposalId: 'prop-1' } })
597
+ })
598
+
599
+ it('keeps existing context and correlation keys instead of overwriting them', async () => {
600
+ const payload = await runWithCorrelation(
601
+ 'test.correlation.no-overwrite',
602
+ { agentRunId: 'run-new', proposalId: 'prop-1', source: 'evil' },
603
+ { source: 'api', correlation: { agentRunId: 'run-existing' } },
604
+ )
605
+ expect(payload.context).toEqual({
606
+ source: 'api',
607
+ correlation: { agentRunId: 'run-existing', proposalId: 'prop-1', source: 'evil' },
608
+ })
609
+ })
610
+
611
+ it('drops non-string values and leaves the context untouched when nothing remains', async () => {
612
+ const payload = await runWithCorrelation(
613
+ 'test.correlation.non-string',
614
+ { agentRunId: 42, nested: { id: 'x' }, empty: '' },
615
+ { untouched: true },
616
+ )
617
+ expect(payload.context).toEqual({ untouched: true })
618
+ })
619
+
620
+ it('does not replace a non-object correlation value', async () => {
621
+ const payload = await runWithCorrelation(
622
+ 'test.correlation.scalar',
623
+ { agentRunId: 'run-1' },
624
+ { correlation: 'legacy' },
625
+ )
626
+ expect(payload.context).toEqual({ correlation: 'legacy' })
627
+ })
628
+
629
+ it('omits correlation when no auditCorrelation is provided', async () => {
630
+ const payload = await runWithCorrelation('test.correlation.absent', undefined)
631
+ expect(payload.context).toBeUndefined()
632
+ })
633
+
634
+ it('merges the ambient correlation when no explicit correlation is provided', async () => {
635
+ const payload = await withAuditCorrelation({ agentRunId: 'run-ambient' }, () =>
636
+ runWithCorrelation('test.correlation.ambient', undefined),
637
+ )
638
+ expect(payload.context).toEqual({ correlation: { agentRunId: 'run-ambient' } })
639
+ })
640
+
641
+ it('ranks existing context keys over explicit correlation over the ambient scope', async () => {
642
+ const payload = await withAuditCorrelation(
643
+ { agentRunId: 'run-ambient', proposalId: 'prop-ambient', workflowInstanceId: 'wf-ambient' },
644
+ () =>
645
+ runWithCorrelation(
646
+ 'test.correlation.precedence',
647
+ { proposalId: 'prop-explicit', correlationId: 'corr-explicit' },
648
+ { correlation: { workflowInstanceId: 'wf-existing' } },
649
+ ),
650
+ )
651
+ expect(payload.context).toEqual({
652
+ correlation: {
653
+ workflowInstanceId: 'wf-existing',
654
+ proposalId: 'prop-explicit',
655
+ correlationId: 'corr-explicit',
656
+ agentRunId: 'run-ambient',
657
+ },
658
+ })
659
+ })
660
+
661
+ it('does not leak an ambient correlation into writes outside the scope', async () => {
662
+ await withAuditCorrelation({ agentRunId: 'run-scoped' }, async () => undefined)
663
+ const payload = await runWithCorrelation('test.correlation.outside-scope', undefined)
664
+ expect(payload.context).toBeUndefined()
665
+ })
666
+ })
667
+
564
668
  it('does not set onBehalfOfUserId for ordinary (non-runAs) human writes — additive default', async () => {
565
669
  const logMock = jest.fn(async () => ({ id: 'log-plain' }))
566
670
  registerCommand({
@@ -0,0 +1,53 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+
3
+ /**
4
+ * Keyed off globalThis so duplicated bundle chunks of this module share one
5
+ * AsyncLocalStorage; otherwise a scope entered through one copy would be
6
+ * invisible to the command bus reading another (same fix as the cache tenant
7
+ * context).
8
+ */
9
+ const AUDIT_CORRELATION_STORAGE_KEY = Symbol.for('@open-mercato/shared/commands/audit-correlation')
10
+
11
+ type AuditCorrelation = Readonly<Record<string, string>>
12
+
13
+ type GlobalWithAuditCorrelationStorage = typeof globalThis & {
14
+ [AUDIT_CORRELATION_STORAGE_KEY]?: AsyncLocalStorage<AuditCorrelation>
15
+ }
16
+
17
+ function resolveAuditCorrelationStorage(): AsyncLocalStorage<AuditCorrelation> {
18
+ const scope = globalThis as GlobalWithAuditCorrelationStorage
19
+ if (!scope[AUDIT_CORRELATION_STORAGE_KEY]) {
20
+ scope[AUDIT_CORRELATION_STORAGE_KEY] = new AsyncLocalStorage<AuditCorrelation>()
21
+ }
22
+ return scope[AUDIT_CORRELATION_STORAGE_KEY]
23
+ }
24
+
25
+ const auditCorrelationStorage = resolveAuditCorrelationStorage()
26
+
27
+ function sanitizeCorrelation(correlation: Record<string, unknown> | null | undefined): Record<string, string> {
28
+ const sanitized: Record<string, string> = {}
29
+ if (!correlation || typeof correlation !== 'object' || Array.isArray(correlation)) return sanitized
30
+ for (const [key, value] of Object.entries(correlation)) {
31
+ if (typeof value === 'string' && value.length > 0) sanitized[key] = value
32
+ }
33
+ return sanitized
34
+ }
35
+
36
+ /**
37
+ * Runs `fn` with an ambient audit correlation that the command bus merges into
38
+ * every action log written inside the async scope. Nested scopes merge, with
39
+ * the inner scope winning for the same key. Explicit `ctx.auditCorrelation`
40
+ * and existing log context keys always take precedence over the ambient value.
41
+ */
42
+ export function withAuditCorrelation<T>(correlation: Record<string, string>, fn: () => T): T
43
+ export function withAuditCorrelation<T>(correlation: Record<string, string>, fn: () => Promise<T>): Promise<T>
44
+ export function withAuditCorrelation<T>(correlation: Record<string, string>, fn: () => T | Promise<T>): T | Promise<T> {
45
+ const merged = { ...(auditCorrelationStorage.getStore() ?? {}), ...sanitizeCorrelation(correlation) }
46
+ return auditCorrelationStorage.run(Object.freeze(merged), fn)
47
+ }
48
+
49
+ export function getAmbientAuditCorrelation(): Record<string, string> | null {
50
+ const current = auditCorrelationStorage.getStore()
51
+ if (!current || Object.keys(current).length === 0) return null
52
+ return { ...current }
53
+ }
@@ -34,6 +34,7 @@ import { CommandInterceptorError } from './errors'
34
34
  import { isReadProjectionAlwaysConsistent } from '@open-mercato/shared/lib/data/consistency'
35
35
  import { createLogger } from '../logger'
36
36
  import { withAtomicFlush } from './flush'
37
+ import { getAmbientAuditCorrelation } from './auditCorrelationScope'
37
38
  import { getTelemetryRuntime } from '../telemetry/runtime'
38
39
  import type { EntityManager } from '@mikro-orm/postgresql'
39
40
  import {
@@ -99,6 +100,28 @@ function asRecord(input: unknown): Record<string, unknown> | null {
99
100
  return input as Record<string, unknown>
100
101
  }
101
102
 
103
+ function mergeAuditCorrelation(
104
+ baseContext: Record<string, unknown> | null,
105
+ auditCorrelation: Record<string, unknown> | null | undefined,
106
+ ): Record<string, unknown> | null {
107
+ const incoming = asRecord(auditCorrelation)
108
+ if (!incoming) return null
109
+ const context = baseContext ?? {}
110
+ const existingValue = context.correlation
111
+ const existing = asRecord(existingValue)
112
+ if (existingValue !== undefined && existingValue !== null && !existing) return null
113
+ const merged: Record<string, unknown> = { ...(existing ?? {}) }
114
+ let added = false
115
+ for (const [key, value] of Object.entries(incoming)) {
116
+ if (typeof value !== 'string' || value.length === 0) continue
117
+ if (Object.prototype.hasOwnProperty.call(merged, key)) continue
118
+ merged[key] = value
119
+ added = true
120
+ }
121
+ if (!added) return null
122
+ return { ...context, correlation: merged }
123
+ }
124
+
102
125
  /** Command handlers often return domain keys (e.g. warehouseId) without `id`; cache invalidation must still resolve the record. */
103
126
  function extractPrimaryIdFromCommandResult(result: unknown): string | null {
104
127
  const r = asRecord(result)
@@ -1033,6 +1056,11 @@ export class CommandBus {
1033
1056
  payload.context = { ...baseContext, source: runAs.source }
1034
1057
  }
1035
1058
 
1059
+ const correlationContext = mergeAuditCorrelation(asRecord(payload.context), options.ctx.auditCorrelation)
1060
+ if (correlationContext) payload.context = correlationContext
1061
+ const ambientCorrelationContext = mergeAuditCorrelation(asRecord(payload.context), getAmbientAuditCorrelation())
1062
+ if (ambientCorrelationContext) payload.context = ambientCorrelationContext
1063
+
1036
1064
  if (metadata.replayable === false) {
1037
1065
  delete payload.commandPayload
1038
1066
  } else {
@@ -26,3 +26,4 @@ export {
26
26
  type CrudCommandWriteScope,
27
27
  type CrudCommandWriteSideEffectTarget,
28
28
  } from './runCrudCommandWrite'
29
+ export { withAuditCorrelation, getAmbientAuditCorrelation } from './auditCorrelationScope'
@@ -109,6 +109,12 @@ export type CommandRuntimeContext = {
109
109
  * audit path.
110
110
  */
111
111
  runAs?: CommandRunAsContext
112
+ /**
113
+ * Correlation ids (e.g. `agentRunId`, `proposalId`) merged into the action log
114
+ * `context.correlation` of every write this context produces. Additive: keys
115
+ * already present in the logged context win, and non-string values are dropped.
116
+ */
117
+ auditCorrelation?: Record<string, string>
112
118
  }
113
119
 
114
120
  export type CommandRunAsContext = {
@@ -1,5 +1,6 @@
1
1
  import type { EntityId } from './entities'
2
2
  import { createLogger } from '../lib/logger'
3
+ import type { AuthContext } from '../lib/auth/server'
3
4
 
4
5
  const logger = createLogger('shared').child({ component: 'search-registry' })
5
6
 
@@ -113,6 +114,36 @@ export type SearchOptions = {
113
114
  * filtered search; any other strategy returns no results for it rather than unfiltered ones.
114
115
  */
115
116
  indexDocFilter?: SearchIndexDocFilter
117
+ /**
118
+ * Caller the search runs for (additive, 2026-11-13). Entities that declare
119
+ * `SearchEntityConfig.filterResults` only return results when it is set: the
120
+ * service passes it to the hook, and drops every result of such an entity when
121
+ * the viewer is missing or the hook throws (fail closed). Entities without the
122
+ * hook ignore it.
123
+ */
124
+ viewer?: SearchViewer
125
+ }
126
+
127
+ /**
128
+ * Authenticated caller of a search, with the request container its visibility
129
+ * checks resolve services from.
130
+ */
131
+ export type SearchViewer = {
132
+ auth: NonNullable<AuthContext>
133
+ container?: unknown
134
+ }
135
+
136
+ /**
137
+ * Input of `SearchEntityConfig.filterResults`: the merged results of one entity,
138
+ * already tenant- and organization-scoped, plus the caller.
139
+ */
140
+ export type SearchResultVisibilityContext = {
141
+ entityId: EntityId
142
+ results: SearchResult[]
143
+ tenantId: string
144
+ organizationId?: string | null
145
+ organizationIds?: string[] | null
146
+ viewer: SearchViewer
116
147
  }
117
148
 
118
149
  /**
@@ -261,6 +292,8 @@ export type SearchServiceOptions = {
261
292
  presenterEnricher?: PresenterEnricherFn
262
293
  /** Resolve entity write restrictions; omission uses the registered search configurations. */
263
294
  resolveEntityStrategies?: (entityId: EntityId) => SearchStrategyId[] | undefined
295
+ /** Resolve an entity's `filterResults` hook; omission skips per-record visibility filtering. */
296
+ resolveResultFilter?: (entityId: EntityId) => SearchEntityConfig['filterResults'] | undefined
264
297
  /** TTL (ms) for the per-strategy availability cache. Defaults to 2_000. */
265
298
  availabilityCacheTtlMs?: number
266
299
  }
@@ -341,6 +374,34 @@ export type SearchEntityConfig = {
341
374
  resolveLinks?: (ctx: SearchBuildContext) => Promise<SearchResultLink[] | null> | SearchResultLink[] | null
342
375
  /** Define which fields are searchable vs hash-only */
343
376
  fieldPolicy?: SearchFieldPolicy
377
+ /**
378
+ * Per-record index gate, evaluated by the search indexer before any strategy
379
+ * (fulltext, vector, tokens) receives the record — on live index events,
380
+ * by-id/batch indexing and every reindex path.
381
+ *
382
+ * Return `true` to index the record. Returning `false` — or throwing — removes
383
+ * the record from every strategy and skips indexing (fail closed). The context
384
+ * carries `queryEngine` for loading related records (opt-in flags, parents).
385
+ * Omit the hook to index every record of the entity (the default).
386
+ *
387
+ * The query index applies the same gate before writing the entity's
388
+ * `search_tokens`: it evaluates the hook per record (with a base-table query
389
+ * engine) and writes tokens on `true`, or deletes that record's tokens on
390
+ * `false` / a throw. Tokens therefore stay available without fulltext or vector
391
+ * providers, and no token writer can surface a record the hook rejects.
392
+ */
393
+ shouldIndex?: (ctx: SearchBuildContext) => boolean | Promise<boolean>
394
+ /**
395
+ * Per-record result visibility, evaluated by `SearchService.search()` after
396
+ * merging and before presenter enrichment (additive, 2026-11-13). Return the
397
+ * subset of `results` (the same objects) the viewer may see; anything else is
398
+ * dropped, and a returned object the service did not pass in is ignored. When the search has no
399
+ * `SearchOptions.viewer`, or the hook throws, every result of the entity is
400
+ * dropped (fail closed). Filtering runs after the strategies' `limit`, so a
401
+ * search can return fewer results than requested. Omit the hook to keep every
402
+ * scoped result (the default).
403
+ */
404
+ filterResults?: (ctx: SearchResultVisibilityContext) => Promise<SearchResult[]> | SearchResult[]
344
405
  /**
345
406
  * Per-entity view feature(s) required to read this entity's records through
346
407
  * data-returning surfaces (e.g. the `search_get` / `search_aggregate` AI tools).
@@ -292,6 +292,8 @@ export type InjectionRowActionDefinition = {
292
292
  icon?: string
293
293
  onSelect: (row: unknown, context: unknown) => void
294
294
  placement?: InjectionPlacement
295
+ /** Hides the action for rows it does not apply to; omitted means the action shows on every row. */
296
+ isVisible?: (row: unknown) => boolean
295
297
  }
296
298
 
297
299
  export type InjectionBulkActionDefinition = {
@@ -0,0 +1,58 @@
1
+ import { intersectFeatureGrants, type FeatureGrantSet } from '../features'
2
+
3
+ function grants(features: string[], isSuperAdmin = false): FeatureGrantSet {
4
+ return { features, isSuperAdmin }
5
+ }
6
+
7
+ describe('intersectFeatureGrants', () => {
8
+ it('keeps exact matches only', () => {
9
+ expect(intersectFeatureGrants(grants(['a.view', 'a.edit']), grants(['a.view', 'b.view']))).toEqual(
10
+ grants(['a.view']),
11
+ )
12
+ })
13
+
14
+ it('narrows a module wildcard to the concrete feature on the other side', () => {
15
+ expect(intersectFeatureGrants(grants(['a.*']), grants(['a.b']))).toEqual(grants(['a.b']))
16
+ expect(intersectFeatureGrants(grants(['a.b']), grants(['a.*']))).toEqual(grants(['a.b']))
17
+ })
18
+
19
+ it('returns empty for disjoint wildcards', () => {
20
+ expect(intersectFeatureGrants(grants(['a.*']), grants(['b.*']))).toEqual(grants([]))
21
+ })
22
+
23
+ it('keeps an identical wildcard and narrows nested wildcards', () => {
24
+ expect(intersectFeatureGrants(grants(['a.*']), grants(['a.*']))).toEqual(grants(['a.*']))
25
+ expect(intersectFeatureGrants(grants(['a.*']), grants(['a.b.*']))).toEqual(grants(['a.b.*']))
26
+ })
27
+
28
+ it('treats the global wildcard as identity', () => {
29
+ expect(intersectFeatureGrants(grants(['*']), grants(['b.view', 'a.*']))).toEqual(
30
+ grants(['a.*', 'b.view']),
31
+ )
32
+ expect(intersectFeatureGrants(grants(['a.*']), grants(['*']))).toEqual(grants(['a.*']))
33
+ expect(intersectFeatureGrants(grants(['*']), grants(['*']))).toEqual(grants(['*']))
34
+ })
35
+
36
+ it('collapses a super-admin side to the other side', () => {
37
+ expect(intersectFeatureGrants(grants([], true), grants(['b.x', 'a.x', 'a.x']))).toEqual(
38
+ grants(['a.x', 'b.x']),
39
+ )
40
+ expect(intersectFeatureGrants(grants(['a.x']), grants([], true))).toEqual(grants(['a.x']))
41
+ })
42
+
43
+ it('stays super-admin when both sides are', () => {
44
+ expect(intersectFeatureGrants(grants([], true), grants([], true))).toEqual(grants([], true))
45
+ })
46
+
47
+ it('returns empty when either side is empty', () => {
48
+ expect(intersectFeatureGrants(grants([]), grants(['a.*']))).toEqual(grants([]))
49
+ expect(intersectFeatureGrants(grants(['a.*']), grants([]))).toEqual(grants([]))
50
+ expect(intersectFeatureGrants(grants([]), grants([], true))).toEqual(grants([]))
51
+ })
52
+
53
+ it('dedupes and sorts the result', () => {
54
+ expect(
55
+ intersectFeatureGrants(grants(['b.x', 'a.x', 'a.x', 'a.*']), grants(['a.x', 'b.x', 'b.x'])),
56
+ ).toEqual(grants(['a.x', 'b.x']))
57
+ })
58
+ })
@@ -14,3 +14,35 @@ export function hasAllFeatures(
14
14
  if (!Array.isArray(granted) || !granted.length) return false
15
15
  return required.every((feature) => hasFeature(granted, feature))
16
16
  }
17
+
18
+ export type FeatureGrantSet = {
19
+ features: readonly string[]
20
+ isSuperAdmin: boolean
21
+ }
22
+
23
+ function normalizeFeatures(features: readonly string[]): string[] {
24
+ return Array.from(new Set(features)).sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))
25
+ }
26
+
27
+ export function intersectFeatureGrants(
28
+ first: FeatureGrantSet,
29
+ second: FeatureGrantSet,
30
+ ): FeatureGrantSet {
31
+ if (first.isSuperAdmin && second.isSuperAdmin) {
32
+ return { features: [], isSuperAdmin: true }
33
+ }
34
+ if (first.isSuperAdmin) {
35
+ return { features: normalizeFeatures(second.features), isSuperAdmin: false }
36
+ }
37
+ if (second.isSuperAdmin) {
38
+ return { features: normalizeFeatures(first.features), isSuperAdmin: false }
39
+ }
40
+ const kept: string[] = []
41
+ for (const left of first.features) {
42
+ for (const right of second.features) {
43
+ if (matchFeature(left, right)) kept.push(left)
44
+ else if (matchFeature(right, left)) kept.push(right)
45
+ }
46
+ }
47
+ return { features: normalizeFeatures(kept), isSuperAdmin: false }
48
+ }