@open-mercato/core 0.6.8-develop.7013.1.48f7adca80 → 0.6.8-develop.7016.1.4ed7b1e49d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/api/keys/route.js +1 -1
  3. package/dist/modules/api_keys/api/keys/route.js.map +2 -2
  4. package/dist/modules/api_keys/di.js +9 -0
  5. package/dist/modules/api_keys/di.js.map +7 -0
  6. package/dist/modules/api_keys/services/principalService.js +31 -0
  7. package/dist/modules/api_keys/services/principalService.js.map +7 -0
  8. package/dist/modules/attachments/di.js +11 -1
  9. package/dist/modules/attachments/di.js.map +2 -2
  10. package/dist/modules/attachments/index.js.map +1 -1
  11. package/dist/modules/attachments/lib/attachment-service.js +313 -0
  12. package/dist/modules/attachments/lib/attachment-service.js.map +7 -0
  13. package/dist/modules/attachments/lib/scoped-upload-service.js +15 -2
  14. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  15. package/dist/modules/attachments/lib/upload-limits.js +6 -2
  16. package/dist/modules/attachments/lib/upload-limits.js.map +2 -2
  17. package/dist/modules/auth/data/entities.js.map +2 -2
  18. package/dist/modules/auth/di.js +35 -9
  19. package/dist/modules/auth/di.js.map +2 -2
  20. package/dist/modules/auth/services/principalService.js +200 -0
  21. package/dist/modules/auth/services/principalService.js.map +7 -0
  22. package/dist/modules/auth/services/rbacService.js +67 -24
  23. package/dist/modules/auth/services/rbacService.js.map +3 -3
  24. package/dist/modules/auth/services/roleOrganizationScope.js +41 -0
  25. package/dist/modules/auth/services/roleOrganizationScope.js.map +7 -0
  26. package/dist/modules/customers/api/companies/[id]/people/route.js +19 -63
  27. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  28. package/dist/modules/customers/api/companies/[id]/route.js +9 -85
  29. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  30. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +4 -3
  31. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  32. package/dist/modules/customers/commands/personCompanyLinks.js +131 -2
  33. package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
  34. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +3 -1
  35. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  36. package/dist/modules/customers/components/detail/PersonCompaniesSection.js +3 -1
  37. package/dist/modules/customers/components/detail/PersonCompaniesSection.js.map +2 -2
  38. package/dist/modules/customers/data/validators.js +10 -2
  39. package/dist/modules/customers/data/validators.js.map +2 -2
  40. package/dist/modules/customers/events.js +5 -0
  41. package/dist/modules/customers/events.js.map +2 -2
  42. package/dist/modules/customers/lib/personCompanies.js +100 -2
  43. package/dist/modules/customers/lib/personCompanies.js.map +2 -2
  44. package/dist/modules/directory/di.js +9 -0
  45. package/dist/modules/directory/di.js.map +2 -2
  46. package/dist/modules/directory/services/organizationHierarchyService.js +29 -0
  47. package/dist/modules/directory/services/organizationHierarchyService.js.map +7 -0
  48. package/dist/modules/directory/services/organizationScopeService.js +56 -0
  49. package/dist/modules/directory/services/organizationScopeService.js.map +7 -0
  50. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  51. package/dist/modules/warranty_claims/api/portal/attachments/route.js +2 -2
  52. package/dist/modules/warranty_claims/api/portal/attachments/route.js.map +2 -2
  53. package/dist/modules/workflows/lib/activity-executor.js +4 -0
  54. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  55. package/package.json +7 -7
  56. package/src/modules/api_keys/api/keys/route.ts +3 -1
  57. package/src/modules/api_keys/di.ts +7 -0
  58. package/src/modules/api_keys/services/principalService.ts +33 -0
  59. package/src/modules/attachments/AGENTS.md +15 -0
  60. package/src/modules/attachments/di.ts +16 -0
  61. package/src/modules/attachments/i18n/de.json +5 -0
  62. package/src/modules/attachments/i18n/en.json +5 -0
  63. package/src/modules/attachments/i18n/es.json +5 -0
  64. package/src/modules/attachments/i18n/ko.json +5 -0
  65. package/src/modules/attachments/i18n/pl.json +5 -0
  66. package/src/modules/attachments/index.ts +10 -0
  67. package/src/modules/attachments/lib/attachment-service.ts +468 -0
  68. package/src/modules/attachments/lib/scoped-upload-service.ts +46 -0
  69. package/src/modules/attachments/lib/upload-limits.ts +6 -2
  70. package/src/modules/auth/data/entities.ts +4 -1
  71. package/src/modules/auth/di.ts +46 -16
  72. package/src/modules/auth/services/principalService.ts +266 -0
  73. package/src/modules/auth/services/rbacService.ts +110 -24
  74. package/src/modules/auth/services/roleOrganizationScope.ts +70 -0
  75. package/src/modules/customers/api/companies/[id]/people/route.ts +20 -72
  76. package/src/modules/customers/api/companies/[id]/route.ts +11 -97
  77. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +12 -4
  78. package/src/modules/customers/commands/personCompanyLinks.ts +224 -8
  79. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +8 -1
  80. package/src/modules/customers/components/detail/PersonCompaniesSection.tsx +8 -1
  81. package/src/modules/customers/data/validators.ts +18 -3
  82. package/src/modules/customers/events.ts +5 -0
  83. package/src/modules/customers/lib/personCompanies.ts +136 -1
  84. package/src/modules/directory/di.ts +14 -2
  85. package/src/modules/directory/services/organizationHierarchyService.ts +34 -0
  86. package/src/modules/directory/services/organizationScopeService.ts +85 -0
  87. package/src/modules/directory/utils/organizationScope.ts +4 -15
  88. package/src/modules/warranty_claims/api/portal/attachments/route.ts +2 -2
  89. package/src/modules/workflows/lib/activity-executor.ts +9 -0
@@ -1,4 +1,4 @@
1
- [build:core] found 4315 entry points
1
+ [build:core] found 4322 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 218 entry points
4
4
  [build:core:generated] built successfully
