@happyvertical/smrt-users 0.70.0 → 0.70.1
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/agents/permissions.md +7 -0
- package/dist/chunks/{PasswordCredentialService-Dec3bz4G.js → PasswordCredentialService-BjobA5uG.js} +22 -731
- package/dist/chunks/PasswordCredentialService-BjobA5uG.js.map +1 -0
- package/dist/chunks/PermissionCatalogService-DcmTn38P.js +716 -0
- package/dist/chunks/PermissionCatalogService-DcmTn38P.js.map +1 -0
- package/dist/chunks/PostgresPermissionPolicies-RzCLuARk.js +314 -0
- package/dist/chunks/PostgresPermissionPolicies-RzCLuARk.js.map +1 -0
- package/dist/chunks/{TerminalAuthService-BCem_pDy.js → TerminalAuthService-CIdx-ed9.js} +4 -3
- package/dist/chunks/{TerminalAuthService-BCem_pDy.js.map → TerminalAuthService-CIdx-ed9.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -285
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/operator.js +1 -1
- package/dist/postgres-policies.d.ts +8 -0
- package/dist/postgres-policies.d.ts.map +1 -0
- package/dist/postgres-policies.js +2 -0
- package/dist/services/PostgresPermissionPolicies.d.ts +40 -1
- package/dist/services/PostgresPermissionPolicies.d.ts.map +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +6 -5
- package/dist/smrt-knowledge.okf.md +3 -2
- package/dist/sveltekit.js +2 -2
- package/package.json +13 -9
- package/dist/chunks/PasswordCredentialService-Dec3bz4G.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PermissionCatalogService-DcmTn38P.js","names":["normalizedAction","registered"],"sources":["../../src/models/Permission.ts","../../src/collections/PermissionCollection.ts","../../src/services/authorization-read-options.ts","../../src/collections/seeding-transaction.ts","../../src/services/PermissionCatalogService.ts"],"sourcesContent":["/**\n * Permission model - named capability in the system\n * @packageDocumentation\n */\n\nimport {\n field,\n SmrtObject,\n type SmrtObjectOptions,\n smrt,\n} from '@happyvertical/smrt-core';\n\n/**\n * Parsed permission slug components\n */\nexport interface ParsedPermissionSlug {\n /** Resource part (e.g., 'articles' from 'articles.create') */\n resource: string;\n /** Action part (e.g., 'create' from 'articles.create') */\n action: string;\n /** Whether the slug follows the valid 'resource.action[.scope...]' pattern */\n isValid: boolean;\n}\n\n/**\n * Parse a permission slug into its resource and action components.\n * Valid format: 'resource.action[.scope...]' (e.g., 'articles.create' or\n * 'products.read.internal')\n *\n * @param slug - The permission slug to parse\n * @returns Parsed components with validation status\n */\nexport function parsePermissionSlug(slug: string): ParsedPermissionSlug {\n const parts = slug.split('.');\n if (parts.length >= 2 && parts.every(Boolean)) {\n return {\n resource: parts[0],\n action: parts.slice(1).join('.'),\n isValid: true,\n };\n }\n return {\n resource: slug,\n action: '',\n isValid: false,\n };\n}\n\n/**\n * Validate that a permission slug follows the 'resource.action[.scope...]'\n * pattern.\n *\n * @param slug - The slug to validate\n * @returns true if valid, false otherwise\n */\nexport function isValidPermissionSlug(slug: string): boolean {\n return parsePermissionSlug(slug).isValid;\n}\n\n/**\n * Constructor options for {@link Permission}.\n */\nexport interface PermissionOptions extends SmrtObjectOptions {\n name?: string;\n description?: string;\n category?: string;\n}\n\n/**\n * Permission represents a named capability in the system.\n *\n * Permissions are defined by the application and assigned to roles.\n * Permission slugs follow the pattern: resource.action[.scope...] (e.g.,\n * 'articles.create' or 'products.read.internal')\n *\n * @example\n * ```typescript\n * const permission = await permissions.create({\n * slug: 'articles.create',\n * name: 'Create Articles',\n * description: 'Allows creating new articles',\n * category: 'articles'\n * });\n * await permission.save();\n * ```\n */\n@smrt({\n // #1400: read-only generated surface — RBAC/identity writes go through\n // permission-gated services, not auth-only generated CRUD.\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n // #3742: CLI mirrors the read-only surface; `cli` without `include` is full CRUD.\n cli: { include: ['list', 'get'] },\n})\nexport class Permission extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-users\";\n /**\n * Display name for the permission\n */\n @field({\n description: 'The name of an action people can be allowed to perform.',\n })\n name: string = '';\n\n /**\n * Description of what this permission allows\n */\n @field({ description: 'What this permission allows someone to do.' })\n description: string = '';\n\n /**\n * Category for grouping in UI (e.g., 'articles', 'users', 'settings')\n */\n @field({\n description: 'The area of the application this permission belongs to.',\n })\n category: string = '';\n\n constructor(options: PermissionOptions = {}) {\n super(options);\n if (options.name !== undefined) this.name = options.name;\n if (options.description !== undefined)\n this.description = options.description;\n if (options.category !== undefined) this.category = options.category;\n }\n\n /**\n * Parse the permission slug into resource and action components.\n * @returns Parsed slug with resource, action, and validation status\n */\n parseSlug(): ParsedPermissionSlug {\n return parsePermissionSlug(this.slug ?? '');\n }\n\n /**\n * Get the resource part of the permission slug\n * e.g., 'articles.create' -> 'articles'\n */\n getResource(): string {\n return this.parseSlug().resource;\n }\n\n /**\n * Get the action part of the permission slug\n * e.g., 'articles.create' -> 'create'\n */\n getAction(): string {\n return this.parseSlug().action;\n }\n\n /**\n * Check if the permission slug is valid (follows 'resource.action' pattern)\n */\n isValidSlug(): boolean {\n return this.parseSlug().isValid;\n }\n}\n","/**\n * PermissionCollection - Collection manager for Permission objects\n * @packageDocumentation\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Permission } from '../models/Permission.js';\n\n/**\n * Collection for managing Permission objects\n */\nexport class PermissionCollection extends SmrtCollection<Permission> {\n static readonly _itemClass = Permission;\n\n /**\n * Find permissions by category\n */\n async findByCategory(category: string): Promise<Permission[]> {\n return await this.list({\n where: { category },\n orderBy: 'slug ASC',\n });\n }\n\n /**\n * Find permission by slug\n */\n async findBySlug(slug: string): Promise<Permission | null> {\n const results = await this.list({\n where: { slug },\n limit: 1,\n });\n return results.length > 0 ? results[0] : null;\n }\n\n /**\n * Batch fetch permissions by IDs\n * Returns a Map of id -> Permission for efficient lookup\n */\n async findByIds(ids: string[]): Promise<Map<string, Permission>> {\n if (ids.length === 0) {\n return new Map();\n }\n\n // Remove duplicates\n const uniqueIds = [...new Set(ids)];\n\n // Build placeholders for SQL IN clause\n const placeholders = uniqueIds.map(() => '?').join(', ');\n const results = await this.query(\n `SELECT * FROM ${this.tableName} WHERE id IN (${placeholders})`,\n uniqueIds,\n );\n\n const map = new Map<string, Permission>();\n for (const perm of results) {\n if (perm.id) {\n map.set(perm.id, perm);\n }\n }\n return map;\n }\n\n /**\n * Get all unique categories\n */\n async getCategories(): Promise<string[]> {\n const results = await this.query(\n `SELECT DISTINCT category FROM ${this.tableName} WHERE category != '' ORDER BY category ASC`,\n );\n return results.map((r) => r.category);\n }\n\n /**\n * Find or create a permission by slug\n */\n async findOrCreate(\n slug: string,\n defaults: Partial<{\n name: string;\n description: string;\n category: string;\n }> = {},\n ): Promise<Permission> {\n const existing = await this.findBySlug(slug);\n if (existing) {\n return existing;\n }\n\n // `create()` already persists; the second `save()` was a redundant UPDATE\n // and an extra change-feed append per row (#3022).\n return await this.create({\n slug,\n name: defaults.name ?? slug,\n description: defaults.description ?? '',\n category: defaults.category ?? slug.split('.')[0],\n });\n }\n}\n","/** Collection options for framework-internal authorization reads. @packageDocumentation */\nimport type {\n SmrtClassOptions,\n SmrtCollectionOptions,\n} from '@happyvertical/smrt-core';\n\n/**\n * The caller's options with its list bounds removed.\n *\n * `SmrtCollection.create()` forwards `defaultListLimit`/`maxListLimit` from\n * any options bag it is handed (#2367), so a bounded bag (for example a\n * bounded collection's own options) would silently truncate a read that an\n * authorization decision needs in full: a dropped DENY widens access, a\n * dropped row in a quota count lifts the quota (#3047 review, #3048).\n * Collections that back an authorization decision are therefore always\n * created from this bag. Only the list bounds are stripped; the database,\n * tenancy context and every other option still apply.\n */\nexport function withoutListBounds(\n options: SmrtClassOptions | SmrtCollectionOptions,\n): SmrtCollectionOptions {\n return { ...options, defaultListLimit: undefined, maxListLimit: undefined };\n}\n","/**\n * Batched commits for permission-catalog and role-permission seeding.\n * @packageDocumentation\n */\n\nimport {\n isEmbeddedDatabase,\n withEmbeddedWriteTransaction,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\n/**\n * Rows a seeding pass writes per transaction (#3323).\n *\n * A cold seed writes every catalog permission and every default grant, each\n * with a change-feed append: thousands of rows on a real registry. When every\n * row autocommits, each is a separate durable commit. On a file-backed SQLite\n * database with `synchronous = FULL` (the local runtime profile), that is an\n * `fsync` per row, and disk flushes, not queries, set the bootstrap's wall\n * clock. Batching cuts the commits by this factor.\n *\n * The batch is bounded, not the whole seed, because a transaction scope in\n * `@happyvertical/sql` tracks every promise created while it is open and\n * keeps each statement's rejection observation until the transaction ends,\n * so its per-statement cost grows with the statements already issued. On the\n * local owner claim, one catalog-wide transaction took ~17s against ~4.5s for\n * batches of 25-100 rows (and ~30s for per-row commits on a real disk).\n */\nexport const SEEDING_BATCH_SIZE = 50;\n\n/**\n * Write `items` in transactions of at most {@link SEEDING_BATCH_SIZE} rows.\n *\n * Seeding is idempotent and additive, so committing per batch keeps the\n * semantics of the previous per-row commits: an interrupted pass leaves only\n * complete rows behind, and re-running converges. `write` receives the handle\n * bound to its batch's transaction and must issue every write through it.\n *\n * Nesting follows `@happyvertical/sql`'s rules. Given a transaction handle,\n * SQLite and PostgreSQL re-enter it under a SAVEPOINT, and adapters without\n * savepoints (DuckDB/JSON) reuse the caller's transaction directly. A handle\n * with no `transaction()` keeps per-statement commits. A caller already inside\n * a transaction must pass that transaction's handle: on a single-connection\n * adapter the root handle waits for the open transaction instead of joining\n * it.\n *\n * @internal\n */\nexport async function writeInSeedingBatches<T>(\n db: DatabaseInterface,\n items: readonly T[],\n write: (database: DatabaseInterface, batch: readonly T[]) => Promise<void>,\n): Promise<void> {\n for (let start = 0; start < items.length; start += SEEDING_BATCH_SIZE) {\n const batch = items.slice(start, start + SEEDING_BATCH_SIZE);\n if (typeof db.transaction !== 'function') {\n await write(db, batch);\n continue;\n }\n await withEmbeddedWriteTransaction(\n db,\n isEmbeddedDatabase(db),\n (database) => write(database, batch),\n true,\n );\n }\n}\n","/**\n * Manifest-derived permission cataloging and syncing\n * @packageDocumentation\n */\n\nimport { getPackageConfig } from '@happyvertical/smrt-config';\nimport {\n findManifestEntryByQualifiedName,\n inheritedCollectionSurface,\n ObjectRegistry,\n resolveOperationPermissionAlias,\n type SmartObjectDefinition,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { PermissionCollection } from '../collections/PermissionCollection.js';\nimport { writeInSeedingBatches } from '../collections/seeding-transaction.js';\nimport {\n isValidPermissionSlug,\n type Permission,\n parsePermissionSlug,\n} from '../models/Permission.js';\nimport type {\n PermissionCatalogSource,\n PermissionDefinition,\n PostgresPermissionAction,\n PostgresPermissionBinding,\n} from '../permission-registry.js';\n\nimport { getRuntimePermissionRegistrations } from '../permission-registry-state.js';\nimport { withoutListBounds } from './authorization-read-options.js';\n\nexport {\n type PermissionCatalogSource,\n type PermissionDefinition,\n type PostgresPermissionAction,\n type PostgresPermissionBinding,\n registerPermissionDefinitions,\n} from '../permission-registry.js';\n\nexport interface PermissionCatalog {\n customPermissions: PermissionDefinition[];\n manifestPermissions: PermissionDefinition[];\n permissions: PermissionDefinition[];\n runtimePermissions: PermissionDefinition[];\n}\n\nexport interface PermissionCatalogSyncResult {\n catalog: PermissionCatalog;\n created: string[];\n unchanged: string[];\n updated: string[];\n}\n\nexport interface UsersConfig extends Record<string, unknown> {\n permissions?: {\n custom?: PermissionDefinition[];\n postgres?: {\n bindings?: PostgresPermissionBinding[];\n enabled?: boolean;\n };\n };\n}\n\nexport interface ConstructorLike {\n name?: string;\n}\n\nexport interface CollectionLike {\n getItemClass?: () => ConstructorLike;\n}\n\nexport type OperationPermissionCollectionInput =\n | string\n | ConstructorLike\n | CollectionLike\n | object;\n\nfunction toSnakeCase(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\nfunction pluralize(word: string): string {\n if (word.endsWith('y') && !/[aeiou]y$/i.test(word)) {\n return `${word.slice(0, -1)}ies`;\n }\n\n if (\n word.endsWith('s') ||\n word.endsWith('x') ||\n word.endsWith('z') ||\n word.endsWith('ch') ||\n word.endsWith('sh')\n ) {\n return `${word}es`;\n }\n\n return `${word}s`;\n}\n\nfunction deriveCollectionName(className: string): string {\n return pluralize(toSnakeCase(className));\n}\n\nfunction humanizeResource(resource: string): string {\n return resource\n .replace(/[._-]+/g, ' ')\n .replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\n\nfunction capitalize(value: string): string {\n return `${value[0]?.toUpperCase() ?? ''}${value.slice(1)}`;\n}\n\nfunction defaultPermissionName(slug: string): string {\n const parsed = parsePermissionSlug(slug);\n if (!parsed.isValid) {\n return humanizeResource(slug);\n }\n\n return `${humanizeResource(parsed.action)} ${humanizeResource(parsed.resource)}`;\n}\n\nfunction defaultPermissionDescription(slug: string): string {\n const parsed = parsePermissionSlug(slug);\n if (!parsed.isValid) {\n return `Allows ${slug}`;\n }\n\n return `Allows ${humanizeResource(parsed.action).toLowerCase()} access for ${humanizeResource(parsed.resource).toLowerCase()}`;\n}\n\nexport function normalizeOperationPermissionAction(action: string): string {\n const trimmed = action.trim();\n const lower = trimmed.toLowerCase();\n\n if (lower === 'list' || lower === 'get') {\n return 'read';\n }\n\n if (\n lower === 'read' ||\n lower === 'create' ||\n lower === 'update' ||\n lower === 'delete'\n ) {\n return lower;\n }\n\n return trimmed;\n}\n\nfunction isConstructorLike(value: unknown): value is ConstructorLike {\n return typeof value === 'function';\n}\n\nfunction isCollectionLike(value: unknown): value is CollectionLike {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as CollectionLike).getItemClass === 'function'\n );\n}\n\nfunction resolveConstructor(\n value: OperationPermissionCollectionInput,\n): ConstructorLike | undefined {\n if (isConstructorLike(value)) {\n return value;\n }\n\n if (isCollectionLike(value)) {\n return value.getItemClass?.();\n }\n\n if (typeof value === 'object' && value !== null) {\n const ctor = value.constructor;\n if (typeof ctor === 'function' && ctor.name && ctor.name !== 'Object') {\n return ctor;\n }\n }\n\n return undefined;\n}\n\nexport function deriveOperationPermissionCollectionName(\n input: OperationPermissionCollectionInput,\n): string {\n if (typeof input === 'string') {\n const collection = input.trim();\n if (!collection) {\n throw new Error('Operation permission collection must not be empty.');\n }\n return collection;\n }\n\n const ctor = resolveConstructor(input);\n if (!ctor?.name) {\n throw new Error(\n 'Operation permission collection must be a collection slug, model class, model instance, or collection instance.',\n );\n }\n\n const registered =\n ObjectRegistry.getClassByConstructor(\n ctor as Parameters<typeof ObjectRegistry.getClassByConstructor>[0],\n ) ?? ObjectRegistry.getClass(ctor.name);\n if (!registered) {\n return deriveCollectionName(ctor.name);\n }\n\n // The catalog's resolution (explicit collection, manifest entry, STI base),\n // so an STI subtype never derives a slug the catalog does not list (#3125).\n // Only the last-resort fallback stays the guard's own: the registration's\n // collection.\n return resolveCollectionName(\n registered,\n manifestEntryFor(registered),\n (target) => target.collection ?? deriveCollectionName(target.name),\n );\n}\n\nexport function deriveOperationPermissionSlug(\n collection: OperationPermissionCollectionInput,\n action: string,\n): string {\n const collectionName = deriveOperationPermissionCollectionName(collection);\n const standard = normalizeOperationPermissionAction(action);\n if (['read', 'create', 'update', 'delete'].includes(standard)) {\n return `${collectionName}.${standard}`;\n }\n const ctor =\n typeof collection === 'string' ? undefined : resolveConstructor(collection);\n const registered = ctor\n ? (ObjectRegistry.getClassByConstructor(\n ctor as Parameters<typeof ObjectRegistry.getClassByConstructor>[0],\n ) ?? ObjectRegistry.getClass(ctor.name ?? ''))\n : undefined;\n if (registered) {\n const entry = manifestEntryFor(registered);\n const alias = resolveOperationPermissionAlias(\n entry?.decoratorConfig ?? registered.config,\n action,\n );\n const normalizedAction = normalizeOperationPermissionAction(\n alias?.action ?? action,\n );\n if (!normalizedAction) {\n throw new Error('Operation permission action must not be empty.');\n }\n return `${collectionName}.${normalizedAction}`;\n }\n // Resolve by the catalog slug even for string callers (CLI/MCP/tool runs).\n // Two models sharing a collection must agree. An unaliased matching method\n // conflicts with an alias rather than silently inheriting its broader grant.\n const actions = new Set<string>();\n for (const registered of new Set(ObjectRegistry.getAllClasses().values())) {\n const entry = manifestEntryFor(registered);\n const owner =\n entry && isCollectionClass(registered, entry)\n ? resolveCollectionItemRegistration(registered, entry)\n : registered;\n if (\n !owner ||\n resolveCatalogCollectionName(owner, manifestEntryFor(owner)) !==\n collectionName\n )\n continue;\n const alias = resolveOperationPermissionAlias(\n entry?.decoratorConfig ?? registered.config,\n action,\n );\n if (alias) {\n actions.add(alias.action);\n continue;\n }\n const methodEntries = entry?.methods\n ? Object.values(entry.methods)\n : Array.from(registered.methods.entries());\n if (\n getPublicCustomMethodNames(methodEntries, [\n 'list',\n 'get',\n 'create',\n 'update',\n 'delete',\n ]).includes(action)\n ) {\n actions.add(action);\n }\n }\n if (actions.size > 1) throw new Error('Ambiguous operation permission alias');\n const normalizedAction = normalizeOperationPermissionAction(\n [...actions][0] ?? action,\n );\n if (!normalizedAction) {\n throw new Error('Operation permission action must not be empty.');\n }\n\n return `${collectionName}.${normalizedAction}`;\n}\n\ntype RegisteredCatalogClass = NonNullable<\n ReturnType<typeof ObjectRegistry.getClass>\n>;\n\nfunction manifestEntryFor(\n registered: RegisteredCatalogClass,\n): SmartObjectDefinition | undefined {\n return registered.qualifiedName\n ? findManifestEntryByQualifiedName(registered.qualifiedName)\n : undefined;\n}\n\n/**\n * The STI base of a registered class: its oldest registered prototype\n * ancestor declaring `tableStrategy: 'sti'` — the manifest generator's\n * `findSTIBase` rule. Ancestors resolve by constructor, so another package's\n * same-named class cannot stand in for the base.\n */\nfunction registeredStiBase(\n registered: RegisteredCatalogClass,\n): RegisteredCatalogClass | undefined {\n let base: RegisteredCatalogClass | undefined;\n for (\n let parent = Object.getPrototypeOf(registered.constructor);\n parent && parent !== Function.prototype;\n parent = Object.getPrototypeOf(parent)\n ) {\n const ancestor = ObjectRegistry.getClassByConstructor(parent);\n if (ancestor?.config?.tableStrategy === 'sti') base = ancestor;\n }\n return base === registered ? undefined : base;\n}\n\n/**\n * The permission collection of a registered class, shared by the catalog and\n * the operation guards (#3125): an explicit `collection`, then the manifest\n * entry's (the scanner gives an STI subtype its base's), then — for an STI\n * subtype with no manifest entry, as in a consumer bundle decorated before its\n * manifest loads — its STI base's. `fallback` names a class with none of\n * these; it differs between the catalog and the guards for historical slugs\n * and is deliberately left unchanged here.\n */\nfunction resolveCollectionName(\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition | undefined,\n fallback: (registered: RegisteredCatalogClass) => string,\n): string {\n const objectConfig = manifestEntry?.decoratorConfig ?? registered.config;\n const rawCollection = (objectConfig as { collection?: unknown } | undefined)\n ?.collection;\n if (typeof rawCollection === 'string' && rawCollection.length > 0) {\n return rawCollection;\n }\n if (manifestEntry?.collection) return manifestEntry.collection;\n const stiBase = registeredStiBase(registered);\n return stiBase\n ? resolveCollectionName(stiBase, manifestEntryFor(stiBase), fallback)\n : fallback(registered);\n}\n\nfunction resolveCatalogCollectionName(\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition | undefined,\n): string {\n return resolveCollectionName(registered, manifestEntry, (target) =>\n deriveCollectionName(target.name),\n );\n}\n\ninterface CatalogAncestor {\n entry: SmartObjectDefinition;\n registered: RegisteredCatalogClass;\n}\n\nfunction packagePrefix(qualifiedName: string | undefined): string | undefined {\n const separator = qualifiedName?.lastIndexOf(':') ?? -1;\n return qualifiedName && separator > 0\n ? qualifiedName.slice(0, separator)\n : undefined;\n}\n\nfunction findCatalogClass(\n name: string,\n nearQualifiedName: string | undefined,\n): RegisteredCatalogClass | undefined {\n if (name.includes(':')) return ObjectRegistry.getClassByQualifiedName(name);\n const prefix = packagePrefix(nearQualifiedName);\n return (\n (prefix\n ? ObjectRegistry.getClassByQualifiedName(`${prefix}:${name}`)\n : undefined) ?? ObjectRegistry.getClass(name)\n );\n}\n\n/**\n * The class and its manifest ancestors, nearest first — mirroring the route\n * generator's collection-ancestry walk so an inherited collection class (one\n * that extends another collection without its own type argument) is detected\n * and resolved to the same item.\n */\nfunction collectCatalogAncestry(\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition | undefined,\n): CatalogAncestor[] {\n const chain: CatalogAncestor[] = [];\n const seen = new Set<string>();\n let current: CatalogAncestor | undefined = manifestEntry\n ? { entry: manifestEntry, registered }\n : undefined;\n while (current && chain.length < 32) {\n const key = current.registered.qualifiedName ?? current.registered.name;\n if (seen.has(key)) break;\n seen.add(key);\n chain.push(current);\n const parentName =\n current.entry.extendsQualified || current.entry.extends || undefined;\n if (!parentName || parentName === 'SmrtCollection') break;\n const parent = findCatalogClass(\n parentName,\n current.registered.qualifiedName,\n );\n const parentEntry = parent?.qualifiedName\n ? findManifestEntryByQualifiedName(parent.qualifiedName)\n : undefined;\n current =\n parent && parentEntry\n ? { entry: parentEntry, registered: parent }\n : undefined;\n }\n return chain;\n}\n\nfunction isCollectionClass(\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition | undefined,\n): boolean {\n return collectCatalogAncestry(registered, manifestEntry).some(({ entry }) =>\n isCollectionManifestEntry(entry),\n );\n}\n\nfunction resolveCollectionItemRegistration(\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition,\n): RegisteredCatalogClass | undefined {\n const ancestry = collectCatalogAncestry(registered, manifestEntry);\n for (const { entry, registered: ancestor } of ancestry) {\n const typeArg = entry.extendsTypeArg;\n if (typeof typeArg === 'string' && typeArg.length > 0) {\n return findCatalogClass(typeArg, ancestor.qualifiedName);\n }\n }\n for (const { registered: ancestor } of ancestry) {\n if (!ancestor.name.endsWith('Collection')) continue;\n const item = findCatalogClass(\n ancestor.name.slice(0, -'Collection'.length),\n ancestor.qualifiedName,\n );\n if (item) return item;\n }\n return undefined;\n}\n\nfunction getCollectionClassActionDefinitions(\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition | undefined,\n standardActions: readonly string[],\n): PermissionDefinition[] {\n if (!manifestEntry) return [];\n const item = resolveCollectionItemRegistration(registered, manifestEntry);\n if (!item) return [];\n const itemEntry = item.qualifiedName\n ? findManifestEntryByQualifiedName(item.qualifiedName)\n : undefined;\n if (isCollectionClass(item, itemEntry)) return [];\n const collection = resolveCatalogCollectionName(item, itemEntry);\n const objectConfig = manifestEntry.decoratorConfig ?? registered.config;\n const methodEntries = manifestEntry.methods\n ? Object.values(manifestEntry.methods)\n : Array.from(registered.methods.entries());\n const catalogApi = ownCollectionApiConfig(\n objectConfig?.api,\n manifestEntry,\n itemEntry,\n );\n return getPublicCustomMethodNames(methodEntries, standardActions)\n .filter((methodName) => isOperationEnabled(catalogApi, methodName))\n .map((methodName) => {\n const alias = resolveOperationPermissionAlias(objectConfig, methodName);\n const action = alias?.action ?? methodName;\n const definition: PermissionDefinition = {\n className: item.name,\n collection,\n description: `Allows ${action} on ${humanizeResource(collection).toLowerCase()}`,\n name: `${capitalize(action)} ${humanizeResource(collection)}`,\n qualifiedName: item.qualifiedName,\n slug: `${collection}.${action}`,\n };\n addAliasDatabaseBindings(definition, alias, item, itemEntry);\n return definition;\n });\n}\n\n/**\n * The collection's own `api` config for cataloguing its operation slugs. A\n * collection's unset surface inherits its model's (smrt-core\n * `inheritedCollectionSurface`), which gates the generated routes; the\n * services in this package still assert the collection's operation slugs\n * (`tenants.moveToParent`, ...), so an inherited include list reads as unset\n * here, exactly as before the collection inherited it. An inherited `false`\n * stays `false`, as it always has.\n */\nfunction ownCollectionApiConfig(\n apiConfig: unknown,\n collectionEntry: SmartObjectDefinition,\n itemEntry: SmartObjectDefinition | undefined,\n): unknown {\n if (apiConfig === undefined || apiConfig === false || !itemEntry) {\n return apiConfig;\n }\n const inherited = inheritedCollectionSurface(\n 'api',\n itemEntry.decoratorConfig ?? {},\n {\n collection: new Set(Object.keys(collectionEntry.methods ?? {})),\n item: new Set(Object.keys(itemEntry.methods ?? {})),\n },\n );\n return inherited !== undefined &&\n inherited !== false &&\n JSON.stringify(inherited) === JSON.stringify(apiConfig)\n ? undefined\n : apiConfig;\n}\n\nfunction addAliasDatabaseBindings(\n definition: PermissionDefinition,\n alias: ReturnType<typeof resolveOperationPermissionAlias>,\n registered: RegisteredCatalogClass,\n manifestEntry: SmartObjectDefinition | undefined,\n): void {\n if (!alias?.databaseActions?.length) return;\n const tableName =\n manifestEntry?.schema?.tableName ??\n registered.schema?.tableName ??\n registered.config.tableName;\n if (!tableName)\n throw new Error('Permission SQL binding requires a table name');\n mergeBindings(definition, {\n slug: definition.slug,\n postgres: {\n bindings: alias.databaseActions.map((action) => ({\n action,\n tableName,\n ...(registered.tenantScopedConfig?.field\n ? { tenantField: toSnakeCase(registered.tenantScopedConfig.field) }\n : {}),\n })),\n },\n });\n}\n\nfunction isCollectionManifestEntry(objectDef?: SmartObjectDefinition): boolean {\n return (\n objectDef?.extends === 'SmrtCollection' ||\n objectDef?.extendsTypeArg !== undefined\n );\n}\n\ninterface ManifestMethodCandidate {\n isPublic?: boolean;\n name?: string;\n}\n\ninterface FieldReadPermissionCandidate {\n _meta?: {\n readPermission?: unknown;\n };\n readPermission?: unknown;\n}\n\ntype MethodCandidate =\n | ManifestMethodCandidate\n | readonly [string, ManifestMethodCandidate];\n\nfunction isMethodEntryTuple(\n method: MethodCandidate,\n): method is readonly [string, ManifestMethodCandidate] {\n return Array.isArray(method);\n}\n\nfunction normalizeMethodCandidate(\n method: MethodCandidate,\n): ManifestMethodCandidate {\n if (isMethodEntryTuple(method)) {\n const [name, definition] = method;\n return { ...definition, name: definition.name ?? name };\n }\n return method;\n}\n\nfunction getPublicCustomMethodNames(\n methodEntries: MethodCandidate[],\n standardActions: readonly string[],\n): string[] {\n return Array.from(\n new Set(\n methodEntries.flatMap((method) => {\n const { isPublic, name } = normalizeMethodCandidate(method);\n if (!name || isPublic !== true || standardActions.includes(name)) {\n return [];\n }\n return [name];\n }),\n ),\n );\n}\n\nfunction getCustomMethodExposureNames(\n config: unknown,\n availableCustomMethods: string[],\n): Set<string> {\n if (!config || config === false) {\n return new Set();\n }\n\n if (config === true || typeof config !== 'object') {\n return new Set(availableCustomMethods);\n }\n\n const rawInclude = (config as { include?: string[] }).include;\n const include = Array.isArray(rawInclude) ? [...rawInclude] : undefined;\n const rawExclude = (config as { exclude?: string[] }).exclude;\n const exclude: string[] = Array.isArray(rawExclude) ? [...rawExclude] : [];\n\n if (!include) {\n return new Set(\n availableCustomMethods.filter(\n (methodName) => !exclude.includes(methodName),\n ),\n );\n }\n\n const baseMethods = include.filter((methodName) =>\n availableCustomMethods.includes(methodName),\n );\n\n return new Set(\n baseMethods.filter((methodName) => !exclude.includes(methodName)),\n );\n}\n\n/**\n * Identity/RBAC models whose operation slugs are catalogued as their FULL\n * vocabulary (CRUD plus every public custom method), independent of which\n * generated transports they expose (#3742).\n *\n * Their generated REST/MCP surface is read-only (#1400) and their generated\n * CLI is now read-only or closed (#3742), yet the permission-gated users\n * services and consumers' hand-written handlers still assert slugs such as\n * `memberships.create` or `tenants.moveToParent` through\n * `assertOperationPermission()`, which requires catalog presence. Those slugs\n * used to be catalogued only because the CLI accidentally exposed full CRUD;\n * closing the transport must not silently drop them from the catalog (and so\n * from role seeding).\n */\nconst USERS_AUTHORITY_CATALOG_MODELS: ReadonlySet<string> = new Set(\n [\n 'Group',\n 'GroupMember',\n 'GroupRole',\n 'Membership',\n 'MembershipOverride',\n 'Permission',\n 'ResourceGrant',\n 'Role',\n 'RolePermission',\n 'Session',\n 'Tenant',\n 'TenantIntegration',\n 'TenantPermissionOverride',\n 'User',\n 'UsersMagicLinkToken',\n ].map((className) => `@happyvertical/smrt-users:${className}`),\n);\n\nfunction isOperationEnabled(config: unknown, action: string): boolean {\n if (config === false) {\n return false;\n }\n\n if (config && typeof config === 'object') {\n const include = Array.isArray((config as { include?: string[] }).include)\n ? (config as { include?: string[] }).include\n : undefined;\n const rawExclude = (config as { exclude?: string[] }).exclude;\n const exclude: string[] = Array.isArray(rawExclude) ? [...rawExclude] : [];\n\n if (include && !include.includes(action)) {\n return false;\n }\n if (exclude.includes(action)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction normalizePostgresAction(\n action: PostgresPermissionBinding['action'],\n): PostgresPermissionAction {\n const normalized = action.toUpperCase();\n if (\n normalized === 'SELECT' ||\n normalized === 'INSERT' ||\n normalized === 'UPDATE' ||\n normalized === 'DELETE'\n ) {\n return normalized;\n }\n\n throw new Error(\n `Unsupported Postgres permission action '${action}'. Expected SELECT, INSERT, UPDATE, or DELETE.`,\n );\n}\n\nfunction normalizeBinding(\n binding: PostgresPermissionBinding,\n fallbackPermission: string,\n): PostgresPermissionBinding {\n return {\n action: normalizePostgresAction(binding.action),\n permission: binding.permission || fallbackPermission,\n schemaName: binding.schemaName,\n tableName: binding.tableName,\n tenantField: binding.tenantField,\n };\n}\n\nfunction mergeStringField(\n fieldName:\n | 'category'\n | 'className'\n | 'collection'\n | 'description'\n | 'name'\n | 'qualifiedName',\n existing: PermissionDefinition,\n incoming: PermissionDefinition,\n slug: string,\n): void {\n const existingValue = existing[fieldName];\n const incomingValue = incoming[fieldName];\n\n if (!incomingValue) {\n return;\n }\n\n if (!existingValue) {\n existing[fieldName] = incomingValue;\n return;\n }\n\n if (existingValue !== incomingValue) {\n throw new Error(\n `Conflicting permission metadata for '${slug}' field '${fieldName}': '${existingValue}' !== '${incomingValue}'`,\n );\n }\n}\n\nfunction mergeBindings(\n existing: PermissionDefinition,\n incoming: PermissionDefinition,\n): void {\n const existingBindings = existing.postgres?.bindings ?? [];\n const incomingBindings = incoming.postgres?.bindings ?? [];\n if (incomingBindings.length === 0) {\n return;\n }\n\n const seen = new Set(\n existingBindings.map((binding) =>\n [\n binding.permission,\n binding.action,\n binding.schemaName ?? '',\n binding.tableName,\n binding.tenantField ?? '',\n ].join('|'),\n ),\n );\n\n const mergedBindings = [...existingBindings];\n for (const binding of incomingBindings) {\n const normalized = normalizeBinding(binding, incoming.slug);\n const key = [\n normalized.permission,\n normalized.action,\n normalized.schemaName ?? '',\n normalized.tableName,\n normalized.tenantField ?? '',\n ].join('|');\n if (!seen.has(key)) {\n seen.add(key);\n mergedBindings.push(normalized);\n }\n }\n\n existing.postgres = {\n bindings: mergedBindings,\n };\n}\n\nfunction normalizeDefinition(\n definition: PermissionDefinition,\n source: PermissionCatalogSource,\n): PermissionDefinition {\n if (!definition.slug || !isValidPermissionSlug(definition.slug.trim())) {\n throw new Error(\n `Invalid permission slug '${definition.slug}'. Expected 'resource.action[.scope...]'.`,\n );\n }\n\n const slug = definition.slug.trim();\n return {\n category: definition.category ?? parsePermissionSlug(slug).resource,\n className: definition.className,\n collection: definition.collection,\n description: definition.description ?? defaultPermissionDescription(slug),\n name: definition.name ?? defaultPermissionName(slug),\n postgres: definition.postgres?.bindings\n ? {\n bindings: definition.postgres.bindings.map((binding) =>\n normalizeBinding(binding, slug),\n ),\n }\n : undefined,\n qualifiedName: definition.qualifiedName,\n slug,\n source,\n };\n}\n\nfunction mergeDefinitionSet(\n current: Map<string, PermissionDefinition>,\n incomingDefinitions: PermissionDefinition[],\n source: PermissionCatalogSource,\n): void {\n for (const rawDefinition of incomingDefinitions) {\n const definition = normalizeDefinition(rawDefinition, source);\n const existing = current.get(definition.slug);\n\n if (!existing) {\n current.set(definition.slug, definition);\n continue;\n }\n\n mergeStringField('category', existing, definition, definition.slug);\n mergeStringField('className', existing, definition, definition.slug);\n mergeStringField('collection', existing, definition, definition.slug);\n mergeStringField('description', existing, definition, definition.slug);\n mergeStringField('name', existing, definition, definition.slug);\n mergeStringField('qualifiedName', existing, definition, definition.slug);\n mergeBindings(existing, definition);\n }\n}\n\n/** Whether syncing `definition` would change the persisted row. */\nfunction definitionChangesPermission(\n existing: Permission,\n definition: PermissionDefinition,\n): boolean {\n return (\n (definition.name ?? existing.name) !== existing.name ||\n (definition.description ?? existing.description) !== existing.description ||\n (definition.category ?? existing.category) !== existing.category\n );\n}\n\nexport class PermissionCatalogService {\n constructor(private readonly options: SmrtClassOptions = {}) {}\n\n getUsersConfig(): UsersConfig {\n return getPackageConfig<UsersConfig>('users', {});\n }\n\n getRuntimePermissionDefinitions(): PermissionDefinition[] {\n return Array.from(getRuntimePermissionRegistrations().values()).flat();\n }\n\n getCustomPermissionDefinitions(): PermissionDefinition[] {\n return this.getUsersConfig().permissions?.custom ?? [];\n }\n\n getCatalog(): PermissionCatalog {\n const manifestPermissions = this.getManifestPermissionDefinitions();\n const customPermissions = this.getCustomPermissionDefinitions();\n const runtimePermissions = this.getRuntimePermissionDefinitions();\n\n const merged = new Map<string, PermissionDefinition>();\n mergeDefinitionSet(merged, manifestPermissions, 'manifest');\n mergeDefinitionSet(merged, customPermissions, 'config');\n mergeDefinitionSet(merged, runtimePermissions, 'runtime');\n\n return {\n customPermissions: customPermissions.map((definition) =>\n normalizeDefinition(definition, 'config'),\n ),\n manifestPermissions: manifestPermissions.map((definition) =>\n normalizeDefinition(definition, 'manifest'),\n ),\n permissions: Array.from(merged.values()).sort((left, right) =>\n left.slug.localeCompare(right.slug),\n ),\n runtimePermissions: runtimePermissions.map((definition) =>\n normalizeDefinition(definition, 'runtime'),\n ),\n };\n }\n\n deriveOperationPermissionSlug(\n collection: OperationPermissionCollectionInput,\n action: string,\n ): string {\n return deriveOperationPermissionSlug(collection, action);\n }\n\n hasPermissionSlug(slug: string): boolean {\n return this.getCatalog().permissions.some(\n (permission) => permission.slug === slug,\n );\n }\n\n async syncPermissionCatalog(): Promise<PermissionCatalogSyncResult> {\n const catalog = this.getCatalog();\n const permissions = await PermissionCollection.create(\n withoutListBounds(this.options),\n );\n\n const created: string[] = [];\n const unchanged: string[] = [];\n const updated: string[] = [];\n\n // Load the live catalog in ONE read rather than a `findBySlug()` per\n // definition (#3022). The catalog is registry-derived, so its size grows\n // with every consumed package's object and action surface: on a consumer\n // app it is thousands of slugs, and a per-slug SELECT made this bootstrap\n // scale linearly with the registry — it is the dominant cost of a cold\n // first write, and it doubled between 0.51.7 and 0.51.11 purely because\n // the catalog grew. `list({})` applies no implicit bound (see\n // `applyListBounds`), so this is the whole table, exactly what the\n // per-slug probes collectively read.\n const existingBySlug = new Map<string, Permission>();\n for (const permission of await permissions.list({})) {\n if (typeof permission.slug === 'string' && permission.slug.length > 0) {\n existingBySlug.set(permission.slug, permission);\n }\n }\n\n // Unchanged slugs settle from that one read. Only rows that need a write\n // go to the writer, which commits them in batches rather than one durable\n // commit per row (#3323).\n const pending = catalog.permissions.filter((definition) => {\n const existing = existingBySlug.get(definition.slug);\n if (existing && !definitionChangesPermission(existing, definition)) {\n unchanged.push(definition.slug);\n return false;\n }\n return true;\n });\n\n await writeInSeedingBatches(\n permissions.db as DatabaseInterface,\n pending,\n async (database, batch) => {\n const batchPermissions = await PermissionCollection.create({\n ...this.options,\n db: database,\n });\n for (const definition of batch) {\n const existing = existingBySlug.get(definition.slug) ?? null;\n if (!existing) {\n // `collection.create()` already persists (it calls `save()`), so a\n // second `save()` here was a redundant UPDATE plus a second\n // change-feed append for every seeded row (#3022).\n const permission = await batchPermissions.create({\n category:\n definition.category ??\n parsePermissionSlug(definition.slug).resource,\n description: definition.description ?? '',\n name: definition.name ?? definition.slug,\n slug: definition.slug,\n });\n // Keep the in-memory view authoritative: the removed per-slug read\n // used to see a row this same loop had just written, so a catalog\n // carrying the same slug twice must still resolve to one row.\n existingBySlug.set(definition.slug, permission);\n created.push(definition.slug);\n continue;\n }\n\n if (!definitionChangesPermission(existing, definition)) {\n unchanged.push(definition.slug);\n continue;\n }\n\n existing.name = definition.name ?? existing.name;\n existing.description = definition.description ?? existing.description;\n existing.category = definition.category ?? existing.category;\n // The row may have been loaded or created outside this batch's\n // transaction; persist it through the batch's handle.\n await existing.withDatabase(database, (row) => row.save());\n updated.push(definition.slug);\n }\n },\n );\n\n return {\n catalog,\n created,\n unchanged,\n updated,\n };\n }\n\n private getManifestPermissionDefinitions(): PermissionDefinition[] {\n const standardActions = ['list', 'get', 'create', 'update', 'delete'];\n const definitions = new Map<string, PermissionDefinition>();\n const seenRegistrations = new Set<object>();\n\n for (const [, registered] of ObjectRegistry.getAllClasses()) {\n // A source registration can retain its simple key while manifest\n // hydration adds its qualified key. Build the catalog once per concrete\n // registration, preserving package identity instead of a simple-name\n // first-match lookup.\n if (seenRegistrations.has(registered)) continue;\n seenRegistrations.add(registered);\n\n const manifestEntry = registered?.qualifiedName\n ? findManifestEntryByQualifiedName(registered.qualifiedName)\n : undefined;\n\n if (isCollectionClass(registered, manifestEntry)) {\n // Mutating custom API actions hosted on a collection class are\n // generated at the item collection's route and gated on\n // `<itemCollection>.<method>` (#2977), so catalog that slug here.\n for (const definition of getCollectionClassActionDefinitions(\n registered,\n manifestEntry,\n standardActions,\n )) {\n const existing = definitions.get(definition.slug);\n if (existing) mergeBindings(existing, definition);\n else definitions.set(definition.slug, definition);\n }\n continue;\n }\n\n const className = registered.name;\n const qualifiedName = registered.qualifiedName;\n const objectConfig = manifestEntry?.decoratorConfig ?? registered.config;\n const collection = resolveCatalogCollectionName(\n registered,\n manifestEntry,\n );\n // A shared STI namespace belongs to its effective root, never whichever\n // subtype happens to be visited last. Explicit child namespaces retain\n // their own CRUD; custom methods and field permissions remain below.\n const registryKey = qualifiedName ?? className;\n const ownsCrud =\n !ObjectRegistry.getSTIBase(registryKey) ||\n !ObjectRegistry.getInheritanceChain(registryKey).some((ancestor) => {\n const parent = ObjectRegistry.getClass(ancestor);\n return (\n parent &&\n parent !== registered &&\n resolveCatalogCollectionName(parent, manifestEntryFor(parent)) ===\n collection\n );\n });\n // Authority models catalog their full vocabulary even though their\n // generated CLI is closed or read-only (#3742).\n const catalogCliConfig =\n qualifiedName && USERS_AUTHORITY_CATALOG_MODELS.has(qualifiedName)\n ? true\n : objectConfig.cli;\n\n const readExposed =\n isOperationEnabled(objectConfig.api, 'list') ||\n isOperationEnabled(objectConfig.api, 'get') ||\n isOperationEnabled(catalogCliConfig, 'list') ||\n isOperationEnabled(catalogCliConfig, 'get') ||\n isOperationEnabled(objectConfig.mcp, 'list') ||\n isOperationEnabled(objectConfig.mcp, 'get');\n if (ownsCrud && readExposed) {\n definitions.set(`${collection}.read`, {\n ...definitions.get(`${collection}.read`),\n className,\n collection,\n qualifiedName,\n slug: `${collection}.read`,\n });\n }\n\n const fieldEntries = manifestEntry?.fields\n ? Object.entries(manifestEntry.fields)\n : Array.from(\n (registered.inheritedFields ?? registered.fields).entries(),\n );\n for (const [fieldName, fieldDef] of fieldEntries) {\n const field = fieldDef as FieldReadPermissionCandidate;\n const readPermission =\n typeof field.readPermission === 'string'\n ? field.readPermission\n : typeof field._meta?.readPermission === 'string'\n ? field._meta.readPermission\n : undefined;\n if (!readPermission || definitions.has(readPermission)) {\n continue;\n }\n definitions.set(readPermission, {\n className,\n collection,\n description: `Allows reading ${fieldName} on ${humanizeResource(collection).toLowerCase()}`,\n name: `Read ${humanizeResource(fieldName)} on ${humanizeResource(collection)}`,\n qualifiedName,\n slug: readPermission,\n });\n }\n\n for (const action of ['create', 'update', 'delete'] as const) {\n const exposed =\n isOperationEnabled(objectConfig.api, action) ||\n isOperationEnabled(catalogCliConfig, action) ||\n isOperationEnabled(objectConfig.mcp, action);\n if (!ownsCrud || !exposed) {\n continue;\n }\n\n definitions.set(`${collection}.${action}`, {\n ...definitions.get(`${collection}.${action}`),\n className,\n collection,\n qualifiedName,\n slug: `${collection}.${action}`,\n });\n }\n\n const methodEntries = manifestEntry?.methods\n ? Object.values(manifestEntry.methods)\n : Array.from(registered.methods.entries());\n const publicCustomMethodNames = getPublicCustomMethodNames(\n methodEntries,\n standardActions,\n );\n const customApiMethods = new Set<string>();\n const customCliMethods = getCustomMethodExposureNames(\n catalogCliConfig,\n publicCustomMethodNames,\n );\n const customMcpMethods = getCustomMethodExposureNames(\n objectConfig.mcp,\n publicCustomMethodNames,\n );\n\n for (const methodName of publicCustomMethodNames) {\n if (isOperationEnabled(objectConfig.api, methodName)) {\n customApiMethods.add(methodName);\n }\n }\n\n const customMethods = new Set<string>([\n ...customApiMethods,\n ...customCliMethods,\n ...customMcpMethods,\n ]);\n\n for (const methodName of customMethods) {\n const alias = resolveOperationPermissionAlias(objectConfig, methodName);\n const permissionAction = alias?.action ?? methodName;\n const slug = `${collection}.${permissionAction}`;\n const definition = definitions.get(slug) ?? {\n className,\n collection,\n qualifiedName,\n slug,\n description: `Allows ${permissionAction} on ${humanizeResource(collection).toLowerCase()}`,\n name: `${capitalize(permissionAction)} ${humanizeResource(collection)}`,\n };\n addAliasDatabaseBindings(definition, alias, registered, manifestEntry);\n definitions.set(slug, definition);\n }\n }\n\n return Array.from(definitions.values()).sort((left, right) =>\n left.slug.localeCompare(right.slug),\n );\n }\n\n static create(options: SmrtClassOptions = {}): PermissionCatalogService {\n return new PermissionCatalogService(options);\n }\n}\n\nexport async function syncPermissionCatalog(\n options: SmrtClassOptions = {},\n): Promise<PermissionCatalogSyncResult> {\n return PermissionCatalogService.create(options).syncPermissionCatalog();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCO,SAAS,oBAAoB,MAAoC;CACtE,MAAM,QAAQ,KAAK,MAAM,GAAG;CAC5B,IAAI,MAAM,UAAU,KAAK,MAAM,MAAM,OAAO,GAC1C,OAAO;EACL,UAAU,MAAM;EAChB,QAAQ,MAAM,MAAM,CAAC,CAAA,CAAE,KAAK,GAAG;EAC/B,SAAS;CACX;CAEF,OAAO;EACL,UAAU;EACV,QAAQ;EACR,SAAS;CACX;AACF;AASO,SAAS,sBAAsB,MAAuB;CAC3D,OAAO,oBAAoB,IAAI,CAAA,CAAE;AACnC;AAqCO,IAAM,aAAN,cAAyB,WAAW;CAOzC,OAAe;CAMf,cAAsB;CAQtB,WAAmB;CAEnB,YAAY,UAA6B,CAAC,GAAG;EAC3C,MAAM,OAAO;EACb,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,gBAAgB,KAAA,GAC1B,KAAK,cAAc,QAAQ;EAC7B,IAAI,QAAQ,aAAa,KAA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ACA,yBAAyB,YAAY,OAAO,YAAY,aAAa;IACrE,YAAY,IAAI,MAAM,UAAU;GAClC;EACF;EAEA,OAAO,MAAM,KAAK,YAAY,OAAO,CAAC,CAAA,CAAE,MAAM,MAAM,UAClD,KAAK,KAAK,cAAc,MAAM,IAAI,CACpC;CACF;CAEA,OAAO,OAAO,UAA4B,CAAC,GAA6B;EACtE,OAAO,IAAI,yBAAyB,OAAO;CAC7C;AACF;AAEA,eAAsB,sBACpB,UAA4B,CAAC,GACS;CACtC,OAAO,yBAAyB,OAAO,OAAO,CAAA,CAAE,sBAAsB;AACxE"}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { c as PermissionCollection, t as PermissionCatalogService } from "./PermissionCatalogService-DcmTn38P.js";
|
|
2
|
+
import { ObjectRegistry, findManifestEntryByQualifiedName } from "@happyvertical/smrt-core";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
//#region src/services/PostgresPermissionPolicies.ts
|
|
5
|
+
function toSnakeCase(value) {
|
|
6
|
+
return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
|
|
7
|
+
}
|
|
8
|
+
function quoteIdent(identifier) {
|
|
9
|
+
return `"${identifier.replaceAll("\"", "\"\"")}"`;
|
|
10
|
+
}
|
|
11
|
+
function quoteLiteral(value) {
|
|
12
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
13
|
+
}
|
|
14
|
+
function isProbablyPostgres(configDb, database) {
|
|
15
|
+
if (configDb && typeof configDb === "object" && !("query" in configDb) && "type" in configDb && configDb.type === "postgres") return true;
|
|
16
|
+
if (typeof database.url === "string" && database.url.startsWith("postgres")) return true;
|
|
17
|
+
return (database.constructor?.name || "").toLowerCase().includes("postgres");
|
|
18
|
+
}
|
|
19
|
+
function normalizePostgresPermissionAction(action) {
|
|
20
|
+
const normalized = action.toUpperCase();
|
|
21
|
+
if (normalized === "SELECT" || normalized === "INSERT" || normalized === "UPDATE" || normalized === "DELETE") return normalized;
|
|
22
|
+
throw new Error(`Invalid Postgres permission binding action "${action}". Expected one of SELECT, INSERT, UPDATE, DELETE.`);
|
|
23
|
+
}
|
|
24
|
+
function normalizePostgresPermissionBinding(binding, fallbackPermission) {
|
|
25
|
+
const tableName = binding.tableName?.trim();
|
|
26
|
+
if (!tableName) throw new Error("Postgres permission binding is missing a tableName value.");
|
|
27
|
+
const permission = binding.permission ?? fallbackPermission;
|
|
28
|
+
if (!permission) throw new Error("Postgres permission binding is missing a permission value.");
|
|
29
|
+
return {
|
|
30
|
+
action: normalizePostgresPermissionAction(binding.action),
|
|
31
|
+
permission,
|
|
32
|
+
schemaName: binding.schemaName,
|
|
33
|
+
tableName,
|
|
34
|
+
tenantField: binding.tenantField
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function parseTableReference(binding) {
|
|
38
|
+
if (binding.tableName.includes(".")) {
|
|
39
|
+
const [schemaName, tableName] = binding.tableName.split(".", 2);
|
|
40
|
+
return {
|
|
41
|
+
schemaName,
|
|
42
|
+
tableName
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
schemaName: binding.schemaName ?? "public",
|
|
47
|
+
tableName: binding.tableName
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
var SCOPE_SCHEMA = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
51
|
+
function assertScopeSchemaName(schemaName) {
|
|
52
|
+
if (typeof schemaName !== "string" || !SCOPE_SCHEMA.test(schemaName)) throw new Error("A Postgres policy scope needs an explicit lower-case schemaName (it never falls back to public).");
|
|
53
|
+
}
|
|
54
|
+
function buildPolicyName(tableName, action, schemaName) {
|
|
55
|
+
const actionSegment = action.toLowerCase();
|
|
56
|
+
const hash = createHash("sha1").update(schemaName && schemaName !== "public" ? `${schemaName}.${tableName}:${action}` : `${tableName}:${action}`).digest("hex").slice(0, 8);
|
|
57
|
+
const sanitizedTable = tableName.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
|
|
58
|
+
const prefix = "smrt_";
|
|
59
|
+
const maxTableSegmentLength = 58 - actionSegment.length - hash.length - 2;
|
|
60
|
+
return `${prefix}${(sanitizedTable || "table").slice(0, Math.max(maxTableSegmentLength, 1))}_${actionSegment}_${hash}`;
|
|
61
|
+
}
|
|
62
|
+
function buildPermissionExpression(permissionSlugs) {
|
|
63
|
+
if (permissionSlugs.length === 0) return "FALSE";
|
|
64
|
+
return permissionSlugs.map((permission) => `smrt_has_permission(${quoteLiteral(permission)})`).join(" OR ");
|
|
65
|
+
}
|
|
66
|
+
function buildTenantMatchExpression(tenantField) {
|
|
67
|
+
return `${quoteIdent(tenantField)}::text = smrt_current_tenant_id()`;
|
|
68
|
+
}
|
|
69
|
+
function buildSelectPolicySql(target, permissions) {
|
|
70
|
+
const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;
|
|
71
|
+
const policyName = buildPolicyName(target.tableName, "SELECT", target.schemaName);
|
|
72
|
+
const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;
|
|
73
|
+
return [`DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`, `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR SELECT USING (${condition})`];
|
|
74
|
+
}
|
|
75
|
+
function buildInsertPolicySql(target, permissions) {
|
|
76
|
+
const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;
|
|
77
|
+
const policyName = buildPolicyName(target.tableName, "INSERT", target.schemaName);
|
|
78
|
+
const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;
|
|
79
|
+
return [`DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`, `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR INSERT WITH CHECK (${condition})`];
|
|
80
|
+
}
|
|
81
|
+
function buildUpdatePolicySql(target, permissions) {
|
|
82
|
+
const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;
|
|
83
|
+
const policyName = buildPolicyName(target.tableName, "UPDATE", target.schemaName);
|
|
84
|
+
const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;
|
|
85
|
+
return [`DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`, `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR UPDATE USING (${condition}) WITH CHECK (${condition})`];
|
|
86
|
+
}
|
|
87
|
+
function buildDeletePolicySql(target, permissions) {
|
|
88
|
+
const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;
|
|
89
|
+
const policyName = buildPolicyName(target.tableName, "DELETE", target.schemaName);
|
|
90
|
+
const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;
|
|
91
|
+
return [`DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`, `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR DELETE USING (${condition})`];
|
|
92
|
+
}
|
|
93
|
+
function buildHelperStatements(schemaName) {
|
|
94
|
+
const prefix = schemaName ? `${quoteIdent(schemaName)}.` : "";
|
|
95
|
+
return [
|
|
96
|
+
[
|
|
97
|
+
`CREATE OR REPLACE FUNCTION ${prefix}smrt_rls_bypass()`,
|
|
98
|
+
"RETURNS boolean",
|
|
99
|
+
"LANGUAGE sql",
|
|
100
|
+
"STABLE",
|
|
101
|
+
"AS $$",
|
|
102
|
+
" SELECT COALESCE(NULLIF(current_setting('smrt.system_context', true), ''), 'false')::boolean",
|
|
103
|
+
" OR COALESCE(NULLIF(current_setting('smrt.super_admin_bypass', true), ''), 'false')::boolean",
|
|
104
|
+
"$$"
|
|
105
|
+
].join("\n"),
|
|
106
|
+
[
|
|
107
|
+
`CREATE OR REPLACE FUNCTION ${prefix}smrt_current_tenant_id()`,
|
|
108
|
+
"RETURNS text",
|
|
109
|
+
"LANGUAGE sql",
|
|
110
|
+
"STABLE",
|
|
111
|
+
"AS $$",
|
|
112
|
+
" SELECT NULLIF(current_setting('smrt.tenant_id', true), '')",
|
|
113
|
+
"$$"
|
|
114
|
+
].join("\n"),
|
|
115
|
+
[
|
|
116
|
+
`CREATE OR REPLACE FUNCTION ${prefix}smrt_has_permission(required_permission text)`,
|
|
117
|
+
"RETURNS boolean",
|
|
118
|
+
"LANGUAGE sql",
|
|
119
|
+
"STABLE",
|
|
120
|
+
"AS $$",
|
|
121
|
+
" SELECT COALESCE(NULLIF(current_setting('smrt.system_context', true), ''), 'false')::boolean",
|
|
122
|
+
" OR COALESCE(NULLIF(current_setting('smrt.super_admin_bypass', true), ''), 'false')::boolean",
|
|
123
|
+
" OR jsonb_exists(COALESCE(NULLIF(current_setting('smrt.permissions', true), ''), '[]')::jsonb, required_permission)",
|
|
124
|
+
"$$"
|
|
125
|
+
].join("\n")
|
|
126
|
+
];
|
|
127
|
+
}
|
|
128
|
+
function addBindingToTarget(targets, binding, source = {}) {
|
|
129
|
+
const { schemaName, tableName } = parseTableReference(binding);
|
|
130
|
+
const targetKey = `${schemaName}.${tableName}`;
|
|
131
|
+
const existing = targets.get(targetKey);
|
|
132
|
+
const tenantField = binding.tenantField ?? "tenant_id";
|
|
133
|
+
if (existing && existing.tenantField !== tenantField) throw new Error(`Conflicting tenant fields for table '${targetKey}': '${existing.tenantField}' !== '${tenantField}'`);
|
|
134
|
+
const target = existing ?? {
|
|
135
|
+
actions: /* @__PURE__ */ new Map(),
|
|
136
|
+
...source,
|
|
137
|
+
schemaName,
|
|
138
|
+
tableName,
|
|
139
|
+
tenantField
|
|
140
|
+
};
|
|
141
|
+
const action = normalizePostgresPermissionAction(binding.action);
|
|
142
|
+
const permissions = target.actions.get(action) ?? /* @__PURE__ */ new Set();
|
|
143
|
+
if (binding.permission) permissions.add(binding.permission);
|
|
144
|
+
target.actions.set(action, permissions);
|
|
145
|
+
targets.set(targetKey, target);
|
|
146
|
+
}
|
|
147
|
+
function generatePostgresPermissionSql(options = {}, scope) {
|
|
148
|
+
if (scope) assertScopeSchemaName(scope.schemaName);
|
|
149
|
+
const catalogService = PermissionCatalogService.create(options);
|
|
150
|
+
const catalog = catalogService.getCatalog();
|
|
151
|
+
const config = catalogService.getUsersConfig();
|
|
152
|
+
const candidateTargets = /* @__PURE__ */ new Map();
|
|
153
|
+
const skipped = [];
|
|
154
|
+
const autoCandidates = /* @__PURE__ */ new Map();
|
|
155
|
+
for (const metadata of ObjectRegistry.getAllObjectMetadata()) {
|
|
156
|
+
const registered = ObjectRegistry.getClassByConstructor(metadata.constructor) ?? ObjectRegistry.getClass(metadata.name);
|
|
157
|
+
if (scope && !scope.includeClass({
|
|
158
|
+
className: metadata.name,
|
|
159
|
+
qualifiedName: registered?.qualifiedName
|
|
160
|
+
})) continue;
|
|
161
|
+
const tenantScoped = registered?.tenantScopedConfig;
|
|
162
|
+
const manifestEntry = registered?.qualifiedName ? findManifestEntryByQualifiedName(registered.qualifiedName) : void 0;
|
|
163
|
+
if (!tenantScoped) {
|
|
164
|
+
skipped.push({
|
|
165
|
+
className: metadata.name,
|
|
166
|
+
qualifiedName: registered?.qualifiedName,
|
|
167
|
+
reason: "not tenant-scoped"
|
|
168
|
+
});
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (tenantScoped.mode !== "required") {
|
|
172
|
+
skipped.push({
|
|
173
|
+
className: metadata.name,
|
|
174
|
+
qualifiedName: registered?.qualifiedName,
|
|
175
|
+
reason: `tenant mode '${tenantScoped.mode}' is not supported for automatic Postgres RLS generation`
|
|
176
|
+
});
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const rawTableName = registered?.schema?.tableName ?? manifestEntry?.schema?.tableName;
|
|
180
|
+
if (!rawTableName) {
|
|
181
|
+
skipped.push({
|
|
182
|
+
className: metadata.name,
|
|
183
|
+
qualifiedName: registered?.qualifiedName,
|
|
184
|
+
reason: "no schema table name available"
|
|
185
|
+
});
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const parsedTable = parseTableReference({
|
|
189
|
+
schemaName: scope?.schemaName,
|
|
190
|
+
tableName: rawTableName
|
|
191
|
+
});
|
|
192
|
+
if (scope && parsedTable.schemaName !== scope.schemaName) {
|
|
193
|
+
skipped.push({
|
|
194
|
+
className: metadata.name,
|
|
195
|
+
qualifiedName: registered?.qualifiedName,
|
|
196
|
+
reason: `table '${rawTableName}' is qualified with another schema than '${scope.schemaName}'`
|
|
197
|
+
});
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const tableKey = `${parsedTable.schemaName}.${parsedTable.tableName}`;
|
|
201
|
+
const rawCollection = (manifestEntry?.decoratorConfig ?? metadata.config)?.collection;
|
|
202
|
+
const collection = (typeof rawCollection === "string" && rawCollection.length > 0 ? rawCollection : void 0) ?? manifestEntry?.collection ?? `${toSnakeCase(metadata.name)}s`;
|
|
203
|
+
const entries = autoCandidates.get(tableKey) ?? [];
|
|
204
|
+
entries.push({
|
|
205
|
+
className: metadata.name,
|
|
206
|
+
collection,
|
|
207
|
+
qualifiedName: registered?.qualifiedName,
|
|
208
|
+
schemaName: parsedTable.schemaName,
|
|
209
|
+
tableName: parsedTable.tableName,
|
|
210
|
+
tenantField: toSnakeCase(tenantScoped.field),
|
|
211
|
+
permissions: scope?.permissionsFor?.({
|
|
212
|
+
className: metadata.name,
|
|
213
|
+
collection,
|
|
214
|
+
tableName: parsedTable.tableName
|
|
215
|
+
})
|
|
216
|
+
});
|
|
217
|
+
autoCandidates.set(tableKey, entries);
|
|
218
|
+
}
|
|
219
|
+
for (const [tableKey, entries] of autoCandidates) {
|
|
220
|
+
if (entries.length > 1) {
|
|
221
|
+
for (const entry2 of entries) skipped.push({
|
|
222
|
+
className: entry2.className,
|
|
223
|
+
collection: entry2.collection,
|
|
224
|
+
qualifiedName: entry2.qualifiedName,
|
|
225
|
+
reason: `table '${tableKey}' is shared by multiple objects, so automatic policy generation was skipped`,
|
|
226
|
+
schemaName: entry2.schemaName,
|
|
227
|
+
tableName: entry2.tableName
|
|
228
|
+
});
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const entry = entries[0];
|
|
232
|
+
const permissionSlugs = {
|
|
233
|
+
SELECT: entry.permissions?.SELECT ?? [`${entry.collection}.read`],
|
|
234
|
+
INSERT: entry.permissions?.INSERT ?? [`${entry.collection}.create`],
|
|
235
|
+
UPDATE: entry.permissions?.UPDATE ?? [`${entry.collection}.update`],
|
|
236
|
+
DELETE: entry.permissions?.DELETE ?? [`${entry.collection}.delete`]
|
|
237
|
+
};
|
|
238
|
+
for (const action of [
|
|
239
|
+
"SELECT",
|
|
240
|
+
"INSERT",
|
|
241
|
+
"UPDATE",
|
|
242
|
+
"DELETE"
|
|
243
|
+
]) for (const permission of permissionSlugs[action]) addBindingToTarget(candidateTargets, {
|
|
244
|
+
action,
|
|
245
|
+
permission,
|
|
246
|
+
schemaName: entry.schemaName,
|
|
247
|
+
tableName: entry.tableName,
|
|
248
|
+
tenantField: entry.tenantField
|
|
249
|
+
}, entry);
|
|
250
|
+
}
|
|
251
|
+
const explicitBindings = [];
|
|
252
|
+
if (!scope) {
|
|
253
|
+
for (const definition of catalog.permissions) for (const binding of definition.postgres?.bindings ?? []) explicitBindings.push(normalizePostgresPermissionBinding(binding, definition.slug));
|
|
254
|
+
for (const binding of config.permissions?.postgres?.bindings ?? []) explicitBindings.push(normalizePostgresPermissionBinding(binding));
|
|
255
|
+
}
|
|
256
|
+
for (const binding of explicitBindings) addBindingToTarget(candidateTargets, binding);
|
|
257
|
+
const statements = [...buildHelperStatements(scope?.schemaName)];
|
|
258
|
+
const targets = Array.from(candidateTargets.values()).sort((left, right) => `${left.schemaName}.${left.tableName}`.localeCompare(`${right.schemaName}.${right.tableName}`)).map((target) => ({
|
|
259
|
+
actions: Object.fromEntries(Array.from(target.actions.entries()).map(([action, permissions]) => [action, Array.from(permissions).sort()])),
|
|
260
|
+
className: target.className,
|
|
261
|
+
collection: target.collection,
|
|
262
|
+
qualifiedName: target.qualifiedName,
|
|
263
|
+
schemaName: target.schemaName,
|
|
264
|
+
tableName: target.tableName,
|
|
265
|
+
tenantField: target.tenantField
|
|
266
|
+
}));
|
|
267
|
+
for (const target of Array.from(candidateTargets.values())) {
|
|
268
|
+
const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;
|
|
269
|
+
statements.push(`ALTER TABLE ${qualifiedTable} ENABLE ROW LEVEL SECURITY`);
|
|
270
|
+
statements.push(`ALTER TABLE ${qualifiedTable} FORCE ROW LEVEL SECURITY`);
|
|
271
|
+
const selectPermissions = Array.from(target.actions.get("SELECT") ?? []).sort();
|
|
272
|
+
const insertPermissions = Array.from(target.actions.get("INSERT") ?? []).sort();
|
|
273
|
+
const updatePermissions = Array.from(target.actions.get("UPDATE") ?? []).sort();
|
|
274
|
+
const deletePermissions = Array.from(target.actions.get("DELETE") ?? []).sort();
|
|
275
|
+
if (selectPermissions.length > 0) statements.push(...buildSelectPolicySql(target, selectPermissions));
|
|
276
|
+
if (insertPermissions.length > 0) statements.push(...buildInsertPolicySql(target, insertPermissions));
|
|
277
|
+
if (updatePermissions.length > 0) statements.push(...buildUpdatePolicySql(target, updatePermissions));
|
|
278
|
+
if (deletePermissions.length > 0) statements.push(...buildDeletePolicySql(target, deletePermissions));
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
bindings: explicitBindings,
|
|
282
|
+
skipped,
|
|
283
|
+
sql: `${statements.join(";\n")};
|
|
284
|
+
`,
|
|
285
|
+
statements,
|
|
286
|
+
targets
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
async function applyPostgresPermissionPolicies(options = {}) {
|
|
290
|
+
const permissions = await PermissionCollection.create(options);
|
|
291
|
+
if (!isProbablyPostgres(options.db ?? options.persistence, permissions.db)) throw new Error("applyPostgresPermissionPolicies() requires a Postgres database connection.");
|
|
292
|
+
const result = generatePostgresPermissionSql(options);
|
|
293
|
+
for (const statement of result.statements) try {
|
|
294
|
+
await permissions.db.query(statement);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
throw new Error(`Failed to apply Postgres permission policy statement:
|
|
297
|
+
${statement}`, { cause: error });
|
|
298
|
+
}
|
|
299
|
+
return result;
|
|
300
|
+
}
|
|
301
|
+
async function applyScopedPostgresPermissionPolicies(db, scope, options = {}) {
|
|
302
|
+
const result = generatePostgresPermissionSql(options, scope);
|
|
303
|
+
for (const statement of result.statements) try {
|
|
304
|
+
await db.query(statement);
|
|
305
|
+
} catch (error) {
|
|
306
|
+
throw new Error(`Failed to apply Postgres permission policy statement:
|
|
307
|
+
${statement}`, { cause: error });
|
|
308
|
+
}
|
|
309
|
+
return result;
|
|
310
|
+
}
|
|
311
|
+
//#endregion
|
|
312
|
+
export { applyScopedPostgresPermissionPolicies as n, generatePostgresPermissionSql as r, applyPostgresPermissionPolicies as t };
|
|
313
|
+
|
|
314
|
+
//# sourceMappingURL=PostgresPermissionPolicies-RzCLuARk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PostgresPermissionPolicies-RzCLuARk.js","names":["entry"],"sources":["../../src/services/PostgresPermissionPolicies.ts"],"sourcesContent":["/**\n * Postgres policy generation and application for SMRT permissions\n * @packageDocumentation\n */\n\nimport { createHash } from 'node:crypto';\nimport {\n findManifestEntryByQualifiedName,\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { PermissionCollection } from '../collections/PermissionCollection.js';\nimport {\n PermissionCatalogService,\n type PostgresPermissionAction,\n type PostgresPermissionBinding,\n} from './PermissionCatalogService.js';\n\ninterface QueryableDatabase {\n query: (sql: string, ...params: unknown[]) => Promise<unknown>;\n url?: string;\n}\n\ntype DatabaseConfig = SmrtClassOptions['db'] | SmrtClassOptions['persistence'];\n\n/**\n * Narrows policy generation to one application schema, for a host that holds\n * a registry of run-time models (an app's tables are addressed unqualified\n * through a transaction-local `search_path`).\n *\n * With a scope the generator never falls back to `public`: every table is\n * addressed in `schemaName`, the `smrt_*` helper functions are created there\n * (policies call them unqualified, through that same `search_path`, so a\n * schema copied or renamed whole keeps its own helpers), only the registered classes\n * `includeClass` accepts get policies, and explicit catalog or config bindings\n * (which name tables of the deployment's own schema) are not applied.\n */\nexport interface PostgresPolicyScope {\n /** The schema the scoped tables and helper functions live in. */\n schemaName: string;\n /** Which registered classes get policies (default: none). */\n includeClass: (info: {\n className: string;\n qualifiedName?: string;\n }) => boolean;\n /**\n * The permission slugs that allow each action on a table, for a host whose\n * slugs are not the `<collection>.read|create|update|delete` default.\n */\n permissionsFor?: (info: {\n className: string;\n collection: string;\n tableName: string;\n }) => Partial<Record<PostgresPermissionAction, string[]>> | undefined;\n}\n\ninterface TablePolicyTarget {\n actions: Map<PostgresPermissionAction, Set<string>>;\n className?: string;\n collection?: string;\n qualifiedName?: string;\n schemaName: string;\n tableName: string;\n tenantField: string;\n}\n\nexport interface PostgresPermissionPolicyReportItem {\n className?: string;\n collection?: string;\n qualifiedName?: string;\n reason: string;\n schemaName?: string;\n tableName?: string;\n}\n\nexport interface PostgresPermissionPolicyTarget {\n actions: Partial<Record<PostgresPermissionAction, string[]>>;\n className?: string;\n collection?: string;\n qualifiedName?: string;\n schemaName: string;\n tableName: string;\n tenantField: string;\n}\n\nexport interface GeneratePostgresPermissionSqlResult {\n bindings: PostgresPermissionBinding[];\n skipped: PostgresPermissionPolicyReportItem[];\n sql: string;\n statements: string[];\n targets: PostgresPermissionPolicyTarget[];\n}\n\nfunction toSnakeCase(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\nfunction quoteIdent(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction quoteLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction isProbablyPostgres(\n configDb: DatabaseConfig,\n database: QueryableDatabase,\n): boolean {\n if (\n configDb &&\n typeof configDb === 'object' &&\n !('query' in configDb) &&\n 'type' in configDb &&\n configDb.type === 'postgres'\n ) {\n return true;\n }\n\n if (typeof database.url === 'string' && database.url.startsWith('postgres')) {\n return true;\n }\n\n return (database.constructor?.name || '').toLowerCase().includes('postgres');\n}\n\nfunction normalizePostgresPermissionAction(\n action: PostgresPermissionBinding['action'],\n): PostgresPermissionAction {\n const normalized = action.toUpperCase();\n if (\n normalized === 'SELECT' ||\n normalized === 'INSERT' ||\n normalized === 'UPDATE' ||\n normalized === 'DELETE'\n ) {\n return normalized;\n }\n\n throw new Error(\n `Invalid Postgres permission binding action \"${action}\". Expected one of SELECT, INSERT, UPDATE, DELETE.`,\n );\n}\n\nfunction normalizePostgresPermissionBinding(\n binding: PostgresPermissionBinding,\n fallbackPermission?: string,\n): PostgresPermissionBinding {\n const tableName = binding.tableName?.trim();\n if (!tableName) {\n throw new Error(\n 'Postgres permission binding is missing a tableName value.',\n );\n }\n\n const permission = binding.permission ?? fallbackPermission;\n if (!permission) {\n throw new Error(\n 'Postgres permission binding is missing a permission value.',\n );\n }\n\n return {\n action: normalizePostgresPermissionAction(binding.action),\n permission,\n schemaName: binding.schemaName,\n tableName,\n tenantField: binding.tenantField,\n };\n}\n\nfunction parseTableReference(\n binding: Pick<PostgresPermissionBinding, 'schemaName' | 'tableName'>,\n): { schemaName: string; tableName: string } {\n if (binding.tableName.includes('.')) {\n const [schemaName, tableName] = binding.tableName.split('.', 2);\n return {\n schemaName,\n tableName,\n };\n }\n\n return {\n schemaName: binding.schemaName ?? 'public',\n tableName: binding.tableName,\n };\n}\n\nconst SCOPE_SCHEMA = /^[a-z_][a-z0-9_]{0,62}$/;\n\nfunction assertScopeSchemaName(schemaName: unknown): void {\n if (typeof schemaName !== 'string' || !SCOPE_SCHEMA.test(schemaName)) {\n throw new Error(\n 'A Postgres policy scope needs an explicit lower-case schemaName (it never falls back to public).',\n );\n }\n}\n\n/**\n * A policy is named per table, so names in different schemas cannot clash in\n * PostgreSQL; the schema still goes into the hash (except for `public`, whose\n * names predate it and must not change) so the same table name in two app\n * schemas never yields the same policy name.\n */\nfunction buildPolicyName(\n tableName: string,\n action: PostgresPermissionAction,\n schemaName?: string,\n): string {\n const actionSegment = action.toLowerCase();\n const hash = createHash('sha1')\n .update(\n schemaName && schemaName !== 'public'\n ? `${schemaName}.${tableName}:${action}`\n : `${tableName}:${action}`,\n )\n .digest('hex')\n .slice(0, 8);\n const sanitizedTable = tableName\n .replace(/[^a-zA-Z0-9_]+/g, '_')\n .replace(/^_+|_+$/g, '');\n const prefix = 'smrt_';\n const separatorLength = 2;\n const maxTableSegmentLength =\n 63 - prefix.length - actionSegment.length - hash.length - separatorLength;\n const tableSegment = (sanitizedTable || 'table').slice(\n 0,\n Math.max(maxTableSegmentLength, 1),\n );\n\n return `${prefix}${tableSegment}_${actionSegment}_${hash}`;\n}\n\nfunction buildPermissionExpression(permissionSlugs: string[]): string {\n if (permissionSlugs.length === 0) {\n return 'FALSE';\n }\n\n return permissionSlugs\n .map((permission) => `smrt_has_permission(${quoteLiteral(permission)})`)\n .join(' OR ');\n}\n\nfunction buildTenantMatchExpression(tenantField: string): string {\n return `${quoteIdent(tenantField)}::text = smrt_current_tenant_id()`;\n}\n\nfunction buildSelectPolicySql(\n target: TablePolicyTarget,\n permissions: string[],\n): string[] {\n const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;\n const policyName = buildPolicyName(\n target.tableName,\n 'SELECT',\n target.schemaName,\n );\n const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;\n\n return [\n `DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`,\n `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR SELECT USING (${condition})`,\n ];\n}\n\nfunction buildInsertPolicySql(\n target: TablePolicyTarget,\n permissions: string[],\n): string[] {\n const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;\n const policyName = buildPolicyName(\n target.tableName,\n 'INSERT',\n target.schemaName,\n );\n const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;\n\n return [\n `DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`,\n `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR INSERT WITH CHECK (${condition})`,\n ];\n}\n\nfunction buildUpdatePolicySql(\n target: TablePolicyTarget,\n permissions: string[],\n): string[] {\n const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;\n const policyName = buildPolicyName(\n target.tableName,\n 'UPDATE',\n target.schemaName,\n );\n const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;\n\n return [\n `DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`,\n `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR UPDATE USING (${condition}) WITH CHECK (${condition})`,\n ];\n}\n\nfunction buildDeletePolicySql(\n target: TablePolicyTarget,\n permissions: string[],\n): string[] {\n const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;\n const policyName = buildPolicyName(\n target.tableName,\n 'DELETE',\n target.schemaName,\n );\n const condition = `smrt_rls_bypass() OR ((${buildTenantMatchExpression(target.tenantField)}) AND (${buildPermissionExpression(permissions)}))`;\n\n return [\n `DROP POLICY IF EXISTS ${quoteIdent(policyName)} ON ${qualifiedTable}`,\n `CREATE POLICY ${quoteIdent(policyName)} ON ${qualifiedTable} FOR DELETE USING (${condition})`,\n ];\n}\n\nfunction buildHelperStatements(schemaName?: string): string[] {\n const prefix = schemaName ? `${quoteIdent(schemaName)}.` : '';\n return [\n [\n `CREATE OR REPLACE FUNCTION ${prefix}smrt_rls_bypass()`,\n 'RETURNS boolean',\n 'LANGUAGE sql',\n 'STABLE',\n 'AS $$',\n \" SELECT COALESCE(NULLIF(current_setting('smrt.system_context', true), ''), 'false')::boolean\",\n \" OR COALESCE(NULLIF(current_setting('smrt.super_admin_bypass', true), ''), 'false')::boolean\",\n '$$',\n ].join('\\n'),\n [\n `CREATE OR REPLACE FUNCTION ${prefix}smrt_current_tenant_id()`,\n 'RETURNS text',\n 'LANGUAGE sql',\n 'STABLE',\n 'AS $$',\n \" SELECT NULLIF(current_setting('smrt.tenant_id', true), '')\",\n '$$',\n ].join('\\n'),\n [\n `CREATE OR REPLACE FUNCTION ${prefix}smrt_has_permission(required_permission text)`,\n 'RETURNS boolean',\n 'LANGUAGE sql',\n 'STABLE',\n 'AS $$',\n // The bypass is spelled out, not called: a schema copied whole creates its\n // functions in name order, and a SQL function's body is checked when it\n // is created, so it must not depend on a sibling that comes after it.\n \" SELECT COALESCE(NULLIF(current_setting('smrt.system_context', true), ''), 'false')::boolean\",\n \" OR COALESCE(NULLIF(current_setting('smrt.super_admin_bypass', true), ''), 'false')::boolean\",\n \" OR jsonb_exists(COALESCE(NULLIF(current_setting('smrt.permissions', true), ''), '[]')::jsonb, required_permission)\",\n '$$',\n ].join('\\n'),\n ];\n}\n\nfunction addBindingToTarget(\n targets: Map<string, TablePolicyTarget>,\n binding: PostgresPermissionBinding,\n source: Pick<\n TablePolicyTarget,\n 'className' | 'collection' | 'qualifiedName'\n > = {},\n): void {\n const { schemaName, tableName } = parseTableReference(binding);\n const targetKey = `${schemaName}.${tableName}`;\n const existing = targets.get(targetKey);\n const tenantField = binding.tenantField ?? 'tenant_id';\n\n if (existing && existing.tenantField !== tenantField) {\n throw new Error(\n `Conflicting tenant fields for table '${targetKey}': '${existing.tenantField}' !== '${tenantField}'`,\n );\n }\n\n const target = existing ?? {\n actions: new Map<PostgresPermissionAction, Set<string>>(),\n ...source,\n schemaName,\n tableName,\n tenantField,\n };\n const action = normalizePostgresPermissionAction(binding.action);\n const permissions = target.actions.get(action) ?? new Set<string>();\n if (binding.permission) {\n permissions.add(binding.permission);\n }\n target.actions.set(action, permissions);\n targets.set(targetKey, target);\n}\n\nexport function generatePostgresPermissionSql(\n options: SmrtClassOptions = {},\n scope?: PostgresPolicyScope,\n): GeneratePostgresPermissionSqlResult {\n if (scope) assertScopeSchemaName(scope.schemaName);\n\n const catalogService = PermissionCatalogService.create(options);\n const catalog = catalogService.getCatalog();\n const config = catalogService.getUsersConfig();\n const candidateTargets = new Map<string, TablePolicyTarget>();\n const skipped: PostgresPermissionPolicyReportItem[] = [];\n\n const autoCandidates = new Map<\n string,\n Array<{\n className?: string;\n collection: string;\n qualifiedName?: string;\n schemaName: string;\n tableName: string;\n tenantField: string;\n permissions?: Partial<Record<PostgresPermissionAction, string[]>>;\n }>\n >();\n\n for (const metadata of ObjectRegistry.getAllObjectMetadata()) {\n const registered =\n ObjectRegistry.getClassByConstructor(metadata.constructor) ??\n ObjectRegistry.getClass(metadata.name);\n if (\n scope &&\n !scope.includeClass({\n className: metadata.name,\n qualifiedName: registered?.qualifiedName,\n })\n ) {\n continue;\n }\n const tenantScoped = registered?.tenantScopedConfig;\n const manifestEntry = registered?.qualifiedName\n ? findManifestEntryByQualifiedName(registered.qualifiedName)\n : undefined;\n\n if (!tenantScoped) {\n skipped.push({\n className: metadata.name,\n qualifiedName: registered?.qualifiedName,\n reason: 'not tenant-scoped',\n });\n continue;\n }\n\n if (tenantScoped.mode !== 'required') {\n skipped.push({\n className: metadata.name,\n qualifiedName: registered?.qualifiedName,\n reason: `tenant mode '${tenantScoped.mode}' is not supported for automatic Postgres RLS generation`,\n });\n continue;\n }\n\n const rawTableName =\n registered?.schema?.tableName ?? manifestEntry?.schema?.tableName;\n if (!rawTableName) {\n skipped.push({\n className: metadata.name,\n qualifiedName: registered?.qualifiedName,\n reason: 'no schema table name available',\n });\n continue;\n }\n\n const parsedTable = parseTableReference({\n schemaName: scope?.schemaName,\n tableName: rawTableName,\n });\n if (scope && parsedTable.schemaName !== scope.schemaName) {\n skipped.push({\n className: metadata.name,\n qualifiedName: registered?.qualifiedName,\n reason: `table '${rawTableName}' is qualified with another schema than '${scope.schemaName}'`,\n });\n continue;\n }\n const tableKey = `${parsedTable.schemaName}.${parsedTable.tableName}`;\n const objectConfig = manifestEntry?.decoratorConfig ?? metadata.config;\n const rawCollection = (objectConfig as { collection?: unknown } | undefined)\n ?.collection;\n const configuredCollection =\n typeof rawCollection === 'string' && rawCollection.length > 0\n ? rawCollection\n : undefined;\n const collection =\n configuredCollection ??\n manifestEntry?.collection ??\n `${toSnakeCase(metadata.name)}s`;\n\n const entries = autoCandidates.get(tableKey) ?? [];\n entries.push({\n className: metadata.name,\n collection,\n qualifiedName: registered?.qualifiedName,\n schemaName: parsedTable.schemaName,\n tableName: parsedTable.tableName,\n tenantField: toSnakeCase(tenantScoped.field),\n permissions: scope?.permissionsFor?.({\n className: metadata.name,\n collection,\n tableName: parsedTable.tableName,\n }),\n });\n autoCandidates.set(tableKey, entries);\n }\n\n for (const [tableKey, entries] of autoCandidates) {\n if (entries.length > 1) {\n for (const entry of entries) {\n skipped.push({\n className: entry.className,\n collection: entry.collection,\n qualifiedName: entry.qualifiedName,\n reason: `table '${tableKey}' is shared by multiple objects, so automatic policy generation was skipped`,\n schemaName: entry.schemaName,\n tableName: entry.tableName,\n });\n }\n continue;\n }\n\n const entry = entries[0];\n const permissionSlugs: Record<PostgresPermissionAction, string[]> = {\n SELECT: entry.permissions?.SELECT ?? [`${entry.collection}.read`],\n INSERT: entry.permissions?.INSERT ?? [`${entry.collection}.create`],\n UPDATE: entry.permissions?.UPDATE ?? [`${entry.collection}.update`],\n DELETE: entry.permissions?.DELETE ?? [`${entry.collection}.delete`],\n };\n for (const action of ['SELECT', 'INSERT', 'UPDATE', 'DELETE'] as const) {\n for (const permission of permissionSlugs[action]) {\n addBindingToTarget(\n candidateTargets,\n {\n action,\n permission,\n schemaName: entry.schemaName,\n tableName: entry.tableName,\n tenantField: entry.tenantField,\n },\n entry,\n );\n }\n }\n }\n\n // A scope names the one schema it speaks for; the deployment's own explicit\n // bindings name tables of its default schema and are not applied to it.\n const explicitBindings: PostgresPermissionBinding[] = [];\n if (!scope) {\n for (const definition of catalog.permissions) {\n for (const binding of definition.postgres?.bindings ?? []) {\n explicitBindings.push(\n normalizePostgresPermissionBinding(binding, definition.slug),\n );\n }\n }\n for (const binding of config.permissions?.postgres?.bindings ?? []) {\n explicitBindings.push(normalizePostgresPermissionBinding(binding));\n }\n }\n\n for (const binding of explicitBindings) {\n addBindingToTarget(candidateTargets, binding);\n }\n\n const statements = [...buildHelperStatements(scope?.schemaName)];\n const targets = Array.from(candidateTargets.values())\n .sort((left, right) =>\n `${left.schemaName}.${left.tableName}`.localeCompare(\n `${right.schemaName}.${right.tableName}`,\n ),\n )\n .map((target) => ({\n actions: Object.fromEntries(\n Array.from(target.actions.entries()).map(([action, permissions]) => [\n action,\n Array.from(permissions).sort(),\n ]),\n ) as Partial<Record<PostgresPermissionAction, string[]>>,\n className: target.className,\n collection: target.collection,\n qualifiedName: target.qualifiedName,\n schemaName: target.schemaName,\n tableName: target.tableName,\n tenantField: target.tenantField,\n }));\n\n for (const target of Array.from(candidateTargets.values())) {\n const qualifiedTable = `${quoteIdent(target.schemaName)}.${quoteIdent(target.tableName)}`;\n statements.push(`ALTER TABLE ${qualifiedTable} ENABLE ROW LEVEL SECURITY`);\n statements.push(`ALTER TABLE ${qualifiedTable} FORCE ROW LEVEL SECURITY`);\n\n const selectPermissions = Array.from(\n target.actions.get('SELECT') ?? [],\n ).sort();\n const insertPermissions = Array.from(\n target.actions.get('INSERT') ?? [],\n ).sort();\n const updatePermissions = Array.from(\n target.actions.get('UPDATE') ?? [],\n ).sort();\n const deletePermissions = Array.from(\n target.actions.get('DELETE') ?? [],\n ).sort();\n\n if (selectPermissions.length > 0) {\n statements.push(...buildSelectPolicySql(target, selectPermissions));\n }\n if (insertPermissions.length > 0) {\n statements.push(...buildInsertPolicySql(target, insertPermissions));\n }\n if (updatePermissions.length > 0) {\n statements.push(...buildUpdatePolicySql(target, updatePermissions));\n }\n if (deletePermissions.length > 0) {\n statements.push(...buildDeletePolicySql(target, deletePermissions));\n }\n }\n\n return {\n bindings: explicitBindings,\n skipped,\n sql: `${statements.join(';\\n')};\\n`,\n statements,\n targets,\n };\n}\n\nexport async function applyPostgresPermissionPolicies(\n options: SmrtClassOptions = {},\n): Promise<GeneratePostgresPermissionSqlResult> {\n const permissions = await PermissionCollection.create(options);\n const databaseOptions = options.db ?? options.persistence;\n if (\n !isProbablyPostgres(databaseOptions, permissions.db as QueryableDatabase)\n ) {\n throw new Error(\n 'applyPostgresPermissionPolicies() requires a Postgres database connection.',\n );\n }\n\n const result = generatePostgresPermissionSql(options);\n for (const statement of result.statements) {\n try {\n await permissions.db.query(statement);\n } catch (error) {\n throw new Error(\n `Failed to apply Postgres permission policy statement:\\n${statement}`,\n {\n cause: error,\n },\n );\n }\n }\n\n return result;\n}\n\n/**\n * Apply the policies of one scoped schema through a handle the caller already\n * holds, so they commit or roll back with the caller's own DDL (an app's\n * tables are created in the same transaction). The scope is required: nothing\n * here falls back to `public`. The handle must be a PostgreSQL one.\n */\nexport async function applyScopedPostgresPermissionPolicies(\n db: { query: (sql: string, ...params: unknown[]) => Promise<unknown> },\n scope: PostgresPolicyScope,\n options: SmrtClassOptions = {},\n): Promise<GeneratePostgresPermissionSqlResult> {\n const result = generatePostgresPermissionSql(options, scope);\n for (const statement of result.statements) {\n try {\n await db.query(statement);\n } catch (error) {\n throw new Error(\n `Failed to apply Postgres permission policy statement:\\n${statement}`,\n { cause: error },\n );\n }\n }\n return result;\n}\n"],"mappings":";;;;AA6FA,SAAS,YAAY,OAAuB;CAC1C,OAAO,MACJ,QAAQ,sBAAsB,OAAO,CAAA,CACrC,QAAQ,WAAW,GAAG,CAAA,C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