@open-mercato/core 0.10.1-develop.7736.1.88e07906bf → 0.10.1-develop.7748.1.d745ba61aa

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 (198) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/api_key/index.js +2 -0
  3. package/dist/generated/entities/api_key/index.js.map +2 -2
  4. package/dist/generated/entities/attachment_partition/index.js +2 -0
  5. package/dist/generated/entities/attachment_partition/index.js.map +2 -2
  6. package/dist/generated/entity-fields-registry.js +2 -0
  7. package/dist/generated/entity-fields-registry.js.map +2 -2
  8. package/dist/helpers/integration/attachmentAccessFixtures.js +144 -0
  9. package/dist/helpers/integration/attachmentAccessFixtures.js.map +7 -0
  10. package/dist/modules/api_keys/data/entities.js +7 -0
  11. package/dist/modules/api_keys/data/entities.js.map +2 -2
  12. package/dist/modules/api_keys/migrations/Migration20261012202110_api_keys.js +30 -0
  13. package/dist/modules/api_keys/migrations/Migration20261012202110_api_keys.js.map +7 -0
  14. package/dist/modules/api_keys/services/apiKeyService.js +31 -9
  15. package/dist/modules/api_keys/services/apiKeyService.js.map +2 -2
  16. package/dist/modules/attachments/api/file/[id]/route.js +16 -10
  17. package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
  18. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +15 -9
  19. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
  20. package/dist/modules/attachments/api/library/[id]/route.js +100 -56
  21. package/dist/modules/attachments/api/library/[id]/route.js.map +3 -3
  22. package/dist/modules/attachments/api/library/route.js +56 -17
  23. package/dist/modules/attachments/api/library/route.js.map +2 -2
  24. package/dist/modules/attachments/api/partitions/route.js +2 -0
  25. package/dist/modules/attachments/api/partitions/route.js.map +2 -2
  26. package/dist/modules/attachments/api/route.js +74 -34
  27. package/dist/modules/attachments/api/route.js.map +3 -3
  28. package/dist/modules/attachments/api/transfer/route.js +63 -37
  29. package/dist/modules/attachments/api/transfer/route.js.map +2 -2
  30. package/dist/modules/attachments/data/entities.js +3 -0
  31. package/dist/modules/attachments/data/entities.js.map +2 -2
  32. package/dist/modules/attachments/data/validators.js +41 -0
  33. package/dist/modules/attachments/data/validators.js.map +7 -0
  34. package/dist/modules/attachments/di.js +5 -2
  35. package/dist/modules/attachments/di.js.map +2 -2
  36. package/dist/modules/attachments/generators.js +29 -0
  37. package/dist/modules/attachments/generators.js.map +7 -0
  38. package/dist/modules/attachments/index.js +8 -1
  39. package/dist/modules/attachments/index.js.map +2 -2
  40. package/dist/modules/attachments/lib/access-errors.js +35 -0
  41. package/dist/modules/attachments/lib/access-errors.js.map +7 -0
  42. package/dist/modules/attachments/lib/access-mutation.js +23 -0
  43. package/dist/modules/attachments/lib/access-mutation.js.map +7 -0
  44. package/dist/modules/attachments/lib/access-protection.js +73 -0
  45. package/dist/modules/attachments/lib/access-protection.js.map +7 -0
  46. package/dist/modules/attachments/lib/access-query.js +74 -0
  47. package/dist/modules/attachments/lib/access-query.js.map +7 -0
  48. package/dist/modules/attachments/lib/access-registry.js +87 -0
  49. package/dist/modules/attachments/lib/access-registry.js.map +7 -0
  50. package/dist/modules/attachments/lib/access-runner.js +161 -0
  51. package/dist/modules/attachments/lib/access-runner.js.map +7 -0
  52. package/dist/modules/attachments/lib/access-types.js +1 -0
  53. package/dist/modules/attachments/lib/access-types.js.map +7 -0
  54. package/dist/modules/attachments/lib/attachment-service.js +14 -6
  55. package/dist/modules/attachments/lib/attachment-service.js.map +2 -2
  56. package/dist/modules/attachments/lib/createFromBuffer.js +2 -0
  57. package/dist/modules/attachments/lib/createFromBuffer.js.map +2 -2
  58. package/dist/modules/attachments/lib/partitions.js +3 -2
  59. package/dist/modules/attachments/lib/partitions.js.map +2 -2
  60. package/dist/modules/attachments/lib/scoped-upload-service.js +2 -0
  61. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  62. package/dist/modules/attachments/lib/target-access-service.js +12 -3
  63. package/dist/modules/attachments/lib/target-access-service.js.map +2 -2
  64. package/dist/modules/attachments/migrations/Migration20261001120000_attachments.js +38 -0
  65. package/dist/modules/attachments/migrations/Migration20261001120000_attachments.js.map +7 -0
  66. package/dist/modules/attachments/setup.js +10 -0
  67. package/dist/modules/attachments/setup.js.map +2 -2
  68. package/dist/modules/notifications/api/[id]/action/route.js +8 -0
  69. package/dist/modules/notifications/api/[id]/action/route.js.map +2 -2
  70. package/dist/modules/notifications/api/route.js +17 -0
  71. package/dist/modules/notifications/api/route.js.map +2 -2
  72. package/dist/modules/notifications/data/validators.js +1 -1
  73. package/dist/modules/notifications/data/validators.js.map +2 -2
  74. package/dist/modules/notifications/lib/notificationService.js +45 -3
  75. package/dist/modules/notifications/lib/notificationService.js.map +2 -2
  76. package/dist/modules/notifications/lib/routeHelpers.js +27 -0
  77. package/dist/modules/notifications/lib/routeHelpers.js.map +2 -2
  78. package/dist/modules/payment_gateways/lib/gateway-service.js +50 -34
  79. package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
  80. package/dist/modules/payment_gateways/lib/status-machine.js +10 -1
  81. package/dist/modules/payment_gateways/lib/status-machine.js.map +2 -2
  82. package/dist/modules/payment_gateways/lib/webhook-processor.js +1 -1
  83. package/dist/modules/payment_gateways/lib/webhook-processor.js.map +2 -2
  84. package/dist/modules/staff/notifications.js +4 -2
  85. package/dist/modules/staff/notifications.js.map +2 -2
  86. package/dist/modules/workflows/api/portal/tasks/[id]/complete/route.js +1 -1
  87. package/dist/modules/workflows/api/portal/tasks/[id]/complete/route.js.map +2 -2
  88. package/dist/modules/workflows/api/tasks/[id]/complete/route.js +7 -1
  89. package/dist/modules/workflows/api/tasks/[id]/complete/route.js.map +2 -2
  90. package/dist/modules/workflows/backend/tasks/[id]/page.js +2 -1
  91. package/dist/modules/workflows/backend/tasks/[id]/page.js.map +2 -2
  92. package/dist/modules/workflows/data/entities.js.map +2 -2
  93. package/dist/modules/workflows/lib/activity-executor.js +18 -4
  94. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  95. package/dist/modules/workflows/lib/activity-types.js +2 -2
  96. package/dist/modules/workflows/lib/activity-types.js.map +2 -2
  97. package/dist/modules/workflows/lib/condition-handler.js +7 -1
  98. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  99. package/dist/modules/workflows/lib/duration.js +13 -0
  100. package/dist/modules/workflows/lib/duration.js.map +2 -2
  101. package/dist/modules/workflows/lib/instance-status.js +16 -0
  102. package/dist/modules/workflows/lib/instance-status.js.map +7 -0
  103. package/dist/modules/workflows/lib/step-handler.js +9 -2
  104. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  105. package/dist/modules/workflows/lib/task-handler.js +16 -8
  106. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  107. package/dist/modules/workflows/lib/task-quick-action.js +13 -10
  108. package/dist/modules/workflows/lib/task-quick-action.js.map +2 -2
  109. package/dist/modules/workflows/lib/task-sla.js +10 -0
  110. package/dist/modules/workflows/lib/task-sla.js.map +2 -2
  111. package/dist/modules/workflows/lib/transition-handler.js +2 -1
  112. package/dist/modules/workflows/lib/transition-handler.js.map +2 -2
  113. package/dist/modules/workflows/lib/workflow-executor.js +29 -1
  114. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  115. package/dist/modules/workflows/notifications.js +4 -0
  116. package/dist/modules/workflows/notifications.js.map +2 -2
  117. package/generated/entities/api_key/index.ts +1 -0
  118. package/generated/entities/attachment_partition/index.ts +1 -0
  119. package/generated/entity-fields-registry.ts +2 -0
  120. package/package.json +7 -7
  121. package/src/helpers/integration/attachmentAccessFixtures.ts +141 -0
  122. package/src/modules/api_keys/data/entities.ts +25 -1
  123. package/src/modules/api_keys/migrations/.snapshot-open-mercato.json +234 -68
  124. package/src/modules/api_keys/migrations/Migration20261012202110_api_keys.ts +47 -0
  125. package/src/modules/api_keys/services/apiKeyService.ts +55 -9
  126. package/src/modules/attachments/api/file/[id]/route.ts +12 -9
  127. package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +10 -8
  128. package/src/modules/attachments/api/library/[id]/route.ts +87 -58
  129. package/src/modules/attachments/api/library/route.ts +40 -11
  130. package/src/modules/attachments/api/partitions/route.ts +2 -0
  131. package/src/modules/attachments/api/route.ts +68 -35
  132. package/src/modules/attachments/api/transfer/route.ts +65 -42
  133. package/src/modules/attachments/data/entities.ts +4 -0
  134. package/src/modules/attachments/data/validators.ts +36 -0
  135. package/src/modules/attachments/di.ts +4 -1
  136. package/src/modules/attachments/generators.ts +27 -0
  137. package/src/modules/attachments/i18n/de.json +4 -0
  138. package/src/modules/attachments/i18n/en.json +4 -0
  139. package/src/modules/attachments/i18n/es.json +4 -0
  140. package/src/modules/attachments/i18n/ko.json +4 -0
  141. package/src/modules/attachments/i18n/pl.json +4 -0
  142. package/src/modules/attachments/index.ts +18 -0
  143. package/src/modules/attachments/lib/access-errors.ts +32 -0
  144. package/src/modules/attachments/lib/access-mutation.ts +26 -0
  145. package/src/modules/attachments/lib/access-protection.ts +83 -0
  146. package/src/modules/attachments/lib/access-query.ts +86 -0
  147. package/src/modules/attachments/lib/access-registry.ts +117 -0
  148. package/src/modules/attachments/lib/access-runner.ts +183 -0
  149. package/src/modules/attachments/lib/access-types.ts +78 -0
  150. package/src/modules/attachments/lib/attachment-service.ts +8 -4
  151. package/src/modules/attachments/lib/createFromBuffer.ts +3 -0
  152. package/src/modules/attachments/lib/partitions.ts +3 -2
  153. package/src/modules/attachments/lib/scoped-upload-service.ts +2 -0
  154. package/src/modules/attachments/lib/target-access-service.ts +10 -3
  155. package/src/modules/attachments/migrations/.snapshot-open-mercato.json +17 -0
  156. package/src/modules/attachments/migrations/Migration20261001120000_attachments.ts +35 -0
  157. package/src/modules/attachments/setup.ts +10 -0
  158. package/src/modules/auth/i18n/de.json +3 -0
  159. package/src/modules/auth/i18n/en.json +3 -0
  160. package/src/modules/auth/i18n/es.json +3 -0
  161. package/src/modules/auth/i18n/ko.json +3 -0
  162. package/src/modules/auth/i18n/pl.json +3 -0
  163. package/src/modules/notifications/api/[id]/action/route.ts +8 -0
  164. package/src/modules/notifications/api/route.ts +17 -0
  165. package/src/modules/notifications/data/validators.ts +1 -1
  166. package/src/modules/notifications/i18n/de.json +2 -0
  167. package/src/modules/notifications/i18n/en.json +2 -0
  168. package/src/modules/notifications/i18n/es.json +2 -0
  169. package/src/modules/notifications/i18n/ko.json +2 -0
  170. package/src/modules/notifications/i18n/pl.json +2 -0
  171. package/src/modules/notifications/lib/notificationService.ts +67 -1
  172. package/src/modules/notifications/lib/routeHelpers.ts +38 -0
  173. package/src/modules/payment_gateways/lib/gateway-service.ts +50 -33
  174. package/src/modules/payment_gateways/lib/status-machine.ts +19 -0
  175. package/src/modules/payment_gateways/lib/webhook-processor.ts +1 -1
  176. package/src/modules/staff/notifications.ts +2 -0
  177. package/src/modules/workflows/AGENTS.md +2 -2
  178. package/src/modules/workflows/api/portal/tasks/[id]/complete/route.ts +5 -1
  179. package/src/modules/workflows/api/tasks/[id]/complete/route.ts +7 -1
  180. package/src/modules/workflows/backend/tasks/[id]/page.tsx +6 -2
  181. package/src/modules/workflows/data/entities.ts +6 -0
  182. package/src/modules/workflows/i18n/de.json +2 -0
  183. package/src/modules/workflows/i18n/en.json +2 -0
  184. package/src/modules/workflows/i18n/es.json +2 -0
  185. package/src/modules/workflows/i18n/ko.json +2 -0
  186. package/src/modules/workflows/i18n/pl.json +2 -0
  187. package/src/modules/workflows/lib/activity-executor.ts +36 -4
  188. package/src/modules/workflows/lib/activity-types.ts +2 -2
  189. package/src/modules/workflows/lib/condition-handler.ts +16 -1
  190. package/src/modules/workflows/lib/duration.ts +25 -0
  191. package/src/modules/workflows/lib/instance-status.ts +29 -0
  192. package/src/modules/workflows/lib/step-handler.ts +16 -1
  193. package/src/modules/workflows/lib/task-handler.ts +18 -10
  194. package/src/modules/workflows/lib/task-quick-action.ts +19 -10
  195. package/src/modules/workflows/lib/task-sla.ts +13 -0
  196. package/src/modules/workflows/lib/transition-handler.ts +2 -1
  197. package/src/modules/workflows/lib/workflow-executor.ts +44 -1
  198. package/src/modules/workflows/notifications.ts +4 -0
