@open-pencil/cloud 0.16.0 → 0.17.0-beta.2

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 (54) hide show
  1. package/dist/listen.mjs +236 -117
  2. package/dist/listen.mjs.map +1 -1
  3. package/dist/runtime-node.d.mts +2937 -703
  4. package/dist/runtime-node.d.mts.map +1 -1
  5. package/dist/server.d.ts +3985 -941
  6. package/dist/server.d.ts.map +1 -1
  7. package/dist/server.js +833 -376
  8. package/dist/server.js.map +1 -1
  9. package/dist/server.mjs +665 -271
  10. package/dist/server.mjs.map +1 -1
  11. package/package.json +4 -2
  12. package/src/admin/api/routes.ts +44 -33
  13. package/src/runtime/cloudflare/environment.ts +16 -2
  14. package/src/runtime/cloudflare/relay/index.ts +128 -0
  15. package/src/runtime/cloudflare/relay/sockets.ts +112 -0
  16. package/src/runtime/cloudflare/worker.ts +56 -19
  17. package/src/runtime/node/bootstrap.ts +9 -4
  18. package/src/runtime/node/server.ts +40 -8
  19. package/src/runtime/posthog/errors.ts +48 -0
  20. package/src/runtime/s3/objects.ts +26 -0
  21. package/src/runtime/site/server.ts +5 -3
  22. package/src/server/api/router.ts +3 -2
  23. package/src/server/api/types.ts +7 -0
  24. package/src/server/app.ts +4 -0
  25. package/src/server/cleanup/objects.ts +10 -2
  26. package/src/server/cleanup/revisions.ts +8 -2
  27. package/src/server/collaboration/index.ts +3 -0
  28. package/src/server/collaboration/relay/connection.ts +195 -0
  29. package/src/server/collaboration/relay/hub.ts +199 -187
  30. package/src/server/collaboration/relay/index.ts +3 -1
  31. package/src/server/collaboration/relay/log.ts +76 -0
  32. package/src/server/collaboration/relay/persistence.ts +147 -22
  33. package/src/server/collaboration/relay/resume.ts +28 -0
  34. package/src/server/collaboration/routes.ts +27 -16
  35. package/src/server/config/deployment.ts +11 -0
  36. package/src/server/config/schema.ts +24 -2
  37. package/src/server/db/migrate.ts +3 -1
  38. package/src/server/db/migrations/028_collaboration_updates.ts +84 -0
  39. package/src/server/db/tables.ts +18 -4
  40. package/src/server/documents/routes.ts +106 -80
  41. package/src/server/documents/versions/routes.ts +36 -25
  42. package/src/server/documents/versions/service.ts +9 -0
  43. package/src/server/errors/index.ts +56 -0
  44. package/src/server/index.ts +11 -0
  45. package/src/server/internal/routes.ts +3 -8
  46. package/src/server/objects/types.ts +12 -0
  47. package/src/server/pictures/routes.ts +4 -2
  48. package/src/server/rate-limit/index.ts +4 -1
  49. package/src/server/rate-limit/middleware.ts +99 -11
  50. package/src/server/sharing/document-routes.ts +30 -22
  51. package/src/server/sharing/routes.ts +122 -83
  52. package/src/server/validation.ts +58 -2
  53. package/src/server/workspaces/routes.ts +63 -45
  54. package/src/runtime/cloudflare/relay.ts +0 -136
@@ -1,7 +1,8 @@
1
- import type { CloudAPIEnvironment } from '#cloud/server/api/types'
1
+ import type { CloudAPIEnvironment, RateLimitUse } from '#cloud/server/api/types'
2
2
  import type { CloudDatabase } from '#cloud/server/db'
