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

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 (206) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/server.mjs +1 -1
  3. package/dist/bin/server.mjs.map +1 -1
  4. package/dist/bin/services.mjs +1 -1
  5. package/dist/bin/services.mjs.map +1 -1
  6. package/dist/client.d.ts +296 -27
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +649 -295
  9. package/dist/client.js.map +1 -1
  10. package/dist/contract.d.ts +2 -2
  11. package/dist/contract.js +2 -2
  12. package/dist/contract2.js +331 -21
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +1773 -32
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +3478 -288
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +48 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +466 -13
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +35 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +447 -290
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +89 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +15667 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +2963 -294
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/server.d.ts +3473 -842
  34. package/dist/server.d.ts.map +1 -1
  35. package/dist/server.js +12187 -8244
  36. package/dist/server.js.map +1 -1
  37. package/dist/server.mjs +7739 -3548
  38. package/dist/server.mjs.map +1 -1
  39. package/dist/server2.mjs +5 -5
  40. package/dist/server2.mjs.map +1 -1
  41. package/package.json +22 -5
  42. package/src/admin/audit/service.ts +2 -2
  43. package/src/admin/documents/service.ts +76 -6
  44. package/src/admin/reports/service.ts +7 -1
  45. package/src/client/api.ts +23 -471
  46. package/src/client/auth/client.ts +22 -3
  47. package/src/client/billing.ts +80 -0
  48. package/src/client/community.ts +40 -0
  49. package/src/client/discovery.ts +35 -9
  50. package/src/client/documents.ts +160 -0
  51. package/src/client/index.ts +7 -0
  52. package/src/client/portal/account.ts +54 -2
  53. package/src/client/portal/request.ts +2 -0
  54. package/src/client/response.ts +21 -0
  55. package/src/client/schema.ts +8 -0
  56. package/src/client/services.ts +23 -18
  57. package/src/client/sharing.ts +262 -0
  58. package/src/client/versions.ts +104 -0
  59. package/src/contract/account.ts +50 -0
  60. package/src/contract/billing.ts +166 -0
  61. package/src/contract/collaboration.ts +5 -0
  62. package/src/contract/community.ts +60 -0
  63. package/src/contract/discovery.ts +63 -2
  64. package/src/contract/entitlements.ts +10 -0
  65. package/src/contract/index.ts +54 -5
  66. package/src/contract/links.ts +57 -4
  67. package/src/contract/locale.ts +27 -0
  68. package/src/contract/portal.ts +12 -1
  69. package/src/contract/routes.ts +10 -0
  70. package/src/contract/services.ts +18 -16
  71. package/src/email/i18n.ts +174 -0
  72. package/src/email/index.ts +13 -2
  73. package/src/email/locales/ar.json +141 -0
  74. package/src/email/locales/de.json +141 -0
  75. package/src/email/locales/es.json +141 -0
  76. package/src/email/locales/fr.json +141 -0
  77. package/src/email/locales/it.json +141 -0
  78. package/src/email/locales/ja.json +141 -0
  79. package/src/email/locales/pl.json +141 -0
  80. package/src/email/locales/pt-br.json +141 -0
  81. package/src/email/locales/ru.json +141 -0
  82. package/src/email/locales/zh-cn.json +141 -0
  83. package/src/email/messages.ts +200 -0
  84. package/src/email/render.ts +142 -276
  85. package/src/email/samples.ts +115 -0
  86. package/src/email/schema.ts +70 -6
  87. package/src/email/templates/BrandEmail.vue +54 -0
  88. package/src/email/templates/DocumentBlocked.vue +45 -0
  89. package/src/email/templates/DocumentInvitation.vue +24 -0
  90. package/src/email/templates/DocumentReport.vue +32 -0
  91. package/src/email/templates/DocumentReportDecided.vue +36 -0
  92. package/src/email/templates/DocumentReportReceived.vue +18 -0
  93. package/src/email/templates/DocumentRestored.vue +24 -0
  94. package/src/email/templates/EmailChangeRequested.vue +24 -0
  95. package/src/email/templates/EmailRoot.vue +19 -0
  96. package/src/email/templates/EmailText.vue +9 -0
  97. package/src/email/templates/EmailVerification.vue +38 -0
  98. package/src/email/templates/EnrollmentNotification.vue +24 -0
  99. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  100. package/src/email/templates/NewSignIn.vue +37 -0
  101. package/src/email/templates/PasswordChanged.vue +22 -0
  102. package/src/email/templates/PasswordReset.vue +23 -0
  103. package/src/email/templates/StorageLimitReached.vue +28 -0
  104. package/src/email/templates/TwoStepChanged.vue +32 -0
  105. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  106. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  107. package/src/email/templates/brand.ts +9 -61
  108. package/src/email/templates/localization.ts +17 -0
  109. package/src/errors/index.ts +6 -0
  110. package/src/global.d.ts +7 -0
  111. package/src/runtime/cloudflare/relay/index.ts +7 -1
  112. package/src/runtime/cloudflare/tsconfig.json +2 -1
  113. package/src/runtime/cloudflare/worker.ts +8 -1
  114. package/src/runtime/node/cleanup.ts +5 -1
  115. package/src/runtime/node/email/transport.ts +13 -10
  116. package/src/runtime/node/main.ts +1 -1
  117. package/src/runtime/node/server.ts +12 -2
  118. package/src/runtime/node/services/main.ts +1 -1
  119. package/src/runtime/posthog/errors.ts +2 -1
  120. package/src/runtime/s3/objects.ts +17 -0
  121. package/src/runtime/site/community.ts +101 -0
  122. package/src/runtime/site/server.ts +17 -1
  123. package/src/server/account/deletion.ts +2 -0
  124. package/src/server/account/routes.ts +271 -240
  125. package/src/server/account/tokens.ts +57 -0
  126. package/src/server/api/router.ts +23 -0
  127. package/src/server/app/checks.ts +84 -0
  128. package/src/server/app/editors.ts +20 -0
  129. package/src/server/app/index.ts +128 -0
  130. package/src/server/app/indexing.ts +40 -0
  131. package/src/server/app/limiters.ts +53 -0
  132. package/src/server/app/routes.ts +114 -0
  133. package/src/server/app/services.ts +185 -0
  134. package/src/server/auth/access-tokens.ts +62 -0
  135. package/src/server/auth/adapter.ts +21 -1
  136. package/src/server/auth/email.ts +4 -1
  137. package/src/server/auth/enrollment.ts +116 -0
  138. package/src/server/auth/factory.ts +88 -131
  139. package/src/server/auth/logger.ts +23 -0
  140. package/src/server/auth/mfa-assurance.ts +51 -0
  141. package/src/server/auth/passwords.ts +43 -0
  142. package/src/server/auth/session.ts +2 -0
  143. package/src/server/billing/index.ts +6 -0
  144. package/src/server/billing/routes.ts +27 -0
  145. package/src/server/billing/tokens.ts +37 -0
  146. package/src/server/cleanup/configured.ts +16 -3
  147. package/src/server/cleanup/worker.ts +10 -1
  148. package/src/server/collaboration/relay/hub.ts +25 -142
  149. package/src/server/collaboration/relay/room.ts +154 -0
  150. package/src/server/collaboration/service.ts +21 -2
  151. package/src/server/community/index.ts +2 -0
  152. package/src/server/community/routes.ts +93 -0
  153. package/src/server/community/service.ts +134 -0
  154. package/src/server/config/deployment.ts +17 -5
  155. package/src/server/config/index.ts +1 -1
  156. package/src/server/config/public.ts +7 -1
  157. package/src/server/config/schema.ts +40 -292
  158. package/src/server/config/toml/schema.ts +307 -0
  159. package/src/server/db/index.ts +1 -0
  160. package/src/server/db/migrate.ts +13 -1
  161. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  162. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  163. package/src/server/db/migrations/011_account_ids.ts +30 -0
  164. package/src/server/db/migrations/012_email_locales.ts +34 -0
  165. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  166. package/src/server/db/migrations/014_report_replies.ts +28 -0
  167. package/src/server/db/migrations/schema.ts +26 -1
  168. package/src/server/db/tables.ts +30 -1
  169. package/src/server/db/users.ts +22 -0
  170. package/src/server/documents/index.ts +1 -1
  171. package/src/server/documents/limits.ts +7 -1
  172. package/src/server/documents/service.ts +12 -402
  173. package/src/server/documents/uploads.ts +450 -0
  174. package/src/server/documents/versions/service.ts +81 -24
  175. package/src/server/email/invitations.ts +1 -0
  176. package/src/server/email/service.ts +31 -4
  177. package/src/server/email/types.ts +12 -0
  178. package/src/server/errors/index.ts +1 -9
  179. package/src/server/index.ts +12 -5
  180. package/src/server/invitations/types.ts +5 -1
  181. package/src/server/objects/types.ts +5 -0
  182. package/src/server/policy/configured.ts +9 -3
  183. package/src/server/policy/database.ts +13 -2
  184. package/src/server/policy/policy.ts +39 -12
  185. package/src/server/policy/service.ts +71 -52
  186. package/src/server/policy/storage.ts +33 -0
  187. package/src/server/quota/index.ts +6 -0
  188. package/src/server/quota/notices.ts +121 -0
  189. package/src/server/quota/storage.ts +5 -0
  190. package/src/server/rate-limit/middleware.ts +4 -0
  191. package/src/server/reports/index.ts +1 -0
  192. package/src/server/reports/replies.ts +55 -0
  193. package/src/server/reports/routes.ts +3 -1
  194. package/src/server/reports/service.ts +24 -2
  195. package/src/server/sharing/capabilities/service.ts +2 -3
  196. package/src/server/sharing/invitations/service.ts +14 -4
  197. package/src/server/validation.ts +3 -0
  198. package/src/server/workspaces/members.ts +7 -19
  199. package/src/services/app.ts +1 -3
  200. package/src/services/config.ts +1 -0
  201. package/src/services/usage.ts +6 -14
  202. package/src/email/templates/document-invitation.ts +0 -35
  203. package/src/email/templates/enrollment.ts +0 -27
  204. package/src/email/templates/layout.ts +0 -18
  205. package/src/server/app.ts +0 -453
  206. /package/src/{server/errors → errors}/posthog.ts +0 -0