@@ -0,0 +1,144 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { expect } from "@playwright/test";
3
+ import { apiRequest, clearAuthTokenCache, getAuthToken, withCredentialIsolatedRequest } from "./api.js";
4
+ import { createRoleFixture, createUserFixture, deleteRoleIfExists, deleteUserIfExists, setRoleAclFeatures } from "./authFixtures.js";
5
+ import { deleteAttachmentIfExists, uploadAttachmentFixture } from "./attachmentsFixtures.js";
6
+ import { expectId, getTokenContext, readJsonSafe } from "./generalFixtures.js";
7
+ const OWNER_ACCESS_FEATURES = [
8
+ "documents.view",
9
+ "documents.edit",
10
+ "documents.create",
11
+ "documents.share",
12
+ "documents.delete",
13
+ "attachments.view",
14
+ "attachments.manage"
15
+ ];
16
+ const OWNER_ACCESS_PNG = Buffer.from(
17
+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEUlEQVQImWMwSpn2H4QZYAwASOwIrfM45AsAAAAASUVORK5CYII=",
18
+ "base64"
19
+ );
20
+ async function ownerPolicyRequest(method, path, token, data, scheme = "Bearer") {
21
+ return withCredentialIsolatedRequest(async (isolated) => {
22
+ const response = await isolated.fetch(path, {
23
+ method,
24
+ headers: { Authorization: `${scheme} ${token}`, "Content-Type": "application/json" },
25
+ ...data === void 0 ? {} : { data }
26
+ });
27
+ return {
28
+ status: response.status(),
29
+ headers: response.headers(),
30
+ body: await readJsonSafe(response),
31
+ bytes: await response.body()
32
+ };
33
+ });
34
+ }
35
+ async function withAttachmentOwnerFixture(request, run) {
36
+ const admin = await getAuthToken(request, "admin");
37
+ const scope = getTokenContext(admin);
38
+ const prefix = `attachment-owner-${randomUUID()}`;
39
+ const users = [], documents = [], attachments = [], keys = [];
40
+ let roleId = null;
41
+ try {
42
+ roleId = await createRoleFixture(request, admin, { name: prefix, tenantId: scope.tenantId });
43
+ await setRoleAclFeatures(request, admin, { roleId, features: OWNER_ACCESS_FEATURES });
44
+ const actor = async (label) => {
45
+ const email = `${prefix}-${label}@example.com`, password = `Owner1!${randomUUID()}`;
46
+ const id = await createUserFixture(request, admin, {
47
+ email,
48
+ password,
49
+ organizationId: scope.organizationId,
50
+ roles: [roleId],
51
+ name: label
52
+ });
53
+ users.push(id);
54
+ return { id, token: await getAuthToken(request, email, password), refreshToken: async () => {
55
+ clearAuthTokenCache();
56
+ return getAuthToken(request, email, password);
57
+ } };
58
+ };
59
+ const recipient = await actor("recipient"), unshared = await actor("unshared");
60
+ const document = async (label, token = admin) => {
61
+ const response = await apiRequest(request, "POST", "/api/documents", { token, data: { title: `${prefix}-${label}`, folderId: null } });
62
+ expect(response.status()).toBe(201);
63
+ const body = await readJsonSafe(response);
64
+ const id = expectId(body?.id, "Fixture response must include id");
65
+ documents.push(id);
66
+ return id;
67
+ };
68
+ const share = async (documentId, permission, principalType = "user", principalId = recipient.id, token = admin) => {
69
+ const response = await apiRequest(request, "POST", `/api/documents/${documentId}/shares`, {
70
+ token,
71
+ data: { principalType, principalId, permission }
72
+ });
73
+ expect(response.status()).toBe(201);
74
+ const body = await readJsonSafe(response);
75
+ expect(body?.updatedAt).toBeTruthy();
76
+ return { id: expectId(body?.id, "Fixture response must include id"), updatedAt: body.updatedAt };
77
+ };
78
+ const upload = async (documentId, label, options = {}) => {
79
+ const file = await uploadAttachmentFixture(request, admin, {
80
+ entityId: options.entityId ?? "documents:document",
81
+ recordId: documentId,
82
+ fileName: `${prefix}-${label}.txt`,
83
+ mimeType: "text/plain",
84
+ buffer: Buffer.from(`${prefix}-${label}-content`),
85
+ assignments: options.assignments,
86
+ tags: options.tags
87
+ });
88
+ attachments.push(file.id);
89
+ return file.id;
90
+ };
91
+ const uploadProxy = async (documentId) => {
92
+ const route = `/api/documents/${documentId}/attachments`;
93
+ const response = await request.fetch(process.env.BASE_URL?.trim() ? `${process.env.BASE_URL.trim()}${route}` : route, {
94
+ method: "POST",
95
+ headers: { Authorization: `Bearer ${admin}` },
96
+ multipart: { file: { name: `${prefix}-proxy.png`, mimeType: "image/png", buffer: OWNER_ACCESS_PNG } }
97
+ });
98
+ expect(response.status()).toBe(201);
99
+ const body = await readJsonSafe(response);
100
+ return { attachmentId: expectId(body?.attachmentId, "Document upload must include attachmentId"), url: String(body?.url) };
101
+ };
102
+ const key = async () => {
103
+ const response = await apiRequest(request, "POST", "/api/api_keys/keys", {
104
+ token: admin,
105
+ data: { name: prefix, tenantId: scope.tenantId, organizationId: scope.organizationId, roles: [roleId] }
106
+ });
107
+ expect(response.status()).toBe(201);
108
+ const body = await readJsonSafe(response);
109
+ const id = expectId(body?.id, "Fixture response must include id");
110
+ keys.push(id);
111
+ expect(body?.secret).toMatch(/^omk_/);
112
+ return { id, secret: body.secret };
113
+ };
114
+ const uploadPublicImage = async (documentId) => {
115
+ const file = await uploadAttachmentFixture(request, admin, {
116
+ entityId: "catalog:catalog_product",
117
+ recordId: randomUUID(),
118
+ fileName: `${prefix}-public.png`,
119
+ mimeType: "image/png",
120
+ buffer: OWNER_ACCESS_PNG,
121
+ assignments: [{ type: "documents:document", id: documentId }]
122
+ });
123
+ attachments.push(file.id);
124
+ expect(file.partitionCode).toBe("productsMedia");
125
+ return file.id;
126
+ };
127
+ const visible = await document("visible"), hidden = await document("hidden"), destination = await document("destination");
128
+ await share(visible, "viewer");
129
+ await run({ admin, roleId, prefix, recipient, unshared, visible, hidden, destination, document, share, upload, uploadProxy, uploadPublicImage, key });
130
+ } finally {
131
+ for (const id of keys) await apiRequest(request, "DELETE", `/api/api_keys/keys?id=${id}`, { token: admin }).catch(() => void 0);
132
+ for (const id of attachments) await deleteAttachmentIfExists(request, admin, id);
133
+ for (const id of documents.reverse()) await apiRequest(request, "DELETE", `/api/documents/${id}`, { token: admin }).catch(() => void 0);
134
+ for (const id of users) await deleteUserIfExists(request, admin, id);
135
+ await deleteRoleIfExists(request, admin, roleId);
136
+ }
137
+ }
138
+ export {
139
+ OWNER_ACCESS_FEATURES,
140
+ OWNER_ACCESS_PNG,
141
+ ownerPolicyRequest,
142
+ withAttachmentOwnerFixture
143
+ };
144
+ //# sourceMappingURL=attachmentAccessFixtures.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/helpers/integration/attachmentAccessFixtures.ts"],
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport { expect, type APIRequestContext } from '@playwright/test'\nimport { apiRequest, clearAuthTokenCache, getAuthToken, withCredentialIsolatedRequest } from './api'\nimport { createRoleFixture, createUserFixture, deleteRoleIfExists, deleteUserIfExists, setRoleAclFeatures } from './authFixtures'\nimport { deleteAttachmentIfExists, uploadAttachmentFixture } from './attachmentsFixtures'\nimport { expectId, getTokenContext, readJsonSafe } from './generalFixtures'\n\nexport const OWNER_ACCESS_FEATURES = [\n 'documents.view', 'documents.edit', 'documents.create', 'documents.share', 'documents.delete',\n 'attachments.view', 'attachments.manage',\n]\nexport const OWNER_ACCESS_PNG = Buffer.from(\n 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEUlEQVQImWMwSpn2H4QZYAwASOwIrfM45AsAAAAASUVORK5CYII=',\n 'base64',\n)\n\nexport type OwnerAccessItem = { id: string; tags?: string[]; assignments?: Array<{ type: string; id: string; label?: string | null }> }\nexport type OwnerAccessList = { items: OwnerAccessItem[]; total?: number; availableTags?: string[] }\nexport type OwnerAccessActor = { id: string; token: string; refreshToken: () => Promise<string> }\ntype Assignment = { type: string; id: string; label?: string }\ntype Share = { id: string; updatedAt: string }\n\nexport async function ownerPolicyRequest<Body = { error?: string }>(\n method: string, path: string, token: string, data?: unknown, scheme: 'Bearer' | 'ApiKey' = 'Bearer',\n) {\n return withCredentialIsolatedRequest(async (isolated) => {\n const response = await isolated.fetch(path, {\n method, headers: { Authorization: `${scheme} ${token}`, 'Content-Type': 'application/json' },\n ...(data === undefined ? {} : { data }),\n })\n return {\n status: response.status(), headers: response.headers(),\n body: await readJsonSafe<Body>(response), bytes: await response.body(),\n }\n })\n}\n\nexport type AttachmentOwnerFixture = {\n admin: string\n roleId: string\n prefix: string\n recipient: OwnerAccessActor\n unshared: OwnerAccessActor\n visible: string\n hidden: string\n destination: string\n document: (label: string, token?: string) => Promise<string>\n share: (documentId: string, permission: 'viewer' | 'editor', principalType?: 'user' | 'role', principalId?: string, token?: string) => Promise<Share>\n upload: (documentId: string, label: string, options?: { entityId?: string; assignments?: Assignment[]; tags?: string[] }) => Promise<string>\n uploadProxy: (documentId: string) => Promise<{ attachmentId: string; url: string }>\n uploadPublicImage: (documentId: string) => Promise<string>\n key: () => Promise<{ id: string; secret: string }>\n}\n\nexport async function withAttachmentOwnerFixture(\n request: APIRequestContext, run: (fixture: AttachmentOwnerFixture) => Promise<void>,\n): Promise<void> {\n const admin = await getAuthToken(request, 'admin')\n const scope = getTokenContext(admin)\n const prefix = `attachment-owner-${randomUUID()}`\n const users: string[] = [], documents: string[] = [], attachments: string[] = [], keys: string[] = []\n let roleId: string | null = null\n try {\n roleId = await createRoleFixture(request, admin, { name: prefix, tenantId: scope.tenantId })\n await setRoleAclFeatures(request, admin, { roleId, features: OWNER_ACCESS_FEATURES })\n const actor = async (label: string): Promise<OwnerAccessActor> => {\n const email = `${prefix}-${label}@example.com`, password = `Owner1!${randomUUID()}`\n const id = await createUserFixture(request, admin, {\n email, password, organizationId: scope.organizationId, roles: [roleId!], name: label,\n })\n users.push(id)\n return { id, token: await getAuthToken(request, email, password), refreshToken: async () => {\n clearAuthTokenCache()\n return getAuthToken(request, email, password)\n } }\n }\n const recipient = await actor('recipient'), unshared = await actor('unshared')\n const document = async (label: string, token = admin): Promise<string> => {\n const response = await apiRequest(request, 'POST', '/api/documents', { token, data: { title: `${prefix}-${label}`, folderId: null } })\n expect(response.status()).toBe(201)\n const body = await readJsonSafe<{ id: string }>(response)\n const id = expectId(body?.id, 'Fixture response must include id'); documents.push(id); return id\n }\n const share: AttachmentOwnerFixture['share'] = async (documentId, permission, principalType = 'user', principalId = recipient.id, token = admin) => {\n const response = await apiRequest(request, 'POST', `/api/documents/${documentId}/shares`, {\n token, data: { principalType, principalId, permission },\n })\n expect(response.status()).toBe(201)\n const body = await readJsonSafe<Share>(response)\n expect(body?.updatedAt).toBeTruthy()\n return { id: expectId(body?.id, 'Fixture response must include id'), updatedAt: body!.updatedAt }\n }\n const upload: AttachmentOwnerFixture['upload'] = async (documentId, label, options = {}) => {\n const file = await uploadAttachmentFixture(request, admin, {\n entityId: options.entityId ?? 'documents:document', recordId: documentId,\n fileName: `${prefix}-${label}.txt`, mimeType: 'text/plain', buffer: Buffer.from(`${prefix}-${label}-content`),\n assignments: options.assignments, tags: options.tags,\n })\n attachments.push(file.id); return file.id\n }\n const uploadProxy = async (documentId: string) => {\n const route = `/api/documents/${documentId}/attachments`\n const response = await request.fetch(process.env.BASE_URL?.trim() ? `${process.env.BASE_URL.trim()}${route}` : route, {\n method: 'POST', headers: { Authorization: `Bearer ${admin}` },\n multipart: { file: { name: `${prefix}-proxy.png`, mimeType: 'image/png', buffer: OWNER_ACCESS_PNG } },\n })\n expect(response.status()).toBe(201)\n const body = await readJsonSafe<{ attachmentId: string; url: string }>(response)\n return { attachmentId: expectId(body?.attachmentId, 'Document upload must include attachmentId'), url: String(body?.url) }\n }\n const key = async () => {\n const response = await apiRequest(request, 'POST', '/api/api_keys/keys', {\n token: admin, data: { name: prefix, tenantId: scope.tenantId, organizationId: scope.organizationId, roles: [roleId] },\n })\n expect(response.status()).toBe(201)\n const body = await readJsonSafe<{ id: string; secret: string }>(response)\n const id = expectId(body?.id, 'Fixture response must include id'); keys.push(id)\n expect(body?.secret).toMatch(/^omk_/)\n return { id, secret: body!.secret }\n }\n const uploadPublicImage = async (documentId: string) => {\n const file = await uploadAttachmentFixture(request, admin, {\n entityId: 'catalog:catalog_product', recordId: randomUUID(),\n fileName: `${prefix}-public.png`, mimeType: 'image/png', buffer: OWNER_ACCESS_PNG,\n assignments: [{ type: 'documents:document', id: documentId }],\n })\n attachments.push(file.id)\n expect(file.partitionCode).toBe('productsMedia')\n return file.id\n }\n const visible = await document('visible'), hidden = await document('hidden'), destination = await document('destination')\n await share(visible, 'viewer')\n await run({ admin, roleId, prefix, recipient, unshared, visible, hidden, destination, document, share, upload, uploadProxy, uploadPublicImage, key })\n } finally {\n for (const id of keys) await apiRequest(request, 'DELETE', `/api/api_keys/keys?id=${id}`, { token: admin }).catch(() => undefined)\n for (const id of attachments) await deleteAttachmentIfExists(request, admin, id)\n for (const id of documents.reverse()) await apiRequest(request, 'DELETE', `/api/documents/${id}`, { token: admin }).catch(() => undefined)\n for (const id of users) await deleteUserIfExists(request, admin, id)\n await deleteRoleIfExists(request, admin, roleId)\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,cAAsC;AAC/C,SAAS,YAAY,qBAAqB,cAAc,qCAAqC;AAC7F,SAAS,mBAAmB,mBAAmB,oBAAoB,oBAAoB,0BAA0B;AACjH,SAAS,0BAA0B,+BAA+B;AAClE,SAAS,UAAU,iBAAiB,oBAAoB;AAEjD,MAAM,wBAAwB;AAAA,EACnC;AAAA,EAAkB;AAAA,EAAkB;AAAA,EAAoB;AAAA,EAAmB;AAAA,EAC3E;AAAA,EAAoB;AACtB;AACO,MAAM,mBAAmB,OAAO;AAAA,EACrC;AAAA,EACA;AACF;AAQA,eAAsB,mBACpB,QAAgB,MAAc,OAAe,MAAgB,SAA8B,UAC3F;AACA,SAAO,8BAA8B,OAAO,aAAa;AACvD,UAAM,WAAW,MAAM,SAAS,MAAM,MAAM;AAAA,MAC1C;AAAA,MAAQ,SAAS,EAAE,eAAe,GAAG,MAAM,IAAI,KAAK,IAAI,gBAAgB,mBAAmB;AAAA,MAC3F,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,KAAK;AAAA,IACvC,CAAC;AACD,WAAO;AAAA,MACL,QAAQ,SAAS,OAAO;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AAS,SAAS,GAAG,SAAS,MAAM,SAAS,QAAQ,GAAG,cAAc,MAAM,SAAS,aAAa;AACxH,UAAM,MAAM,SAAS,QAAQ;AAC7B,UAAM,IAAI,EAAE,OAAO,QAAQ,QAAQ,WAAW,UAAU,SAAS,QAAQ,aAAa,UAAU,OAAO,QAAQ,aAAa,mBAAmB,IAAI,CAAC;AAAA,EACtJ,UAAE;AACA,eAAW,MAAM,KAAM,OAAM,WAAW,SAAS,UAAU,yBAAyB,EAAE,IAAI,EAAE,OAAO,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AACjI,eAAW,MAAM,YAAa,OAAM,yBAAyB,SAAS,OAAO,EAAE;AAC/E,eAAW,MAAM,UAAU,QAAQ,EAAG,OAAM,WAAW,SAAS,UAAU,kBAAkB,EAAE,IAAI,EAAE,OAAO,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AACzI,eAAW,MAAM,MAAO,OAAM,mBAAmB,SAAS,OAAO,EAAE;AACnE,UAAM,mBAAmB,SAAS,OAAO,MAAM;AAAA,EACjD;AACF;",
6
+ "names": []
7
+ }
@@ -41,6 +41,9 @@ __decorateClass([
41
41
  __decorateClass([
42
42
  Property({ name: "created_by", type: "uuid", nullable: true })
43
43
  ], ApiKey.prototype, "createdBy", 2);
44
+ __decorateClass([
45
+ Property({ name: "session_token_hash", type: "text", nullable: true })
46
+ ], ApiKey.prototype, "sessionTokenHash", 2);
44
47
  __decorateClass([
45
48
  Property({ name: "session_token", type: "text", nullable: true })
46
49
  ], ApiKey.prototype, "sessionToken", 2);
@@ -74,6 +77,10 @@ ApiKey = __decorateClass([
74
77
  Index({
75
78
  name: "api_keys_opencode_session_id_uq",
76
79
  expression: 'create unique index "api_keys_opencode_session_id_uq" on "api_keys" ("opencode_session_id") where "opencode_session_id" is not null and "deleted_at" is null'
80
+ }),
81
+ Index({
82
+ name: "api_keys_session_token_hash_uq",
83
+ expression: 'create unique index "api_keys_session_token_hash_uq" on "api_keys" ("session_token_hash") where "session_token_hash" is not null and "deleted_at" is null'
77
84
  })
78
85
  ], ApiKey);
79
86
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/api_keys/data/entities.ts"],
4
- "sourcesContent": ["import { Entity, Index, PrimaryKey, Property, Unique } from '@mikro-orm/decorators/legacy'\n\n@Entity({ tableName: 'api_keys' })\n// The unique keyPrefix bounds the bcrypt candidate loop in findApiKeyBySecret to at\n// most one live row. Do not drop this constraint or widen the prefix space without\n// re-evaluating that loop's per-request cost (see #3812).\n@Unique({ properties: ['keyPrefix'] })\n@Index({\n name: 'api_keys_opencode_session_id_uq',\n expression:\n 'create unique index \"api_keys_opencode_session_id_uq\" on \"api_keys\" (\"opencode_session_id\") where \"opencode_session_id\" is not null and \"deleted_at\" is null',\n})\nexport class ApiKey {\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ type: 'text' })\n name!: string\n\n @Property({ name: 'description', type: 'text', nullable: true })\n description?: string | null\n\n @Property({ name: 'tenant_id', type: 'uuid', nullable: true })\n tenantId?: string | null\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'key_hash', type: 'text' })\n keyHash!: string\n\n @Property({ name: 'key_prefix', type: 'text' })\n keyPrefix!: string\n\n @Property({ name: 'roles_json', type: 'json', nullable: true })\n rolesJson?: string[] | null\n\n @Property({ name: 'created_by', type: 'uuid', nullable: true })\n createdBy?: string | null\n\n /** Session token for ephemeral session-scoped keys (used by AI chat) */\n @Property({ name: 'session_token', type: 'text', nullable: true })\n sessionToken?: string | null\n\n /** User ID who owns this session (for ephemeral keys) */\n @Property({ name: 'session_user_id', type: 'uuid', nullable: true })\n sessionUserId?: string | null\n\n /** Encrypted API key secret for session keys (recoverable for API calls) */\n @Property({ name: 'session_secret_encrypted', type: 'text', nullable: true })\n sessionSecretEncrypted?: string | null\n\n /**\n * OpenCode session id bound to this api_key row. Set the first time the\n * chat dispatcher receives a `done` event after minting a session token,\n * then asserted on every subsequent resume to prevent cross-user session\n * continuation (see security fix 2026-05-23).\n */\n @Property({ name: 'opencode_session_id', type: 'text', nullable: true })\n opencodeSessionId?: string | null\n\n @Property({ name: 'last_used_at', type: Date, nullable: true })\n lastUsedAt?: Date | null\n\n @Property({ name: 'expires_at', type: Date, nullable: true })\n expiresAt?: Date | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date(), nullable: true })\n updatedAt?: Date\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n"],
5
- "mappings": ";;;;;;;;;;AAAA,SAAS,QAAQ,OAAO,YAAY,UAAU,cAAc;AAYrD,IAAM,SAAN,MAAa;AAAA,EAAb;AAwDL,qBAAkB,oBAAI,KAAK;AAAA;AAO7B;AA7DE;AAAA,EADC,WAAW,EAAE,MAAM,QAAQ,YAAY,oBAAoB,CAAC;AAAA,GADlD,OAEX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,OAAO,CAAC;AAAA,GAJf,OAKX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,eAAe,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GAPpD,OAQX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,aAAa,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GAVlD,OAWX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,mBAAmB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GAbxD,OAcX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,YAAY,MAAM,OAAO,CAAC;AAAA,GAhBjC,OAiBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,OAAO,CAAC;AAAA,GAnBnC,OAoBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,QAAQ,UAAU,KAAK,CA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, Index, PrimaryKey, Property, Unique } from '@mikro-orm/decorators/legacy'\n\n@Entity({ tableName: 'api_keys' })\n// The unique keyPrefix bounds the bcrypt candidate loop in findApiKeyBySecret to at\n// most one live row. Do not drop this constraint or widen the prefix space without\n// re-evaluating that loop's per-request cost (see #3812).\n@Unique({ properties: ['keyPrefix'] })\n@Index({\n name: 'api_keys_opencode_session_id_uq',\n expression:\n 'create unique index \"api_keys_opencode_session_id_uq\" on \"api_keys\" (\"opencode_session_id\") where \"opencode_session_id\" is not null and \"deleted_at\" is null',\n})\n@Index({\n name: 'api_keys_session_token_hash_uq',\n expression:\n 'create unique index \"api_keys_session_token_hash_uq\" on \"api_keys\" (\"session_token_hash\") where \"session_token_hash\" is not null and \"deleted_at\" is null',\n})\nexport class ApiKey {\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ type: 'text' })\n name!: string\n\n @Property({ name: 'description', type: 'text', nullable: true })\n description?: string | null\n\n @Property({ name: 'tenant_id', type: 'uuid', nullable: true })\n tenantId?: string | null\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'key_hash', type: 'text' })\n keyHash!: string\n\n @Property({ name: 'key_prefix', type: 'text' })\n keyPrefix!: string\n\n @Property({ name: 'roles_json', type: 'json', nullable: true })\n rolesJson?: string[] | null\n\n @Property({ name: 'created_by', type: 'uuid', nullable: true })\n createdBy?: string | null\n\n /**\n * SHA-256 hash of the session token for ephemeral session-scoped keys (used by AI chat).\n * The raw token is a bearer credential \u2014 the same one that unlocks the decrypted API key\n * secret and the user's ACL on the MCP server \u2014 so, like `customer_accounts` session\n * tokens, only its hash is persisted. It is returned to the caller once, at issuance, and\n * never stored or logged in the clear (see #2254).\n */\n @Property({ name: 'session_token_hash', type: 'text', nullable: true })\n sessionTokenHash?: string | null\n\n /**\n * @deprecated Superseded by `sessionTokenHash` (#2254) \u2014 nothing reads or writes this\n * anymore and `Migration20261012202110_api_keys` nulls out every existing value as part of\n * scrubbing the plaintext token. Kept, not dropped, per the \"renamed/removed DB column\" rule in\n * `.ai/review-checklist.md` (keep old column, add new one, backfill, deprecate old) \u2014 chat\n * sessions in flight across the deploy carry a 2-hour TTL and only mint once per\n * conversation (`ai_assistant`'s chat route, `!sessionId` branch), so the column must survive\n * long enough for every session minted before this ships to expire naturally. Safe to drop in\n * a later migration once that window has passed.\n */\n @Property({ name: 'session_token', type: 'text', nullable: true })\n sessionToken?: string | null\n\n /** User ID who owns this session (for ephemeral keys) */\n @Property({ name: 'session_user_id', type: 'uuid', nullable: true })\n sessionUserId?: string | null\n\n /** Encrypted API key secret for session keys (recoverable for API calls) */\n @Property({ name: 'session_secret_encrypted', type: 'text', nullable: true })\n sessionSecretEncrypted?: string | null\n\n /**\n * OpenCode session id bound to this api_key row. Set the first time the\n * chat dispatcher receives a `done` event after minting a session token,\n * then asserted on every subsequent resume to prevent cross-user session\n * continuation (see security fix 2026-05-23).\n */\n @Property({ name: 'opencode_session_id', type: 'text', nullable: true })\n opencodeSessionId?: string | null\n\n @Property({ name: 'last_used_at', type: Date, nullable: true })\n lastUsedAt?: Date | null\n\n @Property({ name: 'expires_at', type: Date, nullable: true })\n expiresAt?: Date | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date(), nullable: true })\n updatedAt?: Date\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n"],
5
+ "mappings": ";;;;;;;;;;AAAA,SAAS,QAAQ,OAAO,YAAY,UAAU,cAAc;AAiBrD,IAAM,SAAN,MAAa;AAAA,EAAb;AA2EL,qBAAkB,oBAAI,KAAK;AAAA;AAO7B;AAhFE;AAAA,EADC,WAAW,EAAE,MAAM,QAAQ,YAAY,oBAAoB,CAAC;AAAA,GADlD,OAEX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,OAAO,CAAC;AAAA,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,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,KAAK,CAAC;AAAA,GAvEjD,OAwEX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,MAAM,oBAAI,KAAK,EAAE,CAAC;AAAA,GA1E7D,OA2EX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,MAAM,oBAAI,KAAK,GAAG,UAAU,KAAK,CAAC;AAAA,GA7E7E,OA8EX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,KAAK,CAAC;AAAA,GAhFjD,OAiFX;AAjFW,SAAN;AAAA,EAfN,OAAO,EAAE,WAAW,WAAW,CAAC;AAAA,EAIhC,OAAO,EAAE,YAAY,CAAC,WAAW,EAAE,CAAC;AAAA,EACpC,MAAM;AAAA,IACL,MAAM;AAAA,IACN,YACE;AAAA,EACJ,CAAC;AAAA,EACA,MAAM;AAAA,IACL,MAAM;AAAA,IACN,YACE;AAAA,EACJ,CAAC;AAAA,GACY;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,30 @@
1
+ import { Migration } from "@mikro-orm/migrations";
2
+ class Migration20261012202110_api_keys extends Migration {
3
+ constructor() {
4
+ super(...arguments);
5
+ this.name = "Migration20261012202110";
6
+ }
7
+ async up() {
8
+ this.addSql(`alter table "api_keys" add "session_token_hash" text null;`);
9
+ this.addSql(`
10
+ update "api_keys"
11
+ set "session_token_hash" = encode(sha256("session_token"::bytea), 'hex')
12
+ where "session_token" is not null and "session_token_hash" is null;
13
+ `);
14
+ this.addSql(`
15
+ update "api_keys"
16
+ set "name" = '__session_' || substr("session_token_hash", 1, 12) || '__'
17
+ where "session_token" is not null and "name" = '__session_' || "session_token" || '__';
18
+ `);
19
+ this.addSql(`update "api_keys" set "session_token" = null where "session_token" is not null;`);
20
+ this.addSql(`create unique index "api_keys_session_token_hash_uq" on "api_keys" ("session_token_hash") where "session_token_hash" is not null and "deleted_at" is null;`);
21
+ }
22
+ down() {
23
+ this.addSql(`drop index "api_keys_session_token_hash_uq";`);
24
+ this.addSql(`alter table "api_keys" drop column "session_token_hash";`);
25
+ }
26
+ }
27
+ export {
28
+ Migration20261012202110_api_keys
29
+ };
30
+ //# sourceMappingURL=Migration20261012202110_api_keys.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/api_keys/migrations/Migration20261012202110_api_keys.ts"],
4
+ "sourcesContent": ["import { Migration } from '@mikro-orm/migrations';\n\nexport class Migration20261012202110_api_keys extends Migration {\n\n override name = 'Migration20261012202110';\n\n override async up(): Promise<void> {\n this.addSql(`alter table \"api_keys\" add \"session_token_hash\" text null;`);\n\n // Backfill before switching any lookup to the hash column (#2254). AI-chat session keys\n // carry a 2-hour TTL and mint once per conversation (ai_assistant chat route, `!sessionId`\n // branch) \u2014 a session already in flight when this deploys must keep resolving, or the\n // conversation silently loses its MCP tool-call auth with no automatic re-mint. `sha256()`\n // is a PostgreSQL 13+ built-in (no pgcrypto dependency) and matches\n // `hashSessionToken`'s `createHash('sha256').update(token).digest('hex')` byte for byte.\n this.addSql(`\n update \"api_keys\"\n set \"session_token_hash\" = encode(sha256(\"session_token\"::bytea), 'hex')\n where \"session_token\" is not null and \"session_token_hash\" is null;\n `);\n\n // Legacy rows embedded the raw token in `name` (`__session_<token>__`, for operator\n // visibility in an admin listing) \u2014 the same credential leaking a second way. Replace it\n // with a hash-derived, non-secret label before the token itself is cleared below.\n this.addSql(`\n update \"api_keys\"\n set \"name\" = '__session_' || substr(\"session_token_hash\", 1, 12) || '__'\n where \"session_token\" is not null and \"name\" = '__session_' || \"session_token\" || '__';\n `);\n\n // Stop storing the plaintext bearer credential. The column is kept, not dropped, per the\n // \"renamed/removed DB column\" rule in `.ai/review-checklist.md` (keep old column, add new\n // one, backfill, deprecate old) \u2014 see `ApiKey.sessionToken`'s `@deprecated` doc comment for\n // the removal criteria for a later migration.\n this.addSql(`update \"api_keys\" set \"session_token\" = null where \"session_token\" is not null;`);\n\n this.addSql(`create unique index \"api_keys_session_token_hash_uq\" on \"api_keys\" (\"session_token_hash\") where \"session_token_hash\" is not null and \"deleted_at\" is null;`);\n }\n\n override down(): void | Promise<void> {\n // Schema-only reversal. The plaintext `session_token` values cleared above cannot be\n // restored \u2014 that data loss is the point of the migration, not an oversight.\n this.addSql(`drop index \"api_keys_session_token_hash_uq\";`);\n this.addSql(`alter table \"api_keys\" drop column \"session_token_hash\";`);\n }\n\n}\n"],
5
+ "mappings": "AAAA,SAAS,iBAAiB;AAEnB,MAAM,yCAAyC,UAAU;AAAA,EAAzD;AAAA;AAEL,SAAS,OAAO;AAAA;AAAA,EAEhB,MAAe,KAAoB;AACjC,SAAK,OAAO,4DAA4D;AAQxE,SAAK,OAAO;AAAA;AAAA;AAAA;AAAA,KAIX;AAKD,SAAK,OAAO;AAAA;AAAA;AAAA;AAAA,KAIX;AAMD,SAAK,OAAO,iFAAiF;AAE7F,SAAK,OAAO,4JAA4J;AAAA,EAC1K;AAAA,EAES,OAA6B;AAGpC,SAAK,OAAO,8CAA8C;AAC1D,SAAK,OAAO,0DAA0D;AAAA,EACxE;AAEF;",
6
+ "names": []
7
+ }
@@ -1,4 +1,4 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { randomBytes, createHash } from "node:crypto";
2
2
  import { hash, compare } from "bcryptjs";
