@open-mercato/documents 0.9.1-develop.7575.1.8480826a9b → 0.10.0

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 (97) hide show
  1. package/dist/contentSecurityPolicy.js +23 -0
  2. package/dist/contentSecurityPolicy.js.map +7 -0
  3. package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
  4. package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
  5. package/dist/modules/documents/api/[id]/comments/route.js +2 -0
  6. package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
  7. package/dist/modules/documents/api/[id]/content/route.js +2 -0
  8. package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
  9. package/dist/modules/documents/api/[id]/route.js +3 -0
  10. package/dist/modules/documents/api/[id]/route.js.map +2 -2
  11. package/dist/modules/documents/api/[id]/shares/route.js +2 -0
  12. package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
  13. package/dist/modules/documents/api/[id]/versions/route.js +2 -0
  14. package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
  15. package/dist/modules/documents/api/_shared.js +10 -27
  16. package/dist/modules/documents/api/_shared.js.map +3 -3
  17. package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
  18. package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
  19. package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
  20. package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
  21. package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
  22. package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
  23. package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
  24. package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
  25. package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
  26. package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
  27. package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
  28. package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
  29. package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
  30. package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
  31. package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
  32. package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
  33. package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
  34. package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
  35. package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
  36. package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
  37. package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
  38. package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
  39. package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
  40. package/dist/modules/documents/commands/comments.js +2 -2
  41. package/dist/modules/documents/commands/comments.js.map +2 -2
  42. package/dist/modules/documents/commands/folders.js +1 -0
  43. package/dist/modules/documents/commands/folders.js.map +2 -2
  44. package/dist/modules/documents/commands/interceptors.js +11 -0
  45. package/dist/modules/documents/commands/interceptors.js.map +2 -2
  46. package/dist/modules/documents/data/attachment-access.js +84 -0
  47. package/dist/modules/documents/data/attachment-access.js.map +7 -0
  48. package/dist/modules/documents/data/validators.js +11 -0
  49. package/dist/modules/documents/data/validators.js.map +2 -2
  50. package/dist/modules/documents/lib/actor.js +32 -0
  51. package/dist/modules/documents/lib/actor.js.map +7 -0
  52. package/dist/modules/documents/lib/collabMaterializer.js +52 -9
  53. package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
  54. package/dist/modules/documents/lib/collabPersistence.js +13 -0
  55. package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
  56. package/dist/modules/documents/lib/permissions.js +35 -2
  57. package/dist/modules/documents/lib/permissions.js.map +2 -2
  58. package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
  59. package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
  60. package/dist/modules/documents/widgets/injection-table.js +12 -3
  61. package/dist/modules/documents/widgets/injection-table.js.map +2 -2
  62. package/dist/server/documents-collab-server.js +74 -1
  63. package/dist/server/documents-collab-server.js.map +2 -2
  64. package/jest.config.cjs +1 -1
  65. package/package.json +37 -37
  66. package/server/documents-collab-server.ts +79 -0
  67. package/src/contentSecurityPolicy.ts +21 -0
  68. package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
  69. package/src/modules/documents/api/[id]/comments/route.ts +2 -0
  70. package/src/modules/documents/api/[id]/content/route.ts +2 -0
  71. package/src/modules/documents/api/[id]/route.ts +3 -0
  72. package/src/modules/documents/api/[id]/shares/route.ts +2 -0
  73. package/src/modules/documents/api/[id]/versions/route.ts +2 -0
  74. package/src/modules/documents/api/_shared.ts +10 -36
  75. package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
  76. package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
  77. package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
  78. package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
  79. package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
  80. package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
  81. package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
  82. package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
  83. package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
  84. package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
  85. package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
  86. package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
  87. package/src/modules/documents/commands/comments.ts +2 -2
  88. package/src/modules/documents/commands/folders.ts +1 -3
  89. package/src/modules/documents/commands/interceptors.ts +11 -0
  90. package/src/modules/documents/data/attachment-access.ts +83 -0
  91. package/src/modules/documents/data/validators.ts +12 -0
  92. package/src/modules/documents/lib/actor.ts +39 -0
  93. package/src/modules/documents/lib/collabMaterializer.ts +62 -11
  94. package/src/modules/documents/lib/collabPersistence.ts +10 -0
  95. package/src/modules/documents/lib/permissions.ts +52 -0
  96. package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
  97. package/src/modules/documents/widgets/injection-table.ts +17 -3
@@ -0,0 +1,84 @@
1
+ import { z } from "zod";
2
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
+ import { resolveActorUserId } from "../lib/actor.js";
4
+ import { deriveDocumentCapabilities } from "../lib/capabilities.js";
5
+ import { loadScopedDocument, resolveActiveSubjectRoleIds, resolvePermission } from "../lib/permissions.js";
6
+ const ownerIdSchema = z.string().uuid();
7
+ const resolverId = "documents.document-attachments";
8
+ async function capabilitiesForDocument(input, documentId) {
9
+ const { subject, container, cache, signal } = input;
10
+ const { tenantId, organizationId } = subject;
11
+ if (!tenantId || !organizationId || !ownerIdSchema.safeParse(documentId).success || signal.aborted) return null;
12
+ let actorUserId;
13
+ try {
14
+ actorUserId = resolveActorUserId(subject.auth);
15
+ } catch (error) {
16
+ if (isCrudHttpError(error) && error.status === 403) return null;
17
+ throw error;
18
+ }
19
+ const principalKey = JSON.stringify([subject.auth.sub, tenantId, organizationId]);
20
+ const cacheKey = JSON.stringify(["document", principalKey, documentId]);
21
+ const cached = cache.get(cacheKey);
22
+ if (cached) return cached;
23
+ const pending = (async () => {
24
+ const em = container.resolve("em");
25
+ const document = await loadScopedDocument(em, documentId, { tenantId, organizationId });
26
+ if (!document || signal.aborted) return null;
27
+ const roleKey = JSON.stringify(["roles", principalKey]);
28
+ let roles = cache.get(roleKey);
29
+ if (!roles) {
30
+ roles = resolveActiveSubjectRoleIds(container, { tenantId, organizationId }, subject.auth.sub);
31
+ cache.set(roleKey, roles);
32
+ }
33
+ const projectedAuth = {
34
+ ...subject.auth,
35
+ userId: actorUserId,
36
+ tenantId,
37
+ orgId: organizationId,
38
+ organizationId,
39
+ resolvedRoleIds: await roles,
40
+ features: [...subject.userFeatures],
41
+ isSuperAdmin: subject.isSuperAdmin
42
+ };
43
+ if (signal.aborted) return null;
44
+ const relationshipTier = await resolvePermission(em, documentId, projectedAuth);
45
+ return deriveDocumentCapabilities({
46
+ relationshipTier,
47
+ managerOverride: subject.userFeatures.includes("documents.manage"),
48
+ archived: document.archivedAt !== null && document.archivedAt !== void 0,
49
+ userFeatures: subject.userFeatures
50
+ });
51
+ })();
52
+ cache.set(cacheKey, pending);
53
+ return pending;
54
+ }
55
+ const attachmentAccessResolvers = [{
56
+ id: resolverId,
57
+ targetPartition: "*",
58
+ targetEntity: "documents:document",
59
+ async resolve(input) {
60
+ const targets = input.targets.filter((target) => target.entityId === "documents:document");
61
+ if (targets.some((target) => !ownerIdSchema.safeParse(target.recordId).success)) {
62
+ return { ok: false, status: 404, reason: "document_not_found" };
63
+ }
64
+ const requireEvery = input.action !== "read" && input.action !== "render";
65
+ let visible = false;
66
+ for (const target of targets) {
67
+ const capabilities = await capabilitiesForDocument(input, target.recordId);
68
+ const allowed = input.action === "delete" || input.action === "reassign" ? capabilities?.canEdit === true : capabilities?.canView === true;
69
+ if (!allowed && requireEvery) return { ok: false, status: 404, reason: "document_not_found" };
70
+ if (allowed) visible = true;
71
+ }
72
+ return visible ? { ok: true } : { ok: false, status: 404, reason: "document_not_found" };
73
+ }
74
+ }];
75
+ const protectedAttachmentTargets = [{
76
+ resolverId,
77
+ targetPartition: "*",
78
+ targetEntity: "documents:document"
79
+ }];
80
+ export {
81
+ attachmentAccessResolvers,
82
+ protectedAttachmentTargets
83
+ };
84
+ //# sourceMappingURL=attachment-access.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/documents/data/attachment-access.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { AttachmentAccessInput, AttachmentAccessResolver, ProtectedAttachmentTarget } from '@open-mercato/core/modules/attachments'\nimport { resolveActorUserId } from '../lib/actor'\nimport { deriveDocumentCapabilities, type DocumentCapabilities } from '../lib/capabilities'\nimport { loadScopedDocument, resolveActiveSubjectRoleIds, resolvePermission } from '../lib/permissions'\n\nconst ownerIdSchema = z.string().uuid()\nconst resolverId = 'documents.document-attachments'\n\nasync function capabilitiesForDocument(input: AttachmentAccessInput, documentId: string): Promise<DocumentCapabilities | null> {\n const { subject, container, cache, signal } = input\n const { tenantId, organizationId } = subject\n if (!tenantId || !organizationId || !ownerIdSchema.safeParse(documentId).success || signal.aborted) return null\n let actorUserId: string\n try {\n actorUserId = resolveActorUserId(subject.auth)\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 403) return null\n throw error\n }\n const principalKey = JSON.stringify([subject.auth.sub, tenantId, organizationId])\n const cacheKey = JSON.stringify(['document', principalKey, documentId])\n const cached = cache.get(cacheKey) as Promise<DocumentCapabilities | null> | undefined\n if (cached) return cached\n const pending = (async () => {\n const em = container.resolve<EntityManager>('em')\n const document = await loadScopedDocument(em, documentId, { tenantId, organizationId })\n if (!document || signal.aborted) return null\n const roleKey = JSON.stringify(['roles', principalKey])\n let roles = cache.get(roleKey) as Promise<string[]> | undefined\n if (!roles) {\n roles = resolveActiveSubjectRoleIds(container, { tenantId, organizationId }, subject.auth.sub)\n cache.set(roleKey, roles)\n }\n const projectedAuth = {\n ...subject.auth,\n userId: actorUserId,\n tenantId, orgId: organizationId, organizationId,\n resolvedRoleIds: await roles,\n features: [...subject.userFeatures],\n isSuperAdmin: subject.isSuperAdmin,\n }\n if (signal.aborted) return null\n const relationshipTier = await resolvePermission(em, documentId, projectedAuth)\n return deriveDocumentCapabilities({\n relationshipTier,\n managerOverride: subject.userFeatures.includes('documents.manage'),\n archived: document.archivedAt !== null && document.archivedAt !== undefined,\n userFeatures: subject.userFeatures,\n })\n })()\n cache.set(cacheKey, pending)\n return pending\n}\n\nexport const attachmentAccessResolvers: AttachmentAccessResolver[] = [{\n id: resolverId,\n targetPartition: '*',\n targetEntity: 'documents:document',\n async resolve(input) {\n const targets = input.targets.filter((target) => target.entityId === 'documents:document')\n if (targets.some((target) => !ownerIdSchema.safeParse(target.recordId).success)) {\n return { ok: false, status: 404, reason: 'document_not_found' }\n }\n const requireEvery = input.action !== 'read' && input.action !== 'render'\n let visible = false\n for (const target of targets) {\n const capabilities = await capabilitiesForDocument(input, target.recordId)\n const allowed = input.action === 'delete' || input.action === 'reassign'\n ? capabilities?.canEdit === true\n : capabilities?.canView === true\n if (!allowed && requireEvery) return { ok: false, status: 404, reason: 'document_not_found' }\n if (allowed) visible = true\n }\n return visible ? { ok: true } : { ok: false, status: 404, reason: 'document_not_found' }\n },\n}]\n\nexport const protectedAttachmentTargets: ProtectedAttachmentTarget[] = [{\n resolverId, targetPartition: '*', targetEntity: 'documents:document',\n}]\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAElB,SAAS,uBAAuB;AAEhC,SAAS,0BAA0B;AACnC,SAAS,kCAA6D;AACtE,SAAS,oBAAoB,6BAA6B,yBAAyB;AAEnF,MAAM,gBAAgB,EAAE,OAAO,EAAE,KAAK;AACtC,MAAM,aAAa;AAEnB,eAAe,wBAAwB,OAA8B,YAA0D;AAC7H,QAAM,EAAE,SAAS,WAAW,OAAO,OAAO,IAAI;AAC9C,QAAM,EAAE,UAAU,eAAe,IAAI;AACrC,MAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,cAAc,UAAU,UAAU,EAAE,WAAW,OAAO,QAAS,QAAO;AAC3G,MAAI;AACJ,MAAI;AACF,kBAAc,mBAAmB,QAAQ,IAAI;AAAA,EAC/C,SAA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BAAwD,CAAC;AAAA,EACpE,IAAI;AAAA,EACJ,iBAAiB;AAAA,EACjB,cAAc;AAAA,EACd,MAAM,QAAQ,OAAO;AACnB,UAAM,UAAU,MAAM,QAAQ,OAAO,CAAC,WAAW,OAAO,aAAa,oBAAoB;AACzF,QAAI,QAAQ,KAAK,CAAC,WAAW,CAAC,cAAc,UAAU,OAAO,QAAQ,EAAE,OAAO,GAAG;AAC/E,aAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,QAAQ,qBAAqB;AAAA,IAChE;AACA,UAAM,eAAe,MAAM,WAAW,UAAU,MAAM,WAAW;AACjE,QAAI,UAAU;AACd,eAAW,UAAU,SAAS;AAC5B,YAAM,eAAe,MAAM,wBAAwB,OAAO,OAAO,QAAQ;AACzE,YAAM,UAAU,MAAM,WAAW,YAAY,MAAM,WAAW,aAC1D,cAAc,YAAY,OAC1B,cAAc,YAAY;AAC9B,UAAI,CAAC,WAAW,aAAc,QAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,QAAQ,qBAAqB;AAC5F,UAAI,QAAS,WAAU;AAAA,IACzB;AACA,WAAO,UAAU,EAAE,IAAI,KAAK,IAAI,EAAE,IAAI,OAAO,QAAQ,KAAK,QAAQ,qBAAqB;AAAA,EACzF;AACF,CAAC;AAEM,MAAM,6BAA0D,CAAC;AAAA,EACtE;AAAA,EAAY,iBAAiB;AAAA,EAAK,cAAc;AAClD,CAAC;",
6
+ "names": []
7
+ }
@@ -6,6 +6,15 @@ import {
6
6
  } from "../lib/resourceLimits.js";
