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

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 (223) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/{ai-relay.mjs → services.mjs} +8 -8
  3. package/dist/bin/services.mjs.map +1 -0
  4. package/dist/client.d.ts +236 -46
  5. package/dist/client.d.ts.map +1 -1
  6. package/dist/client.js +649 -400
  7. package/dist/client.js.map +1 -1
  8. package/dist/contract.d.ts +2 -2
  9. package/dist/contract.js +2 -2
  10. package/dist/contract2.js +680 -443
  11. package/dist/contract2.js.map +1 -1
  12. package/dist/email.d.ts +9 -1
  13. package/dist/email.d.ts.map +1 -1
  14. package/dist/email.js +99 -58
  15. package/dist/email.js.map +1 -1
  16. package/dist/index.d.ts +469 -65
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/listen.mjs +505 -787
  19. package/dist/listen.mjs.map +1 -1
  20. package/dist/runtime-node.d.mts +3920 -2524
  21. package/dist/runtime-node.d.mts.map +1 -1
  22. package/dist/runtime-node.mjs +6 -5
  23. package/dist/runtime-node.mjs.map +1 -1
  24. package/dist/server.d.ts +3586 -1897
  25. package/dist/server.d.ts.map +1 -1
  26. package/dist/server.js +5216 -4272
  27. package/dist/server.js.map +1 -1
  28. package/dist/server.mjs +5179 -3623
  29. package/dist/server.mjs.map +1 -1
  30. package/dist/server2.mjs +101 -79
  31. package/dist/server2.mjs.map +1 -1
  32. package/package.json +7 -6
  33. package/src/admin/api/routes.ts +59 -0
  34. package/src/admin/audit/service.ts +25 -6
  35. package/src/admin/documents/service.ts +361 -0
  36. package/src/admin/errors.ts +9 -1
  37. package/src/admin/index.ts +6 -0
  38. package/src/admin/operations/service.ts +7 -0
  39. package/src/admin/reports/service.ts +147 -0
  40. package/src/admin/schema.ts +6 -0
  41. package/src/client/api.ts +36 -21
  42. package/src/client/auth/navigation.ts +6 -5
  43. package/src/client/index.ts +7 -7
  44. package/src/client/portal/account.ts +25 -0
  45. package/src/client/portal/administration.ts +56 -0
  46. package/src/client/{ai.ts → services.ts} +44 -27
  47. package/src/contract/account.ts +58 -2
  48. package/src/contract/admin/index.ts +67 -3
  49. package/src/contract/collaboration.ts +6 -1
  50. package/src/contract/discovery.ts +22 -4
  51. package/src/contract/documents.ts +27 -0
  52. package/src/contract/entitlements.ts +2 -2
  53. package/src/contract/index.ts +63 -37
  54. package/src/contract/relay.ts +6 -0
  55. package/src/contract/reports.ts +42 -0
  56. package/src/contract/services.ts +233 -0
  57. package/src/contract/sharing.ts +3 -9
  58. package/src/email/render.ts +26 -0
  59. package/src/email/schema.ts +11 -1
  60. package/src/email/templates/brand.ts +1 -1
  61. package/src/runtime/cloudflare/environment.ts +22 -11
  62. package/src/runtime/cloudflare/index.ts +1 -1
  63. package/src/runtime/cloudflare/logging.ts +15 -0
  64. package/src/runtime/cloudflare/maintenance.ts +31 -0
  65. package/src/runtime/cloudflare/relay/index.ts +62 -14
  66. package/src/runtime/cloudflare/worker.ts +39 -13
  67. package/src/runtime/node/application.ts +5 -3
  68. package/src/runtime/node/bootstrap.ts +15 -4
  69. package/src/runtime/node/cleanup.ts +16 -3
  70. package/src/runtime/node/entitlements/main.ts +14 -11
  71. package/src/runtime/node/index.ts +1 -1
  72. package/src/runtime/node/migrate.ts +5 -1
  73. package/src/runtime/node/relay.ts +8 -2
  74. package/src/runtime/node/request-id.ts +13 -0
  75. package/src/runtime/node/server.ts +39 -15
  76. package/src/runtime/node/{ai-relay → services}/main.ts +6 -6
  77. package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
  78. package/src/runtime/postgres/database.ts +20 -1
  79. package/src/runtime/posthog/errors.ts +15 -31
  80. package/src/runtime/s3/objects.ts +24 -1
  81. package/src/runtime/site/server.ts +32 -5
  82. package/src/server/account/actions.ts +5 -0
  83. package/src/server/account/deletion.ts +302 -0
  84. package/src/server/account/routes.ts +47 -3
  85. package/src/server/account/terms.ts +42 -0
  86. package/src/server/api/router.ts +9 -5
  87. package/src/server/api/types.ts +2 -0
  88. package/src/server/app.ts +90 -16
  89. package/src/server/auth/access-control.ts +63 -0
  90. package/src/server/auth/adapter.ts +11 -0
  91. package/src/server/auth/endpoints.ts +5 -1
  92. package/src/server/auth/factory.ts +30 -3
  93. package/src/server/auth/index.ts +10 -1
  94. package/src/server/cleanup/configured.ts +12 -5
  95. package/src/server/cleanup/documents.ts +165 -71
  96. package/src/server/cleanup/revisions.ts +16 -5
  97. package/src/server/cleanup/uploads.ts +8 -2
  98. package/src/server/cleanup/worker.ts +5 -2
  99. package/src/server/collaboration/relay/connection.ts +4 -3
  100. package/src/server/collaboration/relay/documents.ts +13 -10
  101. package/src/server/collaboration/relay/hub.ts +97 -25
  102. package/src/server/collaboration/relay/log.ts +5 -2
  103. package/src/server/collaboration/service.ts +27 -31
  104. package/src/server/config/deployment.ts +24 -4
  105. package/src/server/config/public.ts +5 -4
  106. package/src/server/config/schema.ts +82 -16
  107. package/src/server/db/expressions.ts +15 -1
  108. package/src/server/db/migrate.ts +34 -116
  109. package/src/server/db/migrations/001_accounts.ts +79 -0
  110. package/src/server/db/migrations/002_workspaces.ts +48 -0
  111. package/src/server/db/migrations/003_storage.ts +44 -0
  112. package/src/server/db/migrations/004_documents.ts +193 -0
  113. package/src/server/db/migrations/005_sharing.ts +95 -0
  114. package/src/server/db/migrations/006_operations.ts +110 -0
  115. package/src/server/db/migrations/007_trash.ts +33 -0
  116. package/src/server/db/migrations/008_terms.ts +18 -0
  117. package/src/server/db/migrations/schema.ts +71 -0
  118. package/src/server/db/tables.ts +52 -3
  119. package/src/server/documents/access.ts +66 -55
  120. package/src/server/documents/errors.ts +7 -0
  121. package/src/server/documents/images.ts +2 -1
  122. package/src/server/documents/limits.ts +9 -9
  123. package/src/server/documents/purge.ts +75 -0
  124. package/src/server/documents/repository.ts +2 -0
  125. package/src/server/documents/routes.ts +26 -0
  126. package/src/server/documents/service.ts +18 -4
  127. package/src/server/documents/summary.ts +1 -0
  128. package/src/server/documents/trash.ts +203 -0
  129. package/src/server/documents/versions/checkpoint.ts +2 -1
  130. package/src/server/documents/versions/history.ts +11 -7
  131. package/src/server/documents/versions/service.ts +13 -4
  132. package/src/server/errors/index.ts +59 -16
  133. package/src/server/errors/posthog.ts +80 -0
  134. package/src/server/index.ts +46 -17
  135. package/src/server/internal/index.ts +3 -3
  136. package/src/server/internal/routes.ts +7 -10
  137. package/src/server/internal/schema.ts +1 -1
  138. package/src/server/internal/service.ts +17 -23
  139. package/src/server/invitations/budget.ts +66 -0
  140. package/src/server/invitations/index.ts +1 -0
  141. package/src/server/logging.ts +76 -0
  142. package/src/server/pictures/service.ts +2 -1
  143. package/src/server/policy/database.ts +39 -25
  144. package/src/server/policy/index.ts +2 -1
  145. package/src/server/policy/keys.ts +5 -2
  146. package/src/server/policy/policy.ts +1 -0
  147. package/src/server/policy/schema.ts +2 -2
  148. package/src/server/policy/service.ts +12 -9
  149. package/src/server/policy/static.ts +5 -5
  150. package/src/server/policy/workspace.ts +41 -0
  151. package/src/server/quota/reconcile.ts +2 -0
  152. package/src/server/quota/storage.ts +69 -31
  153. package/src/server/rate-limit/cleanup.ts +17 -5
  154. package/src/server/rate-limit/middleware.ts +2 -2
  155. package/src/server/reports/index.ts +8 -0
  156. package/src/server/reports/routes.ts +37 -0
  157. package/src/server/reports/service.ts +123 -0
  158. package/src/server/services/errors.ts +7 -0
  159. package/src/server/services/index.ts +8 -0
  160. package/src/server/{ai → services}/keys.ts +11 -11
  161. package/src/server/services/routes.ts +47 -0
  162. package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
  163. package/src/server/sharing/capabilities/service.ts +68 -22
  164. package/src/server/sharing/grants/service.ts +11 -18
  165. package/src/server/sharing/http.ts +4 -0
  166. package/src/server/sharing/invitations/service.ts +21 -11
  167. package/src/server/sharing/policy.ts +9 -14
  168. package/src/server/sharing/routes.ts +0 -16
  169. package/src/server/sharing/service.ts +1 -17
  170. package/src/server/validation.ts +1 -0
  171. package/src/server/workspaces/index.ts +1 -0
  172. package/src/server/workspaces/members.ts +89 -38
  173. package/src/server/workspaces/repository.ts +2 -1
  174. package/src/server/workspaces/routes.ts +4 -0
  175. package/src/{ai-relay → services}/app.ts +48 -44
  176. package/src/{ai-relay → services}/config.ts +25 -19
  177. package/src/services/db/index.ts +10 -0
  178. package/src/services/db/migrate.ts +37 -0
  179. package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
  180. package/src/services/db/schema.ts +22 -0
  181. package/src/services/index.ts +18 -0
  182. package/src/{ai-relay → services}/metering.ts +2 -2
  183. package/src/{ai-relay → services}/usage.ts +43 -19
  184. package/dist/bin/ai-relay.mjs.map +0 -1
  185. package/src/ai-relay/db/index.ts +0 -10
  186. package/src/ai-relay/db/migrate.ts +0 -32
  187. package/src/ai-relay/db/schema.ts +0 -20
  188. package/src/ai-relay/index.ts +0 -18
  189. package/src/contract/ai.ts +0 -150
  190. package/src/server/ai/errors.ts +0 -7
  191. package/src/server/ai/index.ts +0 -4
  192. package/src/server/ai/routes.ts +0 -43
  193. package/src/server/auth/workspace-access.ts +0 -23
  194. package/src/server/db/migrations/001_foundation.ts +0 -164
  195. package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
  196. package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
  197. package/src/server/db/migrations/004_document_sharing.ts +0 -82
  198. package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
  199. package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
  200. package/src/server/db/migrations/007_collaboration_state.ts +0 -25
  201. package/src/server/db/migrations/008_storage_reservations.ts +0 -37
  202. package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
  203. package/src/server/db/migrations/010_upload_finalization.ts +0 -22
  204. package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
  205. package/src/server/db/migrations/012_transactional_email.ts +0 -48
  206. package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
  207. package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
  208. package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
  209. package/src/server/db/migrations/016_auth_schema.ts +0 -16
  210. package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
  211. package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
  212. package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
  213. package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
  214. package/src/server/db/migrations/021_document_versions.ts +0 -66
  215. package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
  216. package/src/server/db/migrations/023_document_images.ts +0 -61
  217. package/src/server/db/migrations/024_account_activity.ts +0 -66
  218. package/src/server/db/migrations/025_table_names.ts +0 -58
  219. package/src/server/db/migrations/026_user_picture.ts +0 -30
  220. package/src/server/db/migrations/027_document_kind.ts +0 -19
  221. package/src/server/db/migrations/028_collaboration_updates.ts +0 -84
  222. package/src/server/db/migrations/helpers.ts +0 -78
  223. /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
