@open-pencil/cloud 0.17.0-beta.5 → 0.17.0-beta.7

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 (188) hide show
  1. package/dist/client.d.ts +560 -93
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +1101 -186
  4. package/dist/client.js.map +1 -1
  5. package/dist/contract.d.ts +2 -2
  6. package/dist/contract.js +2 -2
  7. package/dist/contract2.js +390 -44
  8. package/dist/contract2.js.map +1 -1
  9. package/dist/email.d.ts +366 -3
  10. package/dist/email.d.ts.map +1 -1
  11. package/dist/email.js +1403 -556
  12. package/dist/email.js.map +1 -1
  13. package/dist/errors.js +16 -3
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +878 -37
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index2.d.ts +12 -2
  18. package/dist/index2.d.ts.map +1 -1
  19. package/dist/listen.mjs +589 -128
  20. package/dist/listen.mjs.map +1 -1
  21. package/dist/runtime-cloudflare.d.ts +4 -0
  22. package/dist/runtime-cloudflare.d.ts.map +1 -1
  23. package/dist/runtime-cloudflare.js +8690 -6325
  24. package/dist/runtime-cloudflare.js.map +1 -1
  25. package/dist/runtime-node.d.mts +10098 -5401
  26. package/dist/runtime-node.d.mts.map +1 -1
  27. package/dist/server.d.ts +13807 -7638
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +11723 -9412
  30. package/dist/server.js.map +1 -1
  31. package/dist/server.mjs +10659 -8650
  32. package/dist/server.mjs.map +1 -1
  33. package/dist/server2.mjs +79 -57
  34. package/dist/server2.mjs.map +1 -1
  35. package/package.json +13 -4
  36. package/src/admin/api/routes.ts +263 -190
  37. package/src/admin/audit/service.ts +9 -1
  38. package/src/admin/bootstrap.ts +86 -0
  39. package/src/admin/documents/service.ts +119 -4
  40. package/src/admin/email/service.ts +2 -1
  41. package/src/admin/enrollment/email.ts +17 -3
  42. package/src/admin/enrollment/service.ts +71 -10
  43. package/src/admin/errors.ts +5 -0
  44. package/src/admin/index.ts +1 -0
  45. package/src/admin/reports/service.ts +9 -3
  46. package/src/admin/schema.ts +6 -5
  47. package/src/admin/users/service.ts +173 -16
  48. package/src/client/api.ts +29 -2
  49. package/src/client/comments.ts +205 -0
  50. package/src/client/device-authorization.ts +4 -20
  51. package/src/client/discovery.ts +4 -2
  52. package/src/client/files/archive.ts +60 -0
  53. package/src/client/files/checksum.ts +7 -0
  54. package/src/client/files/download.ts +122 -0
  55. package/src/client/files/images.ts +89 -0
  56. package/src/client/files/index.ts +15 -0
  57. package/src/client/files/objects.ts +173 -0
  58. package/src/client/files/save.ts +79 -0
  59. package/src/client/index.ts +3 -6
  60. package/src/client/portal/account.ts +20 -2
  61. package/src/client/portal/administration.ts +52 -5
  62. package/src/client/portal/request.ts +4 -2
  63. package/src/client/tour.ts +44 -0
  64. package/src/client/versions.ts +7 -1
  65. package/src/contract/account.ts +61 -11
  66. package/src/contract/admin/index.ts +48 -3
  67. package/src/contract/billing.ts +73 -4
  68. package/src/contract/comments.ts +223 -0
  69. package/src/contract/discovery.ts +47 -19
  70. package/src/contract/index.ts +10 -0
  71. package/src/contract/links.ts +5 -0
  72. package/src/contract/relay.ts +3 -1
  73. package/src/contract/services.ts +44 -4
  74. package/src/contract/workspaces.ts +5 -0
  75. package/src/email/locales/ar.json +28 -0
  76. package/src/email/locales/de.json +28 -0
  77. package/src/email/locales/es.json +28 -0
  78. package/src/email/locales/fr.json +28 -0
  79. package/src/email/locales/it.json +28 -0
  80. package/src/email/locales/ja.json +28 -0
  81. package/src/email/locales/pl.json +28 -0
  82. package/src/email/locales/pt-br.json +28 -0
  83. package/src/email/locales/ru.json +28 -0
  84. package/src/email/locales/zh-cn.json +28 -0
  85. package/src/email/messages.ts +35 -0
  86. package/src/email/render.ts +18 -0
  87. package/src/email/samples.ts +28 -1
  88. package/src/email/schema.ts +29 -3
  89. package/src/email/templates/BrandEmail.vue +3 -1
  90. package/src/email/templates/CommentNotification.vue +39 -0
  91. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  92. package/src/email/templates/TwoStepChanged.vue +17 -2
  93. package/src/email/templates/brand.ts +6 -0
  94. package/src/errors/posthog.ts +28 -4
  95. package/src/runtime/cloudflare/email.ts +2 -0
  96. package/src/runtime/cloudflare/relay/index.ts +21 -6
  97. package/src/runtime/cloudflare/worker.ts +6 -0
  98. package/src/runtime/cloudflare/xml.ts +12 -0
  99. package/src/runtime/node/admin.ts +51 -47
  100. package/src/runtime/node/email/runtime.ts +1 -0
  101. package/src/runtime/node/email/transport.ts +1 -0
  102. package/src/runtime/node/server.ts +8 -2
  103. package/src/runtime/posthog/errors.ts +3 -1
  104. package/src/runtime/site/server.ts +4 -1
  105. package/src/server/account/actions.ts +3 -1
  106. package/src/server/account/deletion.ts +38 -4
  107. package/src/server/account/routes.ts +67 -46
  108. package/src/server/account/tokens.ts +3 -3
  109. package/src/server/api/router.ts +22 -7
  110. package/src/server/app/checks.ts +6 -1
  111. package/src/server/app/cors.ts +44 -0
  112. package/src/server/app/index.ts +76 -76
  113. package/src/server/app/routes.ts +14 -5
  114. package/src/server/app/services.ts +49 -15
  115. package/src/server/auth/access-control.ts +13 -8
  116. package/src/server/auth/account.ts +13 -12
  117. package/src/server/auth/activity.ts +7 -2
  118. package/src/server/auth/adapter.ts +16 -3
  119. package/src/server/auth/email.ts +29 -17
  120. package/src/server/auth/endpoints.ts +4 -0
  121. package/src/server/auth/factory.ts +83 -64
  122. package/src/server/auth/index.ts +1 -1
  123. package/src/server/auth/methods.ts +162 -0
  124. package/src/server/auth/mfa-assurance.ts +147 -10
  125. package/src/server/auth/rate-limit.ts +31 -0
  126. package/src/server/auth/runtime.ts +19 -5
  127. package/src/server/auth/social-providers.ts +70 -24
  128. package/src/server/billing/index.ts +2 -0
  129. package/src/server/billing/notify.ts +55 -0
  130. package/src/server/billing/seats.ts +17 -0
  131. package/src/server/billing/tokens.ts +1 -1
  132. package/src/server/cleanup/documents.ts +5 -2
  133. package/src/server/cleanup/revisions.ts +6 -3
  134. package/src/server/cleanup/uploads.ts +2 -1
  135. package/src/server/collaboration/relay/connection.ts +7 -2
  136. package/src/server/collaboration/relay/hub.ts +55 -24
  137. package/src/server/collaboration/routes.ts +8 -5
  138. package/src/server/comments/index.ts +9 -0
  139. package/src/server/comments/notify.ts +277 -0
  140. package/src/server/comments/routes.ts +352 -0
  141. package/src/server/comments/rows.ts +249 -0
  142. package/src/server/comments/service.ts +570 -0
  143. package/src/server/community/routes.ts +6 -6
  144. package/src/server/config/deployment.ts +19 -6
  145. package/src/server/config/index.ts +1 -1
  146. package/src/server/config/public.ts +19 -6
  147. package/src/server/config/schema.ts +14 -2
  148. package/src/server/config/toml/schema.ts +27 -4
  149. package/src/server/db/index.ts +2 -1
  150. package/src/server/db/migrate.ts +21 -1
  151. package/src/server/db/migrations/015_comments.ts +57 -0
  152. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  153. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  154. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  155. package/src/server/db/tables.ts +92 -2
  156. package/src/server/documents/access.ts +17 -0
  157. package/src/server/documents/images.ts +6 -1
  158. package/src/server/documents/routes.ts +12 -12
  159. package/src/server/documents/service.ts +19 -5
  160. package/src/server/documents/summary.ts +15 -0
  161. package/src/server/documents/versions/routes.ts +7 -8
  162. package/src/server/documents/versions/service.ts +5 -2
  163. package/src/server/email/service.ts +8 -2
  164. package/src/server/email/types.ts +1 -0
  165. package/src/server/errors/index.ts +48 -3
  166. package/src/server/index.ts +15 -1
  167. package/src/server/internal/routes.ts +8 -2
  168. package/src/server/internal/service.ts +10 -0
  169. package/src/server/invitations/budget.ts +3 -1
  170. package/src/server/invitations/index.ts +1 -0
  171. package/src/server/invitations/links.ts +6 -0
  172. package/src/server/pictures/service.ts +3 -1
  173. package/src/server/policy/workspace.ts +5 -2
  174. package/src/server/reports/routes.ts +2 -2
  175. package/src/server/reports/service.ts +3 -1
  176. package/src/server/services/routes.ts +2 -2
  177. package/src/server/sharing/capabilities/service.ts +1 -1
  178. package/src/server/sharing/document-routes.ts +3 -3
  179. package/src/server/sharing/invitations/service.ts +3 -4
  180. package/src/server/sharing/routes.ts +15 -15
  181. package/src/server/validation.ts +33 -25
  182. package/src/server/workspaces/members.ts +50 -12
  183. package/src/server/workspaces/repository.ts +23 -12
  184. package/src/server/workspaces/routes.ts +8 -8
  185. package/src/services/app.ts +30 -19
  186. package/src/services/config.ts +47 -8
  187. package/src/services/metering.ts +15 -27
  188. package/src/client/billing.ts +0 -80
