Skip to main content

Framework Reference

Read scope for custom read paths

Custom (non-makeCrudRoute) read paths used to pass tenantId / organizationId to services as optional filters. A missing value meant "no restriction", so a route that forgot to deny an empty scope read every organization, or every tenant. A ReadScope makes that decision explicit and required.

The rule​

Read services take a ReadScope. A service method that lists tenant data accepts a branded ReadScope (from @open-mercato/shared/lib/auth/readScope) instead of optional ids, and applies it with the shared helpers. A caller cannot build one from a plain object literal: it has to come from one of the constructors below.

import type { ReadScope } from '@open-mercato/shared/lib/auth/readScope'

async listScoped(scope: ReadScope, filters: MyScopedFilters) { /* ... */ }

A ReadScope is one of:

KindReads
tenant + allEvery organization of one tenant
tenant + someThe listed organizations of one tenant (rows with organization_id IS NULL are not included)
allTenants + all / someEvery tenant (superadmin and system reads only)
noneNothing

An empty organization set is not representable: it becomes none. Malformed data (a blank tenant id, a missing organization part) also becomes none.

Applying a scope in a service​

Use the helpers; they always produce the WHERE predicate. The scope argument of findWithDecryption is not a filter and must not replace it.

import {
applyReadScopeToKysely,
isNoneScope,
readScopeToMikroFilter,
} from '@open-mercato/shared/lib/auth/readScope'

if (isNoneScope(scope)) return { items: [], total: 0 }

const where = {
...readScopeToMikroFilter(scope, { tenantField: 'tenantId', organizationField: 'organizationId' }),
deletedAt: null,
}

const query = applyReadScopeToKysely(db.selectFrom('my_rows').selectAll(), scope, {
tenantColumn: 'my_rows.tenant_id',
organizationColumn: 'my_rows.organization_id',
})

none compiles to where false (Kysely) and { id: { $in: [] } } (MikroORM); short-circuiting with isNoneScope skips the query entirely.

Getting a scope​

Request handlers: resolveReadScope​

import { resolveReadScope } from '@open-mercato/core/modules/directory/utils/readScope'

const url = new URL(req.url)
const { scope, organizationId, featureContext } = await resolveReadScope({
container,
auth,
request: req,
requestedOrganizationId: url.searchParams.get('organizationId'),
})
const page = await service.listScoped(scope, filters)

The resolver reuses the request's feature-check context (no extra query when the API dispatcher already resolved it) and applies the ?organizationId= narrowing against the caller's visible organizations. It returns:

  • scope: the ReadScope to pass to the service.
  • organizationId: the effective single organization (the one requested, if visible, otherwise the default one), or null. Use it where the route used its organization before, such as RBAC checks for the organization being read.
  • featureContext: the underlying feature-check context, for route-level guards that still need it.

A caller without auth, a tenant-less caller that is not a superadmin, or a caller whose organization scope is explicitly empty gets none. A restricted caller (organization visibility is a list) never gets every organization. Routes keep their own 401 / 403 responses; the scope is the service-level safety net.

Reads that follow an authorized record: recordReadScope​

When a read is keyed by a record the caller already loaded and authorized (a document's history, a deal's stage log, a command's own scope), take the scope from that record:

import { recordReadScope } from '@open-mercato/shared/lib/auth/readScope'

await actionLogService.listScoped(
recordReadScope({ tenantId: order.tenantId, organizationId: order.organizationId }),
{ resourceKind: 'sales.order', resourceId: order.id },
)

organizationId is a required key. An explicit null reads the whole tenant; a blank tenant or a blank organization id gives none. It never produces allTenants.

Workers, CLI and subscribers: systemScope​

Code without a request principal names its unrestricted reads explicitly, so reviewers can find them:

import { systemScope } from '@open-mercato/shared/lib/auth/readScope'

await service.listScoped(systemScope({ tenantId }), filters)
await service.listScoped(systemScope.allTenants(), filters)

A repo-wide guard test rejects systemScope imports in module api/ directories: a request handler has a principal and must use resolveReadScope.

Tests: testScope​

Unit tests build arbitrary scopes with testScope from @open-mercato/shared/lib/testing/readScope. The guard test rejects it in production code.

Audit logs​

ActionLogService and AccessLogService are the first services on this contract: use listScoped / countScoped. Their list / count methods are deprecated (removal no earlier than 0.13.0).

Code that reads the service from DI, where an app may have registered a replacement or a subclass, goes through listActionLogsWithReadScope / listAccessLogsWithReadScope from @open-mercato/core/modules/audit_logs/lib/readScopeBridge. They call listScoped, or fall back to the deprecated list when the service has no listScoped or overrides list (or, for action logs, count) without overriding listScoped. See the upgrade notes for apps that replace or subclass these services.