arocapi 5.0.0-beta.1 → 5.0.0-beta.3

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 (128) hide show
  1. package/README.md +37 -802
  2. package/dist/app.d.ts +22 -9
  3. package/dist/app.js +46 -30
  4. package/dist/app.js.map +1 -1
  5. package/dist/app.test.js +41 -56
  6. package/dist/app.test.js.map +1 -1
  7. package/dist/errorHandling.test.d.ts +1 -0
  8. package/dist/errorHandling.test.js +222 -0
  9. package/dist/errorHandling.test.js.map +1 -0
  10. package/dist/index.dev.js +4 -3
  11. package/dist/index.dev.js.map +1 -1
  12. package/dist/routes/capabilities.d.ts +7 -0
  13. package/dist/routes/capabilities.js +13 -0
  14. package/dist/routes/capabilities.js.map +1 -0
  15. package/dist/routes/capabilities.test.d.ts +1 -0
  16. package/dist/routes/capabilities.test.js +81 -0
  17. package/dist/routes/capabilities.test.js.map +1 -0
  18. package/dist/routes/crate.test.js +67 -19
  19. package/dist/routes/crate.test.js.map +1 -1
  20. package/dist/routes/entities.d.ts +5 -2
  21. package/dist/routes/entities.js +31 -49
  22. package/dist/routes/entities.js.map +1 -1
  23. package/dist/routes/entities.test.js +16 -12
  24. package/dist/routes/entities.test.js.map +1 -1
  25. package/dist/routes/entity.d.ts +7 -2
  26. package/dist/routes/entity.js +14 -29
  27. package/dist/routes/entity.js.map +1 -1
  28. package/dist/routes/entity.test.js +19 -13
  29. package/dist/routes/entity.test.js.map +1 -1
  30. package/dist/routes/file.d.ts +6 -0
  31. package/dist/routes/file.js +67 -59
  32. package/dist/routes/file.js.map +1 -1
  33. package/dist/routes/file.test.js +99 -22
  34. package/dist/routes/file.test.js.map +1 -1
  35. package/dist/routes/files.d.ts +5 -2
  36. package/dist/routes/files.js +24 -39
  37. package/dist/routes/files.js.map +1 -1
  38. package/dist/routes/files.test.js +44 -21
  39. package/dist/routes/files.test.js.map +1 -1
  40. package/dist/routes/metadata.d.ts +6 -0
  41. package/dist/routes/metadata.js +49 -54
  42. package/dist/routes/metadata.js.map +1 -1
  43. package/dist/routes/search.d.ts +8 -5
  44. package/dist/routes/search.js +95 -101
  45. package/dist/routes/search.js.map +1 -1
  46. package/dist/routes/search.test.js +92 -39
  47. package/dist/routes/search.test.js.map +1 -1
  48. package/dist/test/helpers/fastify.d.ts +1 -1
  49. package/dist/test/helpers/fastify.js +2 -3
  50. package/dist/test/helpers/fastify.js.map +1 -1
  51. package/dist/test/integration.setup.d.ts +19 -1
  52. package/dist/test/integration.setup.js +15 -7
  53. package/dist/test/integration.setup.js.map +1 -1
  54. package/dist/test/integration.test.js +368 -2
  55. package/dist/test/integration.test.js.map +1 -1
  56. package/dist/transformers/default.d.ts +10 -18
  57. package/dist/transformers/default.js +41 -15
  58. package/dist/transformers/default.js.map +1 -1
  59. package/dist/transformers/default.test.js +109 -47
  60. package/dist/transformers/default.test.js.map +1 -1
  61. package/dist/transformers/transformer.test.js +12 -34
  62. package/dist/transformers/transformer.test.js.map +1 -1
  63. package/dist/types/access.d.ts +9 -0
  64. package/dist/types/access.js +2 -0
  65. package/dist/types/access.js.map +1 -0
  66. package/dist/types/context.d.ts +6 -0
  67. package/dist/types/context.js +2 -0
  68. package/dist/types/context.js.map +1 -0
  69. package/dist/types/fileHandlers.d.ts +5 -9
  70. package/dist/types/transformers.d.ts +4 -10
  71. package/dist/types/visibility.d.ts +5 -0
  72. package/dist/types/visibility.js +2 -0
  73. package/dist/types/visibility.js.map +1 -0
  74. package/dist/utils/access.d.ts +17 -0
  75. package/dist/utils/access.js +41 -0
  76. package/dist/utils/access.js.map +1 -0
  77. package/dist/utils/errors.d.ts +19 -10
  78. package/dist/utils/errors.js +44 -8
  79. package/dist/utils/errors.js.map +1 -1
  80. package/dist/utils/errors.test.js +14 -1
  81. package/dist/utils/errors.test.js.map +1 -1
  82. package/dist/utils/queryBuilder.d.ts +12 -0
  83. package/dist/utils/queryBuilder.js +9 -0
  84. package/dist/utils/queryBuilder.js.map +1 -1
  85. package/dist/utils/validation.d.ts +2 -0
  86. package/dist/utils/validation.js +8 -0
  87. package/dist/utils/validation.js.map +1 -0
  88. package/dist/utils/visibility.d.ts +18 -0
  89. package/dist/utils/visibility.js +16 -0
  90. package/dist/utils/visibility.js.map +1 -0
  91. package/package.json +34 -33
  92. package/src/app.test.ts +45 -66
  93. package/src/app.ts +92 -58
  94. package/src/errorHandling.test.ts +288 -0
  95. package/src/index.dev.ts +6 -4
  96. package/src/routes/__snapshots__/capabilities.test.ts.snap +34 -0
  97. package/src/routes/__snapshots__/search.test.ts.snap +2 -2
  98. package/src/routes/capabilities.test.ts +102 -0
  99. package/src/routes/capabilities.ts +22 -0
  100. package/src/routes/crate.test.ts +80 -19
  101. package/src/routes/entities.test.ts +16 -12
  102. package/src/routes/entities.ts +40 -59
  103. package/src/routes/entity.test.ts +19 -13
  104. package/src/routes/entity.ts +22 -35
  105. package/src/routes/file.test.ts +117 -22
  106. package/src/routes/file.ts +84 -62
  107. package/src/routes/files.test.ts +52 -26
  108. package/src/routes/files.ts +31 -47
  109. package/src/routes/metadata.ts +64 -58
  110. package/src/routes/search.test.ts +95 -39
  111. package/src/routes/search.ts +120 -125
  112. package/src/test/helpers/fastify.ts +2 -3
  113. package/src/test/integration.setup.ts +18 -7
  114. package/src/test/integration.test.ts +472 -1
  115. package/src/transformers/default.test.ts +139 -47
  116. package/src/transformers/default.ts +103 -83
  117. package/src/transformers/transformer.test.ts +18 -44
  118. package/src/types/access.ts +20 -0
  119. package/src/types/context.ts +15 -0
  120. package/src/types/fileHandlers.ts +5 -13
  121. package/src/types/transformers.ts +4 -32
  122. package/src/types/visibility.ts +18 -0
  123. package/src/utils/access.ts +80 -0
  124. package/src/utils/errors.test.ts +16 -1
  125. package/src/utils/errors.ts +68 -11
  126. package/src/utils/queryBuilder.ts +25 -0
  127. package/src/utils/validation.ts +11 -0
  128. package/src/utils/visibility.ts +56 -0