@@ -249,7 +249,7 @@ const crud = makeCrudRoute({
249
249
  scopedCtx.__apiKeyRoles = roleEntities;
250
250
  scopedCtx.__apiKeyRoleIds = roleIds;
251
251
  const allowedIds = ctx.organizationScope?.allowedIds ?? null;
252
- const organizationId = input.organizationId ?? ctx.selectedOrganizationId ?? auth.orgId ?? null;
252
+ const organizationId = Object.prototype.hasOwnProperty.call(input, "organizationId") ? input.organizationId ?? null : ctx.selectedOrganizationId ?? auth.orgId ?? null;
253
253
  const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx);
254
254
  if (!isOrganizationAccessAllowed({
255
255
  isSuperAdmin,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/api_keys/api/keys/route.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { ApiKey } from '../../data/entities'\nimport { createApiKeySchema } from '../../data/validators'\nimport { generateApiKeySecret, hashApiKey } from '../../services/apiKeyService'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { enforceTenantSelection, resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { assertActorCanGrantRoles } from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport { isOrganizationAccessAllowed } from '@open-mercato/shared/lib/auth/organizationAccess'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\ntype ApiKeyCrudCtx = CrudCtx & {\n __apiKeySecret?: { secret: string; prefix: string }\n __apiKeyHash?: string\n __apiKeyRoleIds?: string[]\n __apiKeyRoles?: Role[]\n __apiKeyOrganizationId?: string | null\n __apiKeyTenantId?: string | null\n}\n\ntype ApiKeyEntityWithMeta = ApiKey & {\n __apiKeySecret?: string\n __apiKeyRoles?: Role[]\n}\n\nconst listQuerySchema = z.object({\n page: z.string().optional(),\n pageSize: z.string().optional(),\n search: z.string().optional(),\n})\n\nconst apiKeyRoleSchema = z.object({\n id: z.string().describe('Role identifier or alias assigned to the key'),\n name: z.string().nullable().describe('Display name of the mapped role, if available'),\n})\n\nconst apiKeyListItemSchema = z.object({\n id: z.string().describe('API key identifier'),\n name: z.string().describe('Friendly label used to identify the key'),\n description: z.string().nullable().describe('Optional free-form description'),\n keyPrefix: z.string().describe('Public prefix exposed to clients'),\n organizationId: z.string().uuid().nullable().describe('Organization scope of the key'),\n organizationName: z.string().nullable().describe('Resolved organization display name'),\n createdAt: z.string().describe('Creation timestamp (ISO 8601)'),\n lastUsedAt: z.string().nullable().describe('Last time the key was observed in use (ISO 8601)'),\n expiresAt: z.string().nullable().describe('When the key expires (ISO 8601)'),\n roles: z.array(apiKeyRoleSchema).describe('Effective roles applied when this key authenticates'),\n})\n\nconst apiKeyCollectionResponseSchema = z.object({\n items: z.array(apiKeyListItemSchema),\n total: z.number().int().nonnegative(),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n totalPages: z.number().int().nonnegative(),\n})\n\nconst apiKeyCreateResponseSchema = z.object({\n id: z.string().describe('Newly created API key identifier'),\n name: z.string(),\n keyPrefix: z.string(),\n secret: z.string().describe('Full API key value. Shown once for secure persistence.').optional(),\n tenantId: z.string().uuid().nullable(),\n organizationId: z.string().uuid().nullable(),\n roles: z.array(apiKeyRoleSchema),\n})\n\nconst deleteResponseSchema = z.object({\n success: z.literal(true),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nfunction json(payload: unknown, init: ResponseInit = { status: 200 }) {\n return new Response(JSON.stringify(payload), {\n ...init,\n headers: { 'content-type': 'application/json', ...(init.headers || {}) },\n })\n}\n\nconst crud = makeCrudRoute<\n z.infer<typeof createApiKeySchema>,\n never,\n z.infer<typeof listQuerySchema>\n>({\n metadata: {\n GET: { requireAuth: true, requireFeatures: ['api_keys.view'] },\n POST: { requireAuth: true, requireFeatures: ['api_keys.create'] },\n DELETE: { requireAuth: true, requireFeatures: ['api_keys.delete'] },\n },\n orm: { entity: ApiKey, orgField: null },\n list: { schema: listQuerySchema },\n create: {\n schema: createApiKeySchema,\n mapToEntity: (input, ctx) => {\n const scopedCtx = ctx as ApiKeyCrudCtx\n const secretData = scopedCtx.__apiKeySecret\n const keyHash = scopedCtx.__apiKeyHash\n if (!secretData || !keyHash) throw new Error('API key secret not prepared')\n const roleIds = Array.isArray(scopedCtx.__apiKeyRoleIds) ? scopedCtx.__apiKeyRoleIds : []\n const organizationId = scopedCtx.__apiKeyOrganizationId ?? null\n const tenantId = scopedCtx.__apiKeyTenantId ?? null\n return {\n name: input.name,\n description: input.description ?? null,\n tenantId,\n organizationId,\n keyHash,\n keyPrefix: secretData.prefix,\n rolesJson: roleIds,\n createdBy: ctx.auth?.sub ?? null,\n expiresAt: input.expiresAt ?? null,\n }\n },\n response: (entity) => {\n const meta = entity as ApiKeyEntityWithMeta\n const secret = meta.__apiKeySecret\n const roles = meta.__apiKeyRoles\n return {\n id: String(entity.id),\n name: entity.name,\n keyPrefix: entity.keyPrefix,\n secret,\n tenantId: entity.tenantId ?? null,\n organizationId: entity.organizationId ?? null,\n roles: Array.isArray(roles)\n ? roles.map((role) => ({ id: String(role.id), name: role.name ?? null }))\n : (Array.isArray(entity.rolesJson) ? entity.rolesJson.map((id: string) => ({ id, name: null })) : []),\n }\n },\n },\n del: { idFrom: 'query' },\n hooks: {\n beforeList: async (query, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n const page = Math.max(parseInt(query.page ?? '1', 10) || 1, 1)\n const pageSize = Math.min(Math.max(parseInt(query.pageSize ?? '20', 10) || 20, 1), 200)\n const search = (query.search ?? '').trim().toLowerCase()\n\n const organizationIds = Array.isArray(ctx.organizationIds) ? ctx.organizationIds : null\n if (organizationIds && organizationIds.length === 0) {\n throw json({ items: [], total: 0, page, pageSize, totalPages: 0 })\n }\n\n const em = (ctx.container.resolve('em') as EntityManager)\n const qb = em.createQueryBuilder(ApiKey, 'k')\n qb.where({ deletedAt: null })\n qb.andWhere({ tenantId: auth.tenantId })\n if (organizationIds && organizationIds.length > 0) {\n qb.andWhere({ organizationId: { $in: organizationIds } })\n } else if (auth.orgId) {\n qb.andWhere({ organizationId: auth.orgId })\n }\n if (search) {\n const pattern = `%${escapeLikePattern(search)}%`\n qb.andWhere({\n $or: [\n { name: { $ilike: pattern } },\n { keyPrefix: { $ilike: pattern } },\n ],\n })\n }\n qb.orderBy({ createdAt: 'desc' })\n qb.limit(pageSize).offset((page - 1) * pageSize)\n const [items, total] = await qb.getResultAndCount()\n\n if (!items.length) {\n throw json({ items: [], total, page, pageSize, totalPages: Math.ceil(total / pageSize) })\n }\n\n const roleIdSet = new Set<string>()\n const orgIdSet = new Set<string>()\n for (const item of items) {\n if (Array.isArray(item.rolesJson)) {\n for (const roleId of item.rolesJson) roleIdSet.add(String(roleId))\n }\n if (item.organizationId) orgIdSet.add(String(item.organizationId))\n }\n\n const roleIdArray = Array.from(roleIdSet)\n const organizationIdArray = Array.from(orgIdSet)\n const roleFilter: FilterQuery<Role> = { id: { $in: roleIdArray } }\n const organizationFilter: FilterQuery<Organization> = { id: { $in: organizationIdArray } }\n const [roles, organizations] = await Promise.all([\n roleIdArray.length ? em.find(Role, roleFilter) : [],\n organizationIdArray.length ? em.find(Organization, organizationFilter) : [],\n ])\n const roleMap = new Map(roles.map((role) => [String(role.id), role.name ?? null]))\n const orgMap = new Map(organizations.map((org) => [String(org.id), org.name ?? null]))\n\n const payload = {\n items: items.map((item) => ({\n id: item.id,\n name: item.name,\n description: item.description ?? null,\n keyPrefix: item.keyPrefix,\n organizationId: item.organizationId ?? null,\n organizationName: item.organizationId ? orgMap.get(String(item.organizationId)) ?? null : null,\n createdAt: item.createdAt,\n lastUsedAt: item.lastUsedAt ?? null,\n expiresAt: item.expiresAt ?? null,\n roles: Array.isArray(item.rolesJson)\n ? item.rolesJson.map((id) => ({ id, name: roleMap.get(String(id)) ?? null }))\n : [],\n })),\n total,\n page,\n pageSize,\n totalPages: Math.ceil(total / pageSize),\n }\n\n throw json(payload)\n },\n beforeCreate: async (input, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n\n const requestedTenant = Object.prototype.hasOwnProperty.call(input, 'tenantId') ? input.tenantId : auth.tenantId\n const scopedCtx = ctx as ApiKeyCrudCtx\n const targetTenantId = await enforceTenantSelection(scopedCtx, requestedTenant)\n scopedCtx.__apiKeyTenantId = targetTenantId\n\n const secretData = generateApiKeySecret()\n scopedCtx.__apiKeySecret = secretData\n scopedCtx.__apiKeyHash = await hashApiKey(secretData.secret)\n\n const em = (ctx.container.resolve('em') as EntityManager)\n const roleTokens = Array.isArray(input.roles) ? input.roles.filter((value) => typeof value === 'string' && value.trim().length > 0) : []\n const roleEntities: Role[] = []\n const roleIds: string[] = []\n for (const token of roleTokens) {\n const value = token.trim()\n const rawTenantId = targetTenantId ?? auth.tenantId ?? null\n const effectiveTenantId = typeof rawTenantId === 'string' && rawTenantId.trim().length > 0 ? rawTenantId.trim() : null\n const normalizedEffectiveTenantId = effectiveTenantId ? effectiveTenantId.toLowerCase() : null\n let role: Role | null = null\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) {\n role = await em.findOne(Role, { id: value, deletedAt: null })\n }\n if (!role) {\n const nameFilter: FilterQuery<Role> = { name: value, deletedAt: null }\n if (normalizedEffectiveTenantId) {\n nameFilter.$or = [\n { tenantId: effectiveTenantId },\n { tenantId: null },\n ]\n } else {\n nameFilter.tenantId = null\n }\n const candidates = await em.find(Role, nameFilter, { limit: 5 })\n if (normalizedEffectiveTenantId) {\n role =\n candidates.find((candidate) => {\n if (!candidate.tenantId) return false\n return String(candidate.tenantId).toLowerCase() === normalizedEffectiveTenantId\n }) ??\n candidates.find((candidate) => candidate.tenantId === null) ??\n null\n } else {\n role = candidates.find((candidate) => candidate.tenantId === null) ?? null\n }\n if (!role) {\n role = candidates[0] ?? null\n }\n }\n if (!role) {\n throw json({ error: translate('api_keys.errors.roleNotFound', `Role ${value} not found`, { identifier: value }) }, { status: 400 })\n }\n const roleTenantId = role.tenantId ? String(role.tenantId) : null\n const normalizedRoleTenantId = roleTenantId ? roleTenantId.toLowerCase() : null\n if (normalizedRoleTenantId && normalizedEffectiveTenantId && normalizedRoleTenantId !== normalizedEffectiveTenantId) {\n throw json({ error: translate('api_keys.errors.roleWrongTenant', `Role ${role.name} belongs to another tenant`, { role: role.name ?? value }) }, { status: 400 })\n }\n roleEntities.push(role)\n roleIds.push(String(role.id))\n }\n await assertActorCanGrantRoles({\n em,\n rbacService: ctx.container.resolve('rbacService') as RbacService,\n actorUserId: auth.sub,\n tenantId: targetTenantId,\n organizationId: auth.orgId ?? null,\n roles: roleEntities,\n })\n scopedCtx.__apiKeyRoles = roleEntities\n scopedCtx.__apiKeyRoleIds = roleIds\n\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n const organizationId = input.organizationId ?? ctx.selectedOrganizationId ?? auth.orgId ?? null\n const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx)\n if (\n !isOrganizationAccessAllowed({\n isSuperAdmin,\n allowedOrganizationIds: allowedIds,\n targetOrganizationId: organizationId,\n })\n ) {\n throw json({ error: translate('api_keys.errors.organizationOutOfScope', 'Organization out of scope') }, { status: 403 })\n }\n scopedCtx.__apiKeyOrganizationId = organizationId ?? null\n\n return { ...input, organizationId }\n },\n afterCreate: async (entity, ctx) => {\n const scopedCtx = ctx as ApiKeyCrudCtx\n const secretData = scopedCtx.__apiKeySecret\n const roles = scopedCtx.__apiKeyRoles\n if (secretData) (entity as ApiKeyEntityWithMeta).__apiKeySecret = secretData.secret\n if (roles) (entity as ApiKeyEntityWithMeta).__apiKeyRoles = roles\n try {\n const rbac = (ctx.container.resolve('rbacService') as RbacService)\n await rbac.invalidateUserCache(`api_key:${entity.id}`)\n } catch {}\n },\n beforeDelete: async (id, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n const em = (ctx.container.resolve('em') as EntityManager)\n const scopedCtx = ctx as ApiKeyCrudCtx\n const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx)\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n const recordFilter: FilterQuery<ApiKey> = {\n id,\n tenantId: auth.tenantId,\n deletedAt: null,\n }\n if (!isSuperAdmin && Array.isArray(allowedIds)) {\n recordFilter.organizationId = { $in: allowedIds }\n }\n const record = await findOneWithDecryption(\n em,\n ApiKey,\n recordFilter,\n undefined,\n { tenantId: auth.tenantId, organizationId: null },\n )\n if (\n !record ||\n record.tenantId !== auth.tenantId ||\n !isOrganizationAccessAllowed({\n isSuperAdmin,\n allowedOrganizationIds: allowedIds,\n targetOrganizationId: record.organizationId ?? null,\n })\n ) {\n throw json({ error: translate('api_keys.errors.notFound', 'Not found') }, { status: 404 })\n }\n scopedCtx.__apiKeyOrganizationId = record.organizationId ?? null\n },\n afterDelete: async (id, ctx) => {\n try {\n const rbac = (ctx.container.resolve('rbacService') as RbacService)\n await rbac.invalidateUserCache(`api_key:${id}`)\n } catch {}\n },\n },\n})\n\nexport const metadata = crud.metadata\nexport const GET = crud.GET\nexport const POST = crud.POST\nexport const DELETE = crud.DELETE\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage API keys',\n description:\n 'Provides list, creation, and deletion capabilities for API keys scoped to the authenticated tenant and organization.',\n methods: {\n GET: {\n summary: 'List API keys',\n description:\n 'Returns paginated API keys visible to the current user, including per-key role assignments and organization context.',\n query: listQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Collection of API keys',\n schema: apiKeyCollectionResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Tenant context missing', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Forbidden by organization scope', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Create API key',\n description:\n 'Creates a new API key, returning the one-time secret value together with the generated key prefix and scope details.',\n requestBody: {\n contentType: 'application/json',\n schema: createApiKeySchema,\n description: 'API key definition including optional scope and role assignments.',\n },\n responses: [\n {\n status: 201,\n description: 'API key created successfully',\n schema: apiKeyCreateResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or missing tenant context', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Organization outside allowed scope', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete API key',\n description:\n 'Removes an API key by identifier. The key must belong to the current tenant and fall within the requester organization scope.',\n query: z.object({\n id: z.string().uuid().describe('API key identifier to delete'),\n }),\n responses: [\n { status: 200, description: 'Key deleted successfully', schema: deleteResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Missing or invalid identifier', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Organization outside allowed scope', schema: errorSchema },\n { status: 404, description: 'Key not found within scope', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,qBAAqB;AAG9B,SAAS,YAAY;AACrB,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,0BAA0B;AACnC,SAAS,sBAAsB,kBAAkB;AACjD,SAAS,2BAA2B;AACpC,SAAS,wBAAwB,2BAA2B;AAC5D,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AACzC,SAAS,mCAAmC;AAC5C,SAAS,6BAA6B;AAgBtC,MAAM,kBAAkB,EAAE,OAAO;AAAA,EAC/B,M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AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,qBAAqB;AAAA,MACvF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,YAAY;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,QACtF,EAAE,QAAQ,KAAK,aAAa,8BAA8B,QAAQ,YAAY;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { ApiKey } from '../../data/entities'\nimport { createApiKeySchema } from '../../data/validators'\nimport { generateApiKeySecret, hashApiKey } from '../../services/apiKeyService'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { enforceTenantSelection, resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { assertActorCanGrantRoles } from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport { isOrganizationAccessAllowed } from '@open-mercato/shared/lib/auth/organizationAccess'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\ntype ApiKeyCrudCtx = CrudCtx & {\n __apiKeySecret?: { secret: string; prefix: string }\n __apiKeyHash?: string\n __apiKeyRoleIds?: string[]\n __apiKeyRoles?: Role[]\n __apiKeyOrganizationId?: string | null\n __apiKeyTenantId?: string | null\n}\n\ntype ApiKeyEntityWithMeta = ApiKey & {\n __apiKeySecret?: string\n __apiKeyRoles?: Role[]\n}\n\nconst listQuerySchema = z.object({\n page: z.string().optional(),\n pageSize: z.string().optional(),\n search: z.string().optional(),\n})\n\nconst apiKeyRoleSchema = z.object({\n id: z.string().describe('Role identifier or alias assigned to the key'),\n name: z.string().nullable().describe('Display name of the mapped role, if available'),\n})\n\nconst apiKeyListItemSchema = z.object({\n id: z.string().describe('API key identifier'),\n name: z.string().describe('Friendly label used to identify the key'),\n description: z.string().nullable().describe('Optional free-form description'),\n keyPrefix: z.string().describe('Public prefix exposed to clients'),\n organizationId: z.string().uuid().nullable().describe('Organization scope of the key'),\n organizationName: z.string().nullable().describe('Resolved organization display name'),\n createdAt: z.string().describe('Creation timestamp (ISO 8601)'),\n lastUsedAt: z.string().nullable().describe('Last time the key was observed in use (ISO 8601)'),\n expiresAt: z.string().nullable().describe('When the key expires (ISO 8601)'),\n roles: z.array(apiKeyRoleSchema).describe('Effective roles applied when this key authenticates'),\n})\n\nconst apiKeyCollectionResponseSchema = z.object({\n items: z.array(apiKeyListItemSchema),\n total: z.number().int().nonnegative(),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n totalPages: z.number().int().nonnegative(),\n})\n\nconst apiKeyCreateResponseSchema = z.object({\n id: z.string().describe('Newly created API key identifier'),\n name: z.string(),\n keyPrefix: z.string(),\n secret: z.string().describe('Full API key value. Shown once for secure persistence.').optional(),\n tenantId: z.string().uuid().nullable(),\n organizationId: z.string().uuid().nullable(),\n roles: z.array(apiKeyRoleSchema),\n})\n\nconst deleteResponseSchema = z.object({\n success: z.literal(true),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nfunction json(payload: unknown, init: ResponseInit = { status: 200 }) {\n return new Response(JSON.stringify(payload), {\n ...init,\n headers: { 'content-type': 'application/json', ...(init.headers || {}) },\n })\n}\n\nconst crud = makeCrudRoute<\n z.infer<typeof createApiKeySchema>,\n never,\n z.infer<typeof listQuerySchema>\n>({\n metadata: {\n GET: { requireAuth: true, requireFeatures: ['api_keys.view'] },\n POST: { requireAuth: true, requireFeatures: ['api_keys.create'] },\n DELETE: { requireAuth: true, requireFeatures: ['api_keys.delete'] },\n },\n orm: { entity: ApiKey, orgField: null },\n list: { schema: listQuerySchema },\n create: {\n schema: createApiKeySchema,\n mapToEntity: (input, ctx) => {\n const scopedCtx = ctx as ApiKeyCrudCtx\n const secretData = scopedCtx.__apiKeySecret\n const keyHash = scopedCtx.__apiKeyHash\n if (!secretData || !keyHash) throw new Error('API key secret not prepared')\n const roleIds = Array.isArray(scopedCtx.__apiKeyRoleIds) ? scopedCtx.__apiKeyRoleIds : []\n const organizationId = scopedCtx.__apiKeyOrganizationId ?? null\n const tenantId = scopedCtx.__apiKeyTenantId ?? null\n return {\n name: input.name,\n description: input.description ?? null,\n tenantId,\n organizationId,\n keyHash,\n keyPrefix: secretData.prefix,\n rolesJson: roleIds,\n createdBy: ctx.auth?.sub ?? null,\n expiresAt: input.expiresAt ?? null,\n }\n },\n response: (entity) => {\n const meta = entity as ApiKeyEntityWithMeta\n const secret = meta.__apiKeySecret\n const roles = meta.__apiKeyRoles\n return {\n id: String(entity.id),\n name: entity.name,\n keyPrefix: entity.keyPrefix,\n secret,\n tenantId: entity.tenantId ?? null,\n organizationId: entity.organizationId ?? null,\n roles: Array.isArray(roles)\n ? roles.map((role) => ({ id: String(role.id), name: role.name ?? null }))\n : (Array.isArray(entity.rolesJson) ? entity.rolesJson.map((id: string) => ({ id, name: null })) : []),\n }\n },\n },\n del: { idFrom: 'query' },\n hooks: {\n beforeList: async (query, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n const page = Math.max(parseInt(query.page ?? '1', 10) || 1, 1)\n const pageSize = Math.min(Math.max(parseInt(query.pageSize ?? '20', 10) || 20, 1), 200)\n const search = (query.search ?? '').trim().toLowerCase()\n\n const organizationIds = Array.isArray(ctx.organizationIds) ? ctx.organizationIds : null\n if (organizationIds && organizationIds.length === 0) {\n throw json({ items: [], total: 0, page, pageSize, totalPages: 0 })\n }\n\n const em = (ctx.container.resolve('em') as EntityManager)\n const qb = em.createQueryBuilder(ApiKey, 'k')\n qb.where({ deletedAt: null })\n qb.andWhere({ tenantId: auth.tenantId })\n if (organizationIds && organizationIds.length > 0) {\n qb.andWhere({ organizationId: { $in: organizationIds } })\n } else if (auth.orgId) {\n qb.andWhere({ organizationId: auth.orgId })\n }\n if (search) {\n const pattern = `%${escapeLikePattern(search)}%`\n qb.andWhere({\n $or: [\n { name: { $ilike: pattern } },\n { keyPrefix: { $ilike: pattern } },\n ],\n })\n }\n qb.orderBy({ createdAt: 'desc' })\n qb.limit(pageSize).offset((page - 1) * pageSize)\n const [items, total] = await qb.getResultAndCount()\n\n if (!items.length) {\n throw json({ items: [], total, page, pageSize, totalPages: Math.ceil(total / pageSize) })\n }\n\n const roleIdSet = new Set<string>()\n const orgIdSet = new Set<string>()\n for (const item of items) {\n if (Array.isArray(item.rolesJson)) {\n for (const roleId of item.rolesJson) roleIdSet.add(String(roleId))\n }\n if (item.organizationId) orgIdSet.add(String(item.organizationId))\n }\n\n const roleIdArray = Array.from(roleIdSet)\n const organizationIdArray = Array.from(orgIdSet)\n const roleFilter: FilterQuery<Role> = { id: { $in: roleIdArray } }\n const organizationFilter: FilterQuery<Organization> = { id: { $in: organizationIdArray } }\n const [roles, organizations] = await Promise.all([\n roleIdArray.length ? em.find(Role, roleFilter) : [],\n organizationIdArray.length ? em.find(Organization, organizationFilter) : [],\n ])\n const roleMap = new Map(roles.map((role) => [String(role.id), role.name ?? null]))\n const orgMap = new Map(organizations.map((org) => [String(org.id), org.name ?? null]))\n\n const payload = {\n items: items.map((item) => ({\n id: item.id,\n name: item.name,\n description: item.description ?? null,\n keyPrefix: item.keyPrefix,\n organizationId: item.organizationId ?? null,\n organizationName: item.organizationId ? orgMap.get(String(item.organizationId)) ?? null : null,\n createdAt: item.createdAt,\n lastUsedAt: item.lastUsedAt ?? null,\n expiresAt: item.expiresAt ?? null,\n roles: Array.isArray(item.rolesJson)\n ? item.rolesJson.map((id) => ({ id, name: roleMap.get(String(id)) ?? null }))\n : [],\n })),\n total,\n page,\n pageSize,\n totalPages: Math.ceil(total / pageSize),\n }\n\n throw json(payload)\n },\n beforeCreate: async (input, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n\n const requestedTenant = Object.prototype.hasOwnProperty.call(input, 'tenantId') ? input.tenantId : auth.tenantId\n const scopedCtx = ctx as ApiKeyCrudCtx\n const targetTenantId = await enforceTenantSelection(scopedCtx, requestedTenant)\n scopedCtx.__apiKeyTenantId = targetTenantId\n\n const secretData = generateApiKeySecret()\n scopedCtx.__apiKeySecret = secretData\n scopedCtx.__apiKeyHash = await hashApiKey(secretData.secret)\n\n const em = (ctx.container.resolve('em') as EntityManager)\n const roleTokens = Array.isArray(input.roles) ? input.roles.filter((value) => typeof value === 'string' && value.trim().length > 0) : []\n const roleEntities: Role[] = []\n const roleIds: string[] = []\n for (const token of roleTokens) {\n const value = token.trim()\n const rawTenantId = targetTenantId ?? auth.tenantId ?? null\n const effectiveTenantId = typeof rawTenantId === 'string' && rawTenantId.trim().length > 0 ? rawTenantId.trim() : null\n const normalizedEffectiveTenantId = effectiveTenantId ? effectiveTenantId.toLowerCase() : null\n let role: Role | null = null\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) {\n role = await em.findOne(Role, { id: value, deletedAt: null })\n }\n if (!role) {\n const nameFilter: FilterQuery<Role> = { name: value, deletedAt: null }\n if (normalizedEffectiveTenantId) {\n nameFilter.$or = [\n { tenantId: effectiveTenantId },\n { tenantId: null },\n ]\n } else {\n nameFilter.tenantId = null\n }\n const candidates = await em.find(Role, nameFilter, { limit: 5 })\n if (normalizedEffectiveTenantId) {\n role =\n candidates.find((candidate) => {\n if (!candidate.tenantId) return false\n return String(candidate.tenantId).toLowerCase() === normalizedEffectiveTenantId\n }) ??\n candidates.find((candidate) => candidate.tenantId === null) ??\n null\n } else {\n role = candidates.find((candidate) => candidate.tenantId === null) ?? null\n }\n if (!role) {\n role = candidates[0] ?? null\n }\n }\n if (!role) {\n throw json({ error: translate('api_keys.errors.roleNotFound', `Role ${value} not found`, { identifier: value }) }, { status: 400 })\n }\n const roleTenantId = role.tenantId ? String(role.tenantId) : null\n const normalizedRoleTenantId = roleTenantId ? roleTenantId.toLowerCase() : null\n if (normalizedRoleTenantId && normalizedEffectiveTenantId && normalizedRoleTenantId !== normalizedEffectiveTenantId) {\n throw json({ error: translate('api_keys.errors.roleWrongTenant', `Role ${role.name} belongs to another tenant`, { role: role.name ?? value }) }, { status: 400 })\n }\n roleEntities.push(role)\n roleIds.push(String(role.id))\n }\n await assertActorCanGrantRoles({\n em,\n rbacService: ctx.container.resolve('rbacService') as RbacService,\n actorUserId: auth.sub,\n tenantId: targetTenantId,\n organizationId: auth.orgId ?? null,\n roles: roleEntities,\n })\n scopedCtx.__apiKeyRoles = roleEntities\n scopedCtx.__apiKeyRoleIds = roleIds\n\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n const organizationId = Object.prototype.hasOwnProperty.call(input, 'organizationId')\n ? input.organizationId ?? null\n : ctx.selectedOrganizationId ?? auth.orgId ?? null\n const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx)\n if (\n !isOrganizationAccessAllowed({\n isSuperAdmin,\n allowedOrganizationIds: allowedIds,\n targetOrganizationId: organizationId,\n })\n ) {\n throw json({ error: translate('api_keys.errors.organizationOutOfScope', 'Organization out of scope') }, { status: 403 })\n }\n scopedCtx.__apiKeyOrganizationId = organizationId ?? null\n\n return { ...input, organizationId }\n },\n afterCreate: async (entity, ctx) => {\n const scopedCtx = ctx as ApiKeyCrudCtx\n const secretData = scopedCtx.__apiKeySecret\n const roles = scopedCtx.__apiKeyRoles\n if (secretData) (entity as ApiKeyEntityWithMeta).__apiKeySecret = secretData.secret\n if (roles) (entity as ApiKeyEntityWithMeta).__apiKeyRoles = roles\n try {\n const rbac = (ctx.container.resolve('rbacService') as RbacService)\n await rbac.invalidateUserCache(`api_key:${entity.id}`)\n } catch {}\n },\n beforeDelete: async (id, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n const em = (ctx.container.resolve('em') as EntityManager)\n const scopedCtx = ctx as ApiKeyCrudCtx\n const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx)\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n const recordFilter: FilterQuery<ApiKey> = {\n id,\n tenantId: auth.tenantId,\n deletedAt: null,\n }\n if (!isSuperAdmin && Array.isArray(allowedIds)) {\n recordFilter.organizationId = { $in: allowedIds }\n }\n const record = await findOneWithDecryption(\n em,\n ApiKey,\n recordFilter,\n undefined,\n { tenantId: auth.tenantId, organizationId: null },\n )\n if (\n !record ||\n record.tenantId !== auth.tenantId ||\n !isOrganizationAccessAllowed({\n isSuperAdmin,\n allowedOrganizationIds: allowedIds,\n targetOrganizationId: record.organizationId ?? null,\n })\n ) {\n throw json({ error: translate('api_keys.errors.notFound', 'Not found') }, { status: 404 })\n }\n scopedCtx.__apiKeyOrganizationId = record.organizationId ?? null\n },\n afterDelete: async (id, ctx) => {\n try {\n const rbac = (ctx.container.resolve('rbacService') as RbacService)\n await rbac.invalidateUserCache(`api_key:${id}`)\n } catch {}\n },\n },\n})\n\nexport const metadata = crud.metadata\nexport const GET = crud.GET\nexport const POST = crud.POST\nexport const DELETE = crud.DELETE\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage API keys',\n description:\n 'Provides list, creation, and deletion capabilities for API keys scoped to the authenticated tenant and organization.',\n methods: {\n GET: {\n summary: 'List API keys',\n description:\n 'Returns paginated API keys visible to the current user, including per-key role assignments and organization context.',\n query: listQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Collection of API keys',\n schema: apiKeyCollectionResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Tenant context missing', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Forbidden by organization scope', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Create API key',\n description:\n 'Creates a new API key, returning the one-time secret value together with the generated key prefix and scope details.',\n requestBody: {\n contentType: 'application/json',\n schema: createApiKeySchema,\n description: 'API key definition including optional scope and role assignments.',\n },\n responses: [\n {\n status: 201,\n description: 'API key created successfully',\n schema: apiKeyCreateResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or missing tenant context', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Organization outside allowed scope', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete API key',\n description:\n 'Removes an API key by identifier. The key must belong to the current tenant and fall within the requester organization scope.',\n query: z.object({\n id: z.string().uuid().describe('API key identifier to delete'),\n }),\n responses: [\n { status: 200, description: 'Key deleted successfully', schema: deleteResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Missing or invalid identifier', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Organization outside allowed scope', schema: errorSchema },\n { status: 404, description: 'Key not found within scope', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,qBAAqB;AAG9B,SAAS,YAAY;AACrB,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,0BAA0B;AACnC,SAAS,sBAAsB,kBAAkB;AACjD,SAAS,2BAA2B;AACpC,SAAS,wBAAwB,2BAA2B;AAC5D,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;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AAAA,MACT,aACE;AAAA,MACF,OAAO,EAAE,OAAO;AAAA,QACd,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,8BAA8B;AAAA,MAC/D,CAAC;AAAA,MACD,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,qBAAqB;AAAA,MACvF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,YAAY;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,QACtF,EAAE,QAAQ,KAAK,aAAa,8BAA8B,QAAQ,YAAY;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,9 @@
1
+ import { asClass } from "awilix";
2
+ import { DefaultApiKeyPrincipalService } from "./services/principalService.js";
3
+ function register(container) {
4
+ container.register({ apiKeyPrincipalService: asClass(DefaultApiKeyPrincipalService).scoped() });
5
+ }
6
+ export {
7
+ register
8
+ };
9
+ //# sourceMappingURL=di.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/modules/api_keys/di.ts"],
4
+ "sourcesContent": ["import { asClass } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { DefaultApiKeyPrincipalService } from './services/principalService'\n\nexport function register(container: AppContainer) {\n container.register({ apiKeyPrincipalService: asClass(DefaultApiKeyPrincipalService).scoped() })\n}\n"],
5
+ "mappings": "AAAA,SAAS,eAAe;AAExB,SAAS,qCAAqC;AAEvC,SAAS,SAAS,WAAyB;AAChD,YAAU,SAAS,EAAE,wBAAwB,QAAQ,6BAA6B,EAAE,OAAO,EAAE,CAAC;AAChG;",
6
+ "names": []
7
+ }
@@ -0,0 +1,31 @@
1
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
2
+ import { ApiKey } from "../data/entities.js";
3
+ function normalizeIds(ids) {
4
+ if (!Array.isArray(ids)) return [];
5
+ return Array.from(new Set(ids.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean)));
6
+ }
7
+ class DefaultApiKeyPrincipalService {
8
+ constructor(em) {
9
+ this.em = em;
10
+ }
11
+ async resolveAssignedRoleIds(apiKeyId, scope) {
12
+ const apiKey = await findOneWithDecryption(
13
+ this.em,
14
+ ApiKey,
15
+ {
16
+ id: apiKeyId,
17
+ tenantId: scope.tenantId,
18
+ deletedAt: null,
19
+ $or: [{ organizationId: null }, { organizationId: scope.organizationId }]
20
+ },
21
+ { fields: ["rolesJson", "expiresAt"] },
22
+ scope
23
+ );
24
+ if (!apiKey || apiKey.expiresAt && apiKey.expiresAt.getTime() <= Date.now()) return [];
25
+ return normalizeIds(apiKey.rolesJson);
26
+ }
27
+ }
28
+ export {
29
+ DefaultApiKeyPrincipalService
30
+ };
31
+ //# sourceMappingURL=principalService.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/api_keys/services/principalService.ts"],
4
+ "sourcesContent": ["import type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ApiKeyPrincipalService, PrincipalScope } from '@open-mercato/shared/lib/auth/principal-service'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { ApiKey } from '../data/entities'\n\nfunction normalizeIds(ids: unknown): string[] {\n if (!Array.isArray(ids)) return []\n return Array.from(new Set(ids\n .map((id) => typeof id === 'string' ? id.trim() : '')\n .filter(Boolean)))\n}\n\nexport class DefaultApiKeyPrincipalService implements ApiKeyPrincipalService {\n constructor(private readonly em: EntityManager) {}\n\n async resolveAssignedRoleIds(apiKeyId: string, scope: PrincipalScope): Promise<string[]> {\n const apiKey = await findOneWithDecryption(\n this.em,\n ApiKey,\n {\n id: apiKeyId,\n tenantId: scope.tenantId,\n deletedAt: null,\n $or: [{ organizationId: null }, { organizationId: scope.organizationId }],\n } as FilterQuery<ApiKey>,\n { fields: ['rolesJson', 'expiresAt'] as const },\n scope,\n )\n if (!apiKey || (apiKey.expiresAt && apiKey.expiresAt.getTime() <= Date.now())) return []\n return normalizeIds(apiKey.rolesJson)\n }\n}\n"],
5
+ "mappings": "AAGA,SAAS,6BAA6B;AACtC,SAAS,cAAc;AAEvB,SAAS,aAAa,KAAwB;AAC5C,MAAI,CAAC,MAAM,QAAQ,GAAG,EAAG,QAAO,CAAC;AACjC,SAAO,MAAM,KAAK,IAAI,IAAI,IACvB,IAAI,CAAC,OAAO,OAAO,OAAO,WAAW,GAAG,KAAK,IAAI,EAAE,EACnD,OAAO,OAAO,CAAC,CAAC;AACrB;AAEO,MAAM,8BAAgE;AAAA,EAC3E,YAA6B,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAEjD,MAAM,uBAAuB,UAAkB,OAA0C;AACvF,UAAM,SAAS,MAAM;AAAA,MACnB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,IAAI;AAAA,QACJ,UAAU,MAAM;AAAA,QAChB,WAAW;AAAA,QACX,KAAK,CAAC,EAAE,gBAAgB,KAAK,GAAG,EAAE,gBAAgB,MAAM,eAAe,CAAC;AAAA,MAC1E;AAAA,MACA,EAAE,QAAQ,CAAC,aAAa,WAAW,EAAW;AAAA,MAC9C;AAAA,IACF;AACA,QAAI,CAAC,UAAW,OAAO,aAAa,OAAO,UAAU,QAAQ,KAAK,KAAK,IAAI,EAAI,QAAO,CAAC;AACvF,WAAO,aAAa,OAAO,SAAS;AAAA,EACtC;AACF;",
6
+ "names": []
7
+ }
@@ -1,5 +1,6 @@
1
1
  import { asFunction, asValue } from "awilix";
2
2
  import { StorageDriverFactory } from "./lib/drivers/driverFactory.js";
3
+ import { DefaultAttachmentService } from "./lib/attachment-service.js";
3
4
  import { createAttachmentQuotaService } from "./lib/quota-service.js";
4
5
  import { scheduleAttachmentQuotaRecovery } from "./lib/quota-recovery-queue.js";
5
6
  import { AttachmentTargetAccessService } from "./lib/target-access-service.js";
@@ -28,7 +29,16 @@ function register(container) {
28
29
  })).scoped().proxy(),
29
30
  storageDriverFactory: asFunction(
30
31
  ({ em }) => new StorageDriverFactory(em)
31
- ).singleton().proxy()
32
+ ).singleton().proxy(),
33
+ // The scoped upload service is handed over as a lazy resolver so module
34
+ // uploads share the public attachment route's single fenced reservation
35
+ // ledger, without dragging that service's own dependencies into every
36
+ // container that merely constructs an `attachmentService`.
37
+ attachmentService: asFunction((cradle) => new DefaultAttachmentService(
38
+ cradle.em,
39
+ cradle.storageDriverFactory,
40
+ () => cradle.attachmentScopedUploadService ?? null
41
+ )).scoped().proxy()
32
42
  });