@@ -2,6 +2,7 @@ import {
2
2
  CLOUD_DISCOVERY_PATH,
3
3
  CLOUD_PROTOCOL_VERSION,
4
4
  cloudDiscoverySchema,
5
+ isEditorVersionAtLeast,
5
6
  type CloudDiscovery
6
7
  } from '#cloud/contract'
7
8
  import * as v from 'valibot'
@@ -13,13 +14,21 @@ export type CloudFetch = (input: RequestInfo | URL, init?: RequestInit) => Promi
13
14
  export type DiscoverCloudOptions = {
14
15
  fetch?: CloudFetch
15
16
  signal?: AbortSignal
17
+ /** The editor's own version, checked against the server's minimum. */
18
+ editorVersion?: string
16
19
  }
17
20
 
18
21
  /**
19
22
  * Why a server could not be used: the address is not a web address, nothing answered, something
20
- * answered but not as OpenPencil Cloud, or it speaks another protocol version.
23
+ * answered but not as OpenPencil Cloud, the server is older than this editor supports, or this
24
+ * editor is older than the server supports.
21
25
  */
22
- export type CloudDiscoveryFailure = 'invalid-address' | 'unreachable' | 'not-cloud' | 'outdated'
26
+ export type CloudDiscoveryFailure =
27
+ | 'invalid-address'
28
+ | 'unreachable'
29
+ | 'not-cloud'
30
+ | 'server-outdated'
31
+ | 'editor-outdated'
23
32
 