@@ -0,0 +1,147 @@
1
+ import { adminDocuments, auditContentAction } from '#cloud/admin/documents/service'
2
+ import {
3
+ containsPattern,
4
+ countEachFilter,
5
+ listSearch,
6
+ listWindow,
7
+ type AdminListQuery,
8
+ type ListFilters
9
+ } from '#cloud/admin/list'
10
+ import { isUUID } from '#cloud/admin/schema'
11
+ import {
12
+ cloudAdminReportFilterSchema,
13
+ type CloudAdminReport,
14
+ type CloudAdminReportFilter
15
+ } from '#cloud/contract'
16
+ import type { CloudDatabase } from '#cloud/server/db'
17
+ import { dateString } from '#cloud/server/sharing/contracts'
18
+ import { uniq } from 'es-toolkit'
19
+ import type { ExpressionBuilder, Kysely } from 'kysely'
20
+
21
+ type ReportExpression = ExpressionBuilder<CloudDatabase, 'documentReport'>
22
+
23
+ const FILTERS: ListFilters<CloudAdminReportFilter, 'documentReport'> = {
24
+ open: (expression) => expression('documentReport.status', '=', 'open'),
25
+ actioned: (expression) => expression('documentReport.status', '=', 'actioned'),
26
+ dismissed: (expression) => expression('documentReport.status', '=', 'dismissed'),
27
+ all: (expression) => expression.lit(true)
28
+ }
29
+
30
+ /** Reports whose description, reply address, or document's name has the search in it. */
31
+ function searchCondition(search: string) {
32
+ const pattern = containsPattern(search)
33
+ return (expression: ReportExpression) =>
34
+ expression.or([
35
+ expression('documentReport.description', 'ilike', pattern),
36
+ expression('documentReport.replyEmail', 'ilike', pattern),
37
+ expression.exists(
38
+ expression
39
+ .selectFrom('document')
40
+ .select('document.id')
41
+ .whereRef('document.id', '=', 'documentReport.documentId')
42
+ .where('document.name', 'ilike', pattern)
43
+ )
44
+ ])
45
+ }
46
+
47
+ export function createAdminReportService(database: Kysely<CloudDatabase>) {
48
+ return {
49
+ /** A page of reports, newest first, and how many match the search under each filter. */
50
+ async list(query: AdminListQuery<CloudAdminReportFilter> = {}) {
51
+ const search = listSearch(query)
52
+ const filter = query.filter ?? 'open'
53
+ const { limit, offset } = listWindow(query)
54
+ let searched = database.selectFrom('documentReport')
55
+ if (search) searched = searched.where(searchCondition(search))
56
+ const counts = await countEachFilter(searched, cloudAdminReportFilterSchema.options, FILTERS)
57
+ const rows = await searched
58
+ .where(FILTERS[filter])
59
+ .selectAll()
60
+ .orderBy('createdAt', 'desc')
61
+ .orderBy('id', 'desc')
62
+ .limit(limit)
63
+ .offset(offset)
64
+ .execute()
65
+ const shareIds = uniq(rows.flatMap((row) => (row.shareId ? [row.shareId] : [])))
66
+ const reporterIds = uniq(
67
+ rows.flatMap((row) => (row.reporterUserId ? [row.reporterUserId] : []))
68
+ ).filter(isUUID)
69
+ const [documents, shares, reporters] = await Promise.all([
70
+ adminDocuments(
71
+ database,
72
+ rows.map((row) => row.documentId)
73
+ ),
74
+ shareIds.length
75
+ ? database
76
+ .selectFrom('documentShare')
77
+ .select(['id', 'revokedAt'])
78
+ .where('id', 'in', shareIds)
79
+ .execute()
80
+ : [],
81
+ reporterIds.length
82
+ ? database
83
+ .selectFrom('user')
84
+ .select(['id', 'name'])
85
+ .where('id', 'in', reporterIds)
86
+ .execute()
87
+ : []
88
+ ])
89
+ const revoked = new Map(shares.map((share) => [share.id, share.revokedAt !== null]))
90
+ const reporterNames = new Map(reporters.map((reporter) => [reporter.id, reporter.name]))
91
+ const reports: CloudAdminReport[] = rows.flatMap((row) => {
92
+ const document = documents.get(row.documentId)
93
+ if (!document) return []
94
+ return [
95
+ {
96
+ id: row.id,
97
+ reason: row.reason,
98
+ description: row.description,
99
+ status: row.status,
100
+ reporter: row.reporterUserId
101
+ ? { id: row.reporterUserId, name: reporterNames.get(row.reporterUserId) ?? null }
102
+ : null,
103
+ replyEmail: row.replyEmail,
104
+ createdAt: dateString(row.createdAt) ?? '',
105
+ resolvedAt: dateString(row.resolvedAt),
106
+ document,
107
+ share: row.shareId
108
+ ? { id: row.shareId, revoked: revoked.get(row.shareId) ?? true }
109
+ : null
110
+ }
111
+ ]
112
+ })
113
+ return { reports, total: counts[filter], counts }
114
+ },
115
+
116
+ /** Closes an open report, as dismissed or as acted on; a closed one stays as it was. */
117
+ async resolve(
118
+ actorId: string,
119
+ reportId: string,
120
+ status: 'dismissed' | 'actioned'
121
+ ): Promise<void> {
122
+ await database.transaction().execute(async (transaction) => {
123
+ const report = await transaction
124
+ .selectFrom('documentReport')
125
+ .select(['id', 'status', 'documentId'])
126
+ .where('id', '=', reportId)
127
+ .forUpdate()
128
+ .executeTakeFirstOrThrow()
129
+ if (report.status !== 'open') return
130
+ await transaction
131
+ .updateTable('documentReport')
132
+ .set({ status, resolvedAt: new Date(), resolvedBy: actorId })
133
+ .where('id', '=', reportId)
134
+ .execute()
135
+ await auditContentAction(
136
+ transaction,
137
+ actorId,
138
+ `document-report.${status}`,
139
+ { type: 'document-report', id: reportId },
140
+ { documentId: report.documentId }
141
+ )
142
+ })
143
+ }
144
+ }
145
+ }
146
+
147
+ export type AdminReportService = ReturnType<typeof createAdminReportService>
@@ -21,8 +21,14 @@ export const userMutationSchema = v.object({
21
21
  reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))