@@ -3,9 +3,14 @@ import type { FastifyPluginAsync } from 'fastify';
3
3
  import type { ZodTypeProvider } from 'fastify-type-provider-zod';
4
4
  import { z } from 'zod';
5
5
  import type { PrismaClient } from '../generated/prisma/client.js';
6
+ import type { AccessFunction } from '../types/access.js';
7
+ import type { RequestContext } from '../types/context.js';
6
8
  import type { FileHandler, FileMetadata } from '../types/fileHandlers.js';
7
- import { createInternalError, createNotFoundError } from '../utils/errors.js';
9
+ import type { EntityVisibilityFilter } from '../types/visibility.js';
10
+ import { createAccessGuard } from '../utils/access.js';
11
+ import { createNotFoundError } from '../utils/errors.js';
8
12
  import { setFileHeaders } from '../utils/headers.js';
13
+ import { createNotVisibleResponder, type RefusalOptions } from '../utils/visibility.js';
9
14
 
10
15
  const paramsSchema = z.object({
11
16
  id: z.url(),
@@ -20,10 +25,36 @@ const querySchema = z.object({
20
25
  type FileRouteOptions = {
21
26
  prisma: PrismaClient;
22
27
  fileHandler: FileHandler;
28
+ access: AccessFunction;
29
+ entityVisibilityFilter: EntityVisibilityFilter;
30
+ refusal: RefusalOptions;
23
31
  };
24
32
 
25
33
  const file: FastifyPluginAsync<FileRouteOptions> = async (fastify, opts) => {
26
- const { prisma, fileHandler } = opts;
34
+ const { prisma, fileHandler, access, entityVisibilityFilter, refusal } = opts;
35
+
36
+ // Split the entity off so handlers receive only the File they're typed for
37
+ const findVisibleFile = async (id: string, context: RequestContext) => {
38
+ const found = await prisma.file.findFirst({
39
+ where: { id, entity: await entityVisibilityFilter(context) },
40
+ include: { entity: { omit: { meta: true } } },
41
+ });
42
+ if (!found) {
43
+ return null;
44
+ }
45
+
46
+ const { entity, ...file } = found;
47
+
48
+ return { file, entity };
49
+ };
50
+
51
+ const denyContent = createAccessGuard({ access, isAuthenticated: refusal.isAuthenticated, level: 'content' });
52
+
53
+ const sendFileNotVisible = createNotVisibleResponder({
54
+ ...refusal,
55
+ notFoundMessage: 'The requested file was not found',
56
+ exists: async (id) => (await prisma.file.count({ where: { id } })) > 0,
57
+ });
27
58
 
28
59
  fastify.withTypeProvider<ZodTypeProvider>().head(
29
60
  '/file/:id',
@@ -35,30 +66,27 @@ const file: FastifyPluginAsync<FileRouteOptions> = async (fastify, opts) => {
35
66
  async (request, reply) => {
36
67
  const { id } = request.params;
37
68
 
38
- try {
39
- const file = await prisma.file.findUnique({
40
- where: { id },
41
- });
69
+ const context = { request, fastify };
70
+ const visible = await findVisibleFile(id, context);
42
71
 
43
- if (!file) {
44
- return reply.code(404).send(createNotFoundError('The requested file was not found', id));
45
- }
72
+ if (!visible) {
73
+ return sendFileNotVisible(reply, id, context);
74
+ }
46
75
 
47
- const metadata: FileMetadata | false = await fileHandler.head(file, { request, fastify });
76
+ const { file, entity } = visible;
77
+ if (await denyContent(reply, entity, context)) {
78
+ return reply;
79
+ }
48
80
 
49
- if (!metadata) {
50
- return reply.code(404).send(createNotFoundError('The requested file metadata was not found', id));
51
- }
81
+ const metadata: FileMetadata | false = await fileHandler.head(file, context);
52
82
 
53
- setFileHeaders(reply, metadata);
83
+ if (!metadata) {
84
+ return reply.code(404).send(createNotFoundError('The requested file metadata was not found', id));
85
+ }
54
86
 
55
- return reply.code(200).send();
56
- } catch (error) {
57
- const err = error as Error;
58
- fastify.log.error(`File metadata retrieval error: ${err.message}`);
87
+ setFileHeaders(reply, metadata);
59
88
 
60
- return reply.code(500).send(createInternalError());
61
- }
89
+ return reply.code(200).send();
62
90
  },
63
91
  );
64
92
 
@@ -73,61 +101,55 @@ const file: FastifyPluginAsync<FileRouteOptions> = async (fastify, opts) => {
73
101
  async (request, reply) => {
74
102
  const { id } = request.params;
75
103
 
76
- try {
77
- const file = await prisma.file.findUnique({
78
- where: { id },
79
- });
104
+ const context = { request, fastify };
105
+ const visible = await findVisibleFile(id, context);
80
106
 
81
- if (!file) {
82
- return reply.code(404).send(createNotFoundError('The requested file was not found', id));
83
- }
107
+ if (!visible) {
108
+ return sendFileNotVisible(reply, id, context);
109
+ }
84
110
 
85
- const result = await fileHandler.get(file, { request, fastify });
111
+ const { file, entity } = visible;
112
+ if (await denyContent(reply, entity, context)) {
113
+ return reply;
114
+ }
86
115
 
87
- if (!result) {
88
- return reply.code(404).send(createNotFoundError('The requested file could not be retrieved', id));
89
- }
116
+ const result = await fileHandler.get(file, context);
90
117
 
91
- if (result.type === 'redirect') {
92
- if (request.query.noRedirect) {
93
- return reply.code(200).send({ location: result.url });
94
- }
118
+ if (!result) {
119
+ return reply.code(404).send(createNotFoundError('The requested file could not be retrieved', id));
120
+ }
95
121
 
96
- return reply.code(302).redirect(result.url);
122
+ if (result.type === 'redirect') {
123
+ if (request.query.noRedirect) {
124
+ return reply.code(200).send({ location: result.url });
97
125
  }
98
126
 
99
- const { disposition, filename: customFilename } = request.query;
100
- const filename = customFilename || file.filename;
101
- setFileHeaders(reply, result.metadata);
102
- reply.header('Content-Disposition', `${disposition}; filename="${filename}"`);
127
+ return reply.code(302).redirect(result.url);
128
+ }
103
129
 
104
- // Handle stream response
105
- if (result.type === 'stream') {
106
- return reply.code(200).send(result.stream);
107
- }
130
+ const { disposition, filename: customFilename } = request.query;
131
+ const filename = customFilename || file.filename;
132
+ setFileHeaders(reply, result.metadata);
133
+ reply.header('Content-Disposition', `${disposition}; filename="${filename}"`);
108
134
 
109
- if (result.type === 'file') {
110
- if (result.accelPath) {
111
- reply.header('X-Accel-Redirect', result.accelPath);
112
- return reply.code(200).send();
113
- }
135
+ // Handle stream response
136
+ if (result.type === 'stream') {
137
+ return reply.code(200).send(result.stream);
138
+ }
114
139
 
115
- const stream = createReadStream(result.path);
116
- return reply.code(200).send(stream);
140
+ if (result.type === 'file') {
141
+ if (result.accelPath) {
142
+ reply.header('X-Accel-Redirect', result.accelPath);
143
+ return reply.code(200).send();
117
144
  }
118
145
 
119
- // Exhaustiveness check - should never reach here with proper types
120
- console.error(`Unexpected file result type: ${(result as { type: string }).type}`);
121
- reply.removeHeader('Content-Disposition');
122
- reply.removeHeader('Content-Type');
123
- reply.removeHeader('Content-Length');
124
- return reply.code(500).send(createInternalError());
125
- } catch (error) {
126
- const err = error as Error;
127
- fastify.log.error(`File retrieval error: ${err}`);
128
-
129
- return reply.code(500).send(createInternalError());
146
+ const stream = createReadStream(result.path);
147
+ return reply.code(200).send(stream);
130
148
  }
149
+
150
+ // Exhaustiveness check - should never reach here with proper types
151
+ reply.removeHeader('Content-Disposition');
152
+ throw new Error(`Unexpected file result type: ${(result as { type: string }).type}`);
131
153
  },
132
154
  );
133
155
  };
@@ -1,14 +1,33 @@
1
1
  import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
- import type { FileAccessTransformer, FileTransformer } from '../app.js';
2
+ import type { AccessFunction, FileTransformer } from '../app.js';
3
3
  import { fastify, fastifyAfter, fastifyBefore, prisma } from '../test/helpers/fastify.js';
4
- import { AllPublicFileAccessTransformer } from '../transformers/default.js';
4
+ import { AllPublicAccess } from '../utils/access.js';
5
5
  import type { StandardErrorResponse } from '../utils/errors.js';
6
+ import { AllVisibleEntityFilter } from '../utils/visibility.js';
6
7
  import filesRoute from './files.js';
7
8
 
8
9
  describe('Files Route', () => {
10
+ const mockEntity = (id: string, name: string) => ({
11
+ id,
12
+ name,
13
+ description: '',
14
+ entityType: 'http://schema.org/MediaObject',
15
+ memberOf: null,
16
+ rootCollection: null,
17
+ metadataLicenseId: 'https://creativecommons.org/licenses/by/4.0/',
18
+ contentLicenseId: 'https://creativecommons.org/licenses/by/4.0/',
19
+ meta: {},
20
+ createdAt: new Date('2025-01-01'),
21
+ updatedAt: new Date('2025-01-01'),
22
+ });
23
+
9
24
  beforeEach(async () => {
10
25
  await fastifyBefore();
11
- await fastify.register(filesRoute, { prisma, fileAccessTransformer: AllPublicFileAccessTransformer });
26
+ await fastify.register(filesRoute, {
27
+ entityVisibilityFilter: AllVisibleEntityFilter,
28
+ prisma,
29
+ access: AllPublicAccess,
30
+ });
12
31
  });
13
32
 
14
33
  afterEach(async () => {
@@ -23,6 +42,7 @@ describe('Files Route', () => {
23
42
  meta: {},
24
43
  createdAt: new Date('2025-01-01'),
25
44
  updatedAt: new Date('2025-01-01'),
45
+ entity: mockEntity('http://example.com/file1.wav', 'file1.wav'),
26
46
  };
27
47
 
28
48
  const mockFile2 = {
@@ -33,6 +53,7 @@ describe('Files Route', () => {
33
53
  meta: {},
34
54
  createdAt: new Date('2025-01-02'),
35
55
  updatedAt: new Date('2025-01-02'),
56
+ entity: mockEntity('http://example.com/file2.txt', 'file2.txt'),
36
57
  };
37
58
 
38
59
  describe('GET /files', () => {
@@ -58,6 +79,9 @@ describe('Files Route', () => {
58
79
  content: true,
59
80
  },
60
81
  });
82
+ expect(prisma.file.findMany).toHaveBeenCalledWith(
83
+ expect.objectContaining({ include: { entity: { omit: { meta: true } } } }),
84
+ );
61
85
  });
62
86
 
63
87
  it('should filter files by memberOf', async () => {
@@ -79,7 +103,7 @@ describe('Files Route', () => {
79
103
  });
80
104
  expect(prisma.file.findMany).toHaveBeenCalledWith(
81
105
  expect.objectContaining({
82
- where: { entity: { memberOf: 'http://example.com/collection/1' } },
106
+ where: { entity: { AND: [{ memberOf: 'http://example.com/collection/1' }, {}] } },
83
107
  }),
84
108
  );
85
109
  });
@@ -175,7 +199,7 @@ describe('Files Route', () => {
175
199
  const body = JSON.parse(response.body) as StandardErrorResponse;
176
200
 
177
201
  expect(response.statusCode).toBe(400);
178
- expect(body.error).toBe('Bad Request');
202
+ expect(body.error.code).toBe('VALIDATION_ERROR');
179
203
  });
180
204
 
181
205
  it('should validate memberOf parameter format', async () => {
@@ -186,7 +210,7 @@ describe('Files Route', () => {
186
210
  const body = JSON.parse(response.body) as StandardErrorResponse;
187
211
 
188
212
  expect(response.statusCode).toBe(400);
189
- expect(body.error).toBe('Bad Request');
213
+ expect(body.error.code).toBe('VALIDATION_ERROR');
190
214
  });
191
215
 
192
216
  it('should validate sort parameter', async () => {
@@ -197,7 +221,7 @@ describe('Files Route', () => {
197
221
  const body = JSON.parse(response.body) as StandardErrorResponse;
198
222
 
199
223
  expect(response.statusCode).toBe(400);
200
- expect(body.error).toBe('Bad Request');
224
+ expect(body.error.code).toBe('VALIDATION_ERROR');
201
225
  });
202
226
  });
203
227
 
@@ -213,8 +237,9 @@ describe('Files Route', () => {
213
237
  });
214
238
 
215
239
  await fastify.register(filesRoute, {
240
+ entityVisibilityFilter: AllVisibleEntityFilter,
216
241
  prisma,
217
- fileAccessTransformer: AllPublicFileAccessTransformer,
242
+ access: AllPublicAccess,
218
243
  fileTransformers: [customTransformer],
219
244
  });
220
245
 
@@ -238,25 +263,27 @@ describe('Files Route', () => {
238
263
  await fastifyAfter();
239
264
  });
240
265
 
241
- it('should apply custom file access transformer', async () => {
266
+ it('should attach the content access of each file entity', async () => {
242
267
  await fastifyBefore();
243
268
 
244
- // Custom access transformer that restricts content access
245
- const customFileAccessTransformer: FileAccessTransformer = (file) => ({
246
- ...file,
247
- access: {
248
- content: false,
249
- contentAuthorizationUrl: 'https://example.com/request-access',
250
- },
251
- });
269
+ const access: AccessFunction = (entity) =>
270
+ entity.id === 'http://example.com/file1.wav'
271
+ ? {
272
+ metadata: false,
273
+ content: false,
274
+ metadataAuthorizationUrl: 'https://example.com/request-metadata',
275
+ contentAuthorizationUrl: 'https://example.com/request-access',
276
+ }
277
+ : { metadata: true, content: true };
252
278
 
253
279
  await fastify.register(filesRoute, {
280
+ entityVisibilityFilter: AllVisibleEntityFilter,
254
281
  prisma,
255
- fileAccessTransformer: customFileAccessTransformer,
282
+ access,
256
283
  });
257
284
 
258
- prisma.file.findMany.mockResolvedValue([mockFile1]);
259
- prisma.file.count.mockResolvedValue(1);
285
+ prisma.file.findMany.mockResolvedValue([mockFile1, mockFile2]);
286
+ prisma.file.count.mockResolvedValue(2);
260
287
 
261
288
  const response = await fastify.inject({
262
289
  method: 'GET',
@@ -264,13 +291,12 @@ describe('Files Route', () => {
264
291
  });
265
292
 
266
293
  expect(response.statusCode).toBe(200);
267
- const body = JSON.parse(response.body) as { files: unknown[] };
268
- expect(body.files[0]).toMatchObject({
269
- access: {
270
- content: false,
271
- contentAuthorizationUrl: 'https://example.com/request-access',
272
- },
294
+ const body = JSON.parse(response.body) as { files: Array<{ access: unknown }> };
295
+ expect(body.files[0].access).toEqual({
296
+ content: false,
297
+ contentAuthorizationUrl: 'https://example.com/request-access',
273
298
  });
299
+ expect(body.files[1].access).toEqual({ content: true });
274
300
 
275
301
  await fastifyAfter();
276
302
  });
@@ -2,9 +2,10 @@ import type { FastifyPluginAsync } from 'fastify';
2
2
  import type { ZodTypeProvider } from 'fastify-type-provider-zod';
3
3
  import { z } from 'zod';
4
4
  import type { PrismaClient } from '../generated/prisma/client.js';
5
- import { baseFileTransformer } from '../transformers/default.js';
6
- import type { FileAccessTransformer, FileTransformer } from '../types/transformers.js';
7
- import { createInternalError } from '../utils/errors.js';
5
+ import { applyTransformers, authoriseFiles } from '../transformers/default.js';
6
+ import type { AccessFunction } from '../types/access.js';
7
+ import type { FileTransformer } from '../types/transformers.js';
8
+ import type { EntityVisibilityFilter } from '../types/visibility.js';
8
9
 
9
10
  const querySchema = z.object({
10
11
  memberOf: z.url().optional(),
@@ -16,12 +17,13 @@ const querySchema = z.object({
16
17
 
17
18
  type FilesRouteOptions = {
18
19
  prisma: PrismaClient;
19
- fileAccessTransformer: FileAccessTransformer;
20
+ access: AccessFunction;
20
21
  fileTransformers?: FileTransformer[];
22
+ entityVisibilityFilter: EntityVisibilityFilter;
21
23
  };
22
24
 
23
25
  const files: FastifyPluginAsync<FilesRouteOptions> = async (fastify, opts) => {
24
- const { prisma, fileAccessTransformer, fileTransformers = [] } = opts;
26
+ const { prisma, access, fileTransformers = [], entityVisibilityFilter } = opts;
25
27
 
26
28
  fastify.withTypeProvider<ZodTypeProvider>().get(
27
29
  '/files',
@@ -30,53 +32,35 @@ const files: FastifyPluginAsync<FilesRouteOptions> = async (fastify, opts) => {
30
32
  querystring: querySchema,
31
33
  },
32
34
  },
33
- async (request, reply) => {
35
+ async (request) => {
34
36
  const { memberOf, limit, offset, sort, order } = request.query;
35
37
 
36
- try {
37
- const where: NonNullable<Parameters<typeof prisma.file.findMany>[0]>['where'] = {};
38
+ const context = { request, fastify };
39
+ const visibilityWhere = await entityVisibilityFilter(context);
40
+ const where = { entity: { AND: [{ memberOf }, visibilityWhere] } };
38
41
 
39
- if (memberOf) {
40
- where.entity = { memberOf };
41
- }
42
+ const [dbFiles, total] = await Promise.all([
43
+ prisma.file.findMany({
44
+ where,
45
+ include: { entity: { omit: { meta: true } } },
46
+ orderBy: {
47
+ [sort]: order,
48
+ },
49
+ skip: offset,
50
+ take: limit,
51
+ }),
52
+ prisma.file.count({ where }),
53
+ ]);
42
54
 
43
- const [dbFiles, total] = await Promise.all([
44
- prisma.file.findMany({
45
- where,
46
- orderBy: {
47
- [sort]: order,
48
- },
49
- skip: offset,
50
- take: limit,
51
- }),
52
- prisma.file.count({ where }),
53
- ]);
55
+ const authorisedFiles = await authoriseFiles(dbFiles, access, context);
56
+ const filesWithAccess = await Promise.all(
57
+ authorisedFiles.map((file) => applyTransformers(file, fileTransformers, context)),
58
+ );
54
59
 
55
- // Apply transformers to each entity: base -> access -> additional
56
- const filesWithAccess = await Promise.all(
57
- dbFiles.map(async (dbFile) => {
58
- const standardFile = baseFileTransformer(dbFile);
59
- const authorisedFile = await fileAccessTransformer(standardFile, { request, fastify });
60
-
61
- let result = authorisedFile;
62
- for (const transformer of fileTransformers) {
63
- result = await transformer(result, { request, fastify });
64
- }
65
-
66
- return result;
67
- }),
68
- );
69
-
70
- return {
71
- total,
72
- files: filesWithAccess,
73
- };
74
- } catch (error) {
75
- const err = error as Error;
76
- fastify.log.error(`Database error: ${err.message}`);
77
-
78
- return reply.code(500).send(createInternalError());
79
- }
60
+ return {
61
+ total,
62
+ files: filesWithAccess,
63
+ };
80
64
  },
81
65
  );
82
66
  };
@@ -3,9 +3,14 @@ import type { FastifyPluginAsync } from 'fastify';
3
3
  import type { ZodTypeProvider } from 'fastify-type-provider-zod';
4
4
  import { z } from 'zod';
5
5
  import type { PrismaClient } from '../generated/prisma/client.js';
6
+ import type { AccessFunction } from '../types/access.js';
7
+ import type { RequestContext } from '../types/context.js';
6
8
  import type { FileMetadata, RoCrateHandler } from '../types/fileHandlers.js';
7
- import { createInternalError, createNotFoundError } from '../utils/errors.js';
9
+ import type { EntityVisibilityFilter } from '../types/visibility.js';
10
+ import { createAccessGuard } from '../utils/access.js';
11
+ import { createNotFoundError } from '../utils/errors.js';
8
12
  import { setFileHeaders } from '../utils/headers.js';
13
+ import { createEntityNotVisibleResponder, type RefusalOptions } from '../utils/visibility.js';
9
14
 
10
15
  const paramsSchema = z.object({
11
16
  id: z.url(),
@@ -14,10 +19,19 @@ const paramsSchema = z.object({
14
19
  type CrateRouteOptions = {
15
20
  prisma: PrismaClient;
16
21
  roCrateHandler: RoCrateHandler;
22
+ access: AccessFunction;
23
+ entityVisibilityFilter: EntityVisibilityFilter;
24
+ refusal: RefusalOptions;
17
25
  };
18
26
 
19
27
  const crate: FastifyPluginAsync<CrateRouteOptions> = async (fastify, opts) => {
20
- const { prisma, roCrateHandler } = opts;
28
+ const { prisma, roCrateHandler, access, entityVisibilityFilter, refusal } = opts;
29
+
30
+ const findVisibleEntity = async (id: string, context: RequestContext) =>
31
+ prisma.entity.findFirst({ where: { AND: [{ id }, await entityVisibilityFilter(context)] } });
32
+
33
+ const sendEntityNotVisible = createEntityNotVisibleResponder(prisma, refusal);
34
+ const denyMetadata = createAccessGuard({ access, isAuthenticated: refusal.isAuthenticated, level: 'metadata' });
21
35
 
22
36
  fastify.withTypeProvider<ZodTypeProvider>().head(
23
37
  '/entity/:id/metadata',
@@ -29,30 +43,26 @@ const crate: FastifyPluginAsync<CrateRouteOptions> = async (fastify, opts) => {
29
43
  async (request, reply) => {
30
44
  const { id } = request.params;
31
45
 
32
- try {
33
- const entity = await prisma.entity.findUnique({
34
- where: { id },
35
- });
46
+ const context = { request, fastify };
47
+ const entity = await findVisibleEntity(id, context);
36
48
 
37
- if (!entity) {
38
- return reply.code(404).send(createNotFoundError('The requested entity was not found', id));
39
- }
49
+ if (!entity) {
50
+ return sendEntityNotVisible(reply, id, context);
51
+ }
40
52
 
41
- const metadata: FileMetadata | false = await roCrateHandler.head(entity, { request, fastify });
53
+ if (await denyMetadata(reply, entity, context)) {
54
+ return reply;
55
+ }
42
56
 
43
- if (!metadata) {
44
- return reply.code(404).send(createNotFoundError('The requested RO-Crate metadata was not found', id));
45
- }
57
+ const metadata: FileMetadata | false = await roCrateHandler.head(entity, context);
46
58
 
47
- setFileHeaders(reply, metadata);
59
+ if (!metadata) {
60
+ return reply.code(404).send(createNotFoundError('The requested RO-Crate metadata was not found', id));
61
+ }
48
62
 
49
- return reply.code(200).send();
50
- } catch (error) {
51
- const err = error as Error;
52
- fastify.log.error(`RO-Crate metadata retrieval error: ${err}`);
63
+ setFileHeaders(reply, metadata);
53
64
 
54
- return reply.code(500).send(createInternalError());
55
- }
65
+ return reply.code(200).send();
56
66
  },
57
67
  );
58
68
 
@@ -66,56 +76,52 @@ const crate: FastifyPluginAsync<CrateRouteOptions> = async (fastify, opts) => {
66
76
  async (request, reply) => {
67
77
  const { id } = request.params;
68
78
 
69
- try {
70
- const entity = await prisma.entity.findUnique({
71
- where: { id },
72
- });
79
+ const context = { request, fastify };
80
+ const entity = await findVisibleEntity(id, context);
73
81
 
74
- if (!entity) {
75
- return reply.code(404).send(createNotFoundError('The requested entity was not found', id));
76
- }
82
+ if (!entity) {
83
+ return sendEntityNotVisible(reply, id, context);
84
+ }
77
85
 
78
- const result = await roCrateHandler.get(entity, { request, fastify });
86
+ if (await denyMetadata(reply, entity, context)) {
87
+ return reply;
88
+ }
79
89
 
80
- if (!result) {
81
- return reply.code(404).send(createNotFoundError('The requested RO-Crate could not be retrieved', id));
82
- }
90
+ const result = await roCrateHandler.get(entity, context);
83
91
 
84
- if (result.type === 'redirect') {
85
- return reply.code(302).redirect(result.url);
86
- }
92
+ if (!result) {
93
+ return reply.code(404).send(createNotFoundError('The requested RO-Crate could not be retrieved', id));
94
+ }
87
95
 
88
- // Set content type to application/ld+json for RO-Crate
89
- const metadata = {
90
- ...result.metadata,
91
- contentType: 'application/ld+json',
92
- };
96
+ if (result.type === 'redirect') {
97
+ return reply.code(302).redirect(result.url);
98
+ }
93
99
 
94
- setFileHeaders(reply, metadata);
100
+ // Set content type to application/ld+json for RO-Crate
101
+ const metadata = {
102
+ ...result.metadata,
103
+ contentType: 'application/ld+json',
104
+ };
95
105
 
96
- // Handle stream response
97
- if (result.type === 'stream') {
98
- return reply.code(200).send(result.stream);
99
- }
106
+ setFileHeaders(reply, metadata);
100
107
 
101
- if (result.type === 'file') {
102
- if (result.accelPath) {
103
- reply.header('X-Accel-Redirect', result.accelPath);
104
- return reply.code(200).send();
105
- }
108
+ // Handle stream response
109
+ if (result.type === 'stream') {
110
+ return reply.code(200).send(result.stream);
111
+ }
106
112
 
107
- const stream = createReadStream(result.path);
108
- return reply.code(200).send(stream);
113
+ if (result.type === 'file') {
114
+ if (result.accelPath) {
115
+ reply.header('X-Accel-Redirect', result.accelPath);
116
+ return reply.code(200).send();
109
117
  }
110
118
 
111
- // Exhaustiveness check - should never reach here with proper types
112
- throw new Error(`Unexpected RO-Crate result type: ${(result as { type: string }).type}`);
113
- } catch (error) {
114
- const err = error as Error;
115
- fastify.log.error(`RO-Crate retrieval error: ${err.message}`);
116
-
117
- return reply.code(500).send(createInternalError());
119
+ const stream = createReadStream(result.path);
120
+ return reply.code(200).send(stream);
118
121
  }
122
+
123
+ // Exhaustiveness check - should never reach here with proper types
124
+ throw new Error(`Unexpected RO-Crate result type: ${(result as { type: string }).type}`);
119
125
  },
120
126
  );
121
127
  };