24
33
  export class CloudClientError extends Error {
25
34
  constructor(
@@ -55,21 +64,38 @@ function discoveryURL(serverURL: string): URL {
55
64
  return url
56
65
  }
57
66
 
58
- function parseDiscoveryBody(text: string): CloudDiscovery {
67
+ /** Which side is behind when the server speaks another protocol, or null when it doesn't. */
68
+ function protocolMismatch(version: string): CloudDiscoveryFailure | null {
69
+ if (version === CLOUD_PROTOCOL_VERSION) return null
70
+ return Number(version) > Number(CLOUD_PROTOCOL_VERSION) ? 'editor-outdated' : 'server-outdated'
71
+ }
72
+
73
+ function parseDiscoveryBody(text: string, editorVersion: string | undefined): CloudDiscovery {
59
74
  const body = v.safeParse(discoveryBodySchema, text)
60
75
  if (!body.success) {
61
76
  throw new CloudClientError('OpenPencil server discovery is not JSON', body.issues, 'not-cloud')
62
77
  }
63
78
  const discovery = v.safeParse(cloudDiscoverySchema, body.output)
64
- if (discovery.success) return discovery.output
79
+ if (discovery.success) {
80
+ const minimum = discovery.output.minimumEditorVersion
81
+ if (minimum && editorVersion && !isEditorVersionAtLeast(editorVersion, minimum)) {
82
+ throw new CloudClientError(
83
+ `OpenPencil server needs editor ${minimum} or later`,
84
+ undefined,
85
+ 'editor-outdated'
86
+ )
87
+ }
88
+ return discovery.output
89
+ }
65
90
  const protocol = v.safeParse(protocolSchema, body.output)
66
- const outdated = protocol.success && protocol.output.protocolVersion !== CLOUD_PROTOCOL_VERSION
91
+ const version = protocol.success ? protocol.output.protocolVersion : null
92
+ const mismatch = version === null ? null : protocolMismatch(version)
67
93
  throw new CloudClientError(
68
- outdated
69
- ? `OpenPencil server speaks protocol ${protocol.output.protocolVersion}`
94
+ mismatch
95
+ ? `OpenPencil server speaks protocol ${version}`
70
96
  : 'OpenPencil server discovery is invalid',
71
97
  discovery.issues,
72
- outdated ? 'outdated' : 'not-cloud'
98
+ mismatch ?? 'not-cloud'
73
99
  )
74
100
  }
75
101
 
@@ -94,7 +120,7 @@ export async function discoverCloud(
94
120
  response.status >= 500 ? 'unreachable' : 'not-cloud'
95
121
  )
96
122
  }
97
- return parseDiscoveryBody(await response.text())
123
+ return parseDiscoveryBody(await response.text(), options.editorVersion)
98
124
  } catch (error) {
99
125
  if (error instanceof CloudClientError) throw error
100
126
  if (signal.aborted) {
@@ -0,0 +1,160 @@
1
+ import {
2
+ cloudUserProfileSchema,
3
+ documentAccessSchema,
4
+ documentDownloadSchema,
5
+ objectUploadSchema,
6
+ documentSummarySchema,
7
+ sharedDocumentSchema,
8
+ trashSchema,
9
+ type CloudUserProfile,
10
+ type CollaborationTicket,
11
+ type CommitUploadRequest,
12
+ type CreateDocumentRequest,
13
+ type CreateUploadInput,
14
+ type DocumentAccess,
15
+ type DocumentDownload,
16
+ type DocumentSummary,
17
+ type SharedDocument,
18
+ type TrashedDocument
19
+ } from '#cloud/contract'
20
+ import type { CloudAPI } from '#cloud/server/api'
21
+ import type { hc } from 'hono/client'
22
+ import * as v from 'valibot'
23
+
24
+ import { parseResponse, responseBody, type CloudClientDiagnostic } from './response'
25
+ import { collaborationTicketResponseSchema, documentResponseSchema } from './schema'
26
+
27
+ const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) })
28
+ const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) })
29
+ const downloadResponseSchema = v.object({ document: documentDownloadSchema })
30
+ const accessResponseSchema = v.object({ access: documentAccessSchema })
31
+ const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) })
32
+ const uploadResponseSchema = v.object({
33
+ id: v.pipe(v.string(), v.uuid()),
34
+ upload: objectUploadSchema
35
+ })
36
+
37
+ export type CloudUpload = v.InferOutput<typeof uploadResponseSchema>
38
+
39
+ /** Documents: listing and creating them, Trash, downloads, uploads, and collaboration tickets. */
40
+ export function createDocumentRequests(
41
+ client: ReturnType<typeof hc<CloudAPI>>,
42
+ onDiagnostic?: CloudClientDiagnostic
43
+ ) {
44
+ return {
45
+ async getUserProfile(documentId: string, userId: string): Promise<CloudUserProfile | null> {
46
+ const response = await parseResponse(
47
+ client.documents[':documentId'].users[':userId'].$get({
48
+ param: { documentId, userId }
49
+ }),
50
+ userLookupResponseSchema,
51
+ onDiagnostic
52
+ )
53
+ return response.user
54
+ },
55
+ /** Documents shared with the person directly, outside their workspaces. */
56
+ async listSharedDocuments(): Promise<SharedDocument[]> {
57
+ const response = await parseResponse(
58
+ client['shared-documents'].$get(),
59
+ sharedDocumentsResponseSchema,
60
+ onDiagnostic
61
+ )
62
+ return response.documents
63
+ },
64
+ async listDocuments(workspaceId: string): Promise<DocumentSummary[]> {
65
+ const response = await parseResponse(
66
+ client.workspaces[':workspaceId'].documents.$get({
67
+ param: { workspaceId }
68
+ }),
69
+ documentsResponseSchema,
70
+ onDiagnostic
71
+ )
72
+ return response.documents
73
+ },
74
+ async createDocument(
75
+ workspaceId: string,
76
+ input: CreateDocumentRequest
77
+ ): Promise<DocumentSummary> {
78
+ const response = await parseResponse(
79
+ client.workspaces[':workspaceId'].documents.$post({
80
+ param: { workspaceId },
81
+ json: { ...input, kind: input.kind ?? 'design' }
82
+ }),
83
+ documentResponseSchema,
84
+ onDiagnostic
85
+ )
86
+ return response.document
87
+ },
88
+ /** Documents in Trash the person may restore, across their workspaces, newest first. */
89
+ async listTrash(): Promise<TrashedDocument[]> {
90
+ const response = await parseResponse(client.trash.$get(), trashSchema, onDiagnostic)
91
+ return response.documents
92
+ },
93
+ async restoreDocument(documentId: string): Promise<void> {
94
+ await responseBody(
95
+ await client.trash[':documentId'].restore.$post({ param: { documentId } }),
96
+ onDiagnostic
97
+ )
98
+ },
99
+ /** Deletes a document in Trash for good. */
100
+ async purgeDocument(documentId: string): Promise<void> {
101
+ await responseBody(
102
+ await client.trash[':documentId'].$delete({ param: { documentId } }),
103
+ onDiagnostic
104
+ )
105
+ },
106
+ async deleteDocument(documentId: string): Promise<void> {
107
+ await responseBody(
108
+ await client.documents[':documentId'].$delete({ param: { documentId } }),
109
+ onDiagnostic
110
+ )
111
+ },
112
+ async getDocument(documentId: string): Promise<DocumentDownload> {
113
+ const response = await parseResponse(
114
+ client.documents[':documentId'].$get({ param: { documentId } }),
115
+ downloadResponseSchema,
116
+ onDiagnostic
117
+ )
118
+ return response.document
119
+ },
120
+ async getDocumentAccess(documentId: string): Promise<DocumentAccess> {
121
+ const response = await parseResponse(
122
+ client.documents[':documentId'].access.$get({ param: { documentId } }),
123
+ accessResponseSchema,
124
+ onDiagnostic
125
+ )
126
+ return response.access
127
+ },
128
+ async getCollaborationTicket(documentId: string): Promise<CollaborationTicket> {
129
+ const response = await parseResponse(
130
+ client.documents[':documentId']['collaboration-ticket'].$post({
131
+ param: { documentId }
132
+ }),
133
+ collaborationTicketResponseSchema,
134
+ onDiagnostic
135
+ )
136
+ return response.ticket
137
+ },
138
+ async createUpload(documentId: string, input: CreateUploadInput): Promise<CloudUpload> {
139
+ return parseResponse(
140
+ client.documents[':documentId'].uploads.$post({
141
+ param: { documentId },
142
+ json: input
143
+ }),
144
+ uploadResponseSchema,
145
+ onDiagnostic
146
+ )
147
+ },
148
+ async commitUpload(uploadId: string, input: CommitUploadRequest): Promise<DocumentSummary> {
149
+ const response = await parseResponse(
150
+ client.uploads[':uploadId'].commit.$post({
151
+ param: { uploadId },
152
+ json: { ...input, images: input.images ?? [] }
153
+ }),
154
+ documentResponseSchema,
155
+ onDiagnostic
156
+ )
157
+ return response.document
158
+ }
159
+ }
160
+ }
@@ -1,11 +1,18 @@
1
1
  export {
2
2
  CloudServiceError,
3
+ CloudServiceInsecureEndpointError,
3
4
  cloudServicesFetch,
4
5
  createCloudServicesClient,
5
6
  type CloudServicesClient,
6
7
  type CloudServicesClientOptions,
7
8
  type CloudServicesTokenSource
8
9
  } from './services'