7
7
  import { containsCanonicalUuid } from "../lib/displayLabels.js";
8
8
  import { DOCUMENT_VERSION_LABEL_MAX_LENGTH } from "../lib/versionLabels.js";
9
+ const collabContentSaveRequestSchema = z.object({
10
+ type: z.literal("documents.content.save"),
11
+ requestId: z.string().uuid()
12
+ });
13
+ const collabContentSaveResponseSchema = z.object({
14
+ type: z.literal("documents.content.saved"),
15
+ requestId: z.string().uuid(),
16
+ saved: z.boolean()
17
+ });
9
18
  const uuid = () => z.string().uuid("documents.validation.common.invalidUuid");
10
19
  function blankStringToNull(value) {
11
20
  if (typeof value !== "string") return value;
@@ -191,6 +200,8 @@ const documentTemplateInstantiateSchema = documentTemplateRenderBaseSchema.exten
191
200
  previewDigest: z.string().regex(/^sha256:[0-9a-f]{64}$/)
192
201
  });
193
202
  export {
203
+ collabContentSaveRequestSchema,
204
+ collabContentSaveResponseSchema,
194
205
  documentCommentAnchorWriteSchema,
195
206
  documentCommentCreateSchema,
196
207
  documentContentPutSchema,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/documents/data/validators.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport {\n DOCUMENTS_MAX_CONTENT_HTML_BYTES,\n DOCUMENTS_MAX_CONTENT_TEXT_BYTES,\n isUtf8WithinLimit,\n} from '../lib/resourceLimits'\nimport { containsCanonicalUuid } from '../lib/displayLabels'\nimport { DOCUMENT_VERSION_LABEL_MAX_LENGTH } from '../lib/versionLabels'\n\nconst uuid = () => z.string().uuid('documents.validation.common.invalidUuid')\n\nfunction blankStringToNull(value: unknown): unknown {\n if (typeof value !== 'string') return value\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction requiredTrimmedString(max: number, message: string) {\n return z.string().trim().min(1, { message }).max(max)\n}\n\nexport const documentEntityLabelSchema = requiredTrimmedString(\n 512,\n 'documents.validation.links.labelRequired',\n).refine((label) => !containsCanonicalUuid(label), {\n message: 'documents.validation.links.readableLabelRequired',\n})\n\nexport const documentVersionLabelSchema = z.preprocess(\n blankStringToNull,\n z.string()\n .trim()\n .max(DOCUMENT_VERSION_LABEL_MAX_LENGTH)\n .refine((label) => !containsCanonicalUuid(label), {\n message: 'documents.validation.versions.readableLabelRequired',\n })\n .optional()\n .nullable(),\n)\n\nconst clearableUuidSchema = z.preprocess(\n blankStringToNull,\n uuid().optional().nullable(),\n)\n\nconst finiteNumberSchema = z.number().refine(Number.isFinite, {\n message: 'documents.validation.templates.finiteNumberRequired',\n})\n\nconst localeSchema = z.string().trim().min(2).max(64).superRefine((value, context) => {\n try {\n new Intl.Locale(value)\n } catch {\n context.addIssue({ code: 'custom', message: 'documents.validation.templates.invalidLocale' })\n }\n})\n\nconst relativePositionSchema = z.string().min(1).max(4096).regex(\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,\n 'documents.validation.comment.invalidAnchor',\n)\n\nconst legacyNumericAnchorSchema = z.object({\n from: z.number().int().min(0),\n to: z.number().int().min(0),\n}).strict().refine((anchor) => anchor.to >= anchor.from, {\n message: 'documents.validation.comment.invalidAnchor',\n})\n\nconst relativeAnchorSchema = z.object({\n version: z.literal(2),\n relativeFrom: relativePositionSchema,\n relativeTo: relativePositionSchema,\n}).strict()\n\nexport const documentCommentAnchorWriteSchema = z.union([\n legacyNumericAnchorSchema,\n relativeAnchorSchema,\n])\n\nexport type DocumentCommentAnchor = z.infer<typeof documentCommentAnchorWriteSchema>\n\nexport const documentSharePrincipalTypeSchema = z.enum(['user', 'role'])\nexport const documentSharePermissionSchema = z.enum(['viewer', 'commenter', 'editor'])\nexport const documentEntityTypeSchema = z.enum([\n 'customer-person',\n 'customer-company',\n 'deal',\n 'product',\n 'catalog-offer',\n 'quote',\n 'sales-order',\n 'document',\n])\nexport const documentEntityLinkSourceSchema = z.enum(['chip', 'template', 'related-panel'])\nexport const documentTitleSchema = requiredTrimmedString(512, 'documents.validation.title.required')\n\nexport const documentCreateSchema = z.object({\n title: documentTitleSchema,\n folderId: clearableUuidSchema,\n})\n\nexport const documentUpdateSchema = z.object({\n id: uuid(),\n title: documentTitleSchema.optional(),\n folderId: clearableUuidSchema,\n})\n\nexport const documentFolderCreateSchema = z.object({\n name: requiredTrimmedString(256, 'documents.validation.folder.nameRequired'),\n parentFolderId: clearableUuidSchema,\n})\n\nexport const documentFolderUpdateSchema = z.object({\n id: uuid(),\n name: requiredTrimmedString(256, 'documents.validation.folder.nameRequired').optional(),\n parentFolderId: clearableUuidSchema,\n})\n\nexport const documentShareCreateSchema = z.object({\n principalType: documentSharePrincipalTypeSchema,\n principalId: uuid(),\n permission: documentSharePermissionSchema,\n})\n\nexport const documentShareUpdateSchema = z.object({\n id: uuid(),\n permission: documentSharePermissionSchema,\n})\n\nexport const documentCommentCreateSchema = z.object({\n body: requiredTrimmedString(8000, 'documents.validation.comment.bodyRequired'),\n anchor: documentCommentAnchorWriteSchema.optional().nullable(),\n mentions: z.array(z.object({ userId: z.string().uuid() })).max(50).optional(),\n grantAccessTo: z.array(uuid()).max(50).optional(),\n parentCommentId: clearableUuidSchema,\n})\n\nconst documentHtmlSchema = z.string().refine(\n (value) => isUtf8WithinLimit(value, DOCUMENTS_MAX_CONTENT_HTML_BYTES),\n { message: 'documents.validation.content.tooLarge' },\n)\nconst documentTemplateHtmlSchema = z.string().max(500000).refine(\n (value) => isUtf8WithinLimit(value, DOCUMENTS_MAX_CONTENT_HTML_BYTES),\n { message: 'documents.validation.content.tooLarge' },\n)\n\nexport const documentContentPutSchema = z.object({\n contentHtml: documentHtmlSchema,\n contentText: z.string().refine(\n (value) => isUtf8WithinLimit(value, DOCUMENTS_MAX_CONTENT_TEXT_BYTES),\n { message: 'documents.validation.content.tooLarge' },\n ).optional().nullable(),\n})\n\nexport const documentTemplateContextSlotSchema = z.object({\n slot: z.string().min(1).max(64).regex(/^[a-z][a-zA-Z0-9]*$/),\n entityType: documentEntityTypeSchema,\n required: z.boolean().optional(),\n})\n\nexport const documentTemplateContextSlotsSchema = z.array(documentTemplateContextSlotSchema).max(20).superRefine(\n (slots, context) => {\n const seen = new Set<string>()\n for (const [index, slot] of slots.entries()) {\n if (seen.has(slot.slot)) {\n context.addIssue({\n code: 'custom',\n path: [index, 'slot'],\n message: 'documents.validation.templates.duplicateSlot',\n })\n }\n seen.add(slot.slot)\n }\n },\n)\n\nexport const documentTemplateCreateSchema = z.object({\n name: z.string().min(1).max(256),\n description: z.string().max(2000).nullish(),\n bodyHtml: documentTemplateHtmlSchema,\n contextSlots: documentTemplateContextSlotsSchema.nullish(),\n isActive: z.boolean().optional(),\n})\n\nexport const documentTemplateUpdateSchema = z.object({\n id: uuid(),\n name: z.string().min(1).max(256).optional(),\n description: z.string().max(2000).nullish(),\n bodyHtml: documentTemplateHtmlSchema.optional(),\n contextSlots: documentTemplateContextSlotsSchema.nullish(),\n isActive: z.boolean().optional(),\n})\n\nexport const documentEntityLinkCreateSchema = z.object({\n entityType: documentEntityTypeSchema,\n entityId: uuid(),\n label: documentEntityLabelSchema,\n href: z.string().trim().min(1).max(1024).startsWith('/backend/'),\n source: documentEntityLinkSourceSchema,\n})\n\nexport const documentTemplateFillSlotSchema = z.object({\n slot: z.string().min(1).max(64).regex(/^[a-z][a-zA-Z0-9]*$/),\n entityType: documentEntityTypeSchema,\n entityId: uuid(),\n label: documentEntityLabelSchema,\n href: z.string().trim().min(1).max(1024).startsWith('/backend/'),\n values: z.record(z.string().min(1).max(64), z.union([\n z.string().max(10000),\n finiteNumberSchema,\n z.null(),\n ])),\n})\n\nconst documentTemplateRenderBaseSchema = z.object({\n templateUpdatedAt: z.string().datetime({ offset: true }),\n title: documentTitleSchema,\n locale: localeSchema,\n effectiveDate: z.string().datetime({ offset: true }),\n slots: z.array(documentTemplateFillSlotSchema).max(20),\n})\n\nexport const documentTemplatePreviewSchema = documentTemplateRenderBaseSchema\n\nexport const documentTemplateInstantiateSchema = documentTemplateRenderBaseSchema.extend({\n templateId: uuid(),\n folderId: clearableUuidSchema,\n previewDigest: z.string().regex(/^sha256:[0-9a-f]{64}$/),\n})\n\nexport type DocumentCreateInput = z.infer<typeof documentCreateSchema>\nexport type DocumentUpdateInput = z.infer<typeof documentUpdateSchema>\nexport type DocumentFolderCreateInput = z.infer<typeof documentFolderCreateSchema>\nexport type DocumentFolderUpdateInput = z.infer<typeof documentFolderUpdateSchema>\nexport type DocumentShareCreateInput = z.infer<typeof documentShareCreateSchema>\nexport type DocumentShareUpdateInput = z.infer<typeof documentShareUpdateSchema>\nexport type DocumentCommentCreateInput = z.infer<typeof documentCommentCreateSchema>\nexport type DocumentContentPutInput = z.infer<typeof documentContentPutSchema>\nexport type DocumentTemplateContextSlotInput = z.infer<typeof documentTemplateContextSlotSchema>\nexport type DocumentTemplateCreateInput = z.infer<typeof documentTemplateCreateSchema>\nexport type DocumentTemplateUpdateInput = z.infer<typeof documentTemplateUpdateSchema>\nexport type DocumentEntityType = z.infer<typeof documentEntityTypeSchema>\nexport type DocumentEntityLinkSourceInput = z.infer<typeof documentEntityLinkSourceSchema>\nexport type DocumentEntityLinkCreateInput = z.infer<typeof documentEntityLinkCreateSchema>\nexport type DocumentTemplateFillSlotInput = z.infer<typeof documentTemplateFillSlotSchema>\nexport type DocumentTemplatePreviewInput = z.infer<typeof documentTemplatePreviewSchema>\nexport type DocumentTemplateInstantiateInput = z.infer<typeof documentTemplateInstantiateSchema>\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC,SAAS,yCAAyC;AAElD,MAAM,OAAO,MAAM,EAAE,OAAO,EAAE,KAAK,yCAAyC;AAE5E,SAAS,kBAAkB,OAAyB;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,sBAAsB,KAAa,SAAiB;AAC3D,SAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,QAAQ,CAAC,EAAE,IAAI,GAAG;AACtD;AAEO,MAAM,4BAA4B;AAAA,EACvC;AAAA,EACA;AACF,EAAE,OAAO,CAAC,UAAU,CAAC,sBAAsB,KAAK,GAAG;AAAA,EACjD,SAAS;AACX,CAAC;AAEM,MAAM,6BAA6B,EAAE;AAAA,EAC1C;AAAA,EACA,EAAE,OAAO,EACN,KA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EACvD,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,KAAK,CAAC;AAAA,EACnD,OAAO,EAAE,MAAM,8BAA8B,EAAE,IAAI,EAAE;AACvD,CAAC;AAEM,MAAM,gCAAgC;AAEtC,MAAM,oCAAoC,iCAAiC,OAAO;AAAA,EACvF,YAAY,KAAK;AAAA,EACjB,UAAU;AAAA,EACV,eAAe,EAAE,OAAO,EAAE,MAAM,uBAAuB;AACzD,CAAC;",
4
+ "sourcesContent": ["import { z } from 'zod'\n\nimport {\n DOCUMENTS_MAX_CONTENT_HTML_BYTES,\n DOCUMENTS_MAX_CONTENT_TEXT_BYTES,\n isUtf8WithinLimit,\n} from '../lib/resourceLimits'\nimport { containsCanonicalUuid } from '../lib/displayLabels'\nimport { DOCUMENT_VERSION_LABEL_MAX_LENGTH } from '../lib/versionLabels'\n\nexport const collabContentSaveRequestSchema = z.object({\n type: z.literal('documents.content.save'),\n requestId: z.string().uuid(),\n})\n\nexport const collabContentSaveResponseSchema = z.object({\n type: z.literal('documents.content.saved'),\n requestId: z.string().uuid(),\n saved: z.boolean(),\n})\n\nconst uuid = () => z.string().uuid('documents.validation.common.invalidUuid')\n\nfunction blankStringToNull(value: unknown): unknown {\n if (typeof value !== 'string') return value\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction requiredTrimmedString(max: number, message: string) {\n return z.string().trim().min(1, { message }).max(max)\n}\n\nexport const documentEntityLabelSchema = requiredTrimmedString(\n 512,\n 'documents.validation.links.labelRequired',\n).refine((label) => !containsCanonicalUuid(label), {\n message: 'documents.validation.links.readableLabelRequired',\n})\n\nexport const documentVersionLabelSchema = z.preprocess(\n blankStringToNull,\n z.string()\n .trim()\n .max(DOCUMENT_VERSION_LABEL_MAX_LENGTH)\n .refine((label) => !containsCanonicalUuid(label), {\n message: 'documents.validation.versions.readableLabelRequired',\n })\n .optional()\n .nullable(),\n)\n\nconst clearableUuidSchema = z.preprocess(\n blankStringToNull,\n uuid().optional().nullable(),\n)\n\nconst finiteNumberSchema = z.number().refine(Number.isFinite, {\n message: 'documents.validation.templates.finiteNumberRequired',\n})\n\nconst localeSchema = z.string().trim().min(2).max(64).superRefine((value, context) => {\n try {\n new Intl.Locale(value)\n } catch {\n context.addIssue({ code: 'custom', message: 'documents.validation.templates.invalidLocale' })\n }\n})\n\nconst relativePositionSchema = z.string().min(1).max(4096).regex(\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,\n 'documents.validation.comment.invalidAnchor',\n)\n\nconst legacyNumericAnchorSchema = z.object({\n from: z.number().int().min(0),\n to: z.number().int().min(0),\n}).strict().refine((anchor) => anchor.to >= anchor.from, {\n message: 'documents.validation.comment.invalidAnchor',\n})\n\nconst relativeAnchorSchema = z.object({\n version: z.literal(2),\n relativeFrom: relativePositionSchema,\n relativeTo: relativePositionSchema,\n}).strict()\n\nexport const documentCommentAnchorWriteSchema = z.union([\n legacyNumericAnchorSchema,\n relativeAnchorSchema,\n])\n\nexport type DocumentCommentAnchor = z.infer<typeof documentCommentAnchorWriteSchema>\n\nexport const documentSharePrincipalTypeSchema = z.enum(['user', 'role'])\nexport const documentSharePermissionSchema = z.enum(['viewer', 'commenter', 'editor'])\nexport const documentEntityTypeSchema = z.enum([\n 'customer-person',\n 'customer-company',\n 'deal',\n 'product',\n 'catalog-offer',\n 'quote',\n 'sales-order',\n 'document',\n])\nexport const documentEntityLinkSourceSchema = z.enum(['chip', 'template', 'related-panel'])\nexport const documentTitleSchema = requiredTrimmedString(512, 'documents.validation.title.required')\n\nexport const documentCreateSchema = z.object({\n title: documentTitleSchema,\n folderId: clearableUuidSchema,\n})\n\nexport const documentUpdateSchema = z.object({\n id: uuid(),\n title: documentTitleSchema.optional(),\n folderId: clearableUuidSchema,\n})\n\nexport const documentFolderCreateSchema = z.object({\n name: requiredTrimmedString(256, 'documents.validation.folder.nameRequired'),\n parentFolderId: clearableUuidSchema,\n})\n\nexport const documentFolderUpdateSchema = z.object({\n id: uuid(),\n name: requiredTrimmedString(256, 'documents.validation.folder.nameRequired').optional(),\n parentFolderId: clearableUuidSchema,\n})\n\nexport const documentShareCreateSchema = z.object({\n principalType: documentSharePrincipalTypeSchema,\n principalId: uuid(),\n permission: documentSharePermissionSchema,\n})\n\nexport const documentShareUpdateSchema = z.object({\n id: uuid(),\n permission: documentSharePermissionSchema,\n})\n\nexport const documentCommentCreateSchema = z.object({\n body: requiredTrimmedString(8000, 'documents.validation.comment.bodyRequired'),\n anchor: documentCommentAnchorWriteSchema.optional().nullable(),\n mentions: z.array(z.object({ userId: z.string().uuid() })).max(50).optional(),\n grantAccessTo: z.array(uuid()).max(50).optional(),\n parentCommentId: clearableUuidSchema,\n})\n\nconst documentHtmlSchema = z.string().refine(\n (value) => isUtf8WithinLimit(value, DOCUMENTS_MAX_CONTENT_HTML_BYTES),\n { message: 'documents.validation.content.tooLarge' },\n)\nconst documentTemplateHtmlSchema = z.string().max(500000).refine(\n (value) => isUtf8WithinLimit(value, DOCUMENTS_MAX_CONTENT_HTML_BYTES),\n { message: 'documents.validation.content.tooLarge' },\n)\n\nexport const documentContentPutSchema = z.object({\n contentHtml: documentHtmlSchema,\n contentText: z.string().refine(\n (value) => isUtf8WithinLimit(value, DOCUMENTS_MAX_CONTENT_TEXT_BYTES),\n { message: 'documents.validation.content.tooLarge' },\n ).optional().nullable(),\n})\n\nexport const documentTemplateContextSlotSchema = z.object({\n slot: z.string().min(1).max(64).regex(/^[a-z][a-zA-Z0-9]*$/),\n entityType: documentEntityTypeSchema,\n required: z.boolean().optional(),\n})\n\nexport const documentTemplateContextSlotsSchema = z.array(documentTemplateContextSlotSchema).max(20).superRefine(\n (slots, context) => {\n const seen = new Set<string>()\n for (const [index, slot] of slots.entries()) {\n if (seen.has(slot.slot)) {\n context.addIssue({\n code: 'custom',\n path: [index, 'slot'],\n message: 'documents.validation.templates.duplicateSlot',\n })\n }\n seen.add(slot.slot)\n }\n },\n)\n\nexport const documentTemplateCreateSchema = z.object({\n name: z.string().min(1).max(256),\n description: z.string().max(2000).nullish(),\n bodyHtml: documentTemplateHtmlSchema,\n contextSlots: documentTemplateContextSlotsSchema.nullish(),\n isActive: z.boolean().optional(),\n})\n\nexport const documentTemplateUpdateSchema = z.object({\n id: uuid(),\n name: z.string().min(1).max(256).optional(),\n description: z.string().max(2000).nullish(),\n bodyHtml: documentTemplateHtmlSchema.optional(),\n contextSlots: documentTemplateContextSlotsSchema.nullish(),\n isActive: z.boolean().optional(),\n})\n\nexport const documentEntityLinkCreateSchema = z.object({\n entityType: documentEntityTypeSchema,\n entityId: uuid(),\n label: documentEntityLabelSchema,\n href: z.string().trim().min(1).max(1024).startsWith('/backend/'),\n source: documentEntityLinkSourceSchema,\n})\n\nexport const documentTemplateFillSlotSchema = z.object({\n slot: z.string().min(1).max(64).regex(/^[a-z][a-zA-Z0-9]*$/),\n entityType: documentEntityTypeSchema,\n entityId: uuid(),\n label: documentEntityLabelSchema,\n href: z.string().trim().min(1).max(1024).startsWith('/backend/'),\n values: z.record(z.string().min(1).max(64), z.union([\n z.string().max(10000),\n finiteNumberSchema,\n z.null(),\n ])),\n})\n\nconst documentTemplateRenderBaseSchema = z.object({\n templateUpdatedAt: z.string().datetime({ offset: true }),\n title: documentTitleSchema,\n locale: localeSchema,\n effectiveDate: z.string().datetime({ offset: true }),\n slots: z.array(documentTemplateFillSlotSchema).max(20),\n})\n\nexport const documentTemplatePreviewSchema = documentTemplateRenderBaseSchema\n\nexport const documentTemplateInstantiateSchema = documentTemplateRenderBaseSchema.extend({\n templateId: uuid(),\n folderId: clearableUuidSchema,\n previewDigest: z.string().regex(/^sha256:[0-9a-f]{64}$/),\n})\n\nexport type DocumentCreateInput = z.infer<typeof documentCreateSchema>\nexport type DocumentUpdateInput = z.infer<typeof documentUpdateSchema>\nexport type DocumentFolderCreateInput = z.infer<typeof documentFolderCreateSchema>\nexport type DocumentFolderUpdateInput = z.infer<typeof documentFolderUpdateSchema>\nexport type DocumentShareCreateInput = z.infer<typeof documentShareCreateSchema>\nexport type DocumentShareUpdateInput = z.infer<typeof documentShareUpdateSchema>\nexport type DocumentCommentCreateInput = z.infer<typeof documentCommentCreateSchema>\nexport type DocumentContentPutInput = z.infer<typeof documentContentPutSchema>\nexport type DocumentTemplateContextSlotInput = z.infer<typeof documentTemplateContextSlotSchema>\nexport type DocumentTemplateCreateInput = z.infer<typeof documentTemplateCreateSchema>\nexport type DocumentTemplateUpdateInput = z.infer<typeof documentTemplateUpdateSchema>\nexport type DocumentEntityType = z.infer<typeof documentEntityTypeSchema>\nexport type DocumentEntityLinkSourceInput = z.infer<typeof documentEntityLinkSourceSchema>\nexport type DocumentEntityLinkCreateInput = z.infer<typeof documentEntityLinkCreateSchema>\nexport type DocumentTemplateFillSlotInput = z.infer<typeof documentTemplateFillSlotSchema>\nexport type DocumentTemplatePreviewInput = z.infer<typeof documentTemplatePreviewSchema>\nexport type DocumentTemplateInstantiateInput = z.infer<typeof documentTemplateInstantiateSchema>\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAElB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC,SAAS,yCAAyC;AAE3C,MAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,MAAM,EAAE,QAAQ,wBAAwB;AAAA,EACxC,WAAW,EAAE,OAAO,EAAE,KAAK;AAC7B,CAAC;AAEM,MAAM,kCAAkC,EAAE,OAAO;AAAA,EACtD,MAAM,EAAE,QAAQ,yBAAyB;AAAA,EACzC,WAAW,EAAE,OAAO,EAAE,KAAK;AAAA,EAC3B,OAAO,EAAE,QAAQ;AACnB,CAAC;AAED,MAAM,OAAO,MAAM,EAAE,OAAO,EAAE,KAAK,yCAAyC;AAE5E,SAAS,kBAAkB,OAAyB;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;A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,EAAE,IAAI,CAAC,EAAE,IAAI,IAAI,EAAE,WAAW,WAAW;AAAA,EAC/D,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM;AAAA,IAClD,EAAE,OAAO,EAAE,IAAI,GAAK;AAAA,IACpB;AAAA,IACA,EAAE,KAAK;AAAA,EACT,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,mCAAmC,EAAE,OAAO;AAAA,EAChD,mBAAmB,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,KAAK,CAAC;AAAA,EACvD,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,KAAK,CAAC;AAAA,EACnD,OAAO,EAAE,MAAM,8BAA8B,EAAE,IAAI,EAAE;AACvD,CAAC;AAEM,MAAM,gCAAgC;AAEtC,MAAM,oCAAoC,iCAAiC,OAAO;AAAA,EACvF,YAAY,KAAK;AAAA,EACjB,UAAU;AAAA,EACV,eAAe,EAAE,OAAO,EAAE,MAAM,uBAAuB;AACzD,CAAC;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,32 @@
1
+ import { z } from "zod";
2
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
+ const actorUuidSchema = z.string().uuid();
4
+ function normalizeActorUuid(value) {
5
+ if (typeof value !== "string") return null;
6
+ const normalized = value.trim();
7
+ return actorUuidSchema.safeParse(normalized).success ? normalized : null;
8
+ }
9
+ function isApiKeyAuth(auth) {
10
+ return auth.isApiKey === true || auth.sub.trim().startsWith("api_key:");
11
+ }
12
+ function resolveActorUserId(auth) {
13
+ const subject = auth.sub.trim();
14
+ if (isApiKeyAuth(auth)) {
15
+ const keyId = normalizeActorUuid(auth.keyId);
16
+ if (!keyId || subject !== `api_key:${keyId}`) {
17
+ throw new CrudHttpError(403, { error: "api.errors.forbidden" });
18
+ }
19
+ if (auth.userId === void 0 || auth.userId === null) return keyId;
20
+ const backingUserId = normalizeActorUuid(auth.userId);
21
+ if (backingUserId) return backingUserId;
22
+ throw new CrudHttpError(403, { error: "api.errors.forbidden" });
23
+ }
24
+ const actorUserId = normalizeActorUuid(subject);
25
+ const claimedUserId = auth.userId === void 0 || auth.userId === null ? actorUserId : normalizeActorUuid(auth.userId);
26
+ if (actorUserId && claimedUserId === actorUserId) return actorUserId;
27
+ throw new CrudHttpError(403, { error: "api.errors.forbidden" });
28
+ }
29
+ export {
30
+ resolveActorUserId
31
+ };
32
+ //# sourceMappingURL=actor.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/documents/lib/actor.ts"],
4
+ "sourcesContent": ["import { z } from 'zod'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\n\nconst actorUuidSchema = z.string().uuid()\n\nfunction normalizeActorUuid(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const normalized = value.trim()\n return actorUuidSchema.safeParse(normalized).success ? normalized : null\n}\n\nfunction isApiKeyAuth(auth: NonNullable<AuthContext>): boolean {\n return auth.isApiKey === true || auth.sub.trim().startsWith('api_key:')\n}\n\nexport function resolveActorUserId(auth: NonNullable<AuthContext>): string {\n const subject = auth.sub.trim()\n if (isApiKeyAuth(auth)) {\n // `keyId` is populated only by successful API-key authentication. Do not\n // recover an actor by parsing an arbitrary prefixed subject when that\n // validated field is absent, malformed, or disagrees with the subject.\n const keyId = normalizeActorUuid(auth.keyId)\n if (!keyId || subject !== `api_key:${keyId}`) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n if (auth.userId === undefined || auth.userId === null) return keyId\n const backingUserId = normalizeActorUuid(auth.userId)\n if (backingUserId) return backingUserId\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n\n const actorUserId = normalizeActorUuid(subject)\n const claimedUserId = auth.userId === undefined || auth.userId === null\n ? actorUserId\n : normalizeActorUuid(auth.userId)\n if (actorUserId && claimedUserId === actorUserId) return actorUserId\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAElB,SAAS,qBAAqB;AAE9B,MAAM,kBAAkB,EAAE,OAAO,EAAE,KAAK;AAExC,SAAS,mBAAmB,OAA+B;AACzD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,aAAa,MAAM,KAAK;AAC9B,SAAO,gBAAgB,UAAU,UAAU,EAAE,UAAU,aAAa;AACtE;AAEA,SAAS,aAAa,MAAyC;AAC7D,SAAO,KAAK,aAAa,QAAQ,KAAK,IAAI,KAAK,EAAE,WAAW,UAAU;AACxE;AAEO,SAAS,mBAAmB,MAAwC;AACzE,QAAM,UAAU,KAAK,IAAI,KAAK;AAC9B,MAAI,aAAa,IAAI,GAAG;AAItB,UAAM,QAAQ,mBAAmB,KAAK,KAAK;AAC3C,QAAI,CAAC,SAAS,YAAY,WAAW,KAAK,IAAI;AAC5C,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,IAChE;AACA,QAAI,KAAK,WAAW,UAAa,KAAK,WAAW,KAAM,QAAO;AAC9D,UAAM,gBAAgB,mBAAmB,KAAK,MAAM;AACpD,QAAI,cAAe,QAAO;AAC1B,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,EAChE;AAEA,QAAM,cAAc,mBAAmB,OAAO;AAC9C,QAAM,gBAAgB,KAAK,WAAW,UAAa,KAAK,WAAW,OAC/D,cACA,mBAAmB,KAAK,MAAM;AAClC,MAAI,eAAe,kBAAkB,YAAa,QAAO;AACzD,QAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAChE;",
6
+ "names": []
7
+ }
@@ -1,17 +1,62 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { TiptapTransformer } from "@hocuspocus/transformer";
3
3
  import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
4
+ import { getSchema } from "@tiptap/core";
5
+ import {
6
+ DOMParser as ProseMirrorDOMParser,
7
+ DOMSerializer,
8
+ Node as ProseMirrorNode
9
+ } from "@tiptap/pm/model";
4
10
  import * as Y from "yjs";
5
11
  import { deriveContentTextFromHtml } from "./contentService.js";
6
12
  import { COLLAB_FRAGMENT_FIELD, getDocumentEditorExtensions } from "./editorConfig.js";
7
13
  import { assertDocumentContentResourceLimits } from "./resourceLimits.js";
8
14
  const requireFromHere = createRequire(import.meta.url);
9
- let tiptapHtmlServer = null;
10
- function getTiptapHtmlServer() {
11
- if (!tiptapHtmlServer) {
12
- tiptapHtmlServer = requireFromHere("@tiptap/html/server");
15
+ let happyDomModule = null;
16
+ function createHtmlWindow() {
17
+ if (!happyDomModule) {
18
+ happyDomModule = requireFromHere("happy-dom");
19
+ }
20
+ return new happyDomModule.Window({
21
+ settings: {
22
+ disableJavaScriptEvaluation: true,
23
+ disableJavaScriptFileLoading: true,
24
+ disableCSSFileLoading: true,
25
+ disableIframePageLoading: true,
26
+ disableComputedStyleRendering: true
27
+ }
28
+ });
29
+ }
30
+ function generateHtml(doc, extensions) {
31
+ const schema = getSchema(extensions);
32
+ const documentNode = ProseMirrorNode.fromJSON(schema, doc);
33
+ const localWindow = createHtmlWindow();
34
+ try {
35
+ const wrapper = localWindow.document.createElement("div");
36
+ DOMSerializer.fromSchema(schema).serializeFragment(
37
+ documentNode.content,
38
+ { document: localWindow.document },
39
+ wrapper
40
+ );
41
+ return wrapper.innerHTML;
42
+ } finally {
43
+ localWindow.happyDOM.abort();
44
+ localWindow.happyDOM.close();
45
+ }
46
+ }
47
+ function generateJson(html, extensions, options) {
48
+ const localWindow = createHtmlWindow();
49
+ try {
50
+ const parsedDocument = new localWindow.DOMParser().parseFromString(
51
+ `<!DOCTYPE html><html><body>${html}</body></html>`,
52
+ "text/html"
53
+ );
54
+ const schema = getSchema(extensions);
55
+ return ProseMirrorDOMParser.fromSchema(schema).parse(parsedDocument.body, options).toJSON();
56
+ } finally {
57
+ localWindow.happyDOM.abort();
58
+ localWindow.happyDOM.close();
13
59
  }
14
- return tiptapHtmlServer;
15
60
  }
16
61
  function hasRenderableContent(node) {
17
62
  if (node.type === "text") return Boolean(node.text);
@@ -27,8 +72,7 @@ function yDocToContent(ydoc) {
27
72
  if (!json || !hasRenderableContent(json)) {
28
73
  return { html: "", text: "" };
29
74
  }
30
- const { generateHTML } = getTiptapHtmlServer();
31
- const html = generateHTML(json, getDocumentEditorExtensions());
75
+ const html = generateHtml(json, getDocumentEditorExtensions());
32
76
  const text = deriveContentTextFromHtml(html);
33
77
  assertDocumentContentResourceLimits({ contentHtml: html, contentText: text });
34
78
  return { html, text };
@@ -41,8 +85,7 @@ function htmlToYDoc(html) {
41
85
  assertDocumentContentResourceLimits({ contentHtml: html });
42
86
  if (!html.trim()) return new Y.Doc();
43
87
  const extensions = getDocumentEditorExtensions();
44
- const { generateJSON } = getTiptapHtmlServer();
45
- const json = generateJSON(html, extensions);
88
+ const json = generateJson(html, extensions);
46
89
  return TiptapTransformer.toYdoc(json, COLLAB_FRAGMENT_FIELD, extensions);
47
90
  }
48
91
  function materializeDocumentHtml(html) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/documents/lib/collabMaterializer.ts"],
4
- "sourcesContent": ["import { createRequire } from 'node:module'\nimport type { JSONContent } from '@tiptap/core'\nimport { TiptapTransformer } from '@hocuspocus/transformer'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport * as Y from 'yjs'\nimport { deriveContentTextFromHtml } from './contentService'\nimport { COLLAB_FRAGMENT_FIELD, getDocumentEditorExtensions } from './editorConfig'\nimport { assertDocumentContentResourceLimits } from './resourceLimits'\n\ntype TiptapHtmlServer = typeof import('@tiptap/html/server')\n\nconst requireFromHere = createRequire(import.meta.url)\nlet tiptapHtmlServer: TiptapHtmlServer | null = null\n\nfunction getTiptapHtmlServer(): TiptapHtmlServer {\n if (!tiptapHtmlServer) {\n tiptapHtmlServer = requireFromHere('@tiptap/html/server') as TiptapHtmlServer\n }\n return tiptapHtmlServer\n}\n\nfunction hasRenderableContent(node: JSONContent): boolean {\n if (node.type === 'text') return Boolean(node.text)\n if (Array.isArray(node.content) && node.content.some(hasRenderableContent)) return true\n return Boolean(node.type && node.type !== 'doc' && node.type !== 'paragraph' && node.type !== 'text')\n}\n\nexport function yDocToContent(ydoc: Y.Doc): { html: string; text: string } | null {\n try {\n if (ydoc.getXmlFragment(COLLAB_FRAGMENT_FIELD).length === 0) {\n return { html: '', text: '' }\n }\n\n const json = TiptapTransformer.fromYdoc(ydoc, COLLAB_FRAGMENT_FIELD) as JSONContent | null\n if (!json || !hasRenderableContent(json)) {\n return { html: '', text: '' }\n }\n\n const { generateHTML } = getTiptapHtmlServer()\n const html = generateHTML(json, getDocumentEditorExtensions())\n const text = deriveContentTextFromHtml(html)\n assertDocumentContentResourceLimits({ contentHtml: html, contentText: text })\n return { html, text }\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 413) throw error\n return null\n }\n}\n\nexport function htmlToYDoc(html: string): Y.Doc {\n assertDocumentContentResourceLimits({ contentHtml: html })\n if (!html.trim()) return new Y.Doc()\n\n const extensions = getDocumentEditorExtensions()\n const { generateJSON } = getTiptapHtmlServer()\n const json = generateJSON(html, extensions) as JSONContent\n return TiptapTransformer.toYdoc(json, COLLAB_FRAGMENT_FIELD, extensions)\n}\n\nexport type MaterializedDocumentHtml = {\n yjsState: Buffer\n html: string\n text: string\n}\n\n/**\n * Convert authored HTML through the same editor/Yjs pipeline used by persisted\n * document content. Callers that preview content before writing it must use the\n * returned HTML too, otherwise the preview can differ from the canonical markup\n * users receive after the document is created.\n */\nexport function materializeDocumentHtml(html: string): MaterializedDocumentHtml | null {\n try {\n const ydoc = htmlToYDoc(html)\n const content = yDocToContent(ydoc)\n if (!content) return null\n const result = {\n yjsState: Buffer.from(Y.encodeStateAsUpdate(ydoc)),\n html: content.html,\n text: content.text,\n }\n assertDocumentContentResourceLimits({\n yjsState: result.yjsState,\n contentHtml: result.html,\n contentText: result.text,\n })\n return result\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 413) throw error\n return null\n }\n}\n\n/**\n * Replace REST-authored content as a Yjs update derived from the current CRDT\n * epoch. Keeping the old structs as deleted tombstones means a retained client\n * can merge the replacement without resurrecting or duplicating stale text.\n */\nexport function materializeDocumentContentReplacement(\n existingState: Buffer | Uint8Array | null | undefined,\n html: string,\n): MaterializedDocumentHtml | null {\n try {\n assertDocumentContentResourceLimits({ yjsState: existingState, contentHtml: html })\n const replacement = htmlToYDoc(html)\n const ydoc = new Y.Doc()\n if (existingState && existingState.length > 0) {\n Y.applyUpdate(ydoc, new Uint8Array(existingState))\n }\n\n const target = ydoc.getXmlFragment(COLLAB_FRAGMENT_FIELD)\n const replacementNodes = replacement\n .getXmlFragment(COLLAB_FRAGMENT_FIELD)\n .toArray()\n .filter((node): node is Y.XmlElement | Y.XmlText => (\n node instanceof Y.XmlElement || node instanceof Y.XmlText\n ))\n .map((node) => node.clone())\n ydoc.transact(() => {\n if (target.length > 0) target.delete(0, target.length)\n if (replacementNodes.length > 0) target.insert(0, replacementNodes)\n })\n const content = yDocToContent(ydoc)\n if (!content) return null\n const result = {\n yjsState: Buffer.from(Y.encodeStateAsUpdate(ydoc)),\n html: content.html,\n text: content.text,\n }\n assertDocumentContentResourceLimits({\n yjsState: result.yjsState,\n contentHtml: result.html,\n contentText: result.text,\n })\n return result\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 413) throw error\n return null\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,qBAAqB;AAE9B,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,YAAY,OAAO;AACnB,SAAS,iCAAiC;AAC1C,SAAS,uBAAuB,mCAAmC;AACnE,SAAS,2CAA2C;AAIpD,MAAM,kBAAkB,cAAc,YAAY,GAAG;AACrD,IAAI,mBAA4C;AAEhD,SAAS,sBAA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AAI,CAAC;AAAA,MACjD,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,IAChB;AACA,wCAAoC;AAAA,MAClC,UAAU,OAAO;AAAA,MACjB,aAAa,OAAO;AAAA,MACpB,aAAa,OAAO;AAAA,IACtB,CAAC;AACD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,gBAAgB,KAAK,KAAK,MAAM,WAAW,IAAK,OAAM;AAC1D,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["import { createRequire } from 'node:module'\nimport { TiptapTransformer } from '@hocuspocus/transformer'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { getSchema, type Extensions, type JSONContent } from '@tiptap/core'\nimport {\n DOMParser as ProseMirrorDOMParser,\n DOMSerializer,\n Node as ProseMirrorNode,\n type ParseOptions,\n} from '@tiptap/pm/model'\nimport * as Y from 'yjs'\nimport { deriveContentTextFromHtml } from './contentService'\nimport { COLLAB_FRAGMENT_FIELD, getDocumentEditorExtensions } from './editorConfig'\nimport { assertDocumentContentResourceLimits } from './resourceLimits'\n\ntype HappyDomModule = typeof import('happy-dom')\ntype HappyDomWindow = InstanceType<HappyDomModule['Window']>\n\nconst requireFromHere = createRequire(import.meta.url)\nlet happyDomModule: HappyDomModule | null = null\n\nfunction createHtmlWindow(): HappyDomWindow {\n if (!happyDomModule) {\n happyDomModule = requireFromHere('happy-dom') as HappyDomModule\n }\n\n return new happyDomModule.Window({\n settings: {\n disableJavaScriptEvaluation: true,\n disableJavaScriptFileLoading: true,\n disableCSSFileLoading: true,\n disableIframePageLoading: true,\n disableComputedStyleRendering: true,\n },\n })\n}\n\nfunction generateHtml(doc: JSONContent, extensions: Extensions): string {\n const schema = getSchema(extensions)\n const documentNode = ProseMirrorNode.fromJSON(schema, doc)\n const localWindow = createHtmlWindow()\n\n try {\n const wrapper = localWindow.document.createElement('div')\n DOMSerializer.fromSchema(schema).serializeFragment(\n documentNode.content,\n { document: localWindow.document as unknown as Document },\n wrapper as unknown as HTMLElement,\n )\n return wrapper.innerHTML\n } finally {\n localWindow.happyDOM.abort()\n localWindow.happyDOM.close()\n }\n}\n\nfunction generateJson(html: string, extensions: Extensions, options?: ParseOptions): JSONContent {\n const localWindow = createHtmlWindow()\n\n try {\n const parsedDocument = new localWindow.DOMParser().parseFromString(\n `<!DOCTYPE html><html><body>${html}</body></html>`,\n 'text/html',\n )\n const schema = getSchema(extensions)\n return ProseMirrorDOMParser.fromSchema(schema)\n .parse(parsedDocument.body as unknown as Node, options)\n .toJSON()\n } finally {\n localWindow.happyDOM.abort()\n localWindow.happyDOM.close()\n }\n}\n\nfunction hasRenderableContent(node: JSONContent): boolean {\n if (node.type === 'text') return Boolean(node.text)\n if (Array.isArray(node.content) && node.content.some(hasRenderableContent)) return true\n return Boolean(node.type && node.type !== 'doc' && node.type !== 'paragraph' && node.type !== 'text')\n}\n\nexport function yDocToContent(ydoc: Y.Doc): { html: string; text: string } | null {\n try {\n if (ydoc.getXmlFragment(COLLAB_FRAGMENT_FIELD).length === 0) {\n return { html: '', text: '' }\n }\n\n const json = TiptapTransformer.fromYdoc(ydoc, COLLAB_FRAGMENT_FIELD) as JSONContent | null\n if (!json || !hasRenderableContent(json)) {\n return { html: '', text: '' }\n }\n\n const html = generateHtml(json, getDocumentEditorExtensions())\n const text = deriveContentTextFromHtml(html)\n assertDocumentContentResourceLimits({ contentHtml: html, contentText: text })\n return { html, text }\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 413) throw error\n return null\n }\n}\n\nexport function htmlToYDoc(html: string): Y.Doc {\n assertDocumentContentResourceLimits({ contentHtml: html })\n if (!html.trim()) return new Y.Doc()\n\n const extensions = getDocumentEditorExtensions()\n const json = generateJson(html, extensions)\n return TiptapTransformer.toYdoc(json, COLLAB_FRAGMENT_FIELD, extensions)\n}\n\nexport type MaterializedDocumentHtml = {\n yjsState: Buffer\n html: string\n text: string\n}\n\n/**\n * Convert authored HTML through the same editor/Yjs pipeline used by persisted\n * document content. Callers that preview content before writing it must use the\n * returned HTML too, otherwise the preview can differ from the canonical markup\n * users receive after the document is created.\n */\nexport function materializeDocumentHtml(html: string): MaterializedDocumentHtml | null {\n try {\n const ydoc = htmlToYDoc(html)\n const content = yDocToContent(ydoc)\n if (!content) return null\n const result = {\n yjsState: Buffer.from(Y.encodeStateAsUpdate(ydoc)),\n html: content.html,\n text: content.text,\n }\n assertDocumentContentResourceLimits({\n yjsState: result.yjsState,\n contentHtml: result.html,\n contentText: result.text,\n })\n return result\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 413) throw error\n return null\n }\n}\n\n/**\n * Replace REST-authored content as a Yjs update derived from the current CRDT\n * epoch. Keeping the old structs as deleted tombstones means a retained client\n * can merge the replacement without resurrecting or duplicating stale text.\n */\nexport function materializeDocumentContentReplacement(\n existingState: Buffer | Uint8Array | null | undefined,\n html: string,\n): MaterializedDocumentHtml | null {\n try {\n assertDocumentContentResourceLimits({ yjsState: existingState, contentHtml: html })\n const replacement = htmlToYDoc(html)\n const ydoc = new Y.Doc()\n if (existingState && existingState.length > 0) {\n Y.applyUpdate(ydoc, new Uint8Array(existingState))\n }\n\n const target = ydoc.getXmlFragment(COLLAB_FRAGMENT_FIELD)\n const replacementNodes = replacement\n .getXmlFragment(COLLAB_FRAGMENT_FIELD)\n .toArray()\n .filter((node): node is Y.XmlElement | Y.XmlText => (\n node instanceof Y.XmlElement || node instanceof Y.XmlText\n ))\n .map((node) => node.clone())\n ydoc.transact(() => {\n if (target.length > 0) target.delete(0, target.length)\n if (replacementNodes.length > 0) target.insert(0, replacementNodes)\n })\n const content = yDocToContent(ydoc)\n if (!content) return null\n const result = {\n yjsState: Buffer.from(Y.encodeStateAsUpdate(ydoc)),\n html: content.html,\n text: content.text,\n }\n assertDocumentContentResourceLimits({\n yjsState: result.yjsState,\n contentHtml: result.html,\n contentText: result.text,\n })\n return result\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 413) throw error\n return null\n }\n}\n"],
5
+ "mappings": "AAAA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AChB;AACA,wCAAoC;AAAA,MAClC,UAAU,OAAO;AAAA,MACjB,aAAa,OAAO;AAAA,MACpB,aAAa,OAAO;AAAA,IACtB,CAAC;AACD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,gBAAgB,KAAK,KAAK,MAAM,WAAW,IAAK,OAAM;AAC1D,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,13 @@
1
+ import * as Y from "yjs";
2
+ const COLLAB_CONTENT_SAVE_TIMEOUT_MS = 15e3;
3
+ function containsDocumentSnapshot(durable, requested) {
4
+ for (const [clientId, clock] of requested.sv) {
5
+ if ((durable.sv.get(clientId) ?? 0) < clock) return false;
6
+ }
7
+ return Y.equalDeleteSets(Y.mergeDeleteSets([durable.ds, requested.ds]), durable.ds);
8
+ }
9
+ export {
10
+ COLLAB_CONTENT_SAVE_TIMEOUT_MS,
11
+ containsDocumentSnapshot
12
+ };
13
+ //# sourceMappingURL=collabPersistence.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/documents/lib/collabPersistence.ts"],
4
+ "sourcesContent": ["import * as Y from 'yjs'\n\nexport const COLLAB_CONTENT_SAVE_TIMEOUT_MS = 15000\n\nexport function containsDocumentSnapshot(durable: Y.Snapshot, requested: Y.Snapshot): boolean {\n for (const [clientId, clock] of requested.sv) {\n if ((durable.sv.get(clientId) ?? 0) < clock) return false\n }\n return Y.equalDeleteSets(Y.mergeDeleteSets([durable.ds, requested.ds]), durable.ds)\n}\n"],
5
+ "mappings": "AAAA,YAAY,OAAO;AAEZ,MAAM,iCAAiC;AAEvC,SAAS,yBAAyB,SAAqB,WAAgC;AAC5F,aAAW,CAAC,UAAU,KAAK,KAAK,UAAU,IAAI;AAC5C,SAAK,QAAQ,GAAG,IAAI,QAAQ,KAAK,KAAK,MAAO,QAAO;AAAA,EACtD;AACA,SAAO,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,QAAQ,IAAI,UAAU,EAAE,CAAC,GAAG,QAAQ,EAAE;AACpF;",
6
+ "names": []
7
+ }
@@ -1,11 +1,14 @@
1
1
  import { hasAllFeatures } from "@open-mercato/shared/lib/auth/featureMatch";
2
+ import { authorizeFeatures } from "@open-mercato/shared/security/featurePolicy";
2
3
  import { forbidden } from "@open-mercato/shared/lib/crud/errors";
3
4
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
4
5
  import { Document, DocumentShare } from "../data/entities.js";
6
+ import { hasResolvedDocumentsOrganizationAccess } from "./organizationAccess.js";
5
7
  import {
6
8
  resolveApiKeyPrincipalService,
7
9
  resolveAuthPrincipalService,
8
- resolveDocumentsRbacService
10
+ resolveDocumentsRbacService,
11
+ resolveOrganizationScopeService
9
12
  } from "./platformServices.js";
10
13
  const TIER_RANK = {
11
14
  owner: 3,
@@ -126,6 +129,29 @@ async function loadScopedDocument(em, documentId, scope) {
126
129
  );
127
130
  }
128
131
  async function resolveLoadedDocumentUserAccess(em, document, scope, userId, container) {
132
+ if (!await hasUserDocumentViewPermission(scope, userId, container)) return null;
133
+ return resolveLoadedDocumentUserTier(em, document, scope, userId, container);
134
+ }
135
+ async function hasUserDocumentViewPermission(scope, userId, container) {
136
+ const rbacService = resolveDocumentsRbacService(container);
137
+ if (!rbacService) return false;
138
+ if (!await rbacService.userHasAllFeatures(userId, ["documents.view"], scope)) {
139
+ const organizationScopeService = resolveOrganizationScopeService(container);
140
+ if (!organizationScopeService) return false;
141
+ const authorization = await organizationScopeService.resolveFresh({
142
+ auth: { sub: userId, userId, tenantId: scope.tenantId, orgId: scope.organizationId, isSuperAdmin: false },
143
+ selectedId: scope.organizationId,
144
+ tenantId: scope.tenantId
145
+ });
146
+ if (!authorizeFeatures(["documents.view"], {
147
+ grantedFeatures: authorization.acl.features,
148
+ unrestricted: authorization.acl.isSuperAdmin,
149
+ scopeAllowed: authorization.scope.tenantId === scope.tenantId && !authorization.scope.selectionRejected && hasResolvedDocumentsOrganizationAccess(authorization.acl, scope.organizationId, authorization.scope)
150
+ })) return false;
151
+ }
152
+ return true;
153
+ }
154
+ async function resolveLoadedDocumentUserTier(em, document, scope, userId, container) {
129
155
  if (document.ownerUserId === userId) return "owner";
130
156
  if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(
131
157
  userId,
@@ -154,6 +180,11 @@ async function resolveLoadedDocumentUserAccess(em, document, scope, userId, cont
154
180
  );
155
181
  return maxShareTier(shares);
156
182
  }
183
+ async function resolveUserDocumentTier(em, documentId, scope, userId, container) {
184
+ const document = await loadScopedDocument(em, documentId, scope);
185
+ if (!document) return null;
186
+ return resolveLoadedDocumentUserTier(em, document, scope, userId, container);
187
+ }
157
188
  async function resolveUserAccess(em, documentId, scope, userId, container) {
158
189
  const document = await loadScopedDocument(em, documentId, scope);
159
190
  if (!document) return null;
@@ -211,12 +242,14 @@ export {
211
242
  TIER_RANK,
212
243
  assertTier,
213
244
  hasTier,
245
+ hasUserDocumentViewPermission,
214
246
  loadScopedDocument,
215
247
  resolveActiveSubjectRoleIds,
216
248
  resolveActiveUserRoleIds,
217
249
  resolveLoadedDocumentUserAccess,
218
250
  resolvePermission,
219
251
  resolveSubjectAccess,
220
- resolveUserAccess
252
+ resolveUserAccess,
253
+ resolveUserDocumentTier
221
254
  };
222
255
  //# sourceMappingURL=permissions.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/documents/lib/permissions.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport { forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Document, DocumentShare } from '../data/entities'\nimport {\n resolveApiKeyPrincipalService,\n resolveAuthPrincipalService,\n resolveDocumentsRbacService,\n type DocumentsServiceContainer,\n} from './platformServices'\n\nexport type DocumentTier = 'owner' | 'editor' | 'commenter' | 'viewer'\n\nexport const TIER_RANK: Record<DocumentTier, number> = {\n owner: 3,\n editor: 2,\n commenter: 1,\n viewer: 0,\n}\n\ntype DocumentsPermissionContext = NonNullable<AuthContext> & {\n features?: string[]\n roleIds?: string[]\n resolvedRoleIds?: string[]\n organizationId?: string | null\n}\n\nfunction resolveUserId(ctx: AuthContext): string | null {\n if (!ctx) return null\n if (typeof ctx.userId === 'string' && ctx.userId.trim().length > 0) return ctx.userId\n if (typeof ctx.sub === 'string' && ctx.sub.trim().length > 0 && !ctx.sub.startsWith('api_key:')) return ctx.sub\n return null\n}\n\nfunction resolveOrganizationId(ctx: DocumentsPermissionContext): string | null {\n if (typeof ctx.organizationId === 'string' && ctx.organizationId.trim().length > 0) {\n return ctx.organizationId\n }\n if (typeof ctx.orgId === 'string' && ctx.orgId.trim().length > 0) return ctx.orgId\n return null\n}\n\nfunction normalizeStrings(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n return Array.from(\n new Set(\n values\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ),\n )\n}\n\nfunction hasDocumentsManage(ctx: DocumentsPermissionContext): boolean {\n if (ctx.isSuperAdmin === true) return true\n const features = normalizeStrings(ctx.features)\n return hasAllFeatures(['documents.manage'], features)\n}\n\nexport async function resolveActiveUserRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<string[]> {\n const service = resolveAuthPrincipalService(container)\n if (!service) return []\n return normalizeStrings(await service.resolveActiveUserRoleIds(userId, scope))\n}\n\nexport async function resolveActiveSubjectRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n subject: string,\n): Promise<string[]> {\n if (!subject.startsWith('api_key:')) {\n return resolveActiveUserRoleIds(container, scope, subject)\n }\n\n const apiKeyId = subject.slice('api_key:'.length).trim()\n if (!apiKeyId) return []\n const apiKeyService = resolveApiKeyPrincipalService(container)\n const authService = resolveAuthPrincipalService(container)\n if (!apiKeyService || !authService) return []\n const assigned = normalizeStrings(await apiKeyService.resolveAssignedRoleIds(apiKeyId, scope))\n if (assigned.length === 0) return []\n return normalizeStrings(await authService.filterActiveRoleIds(assigned, scope))\n}\n\nfunction maxShareTier(shares: DocumentShare[]): DocumentTier | null {\n let best: DocumentTier | null = null\n for (const share of shares) {\n const permission = share.permission\n if (permission !== 'viewer' && permission !== 'commenter' && permission !== 'editor') continue\n if (!best || TIER_RANK[permission] > TIER_RANK[best]) best = permission\n }\n return best\n}\n\nexport async function resolvePermission(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n): Promise<DocumentTier | null> {\n if (!ctx || !ctx.tenantId) return null\n const permissionCtx = ctx as DocumentsPermissionContext\n const organizationId = resolveOrganizationId(permissionCtx)\n if (!organizationId) return null\n\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n if (!document) return null\n\n const userId = resolveUserId(ctx)\n if ((userId && document.ownerUserId === userId) || hasDocumentsManage(permissionCtx)) {\n return 'owner'\n }\n if (!userId) return null\n\n // Never trust role ids/names carried by the request token. Role shares are\n // resolved from active UserRole links to active roles in the current tenant.\n // Only consume the server-projected role set. Raw token roleIds/roles are\n // authentication hints and can outlive an assignment revocation.\n const roleIds = normalizeStrings(permissionCtx.resolvedRoleIds)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n\n return maxShareTier(shares)\n}\n\nexport async function loadScopedDocument(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<Document | null> {\n return findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n}\n\n/**\n * Resolve one user's tier against an already scoped document. Callers that\n * evaluate many users for the same document load it once and reuse it here\n * instead of re-reading the identical row per user.\n */\nexport async function resolveLoadedDocumentUserAccess(\n em: EntityManager,\n document: Document,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n if (document.ownerUserId === userId) return 'owner'\n if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(\n userId,\n ['documents.manage'],\n scope,\n )) return 'owner'\n\n const roleIds = await resolveActiveUserRoleIds(container, scope, userId)\n\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId: document.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n\n return maxShareTier(shares)\n}\n\nexport async function resolveUserAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await loadScopedDocument(em, documentId, scope)\n if (!document) return null\n return resolveLoadedDocumentUserAccess(em, document, scope, userId, container)\n}\n\nexport async function resolveSubjectAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n identity: { subject: string; userId: string },\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (!document) return null\n if (document.ownerUserId === identity.userId) return 'owner'\n\n const roleIds = await resolveActiveSubjectRoleIds(container, scope, identity.subject)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: identity.userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n return maxShareTier(shares)\n}\n\nexport function hasTier(tier: DocumentTier | null, required: DocumentTier): boolean {\n if (!tier) return false\n return TIER_RANK[tier] >= TIER_RANK[required]\n}\n\nexport async function assertTier(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n required: DocumentTier,\n): Promise<DocumentTier> {\n const tier = await resolvePermission(em, documentId, ctx)\n if (!tier || !hasTier(tier, required)) {\n throw forbidden('Forbidden')\n }\n return tier\n}\n"],
5
- "mappings": "AAGA,SAAS,sBAAsB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,UAAU,qBAAqB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIA,MAAM,YAA0C;AAAA,EACrD,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,QAAQ;AACV;AASA,SAAS,cAAc,KAAiC;AACtD,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI,OAAO,IAAI,WAAW,YAAY,IAAI,OAAO,KAAK,EAAE,SAAS,EAAG,QAAO,IAAI;AAC/E,MAAI,OAAO,IAAI,QAAQ,YAAY,IAAI,IAAI,KAAK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@mikro-orm/postgresql'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Document, DocumentShare } from '../data/entities'\nimport { hasResolvedDocumentsOrganizationAccess } from './organizationAccess'\nimport {\n resolveApiKeyPrincipalService,\n resolveAuthPrincipalService,\n resolveDocumentsRbacService,\n resolveOrganizationScopeService,\n type DocumentsServiceContainer,\n} from './platformServices'\n\nexport type DocumentTier = 'owner' | 'editor' | 'commenter' | 'viewer'\n\nexport const TIER_RANK: Record<DocumentTier, number> = {\n owner: 3,\n editor: 2,\n commenter: 1,\n viewer: 0,\n}\n\ntype DocumentsPermissionContext = NonNullable<AuthContext> & {\n features?: string[]\n roleIds?: string[]\n resolvedRoleIds?: string[]\n organizationId?: string | null\n}\n\nfunction resolveUserId(ctx: AuthContext): string | null {\n if (!ctx) return null\n if (typeof ctx.userId === 'string' && ctx.userId.trim().length > 0) return ctx.userId\n if (typeof ctx.sub === 'string' && ctx.sub.trim().length > 0 && !ctx.sub.startsWith('api_key:')) return ctx.sub\n return null\n}\n\nfunction resolveOrganizationId(ctx: DocumentsPermissionContext): string | null {\n if (typeof ctx.organizationId === 'string' && ctx.organizationId.trim().length > 0) {\n return ctx.organizationId\n }\n if (typeof ctx.orgId === 'string' && ctx.orgId.trim().length > 0) return ctx.orgId\n return null\n}\n\nfunction normalizeStrings(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n return Array.from(\n new Set(\n values\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ),\n )\n}\n\nfunction hasDocumentsManage(ctx: DocumentsPermissionContext): boolean {\n if (ctx.isSuperAdmin === true) return true\n const features = normalizeStrings(ctx.features)\n return hasAllFeatures(['documents.manage'], features)\n}\n\nexport async function resolveActiveUserRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<string[]> {\n const service = resolveAuthPrincipalService(container)\n if (!service) return []\n return normalizeStrings(await service.resolveActiveUserRoleIds(userId, scope))\n}\n\nexport async function resolveActiveSubjectRoleIds(\n container: DocumentsServiceContainer | null | undefined,\n scope: { tenantId: string; organizationId: string },\n subject: string,\n): Promise<string[]> {\n if (!subject.startsWith('api_key:')) {\n return resolveActiveUserRoleIds(container, scope, subject)\n }\n\n const apiKeyId = subject.slice('api_key:'.length).trim()\n if (!apiKeyId) return []\n const apiKeyService = resolveApiKeyPrincipalService(container)\n const authService = resolveAuthPrincipalService(container)\n if (!apiKeyService || !authService) return []\n const assigned = normalizeStrings(await apiKeyService.resolveAssignedRoleIds(apiKeyId, scope))\n if (assigned.length === 0) return []\n return normalizeStrings(await authService.filterActiveRoleIds(assigned, scope))\n}\n\nfunction maxShareTier(shares: DocumentShare[]): DocumentTier | null {\n let best: DocumentTier | null = null\n for (const share of shares) {\n const permission = share.permission\n if (permission !== 'viewer' && permission !== 'commenter' && permission !== 'editor') continue\n if (!best || TIER_RANK[permission] > TIER_RANK[best]) best = permission\n }\n return best\n}\n\nexport async function resolvePermission(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n): Promise<DocumentTier | null> {\n if (!ctx || !ctx.tenantId) return null\n const permissionCtx = ctx as DocumentsPermissionContext\n const organizationId = resolveOrganizationId(permissionCtx)\n if (!organizationId) return null\n\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n if (!document) return null\n\n const userId = resolveUserId(ctx)\n if ((userId && document.ownerUserId === userId) || hasDocumentsManage(permissionCtx)) {\n return 'owner'\n }\n if (!userId) return null\n\n // Never trust role ids/names carried by the request token. Role shares are\n // resolved from active UserRole links to active roles in the current tenant.\n // Only consume the server-projected role set. Raw token roleIds/roles are\n // authentication hints and can outlive an assignment revocation.\n const roleIds = normalizeStrings(permissionCtx.resolvedRoleIds)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n { tenantId: ctx.tenantId, organizationId },\n )\n\n return maxShareTier(shares)\n}\n\nexport async function loadScopedDocument(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<Document | null> {\n return findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n}\n\n/**\n * Resolve one user's tier against an already scoped document. Callers that\n * evaluate many users for the same document load it once and reuse it here\n * instead of re-reading the identical row per user.\n */\nexport async function resolveLoadedDocumentUserAccess(\n em: EntityManager,\n document: Document,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n if (!await hasUserDocumentViewPermission(scope, userId, container)) return null\n return resolveLoadedDocumentUserTier(em, document, scope, userId, container)\n}\n\nexport async function hasUserDocumentViewPermission(\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<boolean> {\n const rbacService = resolveDocumentsRbacService(container)\n if (!rbacService) return false\n if (!await rbacService.userHasAllFeatures(userId, ['documents.view'], scope)) {\n const organizationScopeService = resolveOrganizationScopeService(container)\n if (!organizationScopeService) return false\n const authorization = await organizationScopeService.resolveFresh({\n auth: { sub: userId, userId, tenantId: scope.tenantId, orgId: scope.organizationId, isSuperAdmin: false },\n selectedId: scope.organizationId,\n tenantId: scope.tenantId,\n })\n if (!authorizeFeatures(['documents.view'], {\n grantedFeatures: authorization.acl.features,\n unrestricted: authorization.acl.isSuperAdmin,\n scopeAllowed: authorization.scope.tenantId === scope.tenantId\n && !authorization.scope.selectionRejected\n && hasResolvedDocumentsOrganizationAccess(authorization.acl, scope.organizationId, authorization.scope),\n })) return false\n }\n return true\n}\n\nasync function resolveLoadedDocumentUserTier(\n em: EntityManager,\n document: Document,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n if (document.ownerUserId === userId) return 'owner'\n if (await resolveDocumentsRbacService(container)?.userHasAllFeatures(\n userId,\n ['documents.manage'],\n scope,\n )) return 'owner'\n\n const roleIds = await resolveActiveUserRoleIds(container, scope, userId)\n\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId: document.id,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n\n return maxShareTier(shares)\n}\n\nexport async function resolveUserDocumentTier(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await loadScopedDocument(em, documentId, scope)\n if (!document) return null\n return resolveLoadedDocumentUserTier(em, document, scope, userId, container)\n}\n\nexport async function resolveUserAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n userId: string,\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await loadScopedDocument(em, documentId, scope)\n if (!document) return null\n return resolveLoadedDocumentUserAccess(em, document, scope, userId, container)\n}\n\nexport async function resolveSubjectAccess(\n em: EntityManager,\n documentId: string,\n scope: { tenantId: string; organizationId: string },\n identity: { subject: string; userId: string },\n container?: DocumentsServiceContainer | null,\n): Promise<DocumentTier | null> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (!document) return null\n if (document.ownerUserId === identity.userId) return 'owner'\n\n const roleIds = await resolveActiveSubjectRoleIds(container, scope, identity.subject)\n const principals: Array<FilterQuery<DocumentShare>> = [\n { principalType: 'user', principalId: identity.userId },\n ]\n if (roleIds.length > 0) {\n principals.push({ principalType: 'role', principalId: { $in: roleIds } } as FilterQuery<DocumentShare>)\n }\n\n const shares = await findWithDecryption(\n em,\n DocumentShare,\n {\n documentId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n $or: principals,\n } as FilterQuery<DocumentShare>,\n undefined,\n scope,\n )\n return maxShareTier(shares)\n}\n\nexport function hasTier(tier: DocumentTier | null, required: DocumentTier): boolean {\n if (!tier) return false\n return TIER_RANK[tier] >= TIER_RANK[required]\n}\n\nexport async function assertTier(\n em: EntityManager,\n documentId: string,\n ctx: AuthContext,\n required: DocumentTier,\n): Promise<DocumentTier> {\n const tier = await resolvePermission(em, documentId, ctx)\n if (!tier || !hasTier(tier, required)) {\n throw forbidden('Forbidden')\n }\n return tier\n}\n"],
5
+ "mappings": "AAGA,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,UAAU,qBAAqB;AACxC,SAAS,8CAA8C;AACvD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIA,MAAM,YAA0C;AAAA,EACrD,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,QAAQ;AACV;AASA,S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;AACA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
3
  import * as React from "react";
4
4
  import dynamic from "next/dynamic";
5
5
  import Link from "next/link";
@@ -44,9 +44,10 @@ function RelatedDocumentsWidget({ context, data, disabled }) {
44
44
  /* @__PURE__ */ jsx(
45
45
  SectionHeader,
46
46
  {
47
+ className: "flex-col items-start gap-3 sm:flex-row sm:items-center",
47
48
  title: t("documents.relatedDocuments.title"),
48
49
  count: related.items.length,
49
- action: actions.canLink || actions.canCreate ? /* @__PURE__ */ jsxs(Fragment, { children: [
50
+ action: actions.canLink || actions.canCreate ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1", "data-testid": "related-documents-actions", children: [
50
51
  actions.canLink ? /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", variant: "outline", onClick: () => setLinkOpen(true), children: [
51
52
  /* @__PURE__ */ jsx(Link2, {}),
52
53
  t("documents.relatedDocuments.actions.link")