@@ -8,10 +8,11 @@ import type { AdminOperationsService } from '#cloud/admin/operations/service'
8
8
  import type { AdminReportService } from '#cloud/admin/reports/service'
9
9
  import {
10
10
  enrollmentStatusSchema,
11
- parseDocumentTakedown,
12
- parseEnrollmentReview,
13
- parseUserMutation,
14
- parseUserRoleMutation
11
+ documentTakedownSchema,
12
+ enrollmentReviewSchema,
13
+ signInMethodMutationSchema,
14
+ userMutationSchema,
15
+ userRoleMutationSchema
15
16
  } from '#cloud/admin/schema'
16
17
  import type { AdminUserService } from '#cloud/admin/users/service'
17
18
  import {
@@ -19,13 +20,20 @@ import {
19
20
  cloudAdminDocumentFilterSchema,
20
21
  cloudAdminEmailFilterSchema,
21
22
  cloudAdminReportFilterSchema,
22
- cloudAdminUserFilterSchema
23
+ cloudAdminUserFilterSchema,
24
+ cloudAdminUserMethodSchema
23
25
  } from '#cloud/contract'
24
26
  import type { CloudAPIEnvironment } from '#cloud/server/api'
25
27
  import type { CloudAuthAdapter } from '#cloud/server/auth'
26
28
  import type { CloudDatabase } from '#cloud/server/db'
29
+ import { DocumentNotFoundError } from '#cloud/server/documents/errors'
27
30
  import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
28
- import { idParams, validatedJSON, validatedQuery } from '#cloud/server/validation'
31
+ import {
32
+ documentRevisionParams,
33
+ idParams,
34
+ validatedJSON,
35
+ validatedQuery
36
+ } from '#cloud/server/validation'
29
37
  import { Hono, type Context } from 'hono'
30
38
  import { NoResultError, type Kysely } from 'kysely'
31
39
  import * as v from 'valibot'
@@ -37,20 +45,22 @@ import * as v from 'valibot'
37
45
  const countSchema = v.optional(v.pipe(v.string(), v.digits(), v.toNumber(), v.safeInteger()))
38
46
  /** What an admin list reads from its query string: a search, one of `filters`, and a page. */
39
47
  function listQuery<const Filter extends string>(filters: v.PicklistSchema<Filter[], undefined>) {
40
- const schema = v.object({
48
+ return v.object({
41
49
  search: v.optional(v.string()),
42
50
  filter: v.optional(filters),
43
51
  limit: countSchema,
44
52
  offset: countSchema
45
53
  })
46
- return (input: unknown) => v.parse(schema, input)
47
54
  }
48
- const parseEnrollmentQuery = listQuery(enrollmentStatusSchema)
49
- const parseUserQuery = listQuery(cloudAdminUserFilterSchema)
50
- const parseEmailQuery = listQuery(cloudAdminEmailFilterSchema)
51
- const parseAuditQuery = listQuery(cloudAdminAuditFilterSchema)
52
- const parseDocumentQuery = listQuery(cloudAdminDocumentFilterSchema)
53
- const parseReportQuery = listQuery(cloudAdminReportFilterSchema)
55
+ const enrollmentQuerySchema = listQuery(enrollmentStatusSchema)
56
+ const userQuerySchema = v.object({
57
+ ...listQuery(cloudAdminUserFilterSchema).entries,
58
+ method: v.optional(cloudAdminUserMethodSchema)
59
+ })
60
+ const emailQuerySchema = listQuery(cloudAdminEmailFilterSchema)
61
+ const auditQuerySchema = listQuery(cloudAdminAuditFilterSchema)
62
+ const documentQuerySchema = listQuery(cloudAdminDocumentFilterSchema)
63
+ const reportQuerySchema = listQuery(cloudAdminReportFilterSchema)
54
64
  /** Accounts are named by UUID; anything else names no one, rather than failing the query. */
55
65
  const accountIdSchema = v.pipe(v.string(), v.uuid())
56
66
 
@@ -63,7 +73,8 @@ async function accountMutation(
63
73
  if (!v.is(accountIdSchema, userId)) {
64
74
  return context.json({ error: { code: 'not_found' as const } }, 404)
65
75
  }
66
- await mutate(context.get('actor').userId, userId)
76
+ // A UUID matches in any case; the lowercase spelling is the one the actor's own ID uses.
77
+ await mutate(context.get('actor').userId, userId.toLowerCase())
67
78
  return context.json({ ok: true as const })
68
79
  }
69
80
 
@@ -99,194 +110,256 @@ export function createCloudAdminRoutes(
99
110
  CLOUD_RATE_LIMITS.adminMutation,
100
111
  (context) => context.req.method === 'GET'
101
112
  )
102
- return new Hono<CloudAPIEnvironment>()
103
- .use('*', requireTrustedMutationOrigin(trustedOrigins))
104
- .use('*', async (context, next) => {
105
- const actor = context.get('actor')
106
- if (actor.deploymentRole !== 'admin') {
107
- return context.json({ error: { code: 'forbidden' as const } }, 403)
108
- }
109
- if (security.requireMFA) {
110
- const status = await security.auth.mfaStatus(context.req.raw.headers)
111
- if (!status?.assured) {
112
- return context.json({ error: { code: 'mfa_required' as const } }, 403)
113
+ return (
114
+ new Hono<CloudAPIEnvironment>()
115
+ .use('*', requireTrustedMutationOrigin(trustedOrigins))
116
+ .use('*', async (context, next) => {
117
+ const actor = context.get('actor')
118
+ if (actor.deploymentRole !== 'admin') {
119
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
113
120
  }
114
- }
115
- return next()
116
- })
117
- .use('*', adminRead)
118
- .use('*', adminMutation)
119
- .onError((error, context) => {
120
- if (error instanceof AdminDomainError) {
121
- return context.json({ error: { code: error.code } }, adminErrorStatus(error))
122
- }
123
- if (error instanceof v.ValiError) {
124
- return context.json({ error: { code: 'invalid_request' as const } }, 400)
125
- }
126
- // An enrollment or message ID that names nothing.
127
- if (error instanceof NoResultError) {
128
- return context.json({ error: { code: 'not_found' as const } }, 404)
129
- }
130
- throw error
131
- })
132
- .get('/enrollments', validatedQuery(parseEnrollmentQuery), async (context) =>
133
- context.json(await services.enrollment.list(context.req.valid('query')))
134
- )
135
- .post(
136
- '/enrollments/:id/approve',
137
- idParams,
138
- validatedJSON(parseEnrollmentReview),
139
- async (context) =>
140
- context.json({
141
- enrollment: await services.enrollment.review(
142
- context.get('actor').userId,
143
- context.req.valid('param').id,
144
- 'approved',
145
- context.req.valid('json')
146
- )
147
- })
148
- )
149
- .post(
150
- '/enrollments/:id/reject',
151
- idParams,
152
- validatedJSON(parseEnrollmentReview),
153
- async (context) =>
154
- context.json({
155
- enrollment: await services.enrollment.review(
156
- context.get('actor').userId,
157
- context.req.valid('param').id,
158
- 'rejected',
159
- context.req.valid('json')
160
- )
161
- })
162
- )
163
- .post(
164
- '/enrollments/:id/revoke',
165
- idParams,
166
- validatedJSON(parseEnrollmentReview),
167
- async (context) =>
168
- context.json({
169
- enrollment: await services.enrollment.review(
170
- context.get('actor').userId,
171
- context.req.valid('param').id,
172
- 'revoked',
173
- context.req.valid('json')
174
- )
175
- })
176
- )
177
- .get('/users', validatedQuery(parseUserQuery), async (context) =>
178
- context.json(await services.users.list(context.req.valid('query')))
179
- )
180
- .get('/users/:id', idParams, async (context) => {
181
- const detail = await services.users.detail(context.req.valid('param').id)
182
- if (!detail) return context.json({ error: { code: 'not_found' as const } }, 404)
183
- return context.json(detail)
184
- })
185
- .post('/users/reset-two-step', validatedJSON(parseUserMutation), (context) =>
186
- accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>
187
- services.users.resetTwoStep(actorId, userId)
121
+ if (security.requireMFA) {
122
+ const status = await security.auth.mfaStatus(context.req.raw.headers)
123
+ if (!status?.assured) {
124
+ // Someone with two-step only has to prove it again; someone without has to turn it on.
125
+ const code = status?.enabled ? 'two_step_unconfirmed' : 'mfa_required'
126
+ return context.json({ error: { code } }, 403)
127
+ }
128
+ }
129
+ return next()
130
+ })
131
+ .use('*', adminRead)
132
+ .use('*', adminMutation)
133
+ .onError((error, context) => {
134
+ if (error instanceof AdminDomainError) {
135
+ return context.json({ error: { code: error.code } }, adminErrorStatus(error))
136
+ }
137
+ if (error instanceof v.ValiError) {
138
+ return context.json({ error: { code: 'invalid_request' as const } }, 400)
139
+ }
140
+ // An enrollment or message ID that names nothing, or a document with nothing saved.
141
+ if (error instanceof NoResultError || error instanceof DocumentNotFoundError) {
142
+ return context.json({ error: { code: 'not_found' as const } }, 404)
143
+ }
144
+ throw error
145
+ })
146
+ .get('/enrollments', validatedQuery(enrollmentQuerySchema), async (context) =>
147
+ context.json(await services.enrollment.list(context.req.valid('query')))
188
148
  )
189
- )
190
- .post('/users/remove-picture', validatedJSON(parseUserMutation), (context) =>
191
- accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>
192
- services.users.removePicture(actorId, userId)
149
+ .post('/enrollments/invite', async (context) =>
150
+ context.json(await services.enrollment.invitePending(context.get('actor').userId))
193
151
  )
194
- )
195
- .post('/users/ban', validatedJSON(parseUserMutation), async (context) => {
196
- const input = context.req.valid('json')
197
- await services.users.ban(
198
- context.req.raw.headers,
199
- context.get('actor').userId,
200
- input.userId,
201
- input.reason
152
+ .post(
153
+ '/enrollments/:id/approve',
154
+ idParams,
155
+ validatedJSON(enrollmentReviewSchema),
156
+ async (context) =>
157
+ context.json({
158
+ enrollment: await services.enrollment.review(
159
+ context.get('actor').userId,
160
+ context.req.valid('param').id,
161
+ 'approved',
162
+ context.req.valid('json')
163
+ )
164
+ })
202
165
  )
203
- return context.json({ ok: true as const })
204
- })
205
- .post('/users/unban', validatedJSON(parseUserMutation), async (context) => {
206
- const input = context.req.valid('json')
207
- await services.users.unban(context.req.raw.headers, context.get('actor').userId, input.userId)
208
- return context.json({ ok: true as const })
209
- })
210
- .post('/users/revoke-sessions', validatedJSON(parseUserMutation), async (context) => {
211
- const input = context.req.valid('json')
212
- await services.users.revokeSessions(
213
- context.req.raw.headers,
214
- context.get('actor').userId,
215
- input.userId
166
+ .post(
167
+ '/enrollments/:id/reject',
168
+ idParams,
169
+ validatedJSON(enrollmentReviewSchema),
170
+ async (context) =>
171
+ context.json({
172
+ enrollment: await services.enrollment.review(
173
+ context.get('actor').userId,
174
+ context.req.valid('param').id,
175
+ 'rejected',
176
+ context.req.valid('json')
177
+ )
178
+ })
216
179
  )
217
- return context.json({ ok: true as const })
218
- })
219
- .post('/users/set-admin', validatedJSON(parseUserRoleMutation), async (context) => {
220
- const input = context.req.valid('json')
221
- await services.users.setAdmin(
222
- context.req.raw.headers,
223
- context.get('actor').userId,
224
- input.userId,
225
- input.enabled
180
+ .post(
181
+ '/enrollments/:id/revoke',
182
+ idParams,
183
+ validatedJSON(enrollmentReviewSchema),
184
+ async (context) =>
185
+ context.json({
186
+ enrollment: await services.enrollment.review(
187
+ context.get('actor').userId,
188
+ context.req.valid('param').id,
189
+ 'revoked',
190
+ context.req.valid('json')
191
+ )
192
+ })
226
193
  )
227
- return context.json({ ok: true as const })
228
- })
229
- .get('/email', validatedQuery(parseEmailQuery), async (context) =>
230
- context.json(await services.email.list(context.req.valid('query')))
231
- )
232
- .post('/email/:id/regenerate', idParams, async (context) => {
233
- await services.email.regenerate(context.get('actor').userId, context.req.valid('param').id)
234
- return context.json({ ok: true as const })
235
- })
236
- .get('/audit', validatedQuery(parseAuditQuery), async (context) =>
237
- context.json(await services.audit.list(context.req.valid('query')))
238
- )
239
- .get('/operations', async (context) => context.json(await services.operations.summary()))
240
- .get('/reports', validatedQuery(parseReportQuery), async (context) =>
241
- context.json(await services.reports.list(context.req.valid('query')))
242
- )
243
- .post('/reports/:id/dismiss', idParams, async (context) => {
244
- await services.reports.resolve(
245
- context.get('actor').userId,
246
- context.req.valid('param').id,
247
- 'dismissed'
194
+ .get('/users', validatedQuery(userQuerySchema), async (context) =>
195
+ context.json(await services.users.list(context.req.valid('query')))
248
196
  )
249
- return context.json({ ok: true as const })
250
- })
251
- .post('/reports/:id/action', idParams, async (context) => {
252
- await services.reports.resolve(
253
- context.get('actor').userId,
254
- context.req.valid('param').id,
255
- 'actioned'
197
+ .get('/users/:id', idParams, async (context) => {
198
+ const detail = await services.users.detail(context.req.valid('param').id)
199
+ if (!detail) return context.json({ error: { code: 'not_found' as const } }, 404)
200
+ return context.json(detail)
201
+ })
202
+ .post('/users/reset-two-step', validatedJSON(userMutationSchema), (context) =>
203
+ accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>
204
+ services.users.resetTwoStep(actorId, userId)
205
+ )
256
206
  )
257
- return context.json({ ok: true as const })
258
- })
259
- .get('/documents', validatedQuery(parseDocumentQuery), async (context) =>
260
- context.json(await services.documents.list(context.req.valid('query')))
261
- )
262
- .post(
263
- '/documents/:id/disable',
264
- idParams,
265
- validatedJSON(parseDocumentTakedown),
266
- async (context) => {
267
- await services.documents.disable(
207
+ .post(
208
+ '/users/remove-sign-in-method',
209
+ validatedJSON(signInMethodMutationSchema),
210
+ (context) => {
211
+ const { userId, methodId } = context.req.valid('json')
212
+ return accountMutation(context, userId, (actorId, id) =>
213
+ services.users.removeSignInMethod(actorId, id, methodId)
214
+ )
215
+ }
216
+ )
217
+ .post('/users/remove-picture', validatedJSON(userMutationSchema), (context) =>
218
+ accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>
219
+ services.users.removePicture(actorId, userId)
220
+ )
221
+ )
222
+ .post('/users/delete', validatedJSON(userMutationSchema), (context) =>
223
+ accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>
224
+ services.users.deleteUnapproved(actorId, userId)
225
+ )
226
+ )
227
+ .post('/users/ban', validatedJSON(userMutationSchema), async (context) => {
228
+ const input = context.req.valid('json')
229
+ await services.users.ban(
230
+ context.req.raw.headers,
231
+ context.get('actor').userId,
232
+ input.userId,
233
+ input.reason
234
+ )
235
+ return context.json({ ok: true as const })
236
+ })
237
+ .post('/users/unban', validatedJSON(userMutationSchema), async (context) => {
238
+ const input = context.req.valid('json')
239
+ await services.users.unban(
240
+ context.req.raw.headers,
241
+ context.get('actor').userId,
242
+ input.userId
243
+ )
244
+ return context.json({ ok: true as const })
245
+ })
246
+ .post('/users/revoke-sessions', validatedJSON(userMutationSchema), async (context) => {
247
+ const input = context.req.valid('json')
248
+ await services.users.revokeSessions(
249
+ context.req.raw.headers,
250
+ context.get('actor').userId,
251
+ input.userId
252
+ )
253
+ return context.json({ ok: true as const })
254
+ })
255
+ .post('/users/set-admin', validatedJSON(userRoleMutationSchema), async (context) => {
256
+ const input = context.req.valid('json')
257
+ await services.users.setAdmin(
258
+ context.req.raw.headers,
259
+ context.get('actor').userId,
260
+ input.userId,
261
+ input.enabled
262
+ )
263
+ return context.json({ ok: true as const })
264
+ })
265
+ .get('/email', validatedQuery(emailQuerySchema), async (context) =>
266
+ context.json(await services.email.list(context.req.valid('query')))
267
+ )
268
+ .post('/email/:id/regenerate', idParams, async (context) => {
269
+ await services.email.regenerate(context.get('actor').userId, context.req.valid('param').id)
270
+ return context.json({ ok: true as const })
271
+ })
272
+ .get('/audit', validatedQuery(auditQuerySchema), async (context) =>
273
+ context.json(await services.audit.list(context.req.valid('query')))
274
+ )
275
+ .get('/operations', async (context) => context.json(await services.operations.summary()))
276
+ .get('/reports', validatedQuery(reportQuerySchema), async (context) =>
277
+ context.json(await services.reports.list(context.req.valid('query')))
278
+ )
279
+ .post('/reports/:id/dismiss', idParams, async (context) => {
280
+ await services.reports.resolve(
268
281
  context.get('actor').userId,
269
282
  context.req.valid('param').id,
270
- context.req.valid('json').reason
283
+ 'dismissed'
271
284
  )
272
285
  return context.json({ ok: true as const })
273
- }
274
- )
275
- .post('/documents/:id/enable', idParams, async (context) => {
276
- await services.documents.enable(context.get('actor').userId, context.req.valid('param').id)
277
- return context.json({ ok: true as const })
278
- })
279
- .post('/documents/:id/undelete', idParams, async (context) => {
280
- await services.documents.undelete(context.get('actor').userId, context.req.valid('param').id)
281
- return context.json({ ok: true as const })
282
- })
283
- .post('/shares/:id/revoke', idParams, async (context) => {
284
- await services.documents.revokeShare(
285
- context.get('actor').userId,
286
- context.req.valid('param').id
286
+ })
287
+ .post('/reports/:id/action', idParams, async (context) => {
288
+ await services.reports.resolve(
289
+ context.get('actor').userId,
290
+ context.req.valid('param').id,
291
+ 'actioned'
292
+ )
293
+ return context.json({ ok: true as const })
294
+ })
295
+ .get('/documents', validatedQuery(documentQuerySchema), async (context) =>
296
+ context.json(await services.documents.list(context.req.valid('query')))
297
+ )
298
+ .post(
299
+ '/documents/:id/disable',
300
+ idParams,
301
+ validatedJSON(documentTakedownSchema),
302
+ async (context) => {
303
+ await services.documents.disable(
304
+ context.get('actor').userId,
305
+ context.req.valid('param').id,
306
+ context.req.valid('json').reason
307
+ )
308
+ return context.json({ ok: true as const })
309
+ }
310
+ )
311
+ .post('/documents/:id/enable', idParams, async (context) => {
312
+ await services.documents.enable(context.get('actor').userId, context.req.valid('param').id)
313
+ return context.json({ ok: true as const })
314
+ })
315
+ // Its address names the revision it shows, which is also its ETag. The browser asks again
316
+ // each time, so the administrator and two-step checks always run, even for another account
317
+ // later in the same browser; an unchanged thumbnail answers 304 without reading storage.
318
+ .get(
319
+ '/documents/:documentId/thumbnails/:revisionId',
320
+ documentRevisionParams,
321
+ async (context) => {
322
+ const { documentId, revisionId } = context.req.valid('param')
323
+ const etag = `"${revisionId}"`
324
+ context.header('Cache-Control', 'private, no-cache')
325
+ context.header('ETag', etag)
326
+ if (
327
+ context.req.header('If-None-Match') === etag &&
328
+ (await services.documents.isCurrentRevision(documentId, revisionId))
329
+ ) {
330
+ return context.body(null, 304)
331
+ }
332
+ const thumbnail = await services.documents.thumbnail(documentId, revisionId)
333
+ if (!thumbnail) return context.json({ error: { code: 'not_found' as const } }, 404)
334
+ context.header('Content-Type', 'image/png')
335
+ context.header('X-Content-Type-Options', 'nosniff')
336
+ context.header('Content-Security-Policy', "default-src 'none'; sandbox")
337
+ return context.body(new Uint8Array(thumbnail))
338
+ }
339
+ )
340
+ .post('/documents/:id/download', idParams, async (context) =>
341
+ context.json(
342
+ await services.documents.download(
343
+ context.get('actor').userId,
344
+ context.req.valid('param').id
345
+ )
346
+ )
287
347
  )
288
- return context.json({ ok: true as const })
289
- })
348
+ .post('/documents/:id/undelete', idParams, async (context) => {
349
+ await services.documents.undelete(
350
+ context.get('actor').userId,
351
+ context.req.valid('param').id
352
+ )
353
+ return context.json({ ok: true as const })
354
+ })
355
+ .post('/shares/:id/revoke', idParams, async (context) => {
356
+ await services.documents.revokeShare(
357
+ context.get('actor').userId,
358
+ context.req.valid('param').id
359
+ )
360
+ return context.json({ ok: true as const })
361
+ })
362
+ )
290
363
  }
291
364
 
292
365
  /** The administration routes' types, for the portal's typed client. */
@@ -72,6 +72,12 @@ function searchCondition(pattern: string) {
72
72
  }
73
73
  }
74
74
 
75
+ /** The name an entry recorded about its subject, as deleting an account does. */
76
+ function recordedName(metadata: unknown): string | undefined {
77
+ if (typeof metadata !== 'object' || metadata === null || !('name' in metadata)) return undefined
78
+ return typeof metadata.name === 'string' ? metadata.name : undefined
79
+ }
80
+
75
81
  export function createAdminAuditService(database: Kysely<CloudDatabase>) {
76
82
  return {
77
83
  /**
@@ -144,7 +150,9 @@ export function createAdminAuditService(database: Kysely<CloudDatabase>) {
144
150
  subject: {
145
151
  type: event.subjectType,
146
152
  id: event.subjectId,
147
- name: subjectName(event.subjectType, event.subjectId) ?? null
153
+ // A deleted account is named by what its deletion's entry recorded.
154
+ name:
155
+ subjectName(event.subjectType, event.subjectId) ?? recordedName(event.metadata) ?? null
148
156
  },
149
157
  metadata: event.metadata,
150
158
  createdAt: event.createdAt
@@ -0,0 +1,86 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import type { Kysely } from 'kysely'
3
+
4
+ import { normalizeEnrollmentEmail } from './enrollment/service'
5
+
6
+ /** Who the audit trail names for what the admin command did, since no account did it. */
7
+ export const ADMIN_BOOTSTRAP_ACTOR = 'cli-bootstrap'
8
+
9
+ /**
10
+ * Approves an email's enrollment from the admin command, whether or not that person has asked
11
+ * yet, for a deployment with no administrator to approve it in the console. As a review there
12
+ * does, it binds the account that already uses the address, which keeps the approval when that
13
+ * account changes its address (`followEmailChange`), and records the approval in the audit trail.
14
+ */
15
+ export async function approveEnrollmentByEmail(
16
+ database: Kysely<CloudDatabase>,
17
+ email: string
18
+ ): Promise<string> {
19
+ const normalized = normalizeEnrollmentEmail(email)
20
+ await database.transaction().execute(async (transaction) => {
21
+ const user = await transaction
22
+ .selectFrom('user')
23
+ .select('id')
24
+ .where('email', '=', normalized)
25
+ .executeTakeFirst()
26
+ const review = {
27
+ status: 'approved',
28
+ reviewedAt: new Date(),
29
+ reviewedBy: ADMIN_BOOTSTRAP_ACTOR,
30
+ reviewNote: 'Approved through CLI bootstrap',
31
+ ...(user ? { approvedUserId: user.id } : {})
32
+ } as const
33
+ const enrollment = await transaction
34
+ .insertInto('enrollment')
35
+ .values({ id: crypto.randomUUID(), emailNormalized: normalized, ...review })
36
+ .onConflict((conflict) => conflict.column('emailNormalized').doUpdateSet(review))
37
+ .returning('id')
38
+ .executeTakeFirstOrThrow()
39
+ await transaction
40
+ .insertInto('adminAuditEvent')
41
+ .values({
42
+ id: crypto.randomUUID(),
43
+ actorUserId: ADMIN_BOOTSTRAP_ACTOR,
44
+ action: 'enrollment.approved',
45
+ subjectType: 'enrollment',
46
+ subjectId: enrollment.id,
47
+ metadata: { email: normalized }
48
+ })
49
+ .execute()
50
+ })
51
+ return normalized
52
+ }
53
+
54
+ /**
55
+ * Makes an existing account a deployment administrator from the admin command, recorded in the
56
+ * audit trail as the console records a grant. The account exists once its person has signed in.
57
+ */
58
+ export async function grantDeploymentAdminByEmail(
59
+ database: Kysely<CloudDatabase>,
60
+ email: string
61
+ ): Promise<{ email: string; userId: string }> {
62
+ const normalized = normalizeEnrollmentEmail(email)
63
+ return database.transaction().execute(async (transaction) => {
64
+ const user = await transaction
65
+ .updateTable('user')
66
+ .set({ role: 'admin' })
67
+ .where('email', '=', normalized)
68
+ .returning('id')
69
+ .executeTakeFirst()
70
+ if (!user) {
71
+ throw new Error(`No account uses ${normalized}; that person signs in once first`)
72
+ }
73
+ await transaction
74
+ .insertInto('adminAuditEvent')
75
+ .values({
76
+ id: crypto.randomUUID(),
77
+ actorUserId: ADMIN_BOOTSTRAP_ACTOR,
78
+ action: 'user.admin-granted',
79
+ subjectType: 'user',
80
+ subjectId: user.id,
81
+ metadata: { email: normalized }
82
+ })
83
+ .execute()
84
+ return { email: normalized, userId: user.id }
85
+ })
86
+ }