10
+ export {
11
+ CloudBillingError,
12
+ createCloudBillingClient,
13
+ type CloudBillingClient,
14
+ type CloudBillingClientOptions
15
+ } from './billing'
9
16
  export { cloudEditorReturnURL, cloudRedirectPath, cloudSignInURL } from './auth/navigation'
10
17
  export {
11
18
  CloudAPIError,
@@ -1,4 +1,8 @@
1
1
  import {
2
+ accountEntitlementsResponseSchema,
3
+ billingTokenSchema,
4
+ cloudAccessTokenCreatedResponseSchema,
5
+ cloudAccessTokensResponseSchema,
2
6
  cloudAccountDeletionResponseSchema,
3
7
  cloudAccountMutationResponseSchema,
4
8
  cloudAccountSessionsResponseSchema,
@@ -12,13 +16,30 @@ import {
12
16
  cloudPictureResponseSchema,
13
17
  cloudProfileResponseSchema,
14
18
  cloudSignInsResponseSchema,
15
- cloudSocialLinkResponseSchema
19
+ cloudSocialLinkResponseSchema,
20
+ type CloudAccessTokenCreate
16
21
  } from '#cloud/contract'
17
22
 
18
23
  import type { CloudCall, PortalRouteClients } from './request'
19
24
 
20
- export function createAccountAPI(call: CloudCall, { account }: PortalRouteClients) {
25
+ export function createAccountAPI(call: CloudCall, { account, tokens, api }: PortalRouteClients) {
21
26
  return {
27
+ /** The account's plan, and the storage its workspaces hold together. */
28
+ entitlements(signal?: AbortSignal) {
29
+ return call(
30
+ (options) => api.account.entitlements.$get(undefined, options),
31
+ accountEntitlementsResponseSchema,
32
+ signal
33
+ )
34
+ },
35
+ /** A short-lived token for the deployment's billing, for this account. */
36
+ billingToken(signal?: AbortSignal) {
37
+ return call(
38
+ (options) => api.billing.token.$post(undefined, options),
39
+ billingTokenSchema,
40
+ signal
41
+ )
42
+ },
22
43
  accountStatus(signal?: AbortSignal) {
23
44
  return call(
24
45
  (options) => account.status.$get(undefined, options),
@@ -123,6 +144,14 @@ export function createAccountAPI(call: CloudCall, { account }: PortalRouteClient
123
144
  signal
124
145
  )
125
146
  },
147
+ /** The app's language tag; the server writes to the account in it, or the nearest it has. */
148
+ setLocale(locale: string, signal?: AbortSignal) {
149
+ return call(
150
+ (options) => account.locale.$put({ json: { locale } }, options),
151
+ cloudAccountMutationResponseSchema,
152
+ signal
153
+ )
154
+ },
126
155
  updateProfile(name: string, signal?: AbortSignal) {
127
156
  return call(
128
157
  (options) => account.profile.$post({ json: { name } }, options),
@@ -153,6 +182,29 @@ export function createAccountAPI(call: CloudCall, { account }: PortalRouteClient
153
182
  signal
154
183
  )
155
184
  },
185
+ /** The account's personal access tokens, by their first characters; never a whole one. */
186
+ accessTokens(signal?: AbortSignal) {
187
+ return call(
188
+ (options) => tokens.$get(undefined, options),
189
+ cloudAccessTokensResponseSchema,
190
+ signal
191
+ )
192
+ },
193
+ /** Makes a token; the answer holds the whole token, which is shown this once. */
194
+ createAccessToken(input: CloudAccessTokenCreate, signal?: AbortSignal) {
195
+ return call(
196
+ (options) => tokens.create.$post({ json: input }, options),
197
+ cloudAccessTokenCreatedResponseSchema,
198
+ signal
199
+ )
200
+ },
201
+ revokeAccessToken(id: string, signal?: AbortSignal) {
202
+ return call(
203
+ (options) => tokens.revoke.$post({ json: { id } }, options),
204
+ cloudAccountMutationResponseSchema,
205
+ signal
206
+ )
207
+ },
156
208
  sessions(signal?: AbortSignal) {
157
209
  return call(
158
210
  (options) => account.sessions.$get(undefined, options),
@@ -7,6 +7,7 @@ import {
7
7
  type AdminErrorCode
8
8
  } from '#cloud/contract'
9
9
  import type { CloudAccountRoutes } from '#cloud/server/account/routes'
10
+ import type { CloudAccessTokenRoutes } from '#cloud/server/account/tokens'
10
11
  import type { CloudAPI } from '#cloud/server/api'
11
12
  import { hc } from 'hono/client'
12
13
  import * as v from 'valibot'
@@ -107,6 +108,7 @@ export function createPortalRouteClients(options: CloudPortalClientOptions = {})
107
108
  }
108
109
  return {
109
110
  account: hc<CloudAccountRoutes>(origin, clientOptions).api.account,
111
+ tokens: hc<CloudAccessTokenRoutes>(origin, clientOptions).api.account.tokens,
110
112
  admin: hc<CloudAdminRoutes>(new URL('/api/admin', origin).href, clientOptions),
111
113
  api: hc<CloudAPI>(new URL('/api', origin).href, clientOptions)
112
114
  }
@@ -49,3 +49,24 @@ export async function parseResponse<
49
49
  ): Promise<v.InferOutput<TSchema>> {
50
50
  return v.parse(schema, await responseBody(await request, onDiagnostic))
51
51
  }
52
+
53
+ /**
54
+ * The JSON a service deployed apart from Cloud answered, parsed with `schema` rather than trusted;
55
+ * a refusal throws what `refused` makes of its status and body.
56
+ */
57
+ export async function serviceJSON<TSchema extends v.GenericSchema>(
58
+ response: Pick<Response, 'ok' | 'status' | 'text'>,
59
+ schema: TSchema,
60
+ refused: (status: number, body: string) => Error
61
+ ): Promise<v.InferOutput<TSchema>> {
62
+ if (!response.ok) {
63
+ // An unreadable body still leaves the status, which callers tell refusals apart by.
64
+ const body = await response.text().catch((failure: unknown) => {
65
+ const error = refused(response.status, '')
66
+ error.cause = failure
67
+ throw error
68
+ })
69
+ throw refused(response.status, body)
70
+ }
71
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), await response.text())
72
+ }
@@ -0,0 +1,8 @@
1
+ import { collaborationTicketSchema, documentSummarySchema } from '#cloud/contract'
2
+ import * as v from 'valibot'
3
+
4
+ /** What the API answers with one document, as creating, restoring, or duplicating one does. */
5
+ export const documentResponseSchema = v.object({ document: documentSummarySchema })
6
+
7
+ /** What the API answers with a ticket into a document's live room. */
8
+ export const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema })
@@ -1,10 +1,12 @@
1
1
  import type { CloudFetch } from '#cloud/client/discovery'
2
+ import { serviceJSON } from '#cloud/client/response'
2
3
  import {
3
4
  serviceCatalogSchema,
4
5
  serviceErrorSchema,
5
6
  creditWalletSchema,
6
7
  searchResponseSchema,
7
8
  CLOUD_SERVICES_API_PATHS,
9
+ sendsTokenSafely,
8
10
  type ServiceCatalog,
9
11
  type ServiceErrorCode,
10
12
  type CreditWallet,
@@ -13,6 +15,7 @@ import {
13
15
  type CloudServicesAPI
14
16
  } from '#cloud/contract'
15
17
  import { hc } from 'hono/client'
18
+ import { joinURL, withoutTrailingSlash } from 'ufo'
16
19
  import * as v from 'valibot'
17
20
 
18
21
  /** Where a request gets the token it sends, and how it drops one the service refused. */
@@ -33,6 +36,15 @@ export class CloudServiceError extends Error {
33
36
  }
34
37
  }
35
38
 
39
+ /** A service endpoint a token would reach in the clear, which no request is sent to. */
40
+ export class CloudServiceInsecureEndpointError extends Error {
41
+ override readonly name = 'CloudServiceInsecureEndpointError'
42
+
43
+ constructor(readonly url: string) {
44
+ super('OpenPencil services and billing are reached only over HTTPS')
45
+ }
46
+ }
47
+
36
48
  /** Whether a request can be sent twice: a stream, in `init` or a `Request`, is read by the first. */
37
49
  function replayable(input: RequestInfo | URL, body: RequestInit['body']): boolean {
38
50
  if (input instanceof Request && input.body) return false
@@ -54,6 +66,9 @@ export function cloudServicesFetch(
54
66
  return fetch(input, { ...init, headers })
55
67
  }
56
68
  return async (input, init) => {
69
+ const url = input instanceof Request ? input.url : input
70
+ // Refused before a token is even signed, so none is sent where the network could read it.
71
+ if (!sendsTokenSafely(url)) throw new CloudServiceInsecureEndpointError(String(url))
57
72
  const token = await tokens.token()
58
73
  const response = await send(input, init, token)
59
74
  if (response.status !== 401) return response
@@ -65,19 +80,9 @@ export function cloudServicesFetch(
65
80
 
66
81
  const errorBodySchema = v.pipe(v.string(), v.parseJson(), serviceErrorSchema)
67
82
 
68
- async function parsed<TSchema extends v.GenericSchema>(
69
- response: Pick<Response, 'ok' | 'status' | 'text'>,
70
- schema: TSchema
71
- ): Promise<v.InferOutput<TSchema>> {
72
- const text = await response.text()
73
- if (!response.ok) {
74
- const error = v.safeParse(errorBodySchema, text)
75
- throw new CloudServiceError(
76
- response.status,
77
- error.success ? error.output.error.code : undefined
78
- )
79
- }
80
- return v.parse(v.pipe(v.string(), v.parseJson(), schema), text)
83
+ function refused(status: number, body: string): CloudServiceError {
84
+ const error = v.safeParse(errorBodySchema, body)
85
+ return new CloudServiceError(status, error.success ? error.output.error.code : undefined)
81
86
  }
82
87
 
83
88
  export type CloudServicesClientOptions = {
@@ -89,23 +94,23 @@ export type CloudServicesClientOptions = {
89
94
 
90
95
  /** The services a Cloud advertises: the model API base URL, catalog, wallet, and search. */
91
96
  export function createCloudServicesClient(options: CloudServicesClientOptions) {
92
- const endpoint = options.endpoint.replace(/\/+$/, '')
97
+ const endpoint = withoutTrailingSlash(options.endpoint)
93
98
  const fetch = cloudServicesFetch(options.tokens, options.fetch)
94
99
  // Answers are parsed rather than trusted: the service is deployed apart from this client.
95
100
  const { v1 } = hc<CloudServicesAPI>(endpoint, { fetch })
96
101
  return {
97
102
  /** The base URL an OpenAI-compatible client sends chat completions below. */
98
- modelBaseURL: `${endpoint}${CLOUD_SERVICES_API_PATHS.base}`,
103
+ modelBaseURL: joinURL(endpoint, CLOUD_SERVICES_API_PATHS.base),
99
104
  fetch,
100
105
  async catalog(): Promise<ServiceCatalog> {
101
- return parsed(await v1.catalog.$get(), serviceCatalogSchema)
106
+ return serviceJSON(await v1.catalog.$get(), serviceCatalogSchema, refused)
102
107
  },
103
108
  async wallet(): Promise<CreditWallet> {
104
- return parsed(await v1.wallet.$get(), creditWalletSchema)
109
+ return serviceJSON(await v1.wallet.$get(), creditWalletSchema, refused)
105
110
  },
106
111
  /** A web search, charged to the workspace; only when the catalog lists `search`. */
107
112
  async search(input: SearchRequestInput): Promise<SearchResponse> {
108
- return parsed(await v1.search.$post({ json: input }), searchResponseSchema)
113
+ return serviceJSON(await v1.search.$post({ json: input }), searchResponseSchema, refused)
109
114
  }
110
115
  }
111
116
  }