33
43
  }
34
44
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/attachments/di.ts"],
4
- "sourcesContent": ["import { asFunction, asValue } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { StorageDriverFactory } from './lib/drivers/driverFactory'\nimport { createAttachmentQuotaService, type AttachmentQuotaService } from './lib/quota-service'\nimport { scheduleAttachmentQuotaRecovery } from './lib/quota-recovery-queue'\nimport { AttachmentTargetAccessService } from './lib/target-access-service'\nimport { ScopedAttachmentUploadService } from './lib/scoped-upload-service'\n\nexport function register(container: AppContainer) {\n container.register({\n attachmentQuotaRecoveryScheduler: asValue(scheduleAttachmentQuotaRecovery),\n attachmentQuotaService: asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>\n createAttachmentQuotaService(em),\n )\n .scoped()\n .proxy(),\n attachmentTargetAccessService: asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>\n new AttachmentTargetAccessService(em),\n )\n .scoped()\n .proxy(),\n attachmentScopedUploadService: asFunction(({\n em,\n dataEngine,\n storageDriverFactory,\n attachmentQuotaService,\n attachmentQuotaRecoveryScheduler,\n }: {\n em: ConstructorParameters<typeof StorageDriverFactory>[0]\n dataEngine: DataEngine\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: typeof scheduleAttachmentQuotaRecovery\n }) => new ScopedAttachmentUploadService({\n em,\n dataEngine,\n storageDriverFactory,\n attachmentQuotaService,\n attachmentQuotaRecoveryScheduler,\n }))\n .scoped()\n .proxy(),\n storageDriverFactory: asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>\n new StorageDriverFactory(em),\n )\n .singleton()\n .proxy(),\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,YAAY,eAAe;AAGpC,SAAS,4BAA4B;AACrC,SAAS,oCAAiE;AAC1E,SAAS,uCAAuC;AAChD,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAEvC,SAAS,SAAS,WAAyB;AAChD,YAAU,SAAS;AAAA,IACjB,kCAAkC,QAAQ,+BAA+B;AAAA,IACzE,wBAAwB;AAAA,MAAW,CAAC,EAAE,GAAG,MACvC,6BAA6B,EAAE;AAAA,IACjC,EACG,OAAO,EACP,MAAM;AAAA,IACT,+BAA+B;AAAA,MAAW,CAAC,EAAE,GAAG,MAC9C,IAAI,8BAA8B,EAAE;AAAA,IACtC,EACG,OAAO,EACP,MAAM;AAAA,IACT,+BAA+B,WAAW,CAAC;AAAA,MACzC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,MAMM,IAAI,8BAA8B;AAAA,MACtC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC,CAAC,EACC,OAAO,EACP,MAAM;AAAA,IACT,sBAAsB;AAAA,MAAW,CAAC,EAAE,GAAG,MACrC,IAAI,qBAAqB,EAAE;AAAA,IAC7B,EACG,UAAU,EACV,MAAM;AAAA,EACX,CAAC;AACH;",
4
+ "sourcesContent": ["import { asFunction, asValue } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { StorageDriverFactory } from './lib/drivers/driverFactory'\nimport { DefaultAttachmentService } from './lib/attachment-service'\nimport { createAttachmentQuotaService, type AttachmentQuotaService } from './lib/quota-service'\nimport { scheduleAttachmentQuotaRecovery } from './lib/quota-recovery-queue'\nimport { AttachmentTargetAccessService } from './lib/target-access-service'\nimport { ScopedAttachmentUploadService } from './lib/scoped-upload-service'\n\nexport function register(container: AppContainer) {\n container.register({\n attachmentQuotaRecoveryScheduler: asValue(scheduleAttachmentQuotaRecovery),\n attachmentQuotaService: asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>\n createAttachmentQuotaService(em),\n )\n .scoped()\n .proxy(),\n attachmentTargetAccessService: asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>\n new AttachmentTargetAccessService(em),\n )\n .scoped()\n .proxy(),\n attachmentScopedUploadService: asFunction(({\n em,\n dataEngine,\n storageDriverFactory,\n attachmentQuotaService,\n attachmentQuotaRecoveryScheduler,\n }: {\n em: ConstructorParameters<typeof StorageDriverFactory>[0]\n dataEngine: DataEngine\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: typeof scheduleAttachmentQuotaRecovery\n }) => new ScopedAttachmentUploadService({\n em,\n dataEngine,\n storageDriverFactory,\n attachmentQuotaService,\n attachmentQuotaRecoveryScheduler,\n }))\n .scoped()\n .proxy(),\n storageDriverFactory: asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>\n new StorageDriverFactory(em),\n )\n .singleton()\n .proxy(),\n // The scoped upload service is handed over as a lazy resolver so module\n // uploads share the public attachment route's single fenced reservation\n // ledger, without dragging that service's own dependencies into every\n // container that merely constructs an `attachmentService`.\n attachmentService: asFunction((cradle: {\n em: ConstructorParameters<typeof DefaultAttachmentService>[0]\n storageDriverFactory: ConstructorParameters<typeof DefaultAttachmentService>[1]\n attachmentScopedUploadService: ScopedAttachmentUploadService\n }) => new DefaultAttachmentService(\n cradle.em,\n cradle.storageDriverFactory,\n () => cradle.attachmentScopedUploadService ?? null,\n ))\n .scoped()\n .proxy(),\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY,eAAe;AAGpC,SAAS,4BAA4B;AACrC,SAAS,gCAAgC;AACzC,SAAS,oCAAiE;AAC1E,SAAS,uCAAuC;AAChD,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAEvC,SAAS,SAAS,WAAyB;AAChD,YAAU,SAAS;AAAA,IACjB,kCAAkC,QAAQ,+BAA+B;AAAA,IACzE,wBAAwB;AAAA,MAAW,CAAC,EAAE,GAAG,MACvC,6BAA6B,EAAE;AAAA,IACjC,EACG,OAAO,EACP,MAAM;AAAA,IACT,+BAA+B;AAAA,MAAW,CAAC,EAAE,GAAG,MAC9C,IAAI,8BAA8B,EAAE;AAAA,IACtC,EACG,OAAO,EACP,MAAM;AAAA,IACT,+BAA+B,WAAW,CAAC;AAAA,MACzC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,MAMM,IAAI,8BAA8B;AAAA,MACtC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC,CAAC,EACC,OAAO,EACP,MAAM;AAAA,IACT,sBAAsB;AAAA,MAAW,CAAC,EAAE,GAAG,MACrC,IAAI,qBAAqB,EAAE;AAAA,IAC7B,EACG,UAAU,EACV,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKT,mBAAmB,WAAW,CAAC,WAIzB,IAAI;AAAA,MACR,OAAO;AAAA,MACP,OAAO;AAAA,MACP,MAAM,OAAO,iCAAiC;AAAA,IAChD,CAAC,EACE,OAAO,EACP,MAAM;AAAA,EACX,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/attachments/index.ts"],
4
- "sourcesContent": ["import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n\nexport const metadata: ModuleInfo = {\n name: 'attachments',\n title: 'Attachments',\n version: '0.1.0',\n description: 'File attachments and media management.',\n author: 'Open Mercato Team',\n license: 'MIT',\n}\n\n"],
4
+ "sourcesContent": ["import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n\nexport const metadata: ModuleInfo = {\n name: 'attachments',\n title: 'Attachments',\n version: '0.1.0',\n description: 'File attachments and media management.',\n author: 'Open Mercato Team',\n license: 'MIT',\n}\n\nexport {\n type AttachmentOwner,\n type AttachmentProviderCleanup,\n type AttachmentService,\n type CreatedScopedAttachment,\n type CreateScopedAttachmentInput,\n type ReadScopedAttachmentInput,\n type ReadScopedAttachmentResult,\n type ReleaseScopedAttachmentInput,\n} from './lib/attachment-service'\n"],
5
5
  "mappings": "AAEO,MAAM,WAAuB;AAAA,EAClC,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AACX;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,313 @@
1
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
2
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
3
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
4
+ import { createLogger } from "@open-mercato/shared/lib/logger";
5
+ import { Attachment, AttachmentPartition } from "../data/entities.js";
6
+ import { assertAttachmentScopeInvariant, checkAttachmentAccess } from "./access.js";
7
+ import { buildAttachmentFileUrl } from "./imageUrls.js";
8
+ import {
9
+ isScopedAttachmentUploadError
10
+ } from "./scoped-upload-service.js";
11
+ import { readAttachmentMetadata } from "./metadata.js";
12
+ import {
13
+ buildAttachmentContentDisposition,
14
+ canRenderInlineAttachment,
15
+ hasDangerousExecutableExtension
16
+ } from "./security.js";
17
+ import {
18
+ isMultipartRequestWithinUploadLimit,
19
+ resolveAttachmentMaxBytes,
20
+ resolveAttachmentMultipartMaxBytes
21
+ } from "./upload-limits.js";
22
+ const logger = createLogger("attachments").child({ component: "attachment-service" });
23
+ const SCOPED_UPLOAD_ERROR_MESSAGES = {
24
+ dangerous_executable: {
25
+ key: "attachments.errors.dangerousExecutable",
26
+ fallback: "Executable file types are not allowed as attachments."
27
+ },
28
+ max_upload_size: {
29
+ key: "attachments.errors.maxUploadSize",
30
+ fallback: "Attachment exceeds the maximum upload size."
31
+ },
32
+ active_content: {
33
+ key: "attachments.errors.activeContentBlocked",
34
+ fallback: "Active content uploads are not allowed."
35
+ },
36
+ partition_unavailable: {
37
+ key: "attachments.errors.partitionUnavailable",
38
+ fallback: "Attachment partition is not available for this scope."
39
+ },
40
+ quota_exceeded: {
41
+ key: "attachments.errors.quotaExceeded",
42
+ fallback: "Attachment storage quota exceeded for this tenant."
43
+ },
44
+ quota_target_exists: {
45
+ key: "attachments.errors.storagePathExists",
46
+ fallback: "The target storage path already exists."
47
+ },
48
+ quota_unavailable: {
49
+ key: "attachments.errors.quotaUnavailable",
50
+ fallback: "Storage quota accounting is unavailable."
51
+ },
52
+ quota_recovery_unsupported: {
53
+ key: "attachments.errors.quotaRecoveryUnsupported",
54
+ fallback: "Storage driver cannot participate in quota recovery."
55
+ },
56
+ storage_failed: {
57
+ key: "attachments.errors.storageFailed",
58
+ fallback: "Failed to store the attachment file."
59
+ },
60
+ persistence_failed: {
61
+ key: "attachments.errors.persistenceFailed",
62
+ fallback: "Failed to persist attachment."
63
+ }
64
+ };
65
+ const UPLOAD_FAILED_MESSAGE = {
66
+ key: "attachments.errors.uploadFailed",
67
+ fallback: "Attachment upload failed."
68
+ };
69
+ const UPLOAD_SERVICE_UNAVAILABLE_MESSAGE = {
70
+ key: "attachments.errors.uploadServiceUnavailable",
71
+ fallback: "The attachment upload service is not available."
72
+ };
73
+ async function translateAttachmentError(message) {
74
+ const { t } = await resolveTranslations();
75
+ return t(message.key, message.fallback);
76
+ }
77
+ async function readRequestBodyWithinLimit(request, maxBytes) {
78
+ const reader = request.body?.getReader();
79
+ if (!reader) throw new CrudHttpError(400, { error: "File is required" });
80
+ const chunks = [];
81
+ let totalBytes = 0;
82
+ try {
83
+ while (true) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ totalBytes += value.byteLength;
87
+ if (totalBytes > maxBytes) {
88
+ await reader.cancel();
89
+ throw new CrudHttpError(413, { error: "Attachment exceeds the maximum upload size." });
90
+ }
91
+ chunks.push(value);
92
+ }
93
+ } finally {
94
+ reader.releaseLock();
95
+ }
96
+ const body = new Uint8Array(totalBytes);
97
+ let offset = 0;
98
+ for (const chunk of chunks) {
99
+ body.set(chunk, offset);
100
+ offset += chunk.byteLength;
101
+ }
102
+ return body;
103
+ }
104
+ function assignmentMatches(candidate, expected) {
105
+ return candidate.type === expected.type && candidate.id === expected.id;
106
+ }
107
+ function partitionMatchesScope(partition, tenantId, organizationId) {
108
+ const partitionTenantId = partition.tenantId ?? null;
109
+ const partitionOrganizationId = partition.organizationId ?? null;
110
+ if (partitionTenantId === null && partitionOrganizationId === null) return true;
111
+ if (partitionTenantId === null || partitionOrganizationId === null) return false;
112
+ return partitionTenantId === tenantId && partitionOrganizationId === organizationId;
113
+ }
114
+ class DefaultAttachmentService {
115
+ /**
116
+ * The scoped upload service is supplied as a *resolver*, not an instance:
117
+ * resolving it eagerly would drag its own dependencies (notably `dataEngine`)
118
+ * into every container that merely constructs an `attachmentService`, even
119
+ * one that never uploads. `createScoped` requires it — module uploads must
120
+ * share the one reservation ledger rather than run a parallel quota
121
+ * mechanism — so its absence surfaces there, at the call that needs it.
122
+ */
123
+ constructor(em, storageDriverFactory, resolveScopedUploadService) {
124
+ this.em = em;
125
+ this.storageDriverFactory = storageDriverFactory;
126
+ this.resolveScopedUploadService = resolveScopedUploadService;
127
+ }
128
+ validateUpload(input) {
129
+ if (!isMultipartRequestWithinUploadLimit(input.contentLength ?? null)) {
130
+ throw new CrudHttpError(413, { error: "Attachment exceeds the maximum upload size." });
131
+ }
132
+ if (input.fileName && hasDangerousExecutableExtension(input.fileName)) {
133
+ throw new CrudHttpError(400, { error: "Executable file types are not allowed as attachments." });
134
+ }
135
+ if (typeof input.fileSize === "number" && input.fileSize > resolveAttachmentMaxBytes(null)) {
136
+ throw new CrudHttpError(413, { error: "Attachment exceeds the maximum upload size." });
137
+ }
138
+ }
139
+ async readUploadForm(request) {
140
+ this.validateUpload({ contentLength: request.headers.get("content-length") });
141
+ const contentType = request.headers.get("content-type") ?? "";
142
+ if (!contentType.toLowerCase().includes("multipart/form-data")) {
143
+ throw new CrudHttpError(400, { error: "Expected multipart/form-data" });
144
+ }
145
+ const body = await readRequestBodyWithinLimit(request, resolveAttachmentMultipartMaxBytes());
146
+ const responseBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
147
+ try {
148
+ return await new Response(responseBody, { headers: { "content-type": contentType } }).formData();
149
+ } catch {
150
+ throw new CrudHttpError(400, { error: "Invalid multipart/form-data" });
151
+ }
152
+ }
153
+ async createScoped(input) {
154
+ assertAttachmentScopeInvariant(input);
155
+ this.validateUpload({ fileName: input.fileName, fileSize: input.buffer.length });
156
+ let uploadService = null;
157
+ try {
158
+ uploadService = this.resolveScopedUploadService?.() ?? null;
159
+ } catch (error) {
160
+ logger.error("Scoped attachment upload service could not be resolved", { err: error });
161
+ }
162
+ if (!uploadService) {
163
+ throw new CrudHttpError(500, {
164
+ error: await translateAttachmentError(UPLOAD_SERVICE_UNAVAILABLE_MESSAGE)
165
+ });
166
+ }
167
+ let attachment;
168
+ try {
169
+ attachment = await uploadService.upload({
170
+ tenantId: input.tenantId,
171
+ organizationId: input.organizationId,
172
+ entityId: input.entityId,
173
+ recordId: input.recordId,
174
+ fileName: input.fileName,
175
+ buffer: input.buffer,
176
+ declaredMimeType: input.declaredMimeType ?? null,
177
+ assignments: input.assignments,
178
+ partitionCode: input.partitionCode,
179
+ requirePrivatePartition: true,
180
+ persistLink: input.persistLink
181
+ });
182
+ } catch (error) {
183
+ if (isScopedAttachmentUploadError(error)) {
184
+ const message = SCOPED_UPLOAD_ERROR_MESSAGES[error.code] ?? UPLOAD_FAILED_MESSAGE;
185
+ throw new CrudHttpError(error.status, { error: await translateAttachmentError(message) });
186
+ }
187
+ throw error;
188
+ }
189
+ return {
190
+ id: attachment.id,
191
+ url: attachment.url ?? buildAttachmentFileUrl(attachment.id),
192
+ fileName: attachment.fileName,
193
+ mimeType: attachment.mimeType,
194
+ fileSize: attachment.fileSize
195
+ };
196
+ }
197
+ async readScoped(input) {
198
+ const attachment = await findOneWithDecryption(
199
+ this.em,
200
+ Attachment,
201
+ {
202
+ id: input.attachmentId,
203
+ tenantId: input.auth.tenantId ?? null,
204
+ organizationId: input.auth.orgId ?? null
205
+ },
206
+ void 0,
207
+ { tenantId: input.auth.tenantId, organizationId: input.auth.orgId }
208
+ );
209
+ if (!attachment) throw new CrudHttpError(404, { error: "Attachment not found" });
210
+ const partition = await findOneWithDecryption(
211
+ this.em,
212
+ AttachmentPartition,
213
+ { code: attachment.partitionCode },
214
+ void 0,
215
+ { tenantId: input.auth.tenantId, organizationId: input.auth.orgId }
216
+ );
217
+ if (!partition) throw new CrudHttpError(500, { error: "Attachment partition is not configured" });
218
+ const access = checkAttachmentAccess(input.auth, attachment, partition, { requireAuthForPublic: true });
219
+ if (!access.ok) {
220
+ throw new CrudHttpError(access.status, { error: access.status === 401 ? "Unauthorized" : "Forbidden" });
221
+ }
222
+ if (!partitionMatchesScope(partition, input.auth.tenantId, input.auth.orgId)) {
223
+ throw new CrudHttpError(403, { error: "Attachment partition is not accessible for this scope" });
224
+ }
225
+ if (input.requirePrivatePartition && partition.isPublic) {
226
+ throw new CrudHttpError(403, { error: "Attachment partition is not accessible for this resource" });
227
+ }
228
+ if (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {
229
+ throw new CrudHttpError(404, { error: "Attachment not found" });
230
+ }
231
+ if (attachment.entityId !== input.expectedOwner.entityId || attachment.recordId !== input.expectedOwner.recordId) {
232
+ throw new CrudHttpError(404, { error: "Attachment not found" });
233
+ }
234
+ if (input.expectedAssignment) {
235
+ const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? [];
236
+ if (!assignments.some((candidate) => assignmentMatches(candidate, input.expectedAssignment))) {
237
+ throw new CrudHttpError(404, { error: "Attachment not found" });
238
+ }
239
+ }
240
+ const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, {
241
+ tenantId: attachment.tenantId ?? "",
242
+ organizationId: attachment.organizationId ?? ""
243
+ });
244
+ let result;
245
+ try {
246
+ result = await driver.read(attachment.partitionCode, attachment.storagePath);
247
+ } catch {
248
+ throw new CrudHttpError(404, { error: "File not available" });
249
+ }
250
+ const mimeType = attachment.mimeType || "application/octet-stream";
251
+ const renderInline = !input.forceDownload && canRenderInlineAttachment(mimeType);
252
+ return {
253
+ buffer: result.buffer,
254
+ contentType: renderInline ? result.contentType ?? mimeType : "application/octet-stream",
255
+ contentDisposition: buildAttachmentContentDisposition(
256
+ attachment.fileName,
257
+ renderInline ? "inline" : "attachment"
258
+ ),
259
+ fileName: attachment.fileName,
260
+ mimeType
261
+ };
262
+ }
263
+ async releaseScoped(input, options = {}) {
264
+ const em = options.em ?? this.em;
265
+ const expectedAssignment = input.expectedAssignment;
266
+ if (!expectedAssignment) {
267
+ throw new CrudHttpError(500, {
268
+ error: "Attachment release requires the expected assignment of the releasing record"
269
+ });
270
+ }
271
+ const isInTransaction = em.isInTransaction;
272
+ if (options.flush !== false && typeof isInTransaction === "function" && isInTransaction.call(em)) {
273
+ throw new CrudHttpError(500, {
274
+ error: "Attachment release inside an ambient transaction requires flush: false and deferred provider cleanup"
275
+ });
276
+ }
277
+ const scope = { tenantId: input.tenantId, organizationId: input.organizationId };
278
+ const attachment = await findOneWithDecryption(
279
+ em,
280
+ Attachment,
281
+ {
282
+ id: input.attachmentId,
283
+ tenantId: input.tenantId,
284
+ organizationId: input.organizationId
285
+ },
286
+ void 0,
287
+ scope
288
+ );
289
+ if (!attachment) throw new CrudHttpError(404, { error: "Attachment not found" });
290
+ if (attachment.entityId !== input.expectedOwner.entityId || attachment.recordId !== input.expectedOwner.recordId || input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {
291
+ throw new CrudHttpError(404, { error: "Attachment not found" });
292
+ }
293
+ const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? [];
294
+ if (!assignments.some((candidate) => assignmentMatches(candidate, expectedAssignment))) {
295
+ throw new CrudHttpError(409, { error: "Attachment is still referenced by another record" });
296
+ }
297
+ if (assignments.some((candidate) => !assignmentMatches(candidate, expectedAssignment))) {
298
+ throw new CrudHttpError(409, { error: "Attachment is still referenced by another record" });
299
+ }
300
+ const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, scope);
301
+ const deleteProviderBytes = () => driver.delete(attachment.partitionCode, attachment.storagePath);
302
+ em.remove(attachment);
303
+ if (options.flush === false) {
304
+ return deleteProviderBytes;
305
+ }
306
+ await em.flush();
307
+ await deleteProviderBytes();
308
+ }
309
+ }
310
+ export {
311
+ DefaultAttachmentService
312
+ };
313
+ //# sourceMappingURL=attachment-service.js.map