22
22
  })
23
23
 
24
+ /** Why an administrator takes a document down, which the audit log keeps. */
25
+ export const documentTakedownSchema = v.object({
26
+ reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))
27
+ })
28
+
24
29
  export type EnrollmentReview = v.InferOutput<typeof enrollmentReviewSchema>
25
30
 
26
31
  export const parseEnrollmentReview = (input: unknown) => v.parse(enrollmentReviewSchema, input)
27
32
  export const parseUserMutation = (input: unknown) => v.parse(userMutationSchema, input)
28
33
  export const parseUserRoleMutation = (input: unknown) => v.parse(userRoleMutationSchema, input)
34
+ export const parseDocumentTakedown = (input: unknown) => v.parse(documentTakedownSchema, input)
package/src/client/api.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { CloudFetch } from '#cloud/client/discovery'
2
2
  import {
3
3
  acceptedInvitationSchema,
4
- aiTokenSchema,
4
+ servicesTokenSchema,
5
5
  cloudSessionSchema,
6
6
  cloudUserProfileSchema,
7
7
  collaborationTicketSchema,
@@ -18,11 +18,12 @@ import {
18
18
  documentVersionsSchema,
19
19
  restoredDocumentSchema,
20
20
  sharedDocumentSchema,
21
+ trashSchema,
21
22
  invitationContinuationSchema,
22
23
  invitationPreviewSchema,
23
24
  resolvedDocumentShareSchema,
24
25
  type AcceptDocumentInvitationInput,
25
- type AIToken,
26
+ type ServicesToken,
26
27
  type CloudSession,
27
28
  type CloudUserProfile,
28
29
  type CollaborationTicket,
@@ -46,10 +47,12 @@ import {
46
47
  type SaveDocumentVersionInput,
47
48
  type UpdateDocumentVersionInput,
48
49
  type SharedDocument,
50
+ type TrashedDocument,
49
51
  type InvitationPreview,
50
- type LookupCloudUserInput,
51
52
  type PutDocumentGrantInput,
52
53
  type ResolveDocumentShareInput,
54
+ fileDocumentReportResponseSchema,
55
+ type FileDocumentReportInput,
53
56
  type UpdateDocumentShareInput,
54
57
  type AcceptedInvitation
55
58
  } from '#cloud/contract'
@@ -137,28 +140,14 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
137
140
  if (response.status === 401) return null
138
141
  return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic))