3
- import type { Context, Env, Input } from 'hono'
3
+ import type { Context, Env, Input, MiddlewareHandler } from 'hono'
4
4
  import { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'
5
+ import { every } from 'hono/combine'
5
6
  import { matchedRoutes } from 'hono/route'
6
7
  import type { Kysely } from 'kysely'
7
8
 
@@ -14,18 +15,39 @@ export type RateLimitPolicy = {
14
15
  limit: number
15
16
  }
16
17
 
18
+ /**
19
+ * A budget counted per resource, such as a document, with `actorLimit` capping one actor across
20
+ * every resource, so new resources do not add budget without end.
21
+ */
22
+ export type ResourceRateLimitPolicy = RateLimitPolicy & { actorLimit: number }
23
+
17
24
  export const CLOUD_RATE_LIMITS = {
18
25
  publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },
19
- collaborationTicket: { namespace: 'collaboration-ticket', windowMs: 60_000, limit: 60 },
20
- invitationMutation: { namespace: 'invitation-mutation', windowMs: 60_000, limit: 30 },
26
+ collaborationTicket: {
27
+ namespace: 'collaboration-ticket',
28
+ windowMs: 60_000,
29
+ limit: 60,
30
+ actorLimit: 300
31
+ },
32
+ invitationMutation: {
33
+ namespace: 'invitation-mutation',
34
+ windowMs: 60_000,
35
+ limit: 30,
36
+ actorLimit: 60
37
+ },
21
38
  workspaceCreation: { namespace: 'workspace-creation', windowMs: 60_000, limit: 30 },
22
- documentCreation: { namespace: 'document-creation', windowMs: 60_000, limit: 60 },
23
- uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120 },
39
+ documentCreation: {
40
+ namespace: 'document-creation',
41
+ windowMs: 60_000,
42
+ limit: 60,
43
+ actorLimit: 120
44
+ },
45
+ uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120, actorLimit: 600 },
24
46
  authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },
25
47
  aiToken: { namespace: 'ai-token', windowMs: 60_000, limit: 30 },
26
48
  adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },
27
49
  adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }
28
- } as const satisfies Record<string, RateLimitPolicy>
50
+ } as const satisfies Record<string, RateLimitPolicy | ResourceRateLimitPolicy>
29
51
 
30
52
  /**
31
53
  * The limiters routes mount for their own budget, each with which requests it counts. A general
@@ -123,15 +145,81 @@ export function createActorRateLimiter(
123
145
  }
124
146
 
125
147
  /**
126
- * A limiter a route mounts for its own budget, such as document creation; general limiters leave
148
+ * A limiter a route mounts for its own budget, such as workspace creation; general limiters leave
127
149
  * the requests it counts to it.
128
150
  */
129
151
  export function createRouteRateLimiter(
130
152
  database: Kysely<CloudDatabase>,
131
153
  secret: string,
132
154
  policy: RateLimitPolicy,
133
- skip?: (context: Context) => boolean,
134
- resource?: (context: Context<CloudAPIEnvironment, '*'>) => string
155
+ skip?: (context: Context) => boolean
156
+ ) {
157
+ return ownBudget(createActorRateLimiter(database, secret, policy, skip), skip)
158
+ }
159
+
160
+ /**
161
+ * A route's own budget counted per resource, such as uploads per document, and capped per actor
162
+ * across resources by `actorLimit`; general limiters leave the requests it counts to it.
163
+ */
164
+ export function createResourceRateLimiter(
165
+ database: Kysely<CloudDatabase>,
166
+ secret: string,
167
+ policy: ResourceRateLimitPolicy,
168
+ resource: (context: Context<CloudAPIEnvironment, '*'>) => string,
169
+ skip?: (context: Context) => boolean
135
170
  ) {
136
- return ownBudget(createActorRateLimiter(database, secret, policy, skip, resource), skip)
171
+ const perResource = createActorRateLimiter(database, secret, policy, skip, resource)
172
+ const perActor = createActorRateLimiter(
173
+ database,
174
+ secret,
175
+ { namespace: `${policy.namespace}-actor`, windowMs: policy.windowMs, limit: policy.actorLimit },
176
+ skip
177
+ )
178
+ return ownBudget(
179
+ every(perResource, keepResourceUse, perActor, reportTighterBudget(policy.windowMs)),
180
+ skip
181
+ )
182
+ }
183
+
184
+ /** Keeps the resource budget's use, which the actor-wide limiter would record over. */
185
+ const keepResourceUse: MiddlewareHandler<CloudAPIEnvironment> = async (context, next) => {
186
+ context.set('resourceRateLimit', context.get('rateLimit'))
187
+ await next()
188
+ }
189
+
190
+ /**
191
+ * Reports whichever budget has fewer requests left in the `RateLimit` headers, as both limiters
192
+ * write them and the last would otherwise win. A refused request keeps the headers of the budget
193
+ * that refused it.
194
+ */
195
+ function reportTighterBudget(windowMs: number): MiddlewareHandler<CloudAPIEnvironment> {
196
+ return async (context, next) => {
197
+ const resource = context.get('resourceRateLimit')
198
+ const actor = context.get('rateLimit')
199
+ const tighter = resource && actor && resource.remaining < actor.remaining ? resource : actor
200
+ if (tighter) setBudgetHeaders(context, tighter, windowMs)
201
+ await next()
202
+ }
203
+ }
204
+
205
+ /** The draft-7 `RateLimit` headers `hono-rate-limiter` writes, for one budget's use. */
206
+ function setBudgetHeaders(context: Context, use: RateLimitUse, windowMs: number): void {
207
+ const windowSeconds = Math.ceil(windowMs / 1000)
208
+ const reset = use.resetTime
209
+ ? Math.max(0, Math.ceil((use.resetTime.getTime() - Date.now()) / 1000))
210
+ : windowSeconds
211
+ context.header('RateLimit-Policy', `${use.limit};w=${windowSeconds}`)
212
+ context.header('RateLimit', `limit=${use.limit}, remaining=${use.remaining}, reset=${reset}`)
213
+ }
214
+
215
+ /**
216
+ * A limiter's resource named by a route parameter, such as the document a request uploads to. It
217
+ * runs before the route's param validator, and the value only names the limiter's counter, which
218
+ * `rateLimitKey` hashes; it never reaches a query.
219
+ */
220
+ export function routeParamResource(name: string) {
221
+ return (context: Context): string =>
222
+ // Lowercased as validation lowercases UUIDs, so one row's spellings share a budget.
223
+ // eslint-disable-next-line open-pencil/no-unvalidated-route-params -- a counter name, hashed, never queried.
224
+ context.req.param(name)?.toLowerCase() ?? 'unknown'
137
225
  }