3
3
  import { ApiKey } from "../data/entities.js";
4
4
  import { createKmsService, resolveEncryptionMode } from "@open-mercato/shared/lib/encryption/kms";
@@ -123,18 +123,22 @@ async function findApiKeyBySecret(em, secret) {
123
123
  function generateSessionToken() {
124
124
  return `sess_${randomBytes(16).toString("hex")}`;
125
125
  }
126
+ function hashSessionToken(sessionToken) {
127
+ return createHash("sha256").update(sessionToken).digest("hex");
128
+ }
126
129
  async function createSessionApiKey(em, input) {
127
130
  const { secret, prefix } = generateApiKeySecret();
128
131
  const ttl = input.ttlMinutes ?? 30;
129
132
  const expiresAt = new Date(Date.now() + ttl * 60 * 1e3);
130
133
  const keyHash = await hashApiKey(secret);
131
134
  const encryptedSecret = await encryptSessionSecret(secret, input.tenantId ?? null);
135
+ const sessionTokenHash = hashSessionToken(input.sessionToken);
132
136
  const roleIds = Array.from(new Set(input.userRoles.filter(Boolean))).sort((left, right) => left.localeCompare(right));
133
137
  let record;
134
138
  await withAtomicFlush(em, [async () => {
135
139
  await lockRoleWriterAuthorizationState(em, roleIds);
136
140
  record = em.create(ApiKey, {
137
- name: `__session_${input.sessionToken}__`,
141
+ name: `__session_${sessionTokenHash.slice(0, 12)}__`,
138
142
  description: "Ephemeral session API key for AI chat",
139
143
  tenantId: input.tenantId ?? null,
140
144
  organizationId: input.organizationId ?? null,
@@ -142,7 +146,7 @@ async function createSessionApiKey(em, input) {
142
146
  keyPrefix: prefix,
143
147
  rolesJson: roleIds,
144
148
  createdBy: input.userId,
145
- sessionToken: input.sessionToken,
149
+ sessionTokenHash,
146
150
  sessionUserId: input.userId,
147
151
  sessionSecretEncrypted: encryptedSecret,
148
152
  expiresAt,
@@ -158,10 +162,17 @@ async function createSessionApiKey(em, input) {
158
162
  }
159
163
  async function findApiKeyBySessionToken(em, sessionToken) {
160
164
  if (!sessionToken) return null;
161
- const record = await em.findOne(ApiKey, {
162
- sessionToken,
163
- deletedAt: null
164
- });
165
+ const sessionTokenHash = hashSessionToken(sessionToken);
166
+ let record = await em.findOne(ApiKey, { sessionTokenHash, deletedAt: null });
167
+ if (!record) {
168
+ const legacyRecord = await em.findOne(ApiKey, { sessionToken, deletedAt: null });
169
+ if (legacyRecord) {
170
+ legacyRecord.sessionTokenHash = sessionTokenHash;
171
+ legacyRecord.sessionToken = null;
172
+ await em.persist(legacyRecord).flush();
173
+ record = legacyRecord;
174
+ }
175
+ }
165
176
  if (!record) return null;
166
177
  if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null;
167
178
  return record;
@@ -204,12 +215,22 @@ async function findSessionApiKeyWithSecret(em, sessionToken) {
204
215
  return { key: record, secret };
205
216
  }
206
217
  async function deleteSessionApiKey(em, sessionToken) {
207
- const candidate = await em.findOne(ApiKey, { sessionToken, deletedAt: null });
218
+ const sessionTokenHash = hashSessionToken(sessionToken);
219
+ let candidate = await em.findOne(ApiKey, { sessionTokenHash, deletedAt: null });
220
+ if (!candidate) {
221
+ const legacyCandidate = await em.findOne(ApiKey, { sessionToken, deletedAt: null });
222
+ if (legacyCandidate) {
223
+ legacyCandidate.sessionTokenHash = sessionTokenHash;
224
+ legacyCandidate.sessionToken = null;
225
+ await em.persist(legacyCandidate).flush();
226
+ candidate = legacyCandidate;
227
+ }
228
+ }
208
229
  if (!candidate) return;
209
230
  let deletedId = null;
210
231
  await withAtomicFlush(em, [async () => {
211
232
  const records = await lockAuthorizationApiKeyRows(em, [String(candidate.id)]);
212
- const record = records.find((entry) => String(entry.id) === String(candidate.id) && entry.sessionToken === sessionToken && !entry.deletedAt);
233
+ const record = records.find((entry) => String(entry.id) === String(candidate.id) && entry.sessionTokenHash === sessionTokenHash && !entry.deletedAt);
213
234
  if (!record) return;
214
235
  record.deletedAt = /* @__PURE__ */ new Date();
215
236
  await em.persist(record).flush();
@@ -251,6 +272,7 @@ export {
251
272
  generateApiKeySecret,
252
273
  generateSessionToken,
253
274
  hashApiKey,
275
+ hashSessionToken,
254
276
  verifyApiKey,
255
277
  withOnetimeApiKey
256
278
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/api_keys/services/apiKeyService.ts"],
4
- "sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { ApiKey } from '../data/entities'\nimport { createKmsService, resolveEncryptionMode } from '@open-mercato/shared/lib/encryption/kms'\nimport { encryptWithAesGcm, decryptWithAesGcm, looksLikeEncryptedPayload } from '@open-mercato/shared/lib/encryption/aes'\nimport { getSharedApiKeyAuthCache } from '@open-mercato/shared/lib/auth/apiKeyAuthCache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport {\n lockAuthorizationApiKeyRows,\n lockRoleWriterAuthorizationState,\n} from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\n\nconst logger = createLogger('api_keys').child({ component: 'api-key-service' })\n\nconst BCRYPT_COST = 10\n\n// =============================================================================\n// Session Secret Encryption Helpers\n// =============================================================================\n\n/**\n * Seal an ephemeral session API key secret for storage in `session_secret_encrypted`.\n *\n * Returns null when the secret cannot be stored at all, which costs the caller MCP session-token\n * auth (the secret is unrecoverable and `findSessionApiKeyWithSecret` gives up).\n *\n * Under `TENANT_DATA_ENCRYPTION=no` the secret is stored as-is. That is the same bargain the rest\n * of the system already strikes in that mode -- emails, integration credentials and the search\n * index all sit in plaintext -- and it is what keeps the AI chat working when an operator opts\n * out. A DEK that is merely unreachable is a different situation and still yields null: writing a\n * secret in the clear because Vault happens to be down is not a downgrade anyone asked for.\n */\nasync function encryptSessionSecret(\n secret: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId) return null\n\n const kms = createKmsService()\n const mode = resolveEncryptionMode(kms)\n if (mode === 'disabled') return secret\n if (mode === 'unavailable') {\n logger.warn(\n 'Tenant data encryption is enabled but no DEK is reachable; session secret not stored. '\n + 'MCP session-token auth will fail until the KMS recovers.',\n { tenantId },\n )\n return null\n }\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) {\n // Try to create a DEK if one doesn't exist\n const created = await kms.createTenantDek(tenantId)\n if (!created) return null\n const encrypted = encryptWithAesGcm(secret, created.key)\n return encrypted.value\n }\n\n const encrypted = encryptWithAesGcm(secret, dek.key)\n return encrypted.value\n}\n\n/**\n * Recover a session API key secret written by {@link encryptSessionSecret}.\n * Returns null if it cannot be recovered.\n */\nasync function decryptSessionSecret(\n stored: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId || !stored) return null\n\n const kms = createKmsService()\n const mode = resolveEncryptionMode(kms)\n if (mode === 'disabled') {\n // Written in the clear by the branch above -- unless it predates the toggle being flipped, in\n // which case it is a sealed envelope no key can open and null is the honest answer.\n return looksLikeEncryptedPayload(stored) ? null : stored\n }\n if (mode === 'unavailable') {\n logger.warn('Tenant data encryption is enabled but no DEK is reachable; cannot recover session secret', { tenantId })\n return null\n }\n\n // Mirror of the `disabled` branch: a secret written in the clear while the toggle was off is\n // still recoverable after it is switched back on. Without this `decryptWithAesGcm` reads the\n // plaintext as a malformed envelope and returns null, so the flip would silently break every\n // live session rather than only the ones sealed under the old setting.\n if (!looksLikeEncryptedPayload(stored)) return stored\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) return null\n\n return decryptWithAesGcm(stored, dek.key)\n}\n\nexport type CreateApiKeyInput = {\n name: string\n description?: string | null\n tenantId?: string | null\n organizationId?: string | null\n roles?: string[]\n expiresAt?: Date | null\n createdBy?: string | null\n}\n\nexport type ApiKeyWithSecret = {\n record: ApiKey\n secret: string\n}\n\nexport function generateApiKeySecret(): { secret: string; prefix: string } {\n const short = randomBytes(4).toString('hex')\n const body = randomBytes(24).toString('hex')\n const secret = `omk_${short}.${body}`\n const prefix = secret.slice(0, 12)\n return { secret, prefix }\n}\n\nexport async function hashApiKey(secret: string): Promise<string> {\n return hash(secret, BCRYPT_COST)\n}\n\nexport async function verifyApiKey(secret: string, keyHash: string): Promise<boolean> {\n return compare(secret, keyHash)\n}\n\nexport async function createApiKey(\n em: EntityManager,\n input: CreateApiKeyInput,\n opts: {\n rbac?: RbacService\n authorizeRoles?: (roleIds: readonly string[]) => Promise<void> | void\n } = {},\n): Promise<ApiKeyWithSecret> {\n const { secret, prefix } = generateApiKeySecret()\n const keyHash = await hashApiKey(secret)\n const roleIds = Array.from(new Set((input.roles ?? []).filter(Boolean))).sort((left, right) => left.localeCompare(right))\n let record!: ApiKey\n await withAtomicFlush(em, [async () => {\n await lockRoleWriterAuthorizationState(em, roleIds)\n await opts.authorizeRoles?.(roleIds)\n record = em.create(ApiKey, {\n name: input.name,\n description: input.description ?? null,\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: roleIds,\n createdBy: input.createdBy ?? null,\n expiresAt: input.expiresAt ?? null,\n createdAt: new Date(),\n })\n em.persist(record)\n }], { transaction: true, label: 'api_keys.create' })\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${record.id}`)\n }\n return { record, secret }\n}\n\nexport async function deleteApiKey(\n em: EntityManager,\n id: string,\n opts: { rbac?: RbacService; authorize?: (record: ApiKey) => Promise<void> | void } = {},\n): Promise<boolean> {\n let deletedId: string | null = null\n await withAtomicFlush(em, [async () => {\n const records = await lockAuthorizationApiKeyRows(em, [id])\n const record = records.find((candidate) => String(candidate.id) === id)\n if (!record || record.deletedAt) return\n await opts.authorize?.(record)\n record.deletedAt = new Date()\n await em.persist(record).flush()\n deletedId = String(record.id)\n }], { transaction: true, label: 'api_keys.delete' })\n if (!deletedId) return false\n getSharedApiKeyAuthCache().invalidateByKeyId(deletedId)\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${deletedId}`)\n }\n return true\n}\n\nexport async function findApiKeyBySecret(em: EntityManager, secret: string): Promise<ApiKey | null> {\n if (!secret) return null\n // Extract prefix from the secret for fast candidate lookup\n const prefix = secret.slice(0, 12)\n // Find candidates by prefix (fast index lookup). Invariant: the unique keyPrefix\n // constraint plus the deletedAt: null filter keep this to at most one live row, so\n // the bcrypt loop below stays bounded. Do not widen the prefix space or relax either\n // filter without re-evaluating that cost (see #3812).\n const candidates = await em.find(ApiKey, { keyPrefix: prefix, deletedAt: null })\n // Verify each candidate with bcrypt until we find a match\n for (const candidate of candidates) {\n if (candidate.expiresAt && candidate.expiresAt.getTime() < Date.now()) continue\n const isValid = await verifyApiKey(secret, candidate.keyHash)\n if (isValid) return candidate\n }\n return null\n}\n\n// =============================================================================\n// Session-scoped API Keys (for AI Chat ephemeral authorization)\n// =============================================================================\n\nexport type CreateSessionApiKeyInput = {\n sessionToken: string\n userId: string\n userRoles: string[]\n tenantId?: string | null\n organizationId?: string | null\n ttlMinutes?: number\n}\n\n/**\n * Generate a unique session token for ephemeral API keys.\n * Format: sess_{32 hex chars}\n */\nexport function generateSessionToken(): string {\n return `sess_${randomBytes(16).toString('hex')}`\n}\n\n/**\n * Create an ephemeral API key scoped to a chat session.\n * The key inherits the user's roles and expires after ttlMinutes (default 30).\n * The API key secret is encrypted and stored so it can be recovered for API calls.\n */\nexport async function createSessionApiKey(\n em: EntityManager,\n input: CreateSessionApiKeyInput\n): Promise<{ keyId: string; secret: string; sessionToken: string }> {\n const { secret, prefix } = generateApiKeySecret()\n const ttl = input.ttlMinutes ?? 30\n const expiresAt = new Date(Date.now() + ttl * 60 * 1000)\n const keyHash = await hashApiKey(secret)\n\n // Encrypt the secret for later retrieval (used by MCP server for API calls)\n const encryptedSecret = await encryptSessionSecret(secret, input.tenantId ?? null)\n\n const roleIds = Array.from(new Set(input.userRoles.filter(Boolean))).sort((left, right) => left.localeCompare(right))\n let record!: ApiKey\n await withAtomicFlush(em, [async () => {\n await lockRoleWriterAuthorizationState(em, roleIds)\n record = em.create(ApiKey, {\n name: `__session_${input.sessionToken}__`,\n description: 'Ephemeral session API key for AI chat',\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: roleIds,\n createdBy: input.userId,\n sessionToken: input.sessionToken,\n sessionUserId: input.userId,\n sessionSecretEncrypted: encryptedSecret,\n expiresAt,\n createdAt: new Date(),\n })\n em.persist(record)\n }], { transaction: true, label: 'api_keys.session.create' })\n\n return {\n keyId: record.id,\n secret,\n sessionToken: input.sessionToken,\n }\n}\n\n/**\n * Find an API key by its session token.\n * Returns null if not found, expired, or deleted.\n */\nexport async function findApiKeyBySessionToken(\n em: EntityManager,\n sessionToken: string\n): Promise<ApiKey | null> {\n if (!sessionToken) return null\n\n const record = await em.findOne(ApiKey, {\n sessionToken,\n deletedAt: null,\n })\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Bind an OpenCode session id to the api_key row that owns this chat session.\n *\n * Called by the chat dispatcher the first time we see the `done` event for a\n * freshly minted session token. From that point on,\n * `findApiKeyByOpencodeSessionId(em, opencodeSessionId)` returns the same row,\n * which the ai-assistant runtime uses to assert ownership on every resume.\n *\n * Throws when the session token has been deleted/expired, and when the api_key\n * row is already bound to a DIFFERENT OpenCode session (defensive: this should\n * never happen in practice because each chat mints a new session token, but we\n * fail closed instead of silently overwriting).\n *\n * Idempotent when the row is already bound to the same OpenCode session id.\n */\nexport async function bindOpencodeSessionToApiKey(\n em: EntityManager,\n sessionToken: string,\n opencodeSessionId: string\n): Promise<void> {\n if (!sessionToken) throw new Error('Session token not found or expired')\n if (!opencodeSessionId) throw new Error('OpenCode session id is required')\n\n const row = await findApiKeyBySessionToken(em, sessionToken)\n if (!row) throw new Error('Session token not found or expired')\n\n if (row.opencodeSessionId === opencodeSessionId) return\n if (row.opencodeSessionId && row.opencodeSessionId !== opencodeSessionId) {\n throw new Error('Session token already bound to a different OpenCode session')\n }\n\n row.opencodeSessionId = opencodeSessionId\n await em.persist(row).flush()\n}\n\n/**\n * Find an api_key row by its bound OpenCode session id.\n *\n * Returns null if no active row matches, or if the matched row is expired\n * (same contract as `findApiKeyBySessionToken`). Uses\n * `findOneWithDecryption` so encrypted-at-rest fields on the row are decrypted\n * before the ai-assistant runtime inspects `sessionUserId` / `tenantId` /\n * `organizationId` for the ownership check.\n */\nexport async function findApiKeyByOpencodeSessionId(\n em: EntityManager,\n opencodeSessionId: string\n): Promise<ApiKey | null> {\n if (!opencodeSessionId) return null\n\n const record = await findOneWithDecryption(\n em,\n ApiKey,\n { opencodeSessionId, deletedAt: null } as any,\n )\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Find a session API key with its decrypted secret.\n * Returns null if not found, expired, deleted, or decryption fails.\n * This is used by the MCP server to recover the API key secret for making\n * authenticated API calls on behalf of the user.\n */\nexport async function findSessionApiKeyWithSecret(\n em: EntityManager,\n sessionToken: string\n): Promise<{ key: ApiKey; secret: string } | null> {\n const record = await findApiKeyBySessionToken(em, sessionToken)\n if (!record) return null\n\n // If no encrypted secret stored, cannot recover\n if (!record.sessionSecretEncrypted) {\n logger.warn('Session key has no encrypted secret', { apiKeyId: record.id })\n return null\n }\n\n // Decrypt the secret\n const secret = await decryptSessionSecret(record.sessionSecretEncrypted, record.tenantId ?? null)\n if (!secret) {\n logger.warn('Failed to decrypt session secret', { apiKeyId: record.id })\n return null\n }\n\n return { key: record, secret }\n}\n\n/**\n * Delete an ephemeral API key by its session token.\n */\nexport async function deleteSessionApiKey(\n em: EntityManager,\n sessionToken: string\n): Promise<void> {\n const candidate = await em.findOne(ApiKey, { sessionToken, deletedAt: null })\n if (!candidate) return\n let deletedId: string | null = null\n await withAtomicFlush(em, [async () => {\n const records = await lockAuthorizationApiKeyRows(em, [String(candidate.id)])\n const record = records.find((entry) => (\n String(entry.id) === String(candidate.id)\n && entry.sessionToken === sessionToken\n && !entry.deletedAt\n ))\n if (!record) return\n record.deletedAt = new Date()\n await em.persist(record).flush()\n deletedId = String(record.id)\n }], { transaction: true, label: 'api_keys.session.delete' })\n if (deletedId) getSharedApiKeyAuthCache().invalidateByKeyId(deletedId)\n}\n\n/**\n * Execute a function with a one-time API key\n *\n * Creates a temporary API key, executes the function, and deletes the key.\n * Perfect for workflow activities that need authenticated access without\n * storing long-lived credentials.\n *\n * @param em - Entity manager\n * @param input - API key configuration\n * @param fn - Function to execute with the API key secret\n * @returns Result of the function\n */\nconst ONETIME_KEY_MAX_TTL_MS = 5 * 60 * 1000\n\nexport async function withOnetimeApiKey<T>(\n em: EntityManager,\n input: CreateApiKeyInput,\n fn: (secret: string) => Promise<T>\n): Promise<T> {\n const maxExpiresAt = new Date(Date.now() + ONETIME_KEY_MAX_TTL_MS)\n const safeExpiresAt = input.expiresAt && input.expiresAt < maxExpiresAt\n ? input.expiresAt\n : maxExpiresAt\n\n const { record, secret } = await createApiKey(em, {\n ...input,\n name: input.name || '__onetime__',\n description: input.description || 'One-time API key',\n expiresAt: safeExpiresAt,\n })\n\n try {\n const result = await fn(secret)\n return result\n } finally {\n try {\n await deleteApiKey(em, String(record.id))\n } catch (error) {\n logger.error('Failed to soft-delete one-time API key', { err: error })\n }\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,MAAM,eAAe;AAE9B,SAAS,cAAc;AACvB,SAAS,kBAAkB,6BAA6B;AACxD,SAAS,mBAAmB,mBAAmB,iCAAiC;AAChF,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAE9E,MAAM,cAAc;AAkBpB,eAAe,qBACb,QACA,UACwB;AACxB,MAAI,CAAC,SAAU,QAAO;AAEtB,QAAM,MAAM,iBAAiB;AAC7B,QAAM,OAAO,sBAAsB,GAAG;AACtC,MAAI,SAAS,WAAY,QAAO;AAChC,MAAI,SAAS,eAAe;AAC1B,WAAO;AAAA,MACL;AAAA,MAEA,EAAE,SAAS;AAAA,IACb;AACA,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,MAAM,IAAI,aAAa,QAAQ;AAC3C,MAAI,CAAC,KAAK;AAER,UAAM,UAAU,MAAM,IAAI,gBAAgB,QAAQ;AAClD,QAAI,CAAC,QAAS,QAAO;AACrB,UAAMA,aAAY,kBAAkB,QAAQ,QAAQ,GAAG;AACvD,WAAOA,WAAU;AAAA,EACnB;AAEA,QAAM,YAAY,kBAAkB,QAAQ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AAM,YAAY,eACvD,MAAM,YACN;AAEJ,QAAM,EAAE,QAAQ,OAAO,IAAI,MAAM,aAAa,IAAI;AAAA,IAChD,GAAG;AAAA,IACH,MAAM,MAAM,QAAQ;AAAA,IACpB,aAAa,MAAM,eAAe;AAAA,IAClC,WAAW;AAAA,EACb,CAAC;AAED,MAAI;AACF,UAAM,SAAS,MAAM,GAAG,MAAM;AAC9B,WAAO;AAAA,EACT,UAAE;AACA,QAAI;AACF,YAAM,aAAa,IAAI,OAAO,OAAO,EAAE,CAAC;AAAA,IAC1C,SAAS,OAAO;AACd,aAAO,MAAM,0CAA0C,EAAE,KAAK,MAAM,CAAC;AAAA,IACvE;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { randomBytes, createHash } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { ApiKey } from '../data/entities'\nimport { createKmsService, resolveEncryptionMode } from '@open-mercato/shared/lib/encryption/kms'\nimport { encryptWithAesGcm, decryptWithAesGcm, looksLikeEncryptedPayload } from '@open-mercato/shared/lib/encryption/aes'\nimport { getSharedApiKeyAuthCache } from '@open-mercato/shared/lib/auth/apiKeyAuthCache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport {\n lockAuthorizationApiKeyRows,\n lockRoleWriterAuthorizationState,\n} from '@open-mercato/core/modules/auth/lib/authorizationStateLocks'\n\nconst logger = createLogger('api_keys').child({ component: 'api-key-service' })\n\nconst BCRYPT_COST = 10\n\n// =============================================================================\n// Session Secret Encryption Helpers\n// =============================================================================\n\n/**\n * Seal an ephemeral session API key secret for storage in `session_secret_encrypted`.\n *\n * Returns null when the secret cannot be stored at all, which costs the caller MCP session-token\n * auth (the secret is unrecoverable and `findSessionApiKeyWithSecret` gives up).\n *\n * Under `TENANT_DATA_ENCRYPTION=no` the secret is stored as-is. That is the same bargain the rest\n * of the system already strikes in that mode -- emails, integration credentials and the search\n * index all sit in plaintext -- and it is what keeps the AI chat working when an operator opts\n * out. A DEK that is merely unreachable is a different situation and still yields null: writing a\n * secret in the clear because Vault happens to be down is not a downgrade anyone asked for.\n */\nasync function encryptSessionSecret(\n secret: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId) return null\n\n const kms = createKmsService()\n const mode = resolveEncryptionMode(kms)\n if (mode === 'disabled') return secret\n if (mode === 'unavailable') {\n logger.warn(\n 'Tenant data encryption is enabled but no DEK is reachable; session secret not stored. '\n + 'MCP session-token auth will fail until the KMS recovers.',\n { tenantId },\n )\n return null\n }\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) {\n // Try to create a DEK if one doesn't exist\n const created = await kms.createTenantDek(tenantId)\n if (!created) return null\n const encrypted = encryptWithAesGcm(secret, created.key)\n return encrypted.value\n }\n\n const encrypted = encryptWithAesGcm(secret, dek.key)\n return encrypted.value\n}\n\n/**\n * Recover a session API key secret written by {@link encryptSessionSecret}.\n * Returns null if it cannot be recovered.\n */\nasync function decryptSessionSecret(\n stored: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId || !stored) return null\n\n const kms = createKmsService()\n const mode = resolveEncryptionMode(kms)\n if (mode === 'disabled') {\n // Written in the clear by the branch above -- unless it predates the toggle being flipped, in\n // which case it is a sealed envelope no key can open and null is the honest answer.\n return looksLikeEncryptedPayload(stored) ? null : stored\n }\n if (mode === 'unavailable') {\n logger.warn('Tenant data encryption is enabled but no DEK is reachable; cannot recover session secret', { tenantId })\n return null\n }\n\n // Mirror of the `disabled` branch: a secret written in the clear while the toggle was off is\n // still recoverable after it is switched back on. Without this `decryptWithAesGcm` reads the\n // plaintext as a malformed envelope and returns null, so the flip would silently break every\n // live session rather than only the ones sealed under the old setting.\n if (!looksLikeEncryptedPayload(stored)) return stored\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) return null\n\n return decryptWithAesGcm(stored, dek.key)\n}\n\nexport type CreateApiKeyInput = {\n name: string\n description?: string | null\n tenantId?: string | null\n organizationId?: string | null\n roles?: string[]\n expiresAt?: Date | null\n createdBy?: string | null\n}\n\nexport type ApiKeyWithSecret = {\n record: ApiKey\n secret: string\n}\n\nexport function generateApiKeySecret(): { secret: string; prefix: string } {\n const short = randomBytes(4).toString('hex')\n const body = randomBytes(24).toString('hex')\n const secret = `omk_${short}.${body}`\n const prefix = secret.slice(0, 12)\n return { secret, prefix }\n}\n\nexport async function hashApiKey(secret: string): Promise<string> {\n return hash(secret, BCRYPT_COST)\n}\n\nexport async function verifyApiKey(secret: string, keyHash: string): Promise<boolean> {\n return compare(secret, keyHash)\n}\n\nexport async function createApiKey(\n em: EntityManager,\n input: CreateApiKeyInput,\n opts: {\n rbac?: RbacService\n authorizeRoles?: (roleIds: readonly string[]) => Promise<void> | void\n } = {},\n): Promise<ApiKeyWithSecret> {\n const { secret, prefix } = generateApiKeySecret()\n const keyHash = await hashApiKey(secret)\n const roleIds = Array.from(new Set((input.roles ?? []).filter(Boolean))).sort((left, right) => left.localeCompare(right))\n let record!: ApiKey\n await withAtomicFlush(em, [async () => {\n await lockRoleWriterAuthorizationState(em, roleIds)\n await opts.authorizeRoles?.(roleIds)\n record = em.create(ApiKey, {\n name: input.name,\n description: input.description ?? null,\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: roleIds,\n createdBy: input.createdBy ?? null,\n expiresAt: input.expiresAt ?? null,\n createdAt: new Date(),\n })\n em.persist(record)\n }], { transaction: true, label: 'api_keys.create' })\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${record.id}`)\n }\n return { record, secret }\n}\n\nexport async function deleteApiKey(\n em: EntityManager,\n id: string,\n opts: { rbac?: RbacService; authorize?: (record: ApiKey) => Promise<void> | void } = {},\n): Promise<boolean> {\n let deletedId: string | null = null\n await withAtomicFlush(em, [async () => {\n const records = await lockAuthorizationApiKeyRows(em, [id])\n const record = records.find((candidate) => String(candidate.id) === id)\n if (!record || record.deletedAt) return\n await opts.authorize?.(record)\n record.deletedAt = new Date()\n await em.persist(record).flush()\n deletedId = String(record.id)\n }], { transaction: true, label: 'api_keys.delete' })\n if (!deletedId) return false\n getSharedApiKeyAuthCache().invalidateByKeyId(deletedId)\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${deletedId}`)\n }\n return true\n}\n\nexport async function findApiKeyBySecret(em: EntityManager, secret: string): Promise<ApiKey | null> {\n if (!secret) return null\n // Extract prefix from the secret for fast candidate lookup\n const prefix = secret.slice(0, 12)\n // Find candidates by prefix (fast index lookup). Invariant: the unique keyPrefix\n // constraint plus the deletedAt: null filter keep this to at most one live row, so\n // the bcrypt loop below stays bounded. Do not widen the prefix space or relax either\n // filter without re-evaluating that cost (see #3812).\n const candidates = await em.find(ApiKey, { keyPrefix: prefix, deletedAt: null })\n // Verify each candidate with bcrypt until we find a match\n for (const candidate of candidates) {\n if (candidate.expiresAt && candidate.expiresAt.getTime() < Date.now()) continue\n const isValid = await verifyApiKey(secret, candidate.keyHash)\n if (isValid) return candidate\n }\n return null\n}\n\n// =============================================================================\n// Session-scoped API Keys (for AI Chat ephemeral authorization)\n// =============================================================================\n\nexport type CreateSessionApiKeyInput = {\n sessionToken: string\n userId: string\n userRoles: string[]\n tenantId?: string | null\n organizationId?: string | null\n ttlMinutes?: number\n}\n\n/**\n * Generate a unique session token for ephemeral API keys.\n * Format: sess_{32 hex chars}\n */\nexport function generateSessionToken(): string {\n return `sess_${randomBytes(16).toString('hex')}`\n}\n\n/**\n * Hash a session token for storage/lookup (#2254). The session token is a bearer credential \u2014\n * it unlocks the decrypted API key secret and the user's ACL on the MCP server \u2014 so, mirroring\n * `customer_accounts`' `hashToken`, only its hash is ever persisted. 128 bits of entropy from\n * `generateSessionToken` is sufficient for a plain SHA-256 (no bcrypt cost needed, and a slow\n * hash would just add latency to every MCP tool call that resolves a session).\n */\nexport function hashSessionToken(sessionToken: string): string {\n return createHash('sha256').update(sessionToken).digest('hex')\n}\n\n/**\n * Create an ephemeral API key scoped to a chat session.\n * The key inherits the user's roles and expires after ttlMinutes (default 30).\n * The API key secret is encrypted and stored so it can be recovered for API calls.\n */\nexport async function createSessionApiKey(\n em: EntityManager,\n input: CreateSessionApiKeyInput\n): Promise<{ keyId: string; secret: string; sessionToken: string }> {\n const { secret, prefix } = generateApiKeySecret()\n const ttl = input.ttlMinutes ?? 30\n const expiresAt = new Date(Date.now() + ttl * 60 * 1000)\n const keyHash = await hashApiKey(secret)\n\n // Encrypt the secret for later retrieval (used by MCP server for API calls)\n const encryptedSecret = await encryptSessionSecret(secret, input.tenantId ?? null)\n\n // Hash before storage (#2254) \u2014 the row (and its `name` column, previously embedding the raw\n // token for operator visibility) must never carry the live bearer credential in the clear.\n const sessionTokenHash = hashSessionToken(input.sessionToken)\n\n const roleIds = Array.from(new Set(input.userRoles.filter(Boolean))).sort((left, right) => left.localeCompare(right))\n let record!: ApiKey\n await withAtomicFlush(em, [async () => {\n await lockRoleWriterAuthorizationState(em, roleIds)\n record = em.create(ApiKey, {\n name: `__session_${sessionTokenHash.slice(0, 12)}__`,\n description: 'Ephemeral session API key for AI chat',\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: roleIds,\n createdBy: input.userId,\n sessionTokenHash,\n sessionUserId: input.userId,\n sessionSecretEncrypted: encryptedSecret,\n expiresAt,\n createdAt: new Date(),\n })\n em.persist(record)\n }], { transaction: true, label: 'api_keys.session.create' })\n\n return {\n keyId: record.id,\n secret,\n sessionToken: input.sessionToken,\n }\n}\n\n/**\n * Find an API key by its session token.\n * Returns null if not found, expired, or deleted.\n */\nexport async function findApiKeyBySessionToken(\n em: EntityManager,\n sessionToken: string\n): Promise<ApiKey | null> {\n if (!sessionToken) return null\n\n // Looked up by hash, never by the raw token (#2254).\n const sessionTokenHash = hashSessionToken(sessionToken)\n let record = await em.findOne(ApiKey, { sessionTokenHash, deletedAt: null })\n\n if (!record) {\n // Version-skew fallback (#7304): during a rolling deploy/rollback window the app and the\n // separate MCP process can briefly run different code versions. A row minted by\n // pre-#2254 code in that window carries only the plaintext token (sessionTokenHash is\n // still null) \u2014 fall back to it so the session still resolves instead of answering a\n // false SESSION_EXPIRED, then self-heal the row onto the hash immediately so this is the\n // only lookup that ever sees the plaintext, and the window closes as soon as each\n // outstanding legacy row is touched once.\n const legacyRecord = await em.findOne(ApiKey, { sessionToken, deletedAt: null })\n if (legacyRecord) {\n legacyRecord.sessionTokenHash = sessionTokenHash\n legacyRecord.sessionToken = null\n await em.persist(legacyRecord).flush()\n record = legacyRecord\n }\n }\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Bind an OpenCode session id to the api_key row that owns this chat session.\n *\n * Called by the chat dispatcher the first time we see the `done` event for a\n * freshly minted session token. From that point on,\n * `findApiKeyByOpencodeSessionId(em, opencodeSessionId)` returns the same row,\n * which the ai-assistant runtime uses to assert ownership on every resume.\n *\n * Throws when the session token has been deleted/expired, and when the api_key\n * row is already bound to a DIFFERENT OpenCode session (defensive: this should\n * never happen in practice because each chat mints a new session token, but we\n * fail closed instead of silently overwriting).\n *\n * Idempotent when the row is already bound to the same OpenCode session id.\n */\nexport async function bindOpencodeSessionToApiKey(\n em: EntityManager,\n sessionToken: string,\n opencodeSessionId: string\n): Promise<void> {\n if (!sessionToken) throw new Error('Session token not found or expired')\n if (!opencodeSessionId) throw new Error('OpenCode session id is required')\n\n const row = await findApiKeyBySessionToken(em, sessionToken)\n if (!row) throw new Error('Session token not found or expired')\n\n if (row.opencodeSessionId === opencodeSessionId) return\n if (row.opencodeSessionId && row.opencodeSessionId !== opencodeSessionId) {\n throw new Error('Session token already bound to a different OpenCode session')\n }\n\n row.opencodeSessionId = opencodeSessionId\n await em.persist(row).flush()\n}\n\n/**\n * Find an api_key row by its bound OpenCode session id.\n *\n * Returns null if no active row matches, or if the matched row is expired\n * (same contract as `findApiKeyBySessionToken`). Uses\n * `findOneWithDecryption` so encrypted-at-rest fields on the row are decrypted\n * before the ai-assistant runtime inspects `sessionUserId` / `tenantId` /\n * `organizationId` for the ownership check.\n */\nexport async function findApiKeyByOpencodeSessionId(\n em: EntityManager,\n opencodeSessionId: string\n): Promise<ApiKey | null> {\n if (!opencodeSessionId) return null\n\n const record = await findOneWithDecryption(\n em,\n ApiKey,\n { opencodeSessionId, deletedAt: null } as any,\n )\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Find a session API key with its decrypted secret.\n * Returns null if not found, expired, deleted, or decryption fails.\n * This is used by the MCP server to recover the API key secret for making\n * authenticated API calls on behalf of the user.\n */\nexport async function findSessionApiKeyWithSecret(\n em: EntityManager,\n sessionToken: string\n): Promise<{ key: ApiKey; secret: string } | null> {\n const record = await findApiKeyBySessionToken(em, sessionToken)\n if (!record) return null\n\n // If no encrypted secret stored, cannot recover\n if (!record.sessionSecretEncrypted) {\n logger.warn('Session key has no encrypted secret', { apiKeyId: record.id })\n return null\n }\n\n // Decrypt the secret\n const secret = await decryptSessionSecret(record.sessionSecretEncrypted, record.tenantId ?? null)\n if (!secret) {\n logger.warn('Failed to decrypt session secret', { apiKeyId: record.id })\n return null\n }\n\n return { key: record, secret }\n}\n\n/**\n * Delete an ephemeral API key by its session token.\n */\nexport async function deleteSessionApiKey(\n em: EntityManager,\n sessionToken: string\n): Promise<void> {\n // Looked up and re-checked by hash, never by the raw token (#2254). Deliberately does not\n // call findApiKeyBySessionToken: that helper also drops already-expired rows, but deleting\n // an expired-but-not-yet-cleaned-up row must still work here.\n const sessionTokenHash = hashSessionToken(sessionToken)\n let candidate = await em.findOne(ApiKey, { sessionTokenHash, deletedAt: null })\n if (!candidate) {\n // Version-skew fallback (#7304): see findApiKeyBySessionToken for the full rationale \u2014 a\n // row minted by pre-#2254 code during a deploy window is plaintext-only until touched.\n const legacyCandidate = await em.findOne(ApiKey, { sessionToken, deletedAt: null })\n if (legacyCandidate) {\n legacyCandidate.sessionTokenHash = sessionTokenHash\n legacyCandidate.sessionToken = null\n await em.persist(legacyCandidate).flush()\n candidate = legacyCandidate\n }\n }\n if (!candidate) return\n let deletedId: string | null = null\n await withAtomicFlush(em, [async () => {\n const records = await lockAuthorizationApiKeyRows(em, [String(candidate.id)])\n const record = records.find((entry) => (\n String(entry.id) === String(candidate.id)\n && entry.sessionTokenHash === sessionTokenHash\n && !entry.deletedAt\n ))\n if (!record) return\n record.deletedAt = new Date()\n await em.persist(record).flush()\n deletedId = String(record.id)\n }], { transaction: true, label: 'api_keys.session.delete' })\n if (deletedId) getSharedApiKeyAuthCache().invalidateByKeyId(deletedId)\n}\n\n/**\n * Execute a function with a one-time API key\n *\n * Creates a temporary API key, executes the function, and deletes the key.\n * Perfect for workflow activities that need authenticated access without\n * storing long-lived credentials.\n *\n * @param em - Entity manager\n * @param input - API key configuration\n * @param fn - Function to execute with the API key secret\n * @returns Result of the function\n */\nconst ONETIME_KEY_MAX_TTL_MS = 5 * 60 * 1000\n\nexport async function withOnetimeApiKey<T>(\n em: EntityManager,\n input: CreateApiKeyInput,\n fn: (secret: string) => Promise<T>\n): Promise<T> {\n const maxExpiresAt = new Date(Date.now() + ONETIME_KEY_MAX_TTL_MS)\n const safeExpiresAt = input.expiresAt && input.expiresAt < maxExpiresAt\n ? input.expiresAt\n : maxExpiresAt\n\n const { record, secret } = await createApiKey(em, {\n ...input,\n name: input.name || '__onetime__',\n description: input.description || 'One-time API key',\n expiresAt: safeExpiresAt,\n })\n\n try {\n const result = await fn(secret)\n return result\n } finally {\n try {\n await deleteApiKey(em, String(record.id))\n } catch (error) {\n logger.error('Failed to soft-delete one-time API key', { err: error })\n }\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,aAAa,kBAAkB;AAExC,SAAS,MAAM,eAAe;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B,CAAC,GAAG,EAAE,aAAa,MAAM,OAAO,0BAA0B,CAAC;AAC3D,MAAI,UAAW,0BAAyB,EAAE,kBAAkB,SAAS;AACvE;AAcA,MAAM,yBAAyB,IAAI,KAAK;AAExC,eAAsB,kBACpB,IACA,OACA,IACY;AACZ,QAAM,eAAe,IAAI,KAAK,KAAK,IAAI,IAAI,sBAAsB;AACjE,QAAM,gBAAgB,MAAM,aAAa,MAAM,YAAY,eACvD,MAAM,YACN;AAEJ,QAAM,EAAE,QAAQ,OAAO,IAAI,MAAM,aAAa,IAAI;AAAA,IAChD,GAAG;AAAA,IACH,MAAM,MAAM,QAAQ;AAAA,IACpB,aAAa,MAAM,eAAe;AAAA,IAClC,WAAW;AAAA,EACb,CAAC;AAED,MAAI;AACF,UAAM,SAAS,MAAM,GAAG,MAAM;AAC9B,WAAO;AAAA,EACT,UAAE;AACA,QAAI;AACF,YAAM,aAAa,IAAI,OAAO,OAAO,EAAE,CAAC;AAAA,IAC1C,SAAS,OAAO;AACd,aAAO,MAAM,0CAA0C,EAAE,KAAK,MAAM,CAAC;AAAA,IACvE;AAAA,EACF;AACF;",
6
6
  "names": ["encrypted"]
7
7
  }
@@ -1,3 +1,5 @@
1
+ import { createAttachmentAccessContext, evaluateAttachmentAccess } from "../../../lib/access-runner.js";
2
+ import { attachmentAccessErrorResponse } from "../../../lib/access-errors.js";
1
3
  import { NextResponse } from "next/server";
2
4
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
3
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
@@ -58,11 +60,17 @@ async function GET(req, context) {
58
60
  { status: 500 }
59
61
  );
60
62
  }
61
- const access = checkAttachmentAccess(scopedAuth, attachment, partition);
62
- if (!access.ok) {
63
- const message = access.status === 401 ? "Unauthorized" : "Forbidden";
64
- return NextResponse.json({ error: message }, { status: access.status });
65
- }
63
+ const url = new URL(req.url);
64
+ const forceDownload = url.searchParams.get("download") === "1";
65
+ const renderInline = !forceDownload && canRenderInlineAttachment(attachment.mimeType);
66
+ const access = await evaluateAttachmentAccess({
67
+ auth: scopedAuth,
68
+ attachment,
69
+ partition,
70
+ action: renderInline ? "render" : "read",
71
+ context: createAttachmentAccessContext(container)
72
+ });
73
+ if (!access.ok) return attachmentAccessErrorResponse(access);
66
74
  const driver = await storageDriverFactory.resolveForPartition(attachment.partitionCode, {
67
75
  tenantId: attachment.tenantId ?? "",
68
76
  organizationId: attachment.organizationId ?? ""
@@ -74,11 +82,8 @@ async function GET(req, context) {
74
82
  } catch {
75
83
  return NextResponse.json({ error: "File not available" }, { status: 404 });
76
84
  }
77
- const url = new URL(req.url);
78
- const forceDownload = url.searchParams.get("download") === "1";
79
- const renderInline = !forceDownload && canRenderInlineAttachment(attachment.mimeType);
80
85
  const headers = {
81
- "Cache-Control": checkAttachmentAccess(null, attachment, partition).ok ? "public, max-age=86400" : "private, max-age=60",
86
+ "Cache-Control": access.protected ? "private, no-store" : checkAttachmentAccess(null, attachment, partition).ok ? "public, max-age=86400" : "private, max-age=60",
82
87
  "Content-Security-Policy": "default-src 'none'; sandbox",
83
88
  "Content-Type": renderInline ? attachment.mimeType || "application/octet-stream" : "application/octet-stream",
84
89
  "Content-Disposition": buildAttachmentContentDisposition(
@@ -132,7 +137,8 @@ const openApi = {
132
137
  status: 500,
133
138
  description: "Partition misconfigured",
134
139
  schema: attachmentErrorSchema
135
- }
140
+ },
141
+ { status: 504, description: "Owner authorization timed out", schema: attachmentErrorSchema }
136
142
  ]
137
143
  }
138
144
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/attachments/api/file/%5Bid%5D/route.ts"],
4
- "sourcesContent": ["import { NextRequest, NextResponse } from \"next/server\";\nimport type { OpenApiRouteDoc } from \"@open-mercato/shared/lib/openapi\";\nimport { getAuthFromRequest } from \"@open-mercato/shared/lib/auth/server\";\nimport { createRequestContainer } from \"@open-mercato/shared/lib/di/container\";\nimport {\n Attachment,\n AttachmentPartition,\n} from \"@open-mercato/core/modules/attachments/data/entities\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport { checkAttachmentAccess, isSuperAdminAuth } from \"@open-mercato/core/modules/attachments/lib/access\";\nimport { z } from \"zod\";\nimport { attachmentsTag, attachmentErrorSchema } from \"../../openapi\";\nimport {\n buildAttachmentContentDisposition,\n canRenderInlineAttachment,\n} from \"@open-mercato/core/modules/attachments/lib/security\";\nimport { StorageDriverFactory } from '../../../lib/drivers';\nimport { resolveAttachmentRequestScope } from '@open-mercato/core/modules/attachments/lib/requestScope';\n\nexport const metadata = {\n GET: { requireAuth: false },\n};\n\nexport async function GET(\n req: NextRequest,\n context: { params: Promise<{ id: string }> },\n) {\n const { id } = await context.params;\n if (!id) {\n return NextResponse.json(\n { error: \"Attachment id is required\" },\n { status: 400 },\n );\n }\n const auth = await getAuthFromRequest(req);\n const container = await createRequestContainer();\n const em = container.resolve(\"em\") as EntityManager;\n const storageDriverFactory =\n (container.resolve(\"storageDriverFactory\") as StorageDriverFactory | null) ??\n new StorageDriverFactory(em);\n\n const requestScope = await resolveAttachmentRequestScope(container, auth, req);\n if (requestScope.denied) {\n return NextResponse.json(\n { error: \"Attachment not found\" },\n { status: 404 },\n );\n }\n const scopedAuth = auth ? { ...auth, orgId: requestScope.organizationId } : auth;\n const findFilter: Record<string, unknown> = { id };\n if (scopedAuth && !isSuperAdminAuth(scopedAuth)) {\n if (scopedAuth.tenantId) findFilter.tenantId = scopedAuth.tenantId;\n if (scopedAuth.orgId) findFilter.organizationId = scopedAuth.orgId;\n }\n const attachment = await em.findOne(Attachment, findFilter);\n if (!attachment) {\n return NextResponse.json(\n { error: \"Attachment not found\" },\n { status: 404 },\n );\n }\n const partition = await em.findOne(AttachmentPartition, {\n code: attachment.partitionCode,\n });\n if (!partition) {\n return NextResponse.json(\n { error: \"Partition misconfigured\" },\n { status: 500 },\n );\n }\n\n const access = checkAttachmentAccess(scopedAuth, attachment, partition);\n if (!access.ok) {\n const message = access.status === 401 ? \"Unauthorized\" : \"Forbidden\";\n return NextResponse.json({ error: message }, { status: access.status });\n }\n\n const driver = await storageDriverFactory.resolveForPartition(attachment.partitionCode, {\n tenantId: attachment.tenantId ?? '',\n organizationId: attachment.organizationId ?? '',\n });\n let buffer: Buffer;\n try {\n const result = await driver.read(attachment.partitionCode, attachment.storagePath);\n buffer = result.buffer;\n } catch {\n return NextResponse.json({ error: \"File not available\" }, { status: 404 });\n }\n\n const url = new URL(req.url);\n const forceDownload = url.searchParams.get(\"download\") === \"1\";\n const renderInline = !forceDownload && canRenderInlineAttachment(attachment.mimeType);\n const headers: Record<string, string> = {\n \"Cache-Control\": checkAttachmentAccess(null, attachment, partition).ok\n ? \"public, max-age=86400\"\n : \"private, max-age=60\",\n \"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n \"Content-Type\": renderInline\n ? attachment.mimeType || \"application/octet-stream\"\n : \"application/octet-stream\",\n \"Content-Disposition\": buildAttachmentContentDisposition(\n attachment.fileName,\n renderInline ? \"inline\" : \"attachment\",\n ),\n \"X-Content-Type-Options\": \"nosniff\",\n };\n if (attachment.fileSize > 0) {\n headers[\"Content-Length\"] = String(attachment.fileSize);\n }\n\n const responseBody = new Uint8Array(buffer);\n\n return new NextResponse(responseBody, { status: 200, headers });\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: attachmentsTag,\n summary: \"Download attachment file\",\n methods: {\n GET: {\n summary: \"Download or serve attachment file\",\n description:\n \"Returns the raw file content for an attachment. Path parameter: {id} - Attachment UUID. Query parameter: ?download=1 - Force file download with Content-Disposition header. Access control is enforced based on partition settings.\",\n responses: [\n {\n status: 200,\n description: \"File content with appropriate MIME type\",\n schema: z.any().describe(\"Binary file content\"),\n },\n ],\n errors: [\n {\n status: 400,\n description: \"Missing attachment ID\",\n schema: attachmentErrorSchema,\n },\n {\n status: 401,\n description:\n \"Unauthorized - authentication required for private partitions\",\n schema: attachmentErrorSchema,\n },\n {\n status: 403,\n description: \"Forbidden - insufficient permissions\",\n schema: attachmentErrorSchema,\n },\n {\n status: 404,\n description: \"Attachment or file not found\",\n schema: attachmentErrorSchema,\n },\n {\n status: 500,\n description: \"Partition misconfigured\",\n schema: attachmentErrorSchema,\n },\n ],\n },\n },\n};\n"],
5
- "mappings": "AAAA,SAAsB,oBAAoB;AAE1C,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,uBAAuB,wBAAwB;AACxD,SAAS,SAAS;AAClB,SAAS,gBAAgB,6BAA6B;AACtD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAEvC,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM;AAC5B;AAEA,eAAsB,IACpB,KACA,SACA;AACA,QAAM,EAAE,GAAG,IAAI,MAAM,QAAQ;AAC7B,MAAI,CAAC,IAAI;AACP,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,4BAA4B;AAAA,MACrC,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACA,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,QAAM,uBACH,UAAU,QAAQ,sBAAsB,KACzC,IAAI,qBAAqB,EAAE;AAE7B,QAAM,eAAe,MAAM,8BAA8B,WAAW,MAAM,GAAG;AAC7E,MAAI,aAAa,QAAQ;AACvB,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,uBAAuB;AAAA,MAChC,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACA,QAAM,aAAa,OAAO,EAAE,GAAG,MAAM,OAAO,aAAa,eAAe,IAAI;AAC5E,QAAM,aAAsC,EAAE,GAAG;AACjD,MAAI,cAAc,CAAC,iBAAiB,UAAU,GAAG;AAC/C,QAAI,WAAW,SAAU,YAAW,WAAW,WAAW;AA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A;AAAA,IACJ,2BAA2B;AAAA,IAC3B,gBAAgB,eACZ,WAAW,YAAY,6BACvB;AAAA,IACJ,uBAAuB;AAAA,MACrB,WAAW;AAAA,MACX,eAAe,WAAW;AAAA,IAC5B;AAAA,IACA,0BAA0B;AAAA,EAC5B;AACA,MAAI,WAAW,WAAW,GAAG;AAC3B,YAAQ,gBAAgB,IAAI,OAAO,WAAW,QAAQ;AAAA,EACxD;AAEA,QAAM,eAAe,IAAI,WAAW,MAAM;AAE1C,SAAO,IAAI,aAAa,cAAc,EAAE,QAAQ,KAAK,QAAQ,CAAC;AAChE;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aACE;AAAA,MACF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,IAAI,EAAE,SAAS,qBAAqB;AAAA,QAChD;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aACE;AAAA,UACF,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { createAttachmentAccessContext, evaluateAttachmentAccess } from '../../../lib/access-runner'\nimport { attachmentAccessErrorResponse } from '../../../lib/access-errors'\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { OpenApiRouteDoc } from \"@open-mercato/shared/lib/openapi\";\nimport { getAuthFromRequest } from \"@open-mercato/shared/lib/auth/server\";\nimport { createRequestContainer } from \"@open-mercato/shared/lib/di/container\";\nimport {\n Attachment,\n AttachmentPartition,\n} from \"@open-mercato/core/modules/attachments/data/entities\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport { checkAttachmentAccess, isSuperAdminAuth } from \"@open-mercato/core/modules/attachments/lib/access\";\nimport { z } from \"zod\";\nimport { attachmentsTag, attachmentErrorSchema } from \"../../openapi\";\nimport {\n buildAttachmentContentDisposition,\n canRenderInlineAttachment,\n} from \"@open-mercato/core/modules/attachments/lib/security\";\nimport { StorageDriverFactory } from '../../../lib/drivers';\nimport { resolveAttachmentRequestScope } from '@open-mercato/core/modules/attachments/lib/requestScope';\n\nexport const metadata = {\n GET: { requireAuth: false },\n};\n\nexport async function GET(\n req: NextRequest,\n context: { params: Promise<{ id: string }> },\n) {\n const { id } = await context.params;\n if (!id) {\n return NextResponse.json(\n { error: \"Attachment id is required\" },\n { status: 400 },\n );\n }\n const auth = await getAuthFromRequest(req);\n const container = await createRequestContainer();\n const em = container.resolve(\"em\") as EntityManager;\n const storageDriverFactory =\n (container.resolve(\"storageDriverFactory\") as StorageDriverFactory | null) ??\n new StorageDriverFactory(em);\n\n const requestScope = await resolveAttachmentRequestScope(container, auth, req);\n if (requestScope.denied) {\n return NextResponse.json(\n { error: \"Attachment not found\" },\n { status: 404 },\n );\n }\n const scopedAuth = auth ? { ...auth, orgId: requestScope.organizationId } : auth;\n const findFilter: Record<string, unknown> = { id };\n if (scopedAuth && !isSuperAdminAuth(scopedAuth)) {\n if (scopedAuth.tenantId) findFilter.tenantId = scopedAuth.tenantId;\n if (scopedAuth.orgId) findFilter.organizationId = scopedAuth.orgId;\n }\n const attachment = await em.findOne(Attachment, findFilter);\n if (!attachment) {\n return NextResponse.json(\n { error: \"Attachment not found\" },\n { status: 404 },\n );\n }\n const partition = await em.findOne(AttachmentPartition, {\n code: attachment.partitionCode,\n });\n if (!partition) {\n return NextResponse.json(\n { error: \"Partition misconfigured\" },\n { status: 500 },\n );\n }\n\n const url = new URL(req.url);\n const forceDownload = url.searchParams.get(\"download\") === \"1\";\n const renderInline = !forceDownload && canRenderInlineAttachment(attachment.mimeType);\n const access = await evaluateAttachmentAccess({\n auth: scopedAuth, attachment, partition, action: renderInline ? 'render' : 'read',\n context: createAttachmentAccessContext(container),\n });\n if (!access.ok) return attachmentAccessErrorResponse(access);\n\n const driver = await storageDriverFactory.resolveForPartition(attachment.partitionCode, {\n tenantId: attachment.tenantId ?? '',\n organizationId: attachment.organizationId ?? '',\n });\n let buffer: Buffer;\n try {\n const result = await driver.read(attachment.partitionCode, attachment.storagePath);\n buffer = result.buffer;\n } catch {\n return NextResponse.json({ error: \"File not available\" }, { status: 404 });\n }\n\n const headers: Record<string, string> = {\n \"Cache-Control\": access.protected ? \"private, no-store\" : checkAttachmentAccess(null, attachment, partition).ok\n ? \"public, max-age=86400\"\n : \"private, max-age=60\",\n \"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n \"Content-Type\": renderInline\n ? attachment.mimeType || \"application/octet-stream\"\n : \"application/octet-stream\",\n \"Content-Disposition\": buildAttachmentContentDisposition(\n attachment.fileName,\n renderInline ? \"inline\" : \"attachment\",\n ),\n \"X-Content-Type-Options\": \"nosniff\",\n };\n if (attachment.fileSize > 0) {\n headers[\"Content-Length\"] = String(attachment.fileSize);\n }\n\n const responseBody = new Uint8Array(buffer);\n\n return new NextResponse(responseBody, { status: 200, headers });\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: attachmentsTag,\n summary: \"Download attachment file\",\n methods: {\n GET: {\n summary: \"Download or serve attachment file\",\n description:\n \"Returns the raw file content for an attachment. Path parameter: {id} - Attachment UUID. Query parameter: ?download=1 - Force file download with Content-Disposition header. Access control is enforced based on partition settings.\",\n responses: [\n {\n status: 200,\n description: \"File content with appropriate MIME type\",\n schema: z.any().describe(\"Binary file content\"),\n },\n ],\n errors: [\n {\n status: 400,\n description: \"Missing attachment ID\",\n schema: attachmentErrorSchema,\n },\n {\n status: 401,\n description:\n \"Unauthorized - authentication required for private partitions\",\n schema: attachmentErrorSchema,\n },\n {\n status: 403,\n description: \"Forbidden - insufficient permissions\",\n schema: attachmentErrorSchema,\n },\n {\n status: 404,\n description: \"Attachment or file not found\",\n schema: attachmentErrorSchema,\n },\n {\n status: 500,\n description: \"Partition misconfigured\",\n schema: attachmentErrorSchema,\n },\n { status: 504, description: 'Owner authorization timed out', schema: attachmentErrorSchema },\n ],\n },\n },\n};\n"],
5
+ "mappings": "AAAA,SAAS,+BAA+B,gCAAgC;AACxE,SAAS,qCAAqC;AAC9C,SAAsB,oBAAoB;AAE1C,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,uBAAuB,wBAAwB;AACxD,SAAS,SAAS;AAClB,SAAS,gBAAgB,6BAA6B;AACtD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAEvC,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM;AAC5B;AAEA,eAAsB,IACpB,KACA,SACA;AACA,QAAM,EAAE,GAAG,IAAI,MAAM,QAAQ;AAC7B,MAAI,CAAC,IAAI;AACP,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,4BAA4B;AAAA,MACrC,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACA,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,QAAM,uBACH,UAAU,QAAQ,sBAAsB,KACzC,IAAI,qBAAqB,EAAE;AAE7B,QAAM,eAAe,MAAM,8BAA8B,WAAW,MAAM,GAAG;AAC7E,MAAI,aAAa,QAAQ;AACvB,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,uBAAuB;AAAA,MAChC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