139
142
  },
140
- /** A short-lived token for the deployment's AI service, on the workspace's behalf. */
141
- async requestAIToken(workspaceId: string): Promise<AIToken> {
143
+ /** A short-lived token for the deployment's services, on the workspace's behalf. */
144
+ async requestServicesToken(workspaceId: string): Promise<ServicesToken> {
142
145
  return parseResponse(
143
- client.ai.token.$post({ json: { workspaceId } }),
144
- aiTokenSchema,
146
+ client.services.token.$post({ json: { workspaceId } }),
147
+ servicesTokenSchema,
145
148
  options.onDiagnostic
146
149
  )
147
150
  },
148
- async lookupUser(
149
- documentId: string,
150
- input: LookupCloudUserInput
151
- ): Promise<CloudUserProfile | null> {
152
- const response = await parseResponse(
153
- client.documents[':documentId'].users.lookup.$post({
154
- param: { documentId },
155
- json: input
156
- }),
157
- userLookupResponseSchema,
158
- options.onDiagnostic
159
- )
160
- return response.user
161
- },
162
151
  async getUserProfile(documentId: string, userId: string): Promise<CloudUserProfile | null> {
163
152
  const response = await parseResponse(
164
153
  client.documents[':documentId'].users[':userId'].$get({
@@ -204,6 +193,24 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
204
193
  )
205
194
  return response.document
206
195
  },
196
+ /** Documents in Trash the person may restore, across their workspaces, newest first. */
197
+ async listTrash(): Promise<TrashedDocument[]> {
198
+ const response = await parseResponse(client.trash.$get(), trashSchema, options.onDiagnostic)
199
+ return response.documents
200
+ },
201
+ async restoreDocument(documentId: string): Promise<void> {
202
+ await responseBody(
203
+ await client.trash[':documentId'].restore.$post({ param: { documentId } }),
204
+ options.onDiagnostic
205
+ )
206
+ },
207
+ /** Deletes a document in Trash for good. */
208
+ async purgeDocument(documentId: string): Promise<void> {
209
+ await responseBody(
210
+ await client.trash[':documentId'].$delete({ param: { documentId } }),
211
+ options.onDiagnostic
212
+ )
213
+ },
207
214
  async deleteDocument(documentId: string): Promise<void> {
208
215
  await responseBody(
209
216
  await client.documents[':documentId'].$delete({ param: { documentId } }),
@@ -380,6 +387,14 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
380
387
  options.onDiagnostic
381
388
  )
382
389
  },
390
+ /** Reports the document a share link opens to the server's administrators. */
391
+ async fileDocumentReport(shareId: string, input: FileDocumentReportInput): Promise<void> {
392
+ await parseResponse(
393
+ publicClient.shares[':shareId'].reports.$post({ param: { shareId }, json: input }),
394
+ fileDocumentReportResponseSchema,
395
+ options.onDiagnostic
396
+ )
397
+ },
383
398
  async resolveDocumentShare(shareId: string, input: ResolveDocumentShareInput) {
384
399
  const response = await parseResponse(
385
400
  publicClient.shares[':shareId'].resolve.$post({
@@ -18,18 +18,19 @@ export function cloudEditorReturnURL(discovery: CloudDiscovery, value: string):
18
18
  }
19
19
 
20
20
  /**
21
- * The server's sign-in page, coming back to `returnURL` on its editor afterwards. A `provider`
22
- * starts that provider's sign-in at once, while the server's pages still handle two-step sign-in
23
- * and approval before the return.
21
+ * The server's sign-in page, or with `page` its sign-up page, coming back to `returnURL` on its
22
+ * editor afterwards. A `provider` starts that provider's sign-in at once, while the server's pages
23
+ * still handle two-step sign-in and approval before the return.
24
24
  */
25
25
  export function cloudSignInURL(
26
26
  discovery: CloudDiscovery,
27
27
  returnURL: string,
28
- provider?: CloudSocialProvider
28
+ provider?: CloudSocialProvider,
29
+ page: 'sign-in' | 'sign-up' = 'sign-in'
29
30
  ): string {
30
31
  const offered = provider && discovery.authentication.socialProviders.includes(provider)
31
32
  // The pages are at the server's root, whatever path the auth API has.
32
- return withQuery(new URL('/auth/sign-in', discovery.authURL).href, {
33
+ return withQuery(new URL(`/auth/${page}`, discovery.authURL).href, {
33
34
  redirect: withQuery('/auth/return', { editor: cloudEditorReturnURL(discovery, returnURL) }),
34
35
  provider: offered ? provider : undefined
35
36
  })
@@ -1,11 +1,11 @@
1
1
  export {
2
- CloudAIError,
3
- cloudAIFetch,
4
- createCloudAIClient,
5
- type CloudAIClient,
6
- type CloudAIClientOptions,
7
- type CloudAITokenSource
8
- } from './ai'
2
+ CloudServiceError,
3
+ cloudServicesFetch,
4
+ createCloudServicesClient,
5
+ type CloudServicesClient,
6
+ type CloudServicesClientOptions,
7
+ type CloudServicesTokenSource
8
+ } from './services'
9
9
  export { cloudEditorReturnURL, cloudRedirectPath, cloudSignInURL } from './auth/navigation'
10
10
  export {
11
11
  CloudAPIError,
@@ -1,4 +1,5 @@
1
1
  import {
2
+ cloudAccountDeletionResponseSchema,
2
3
  cloudAccountMutationResponseSchema,
3
4
  cloudAccountSessionsResponseSchema,
4
5
  cloudAccountStatusResponseSchema,
@@ -25,6 +26,14 @@ export function createAccountAPI(call: CloudCall, { account }: PortalRouteClient
25
26
  signal
26
27
  )
27
28
  },
29
+ /** Accepts the server's terms at `version`, the one its discovery names. */
30
+ acceptTerms(version: string, signal?: AbortSignal) {
31
+ return call(
32
+ (options) => account.terms.$post({ json: { version } }, options),
33
+ cloudAccountMutationResponseSchema,
34
+ signal
35
+ )
36
+ },
28
37
  authenticationMethods(signal?: AbortSignal) {
29
38
  return call(
30
39
  (options) => account.authentication.$get(undefined, options),
@@ -172,6 +181,22 @@ export function createAccountAPI(call: CloudCall, { account }: PortalRouteClient
172
181
  signal
173
182
  )
174
183
  },
184
+ /** What deleting the account takes, and the workspaces that stop it. */
185
+ accountDeletion(signal?: AbortSignal) {
186
+ return call(
187
+ (options) => account.deletion.$get(undefined, options),
188
+ cloudAccountDeletionResponseSchema,
189
+ signal
190
+ )
191
+ },
192
+ /** Deletes the account; a session that signed in a while ago gives its password. */
193
+ deleteAccount(password?: string, signal?: AbortSignal) {
194
+ return call(
195
+ (options) => account.delete.$post({ json: { password } }, options),
196
+ cloudAccountMutationResponseSchema,
197
+ signal
198
+ )
199
+ },
175
200
  unlinkAuthenticationMethod(methodId: string, signal?: AbortSignal) {
176
201
  return call(
177
202
  (options) => account.authentication.unlink.$post({ json: { methodId } }, options),
@@ -3,12 +3,16 @@ import {
3
3
  adminEmailResponseSchema,
4
4
  adminMutationResponseSchema,
5
5
  adminOperationsResponseSchema,
6
+ cloudAdminDocumentsResponseSchema,
7
+ cloudAdminReportsResponseSchema,
6
8
  cloudAdminSessionResponseSchema,
7
9
  cloudAdminUserDetailSchema,
8
10
  cloudAdminUsersResponseSchema,
9
11
  enrollmentReviewResponseSchema,
10
12
  enrollmentsResponseSchema,
11
13
  type CloudAdminAuditFilter,
14
+ type CloudAdminDocumentFilter,
15
+ type CloudAdminReportFilter,
12
16
  type CloudAdminEmailFilter,
13
17
  type CloudAdminUserFilter,
14
18
  type EnrollmentStatus
@@ -119,6 +123,58 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalR
119
123
  signal
120
124
  )
121
125
  },
126
+ reports(request: AdminListRequest<CloudAdminReportFilter>, signal?: AbortSignal) {
127
+ return call(
128
+ (options) => admin.reports.$get(listQuery(request), options),
129
+ cloudAdminReportsResponseSchema,
130
+ signal
131
+ )
132
+ },
133
+ /** Closes a report: dismissed, or acted on outside a takedown. */
134
+ resolveReport(id: string, action: 'dismiss' | 'action', signal?: AbortSignal) {
135
+ return call(
136
+ (options) => admin.reports[':id'][action].$post({ param: { id } }, options),
137
+ adminMutationResponseSchema,
138
+ signal
139
+ )
140
+ },
141
+ documents(request: AdminListRequest<CloudAdminDocumentFilter>, signal?: AbortSignal) {
142
+ return call(
143
+ (options) => admin.documents.$get(listQuery(request), options),
144
+ cloudAdminDocumentsResponseSchema,
145
+ signal
146
+ )
147
+ },
148
+ /** Takes a document down, or puts it back. */
149
+ documentAction(
150
+ id: string,
151
+ action: 'disable' | 'enable' | 'undelete',
152
+ reason?: string,
153
+ signal?: AbortSignal
154
+ ) {
155
+ return call(
156
+ (options) => {
157
+ if (action === 'disable') {
158
+ return admin.documents[':id'].disable.$post(
159
+ { param: { id }, json: { reason } },
160
+ options
161
+ )
162
+ }
163
+ return action === 'enable'
164
+ ? admin.documents[':id'].enable.$post({ param: { id } }, options)
165
+ : admin.documents[':id'].undelete.$post({ param: { id } }, options)
166
+ },
167
+ adminMutationResponseSchema,
168
+ signal
169
+ )
170
+ },
171
+ revokeShare(id: string, signal?: AbortSignal) {
172
+ return call(
173
+ (options) => admin.shares[':id'].revoke.$post({ param: { id } }, options),
174
+ adminMutationResponseSchema,
175
+ signal
176
+ )
177
+ },
122
178
  operations(signal?: AbortSignal) {
123
179
  return call(
124
180
  (options) => admin.operations.$get(undefined, options),
@@ -1,30 +1,35 @@
1
1
  import type { CloudFetch } from '#cloud/client/discovery'
2
2
  import {
3
- aiCatalogSchema,
4
- aiErrorSchema,
5
- aiWalletSchema,
6
- CLOUD_AI_API_PATHS,
7
- type AICatalog,
8
- type AIErrorCode,
9
- type AIWallet
3
+ serviceCatalogSchema,
4
+ serviceErrorSchema,
5
+ creditWalletSchema,
6
+ searchResponseSchema,
7
+ CLOUD_SERVICES_API_PATHS,
8
+ type ServiceCatalog,
9
+ type ServiceErrorCode,
10
+ type CreditWallet,
11
+ type SearchRequestInput,
12
+ type SearchResponse,
13
+ type CloudServicesAPI
10
14
  } from '#cloud/contract'
15
+ import { hc } from 'hono/client'
11
16
  import * as v from 'valibot'
12
17
 
13
18
  /** Where a request gets the token it sends, and how it drops one the service refused. */
14
- export type CloudAITokenSource = {
19
+ export type CloudServicesTokenSource = {
15
20
  token(): Promise<string>
16
21
  /** Forgets `token`, so the next call signs a new one. */
17
22
  invalidate(token: string): void
18
23
  }
19
24
 
20
- export class CloudAIError extends Error {
21
- override readonly name = 'CloudAIError'
25
+ export class CloudServiceError extends Error {
26
+ override readonly name = 'CloudServiceError'
22
27
 
23
28
  constructor(
24
29
  readonly status: number,
25
- readonly code?: AIErrorCode
30
+ readonly code?: ServiceErrorCode
26
31
  ) {
27
- super(`OpenPencil AI request failed with HTTP ${status}`)
32
+ super(`OpenPencil services request failed with HTTP ${status}`)
28
33
  }
29
34
  }
30
35
 
@@ -39,7 +44,10 @@ function replayable(input: RequestInfo | URL, body: RequestInit['body']): boolea
39
44
  * by a key Cloud has since replaced, is dropped and a request that can be replayed is sent once
40
45
  * more with a new one.
41
46
  */
42
- export function cloudAIFetch(tokens: CloudAITokenSource, fetch: CloudFetch): CloudFetch {
47
+ export function cloudServicesFetch(
48
+ tokens: CloudServicesTokenSource,
49
+ fetch: CloudFetch
50
+ ): CloudFetch {
43
51
  const send = async (input: RequestInfo | URL, init: RequestInit | undefined, token: string) => {
44
52
  const headers = new Headers(init?.headers)
45
53
  headers.set('Authorization', `Bearer ${token}`)
@@ -55,42 +63,51 @@ export function cloudAIFetch(tokens: CloudAITokenSource, fetch: CloudFetch): Clo
55
63
  }
56
64
  }
57
65
 
58
- const errorBodySchema = v.pipe(v.string(), v.parseJson(), aiErrorSchema)
66
+ const errorBodySchema = v.pipe(v.string(), v.parseJson(), serviceErrorSchema)
59
67
 
60
68
  async function parsed<TSchema extends v.GenericSchema>(
61
- response: Response,
69
+ response: Pick<Response, 'ok' | 'status' | 'text'>,
62
70
  schema: TSchema
63
71
  ): Promise<v.InferOutput<TSchema>> {
64
72
  const text = await response.text()
65
73
  if (!response.ok) {
66
74
  const error = v.safeParse(errorBodySchema, text)
67
- throw new CloudAIError(response.status, error.success ? error.output.error.code : undefined)
75
+ throw new CloudServiceError(
76
+ response.status,
77
+ error.success ? error.output.error.code : undefined
78
+ )
68
79
  }
69
80
  return v.parse(v.pipe(v.string(), v.parseJson(), schema), text)
70
81
  }
71
82
 
72
- export type CloudAIClientOptions = {
83
+ export type CloudServicesClientOptions = {
73
84
  /** The service's endpoint, as Cloud's discovery names it. */
74
85
  endpoint: string
75
- tokens: CloudAITokenSource
86
+ tokens: CloudServicesTokenSource
76
87
  fetch: CloudFetch
77
88
  }
78
89
 
79
- /** The AI service a Cloud advertises: its model API base URL, catalog, and the wallet. */
80
- export function createCloudAIClient(options: CloudAIClientOptions) {
90
+ /** The services a Cloud advertises: the model API base URL, catalog, wallet, and search. */
91
+ export function createCloudServicesClient(options: CloudServicesClientOptions) {
81
92
  const endpoint = options.endpoint.replace(/\/+$/, '')
82
- const fetch = cloudAIFetch(options.tokens, options.fetch)
93
+ const fetch = cloudServicesFetch(options.tokens, options.fetch)
94
+ // Answers are parsed rather than trusted: the service is deployed apart from this client.
95
+ const { v1 } = hc<CloudServicesAPI>(endpoint, { fetch })
83
96
  return {
84
97
  /** The base URL an OpenAI-compatible client sends chat completions below. */
85
- modelBaseURL: `${endpoint}${CLOUD_AI_API_PATHS.base}`,
98
+ modelBaseURL: `${endpoint}${CLOUD_SERVICES_API_PATHS.base}`,
86
99
  fetch,
87
- async catalog(): Promise<AICatalog> {
88
- return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.catalog}`), aiCatalogSchema)
100
+ async catalog(): Promise<ServiceCatalog> {
101
+ return parsed(await v1.catalog.$get(), serviceCatalogSchema)
102
+ },
103
+ async wallet(): Promise<CreditWallet> {
104
+ return parsed(await v1.wallet.$get(), creditWalletSchema)
89
105
  },
90
- async wallet(): Promise<AIWallet> {
91
- return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.wallet}`), aiWalletSchema)
106
+ /** A web search, charged to the workspace; only when the catalog lists `search`. */
107
+ async search(input: SearchRequestInput): Promise<SearchResponse> {
108
+ return parsed(await v1.search.$post({ json: input }), searchResponseSchema)
92
109
  }
93
110
  }
94
111
  }
95
112
 
96
- export type CloudAIClient = ReturnType<typeof createCloudAIClient>
113
+ export type CloudServicesClient = ReturnType<typeof createCloudServicesClient>
@@ -1,7 +1,17 @@
1
1
  import { isValid as isBase64 } from 'js-base64'
2
2
  import * as v from 'valibot'
3
3
 
4
- export const cloudAccountStateSchema = v.picklist(['active', 'pending', 'rejected', 'revoked'])
4
+ /**
5
+ * Where an account stands: it may use the server, waits for an administrator, was refused or had
6
+ * its access taken back, or has to accept the server's current terms first.
7
+ */
8
+ export const cloudAccountStateSchema = v.picklist([
9
+ 'active',
10
+ 'pending',
11
+ 'rejected',
12
+ 'revoked',
13
+ 'terms'
14
+ ])
5
15
  export const cloudIdentitySchema = v.object({
6
16
  userId: v.string(),
7
17
  email: v.pipe(v.string(), v.email()),
@@ -16,6 +26,9 @@ export const cloudAccountStatusResponseSchema = v.object({
16
26
  state: cloudAccountStateSchema
17
27
  })
18
28
 
29
+ /** Accepting the server's terms: the version the person read, which must be the current one. */
30
+ export const cloudTermsAcceptanceSchema = v.object({ version: v.pipe(v.string(), v.minLength(1)) })
31
+
19
32
  export const cloudAuthenticationProviderSchema = v.picklist(['credential', 'google', 'apple'])
20
33
  export const cloudAuthenticationMethodSchema = v.object({
21
34
  id: v.string(),
@@ -47,7 +60,10 @@ export const accountSecurityErrorCodeSchema = v.picklist([
47
60
  'email_unchanged',
48
61
  'email_change_unavailable',
49
62
  'current_session',
50
- 'picture_invalid'
63
+ 'picture_invalid',
64
+ 'account_sole_admin',
65
+ 'last_admin_required',
66
+ 'terms_changed'
51
67
  ])
52
68
  export const accountSecurityErrorResponseSchema = v.object({
53
69
  error: v.object({ code: accountSecurityErrorCodeSchema })
@@ -79,6 +95,9 @@ export const cloudPasskeySchema = v.object({
79
95
  export const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) })
80
96
  export const cloudPasskeyDeleteSchema = v.object({ id: v.string() })
81
97
 
98
+ export function parseCloudTermsAcceptance(input: unknown) {
99
+ return v.parse(cloudTermsAcceptanceSchema, input)
100
+ }
82
101
  export function parseCloudMFAEnable(input: unknown) {
83
102
  return v.parse(cloudMFAEnableSchema, input)
84
103
  }
@@ -177,6 +196,39 @@ export const cloudSignInSchema = v.object({
177
196
  })
178
197
  export const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) })
179
198
 
199
+ /** A workspace an account deletion reads: one it would delete, or one that stops it. */
200
+ export const cloudAccountDeletionWorkspaceSchema = v.object({
201
+ id: v.pipe(v.string(), v.uuid()),
202
+ name: v.string()
203
+ })
204
+ /** A document the account would lose, which Download all saves first. */
205
+ export const cloudAccountDeletionDocumentSchema = v.object({
206
+ id: v.pipe(v.string(), v.uuid()),
207
+ name: v.string(),
208
+ workspaceName: v.string()
209
+ })
210
+ /**
211
+ * What deleting the account takes: the workspaces only it belongs to, which go with their
212
+ * documents; the ones it leaves to their other members; the ones it alone administers for other
213
+ * members, which stop the deletion until it makes someone else an admin; and the documents it
214
+ * would lose, those workspaces' and the ones it created in workspaces it leaves.
215
+ */
216
+ export const cloudAccountDeletionSchema = v.object({
217
+ /** The account is the deployment's only administrator, which also stops the deletion. */
218
+ lastAdministrator: v.boolean(),
219
+ blockedBy: v.array(cloudAccountDeletionWorkspaceSchema),
220
+ deletes: v.array(cloudAccountDeletionWorkspaceSchema),
221
+ leaves: v.array(cloudAccountDeletionWorkspaceSchema),
222
+ documents: v.array(cloudAccountDeletionDocumentSchema)
223
+ })
224
+ export const cloudAccountDeletionResponseSchema = v.object({
225
+ deletion: cloudAccountDeletionSchema
226
+ })
227
+ /** The password, for a session that signed in too long ago to delete the account on its own. */
228
+ export const cloudAccountDeleteSchema = v.object({
229
+ password: v.optional(v.pipe(v.string(), v.minLength(1)))
230
+ })
231
+
180
232
  export function parseCloudProfileUpdate(input: unknown) {
181
233
  return v.parse(cloudProfileUpdateSchema, input)
182
234
  }
@@ -186,6 +238,9 @@ export function parseCloudPictureUpload(input: unknown) {
186
238
  export function parseCloudEmailChange(input: unknown) {
187
239
  return v.parse(cloudEmailChangeSchema, input)
188
240
  }
241
+ export function parseCloudAccountDelete(input: unknown) {
242
+ return v.parse(cloudAccountDeleteSchema, input)
243
+ }
189
244
  export function parseCloudSessionRevoke(input: unknown) {
190
245
  return v.parse(cloudSessionRevokeSchema, input)
191
246
  }
@@ -202,3 +257,4 @@ export type CloudProfile = v.InferOutput<typeof cloudProfileSchema>
202
257
  export type CloudSignInMethod = v.InferOutput<typeof cloudSignInMethodSchema>
203
258
  export type CloudAccountSession = v.InferOutput<typeof cloudAccountSessionSchema>
204
259
  export type CloudSignIn = v.InferOutput<typeof cloudSignInSchema>
260
+ export type CloudAccountDeletion = v.InferOutput<typeof cloudAccountDeletionSchema>