@@ -3,7 +3,7 @@ import type { CloudSessionResolver } from '#cloud/server/auth'
3
3
  import type { DocumentService } from '#cloud/server/documents'
4
4
  import type { DocumentSharingService } from '#cloud/server/sharing'
5
5
  import { sharingRoute } from '#cloud/server/sharing/http'
6
- import { validatedJSON } from '#cloud/server/validation'
6
+ import { shareParams, validatedJSON } from '#cloud/server/validation'
7
7
  import { Hono } from 'hono'
8
8
 
9
9
  import { shareActor } from './actor'
@@ -14,28 +14,36 @@ export function createPublicDocumentRoutes(
14
14
  resolveSession?: CloudSessionResolver
15
15
  ) {
16
16
  return new Hono()
17
- .post('/shares/:shareId/document', validatedJSON(parseResolveDocumentShare), (context) =>
18
- sharingRoute(context, async () => {
19
- const resolution = await sharing.resolveShare(
20
- context.req.param('shareId'),
21
- context.req.valid('json'),
22
- await shareActor(context.req.raw, resolveSession)
23
- )
24
- return context.json({
25
- resolution,
26
- document: await documents.downloadShared(resolution.documentId)
17
+ .post(
18
+ '/shares/:shareId/document',
19
+ shareParams,
20
+ validatedJSON(parseResolveDocumentShare),
21
+ (context) =>
22
+ sharingRoute(context, async () => {
23
+ const resolution = await sharing.resolveShare(
24
+ context.req.valid('param').shareId,
25
+ context.req.valid('json'),
26
+ await shareActor(context.req.raw, resolveSession)
27
+ )
28
+ return context.json({
29
+ resolution,
30
+ document: await documents.downloadShared(resolution.documentId)
31
+ })
27
32
  })
28
- })
29
33
  )
30
- .post('/shares/:shareId/images', validatedJSON(parseRequestSharedImageLinks), (context) =>
31
- sharingRoute(context, async () => {
32
- const { checksums, ...share } = context.req.valid('json')
33
- const resolution = await sharing.resolveShare(
34
- context.req.param('shareId'),
35
- share,
36
- await shareActor(context.req.raw, resolveSession)
37
- )
38
- return context.json(await documents.imageLinksShared(resolution.documentId, checksums))
39
- })
34
+ .post(
35
+ '/shares/:shareId/images',
36
+ shareParams,
37
+ validatedJSON(parseRequestSharedImageLinks),
38
+ (context) =>
39
+ sharingRoute(context, async () => {
40
+ const { checksums, ...share } = context.req.valid('json')
41
+ const resolution = await sharing.resolveShare(
42
+ context.req.valid('param').shareId,
43
+ share,
44
+ await shareActor(context.req.raw, resolveSession)
45
+ )
46
+ return context.json(await documents.imageLinksShared(resolution.documentId, checksums))
47
+ })
40
48
  )
41
49
  }
@@ -10,10 +10,23 @@ import {
10
10
  } from '#cloud/contract'
11
11
  import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
12
12
  import type { CloudDatabase } from '#cloud/server/db'
13
- import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
13
+ import {
14
+ CLOUD_RATE_LIMITS,
15
+ routeParamResource,
16
+ createResourceRateLimiter
17
+ } from '#cloud/server/rate-limit'
14
18
  import { sharingRoute } from '#cloud/server/sharing/http'
15
19
  import type { DocumentSharingService } from '#cloud/server/sharing/service'
16
- import { validatedJSON } from '#cloud/server/validation'
20
+ import {
21
+ documentInvitationParams,
22
+ documentParams,
23
+ documentShareParams,
24
+ documentUserParams,
25
+ invitationContinuationParams,
26
+ invitationParams,
27
+ shareParams,
28
+ validatedJSON
29
+ } from '#cloud/server/validation'
17
30
  import { Hono } from 'hono'
18
31
  import type { Kysely } from 'kysely'
19
32
 
@@ -31,147 +44,161 @@ export function createDocumentSharingRoutes(
31
44
  if (rateLimit) {
32
45
  router.use(
33
46
  '/documents/:documentId/invitations',
34
- createRouteRateLimiter(
47
+ createResourceRateLimiter(
35
48
  rateLimit.database,
36
49
  rateLimit.secret,
37
50
  CLOUD_RATE_LIMITS.invitationMutation,
38
- (context) => context.req.method !== 'POST',
39
- (context) => context.req.param('documentId') ?? 'unknown'
51
+ routeParamResource('documentId'),
52
+ (context) => context.req.method !== 'POST'
40
53
  )
41
54
  )
42
55
  }
43
56
  return router
44
- .post('/documents/:documentId/users/lookup', validatedJSON(parseLookupCloudUser), (context) =>
45
- sharingRoute(context, async () =>
46
- context.json({
47
- user: await service.lookupUser(
48
- context.get('actor').userId,
49
- context.req.param('documentId'),
50
- context.req.valid('json')
51
- )
52
- })
53
- )
57
+ .post(
58
+ '/documents/:documentId/users/lookup',
59
+ documentParams,
60
+ validatedJSON(parseLookupCloudUser),
61
+ (context) =>
62
+ sharingRoute(context, async () =>
63
+ context.json({
64
+ user: await service.lookupUser(
65
+ context.get('actor').userId,
66
+ context.req.valid('param').documentId,
67
+ context.req.valid('json')
68
+ )
69
+ })
70
+ )
54
71
  )
55
- .get('/documents/:documentId/users/:userId', (context) =>
72
+ .get('/documents/:documentId/users/:userId', documentUserParams, (context) =>
56
73
  sharingRoute(context, async () =>
57
74
  context.json({
58
75
  user: await service.userProfile(
59
76
  context.get('actor').userId,
60
- context.req.param('documentId'),
61
- context.req.param('userId')
77
+ context.req.valid('param').documentId,
78
+ context.req.valid('param').userId
62
79
  )
63
80
  })
64
81
  )
65
82
  )
66
- .get('/documents/:documentId/shares', (context) =>
83
+ .get('/documents/:documentId/shares', documentParams, (context) =>
67
84
  sharingRoute(context, async () =>
68
85
  context.json({
69
86
  shares: await service.listShares(
70
87
  context.get('actor').userId,
71
- context.req.param('documentId')
88
+ context.req.valid('param').documentId
72
89
  )
73
90
  })
74
91
  )
75
92
  )
76
- .post('/documents/:documentId/shares', validatedJSON(parseCreateDocumentShare), (context) =>
77
- sharingRoute(context, async () =>
78
- context.json(
79
- await service.createShare(
80
- context.get('actor').userId,
81
- context.req.param('documentId'),
82
- context.req.valid('json')
83
- ),
84
- 201
93
+ .post(
94
+ '/documents/:documentId/shares',
95
+ documentParams,
96
+ validatedJSON(parseCreateDocumentShare),
97
+ (context) =>
98
+ sharingRoute(context, async () =>
99
+ context.json(
100
+ await service.createShare(
101
+ context.get('actor').userId,
102
+ context.req.valid('param').documentId,
103
+ context.req.valid('json')
104
+ ),
105
+ 201
106
+ )
85
107
  )
86
- )
87
108
  )
88
109
  .patch(
89
110
  '/documents/:documentId/shares/:shareId',
111
+ documentShareParams,
90
112
  validatedJSON(parseUpdateDocumentShare),
91
113
  (context) =>
92
114
  sharingRoute(context, async () =>
93
115
  context.json({
94
116
  share: await service.updateShare(
95
117
  context.get('actor').userId,
96
- context.req.param('documentId'),
97
- context.req.param('shareId'),
118
+ context.req.valid('param').documentId,
119
+ context.req.valid('param').shareId,
98
120
  context.req.valid('json')
99
121
  )
100
122
  })
101
123
  )
102
124
  )
103
- .post('/documents/:documentId/shares/:shareId/rotate', (context) =>
125
+ .post('/documents/:documentId/shares/:shareId/rotate', documentShareParams, (context) =>
104
126
  sharingRoute(context, async () =>
105
127
  context.json(
106
128
  await service.rotateShare(
107
129
  context.get('actor').userId,
108
- context.req.param('documentId'),
109
- context.req.param('shareId')
130
+ context.req.valid('param').documentId,
131
+ context.req.valid('param').shareId
110
132
  )
111
133
  )
112
134
  )
113
135
  )
114
- .delete('/documents/:documentId/shares/:shareId', (context) =>
136
+ .delete('/documents/:documentId/shares/:shareId', documentShareParams, (context) =>
115
137
  sharingRoute(context, async () => {
116
138
  await service.revokeShare(
117
139
  context.get('actor').userId,
118
- context.req.param('documentId'),
119
- context.req.param('shareId')
140
+ context.req.valid('param').documentId,
141
+ context.req.valid('param').shareId
120
142
  )
121
143
  return context.body(null, 204)
122
144
  })
123
145
  )
124
- .get('/documents/:documentId/grants', (context) =>
146
+ .get('/documents/:documentId/grants', documentParams, (context) =>
125
147
  sharingRoute(context, async () =>
126
148
  context.json({
127
149
  grants: await service.listGrants(
128
150
  context.get('actor').userId,
129
- context.req.param('documentId')
151
+ context.req.valid('param').documentId
130
152
  )
131
153
  })
132
154
  )
133
155
  )
134
- .put('/documents/:documentId/grants/:userId', validatedJSON(parsePutDocumentGrant), (context) =>
135
- sharingRoute(context, async () =>
136
- context.json({
137
- grant: await service.putGrant(
138
- context.get('actor').userId,
139
- context.req.param('documentId'),
140
- context.req.param('userId'),
141
- context.req.valid('json')
142
- )
143
- })
144
- )
156
+ .put(
157
+ '/documents/:documentId/grants/:userId',
158
+ documentUserParams,
159
+ validatedJSON(parsePutDocumentGrant),
160
+ (context) =>
161
+ sharingRoute(context, async () =>
162
+ context.json({
163
+ grant: await service.putGrant(
164
+ context.get('actor').userId,
165
+ context.req.valid('param').documentId,
166
+ context.req.valid('param').userId,
167
+ context.req.valid('json')
168
+ )
169
+ })
170
+ )
145
171
  )
146
- .delete('/documents/:documentId/grants/:userId', (context) =>
172
+ .delete('/documents/:documentId/grants/:userId', documentUserParams, (context) =>
147
173
  sharingRoute(context, async () => {
148
174
  await service.revokeGrant(
149
175
  context.get('actor').userId,
150
- context.req.param('documentId'),
151
- context.req.param('userId')
176
+ context.req.valid('param').documentId,
177
+ context.req.valid('param').userId
152
178
  )
153
179
  return context.body(null, 204)
154
180
  })
155
181
  )
156
- .get('/documents/:documentId/invitations', (context) =>
182
+ .get('/documents/:documentId/invitations', documentParams, (context) =>
157
183
  sharingRoute(context, async () =>
158
184
  context.json({
159
185
  invitations: await service.listInvitations(
160
186
  context.get('actor').userId,
161
- context.req.param('documentId')
187
+ context.req.valid('param').documentId
162
188
  )
163
189
  })
164
190
  )
165
191
  )
166
192
  .post(
167
193
  '/documents/:documentId/invitations',
194
+ documentParams,
168
195
  validatedJSON(parseCreateDocumentInvitation),
169
196
  (context) =>
170
197
  sharingRoute(context, async () =>
171
198
  context.json(
172
199
  await service.createInvitation(
173
200
  context.get('actor').userId,
174
- context.req.param('documentId'),
201
+ context.req.valid('param').documentId,
175
202
  context.req.valid('json')
176
203
  ),
177
204
  201
@@ -180,27 +207,31 @@ export function createDocumentSharingRoutes(
180
207
  )
181
208
  .post(
182
209
  '/invitations/:invitationId/accept',
210
+ invitationParams,
183
211
  validatedJSON(parseAcceptDocumentInvitation),
184
212
  (context) =>
185
213
  sharingRoute(context, async () =>
186
214
  context.json({
187
215
  accepted: await service.acceptInvitation(
188
216
  context.get('actor'),
189
- context.req.param('invitationId'),
217
+ context.req.valid('param').invitationId,
190
218
  context.req.valid('json')
191
219
  )
192
220
  })
193
221
  )
194
222
  )
195
- .delete('/documents/:documentId/invitations/:invitationId', (context) =>
196
- sharingRoute(context, async () => {
197
- await service.revokeInvitation(
198
- context.get('actor').userId,
199
- context.req.param('documentId'),
200
- context.req.param('invitationId')
201
- )
202
- return context.body(null, 204)
203
- })
223
+ .delete(
224
+ '/documents/:documentId/invitations/:invitationId',
225
+ documentInvitationParams,
226
+ (context) =>
227
+ sharingRoute(context, async () => {
228
+ await service.revokeInvitation(
229
+ context.get('actor').userId,
230
+ context.req.valid('param').documentId,
231
+ context.req.valid('param').invitationId
232
+ )
233
+ return context.body(null, 204)
234
+ })
204
235
  )
205
236
  }
206
237
 
@@ -217,35 +248,43 @@ export function createPublicSharingRoutes(
217
248
  context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)
218
249
  )
219
250
  )
220
- .post('/invitations/continuations/:continuationId/consume', (context) =>
221
- sharingRoute(context, async () =>
222
- context.json(
223
- await service.consumeInvitationContinuation(context.req.param('continuationId'))
251
+ .post(
252
+ '/invitations/continuations/:continuationId/consume',
253
+ invitationContinuationParams,
254
+ (context) =>
255
+ sharingRoute(context, async () =>
256
+ context.json(
257
+ await service.consumeInvitationContinuation(context.req.valid('param').continuationId)
258
+ )
224
259
  )
225
- )
226
260
  )
227
261
  .post(
228
262
  '/invitations/:invitationId/preview',
263
+ invitationParams,
229
264
  validatedJSON(parseAcceptDocumentInvitation),
230
265
  (context) =>
231
266
  sharingRoute(context, async () =>
232
267
  context.json({
233
268
  invitation: await service.previewInvitation(
234
- context.req.param('invitationId'),
269
+ context.req.valid('param').invitationId,
235
270
  context.req.valid('json')
236
271
  )
237
272
  })
238
273
  )
239
274
  )
240
- .post('/shares/:shareId/resolve', validatedJSON(parseResolveDocumentShare), (context) =>
241
- sharingRoute(context, async () =>
242
- context.json({
243
- resolution: await service.resolveShare(
244
- context.req.param('shareId'),
245
- context.req.valid('json'),
246
- await shareActor(context.req.raw, resolveSession)
247
- )
248
- })
249
- )
275
+ .post(
276
+ '/shares/:shareId/resolve',
277
+ shareParams,
278
+ validatedJSON(parseResolveDocumentShare),
279
+ (context) =>
280
+ sharingRoute(context, async () =>
281
+ context.json({
282
+ resolution: await service.resolveShare(
283
+ context.req.valid('param').shareId,
284
+ context.req.valid('json'),
285
+ await shareActor(context.req.raw, resolveSession)
286
+ )
287
+ })
288
+ )
250
289
  )
251
290
  }
@@ -1,13 +1,13 @@
1
1
  import type { Context } from 'hono'
2
2
  import { validator } from 'hono/validator'
3
- import { ValiError } from 'valibot'
3
+ import * as v from 'valibot'
4
4
 
5
5
  /** A request part that fails its schema is a 400, never a server error. */
6
6
  function parseOrReject<T>(parse: (input: unknown) => T, value: unknown, context: Context) {
7
7
  try {
8
8
  return parse(value)
9
9
  } catch (error) {
10
- if (error instanceof ValiError) {
10
+ if (error instanceof v.ValiError) {
11
11
  return context.json({ error: { code: 'invalid_request' as const } }, 400)
12
12
  }
13
13
  throw error
@@ -22,3 +22,59 @@ export function validatedJSON<T>(parse: (input: unknown) => T) {
22
22
  export function validatedQuery<T>(parse: (input: unknown) => T) {
23
23
  return validator('query', (value, context: Context) => parseOrReject(parse, value, context))
24
24
  }
25
+
26
+ /**
27
+ * A route parameter that names a row by UUID, in lowercase: the database matches any case, but an
28
+ * ID that also names something else, such as a document's relay, must have one spelling.
29
+ */
30
+ const uuidParamSchema = v.pipe(v.string(), v.uuid(), v.toLowerCase())
31
+
32
+ /**
33
+ * Route parameters through `schema`; handlers read them from `context.req.valid('param')`. A
34
+ * parameter that fails it names nothing, so the route answers 404 as for a missing row, and the
35
+ * value never reaches the database.
36
+ */
37
+ export function validatedParams<TOutput>(schema: v.GenericSchema<unknown, TOutput>) {
38
+ return validator('param', (value, context: Context) => {
39
+ const parsed = v.safeParse(schema, value)
40
+ return parsed.success
41
+ ? parsed.output
42
+ : context.json({ error: { code: 'not_found' as const } }, 404)
43
+ })
44
+ }
45
+
46
+ /** A route parameter the server takes as text, such as a user ID, which is not a UUID column. */
47
+ const textParamSchema = v.pipe(v.string(), v.minLength(1))
48
+
49
+ export const documentParams = validatedParams(v.object({ documentId: uuidParamSchema }))
50
+ export const documentVersionParams = validatedParams(
51
+ v.object({ documentId: uuidParamSchema, versionId: uuidParamSchema })
52
+ )
53
+ export const documentShareParams = validatedParams(
54
+ v.object({ documentId: uuidParamSchema, shareId: uuidParamSchema })
55
+ )
56
+ export const documentInvitationParams = validatedParams(
57
+ v.object({ documentId: uuidParamSchema, invitationId: uuidParamSchema })
58
+ )
59
+ export const documentUserParams = validatedParams(
60
+ v.object({ documentId: uuidParamSchema, userId: textParamSchema })
61
+ )
62
+ export const workspaceParams = validatedParams(v.object({ workspaceId: uuidParamSchema }))
63
+ export const workspaceInvitationParams = validatedParams(
64
+ v.object({ workspaceId: uuidParamSchema, invitationId: uuidParamSchema })
65
+ )
66
+ export const workspaceMemberParams = validatedParams(
67
+ v.object({ workspaceId: uuidParamSchema, userId: textParamSchema })
68
+ )
69
+ export const shareParams = validatedParams(v.object({ shareId: uuidParamSchema }))
70
+ export const invitationParams = validatedParams(v.object({ invitationId: uuidParamSchema }))
71
+ export const invitationContinuationParams = validatedParams(
72
+ v.object({ continuationId: textParamSchema })
73
+ )
74
+ export const uploadParams = validatedParams(v.object({ uploadId: uuidParamSchema }))
75
+ /** Admin records (enrollments, accounts, and messages), all named by UUID. */
76
+ export const idParams = validatedParams(v.object({ id: uuidParamSchema }))
77
+ /** A picture's address names its owner and a prefix of its checksum, which the service checks. */
78
+ export const pictureParams = validatedParams(
79
+ v.object({ userId: textParamSchema, version: textParamSchema })
80
+ )