@open-pencil/cloud 0.0.0-stage → 0.17.0-beta.1

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 (279) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +7 -0
  4. package/README.md +37 -2
  5. package/dist/bin/ai-relay.d.mts +1 -0
  6. package/dist/bin/ai-relay.mjs +31 -0
  7. package/dist/bin/ai-relay.mjs.map +1 -0
  8. package/dist/bin/server.d.mts +1 -0
  9. package/dist/bin/server.mjs +29 -0
  10. package/dist/bin/server.mjs.map +1 -0
  11. package/dist/client.d.ts +1520 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +1917 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/contract.d.ts +2 -0
  16. package/dist/contract.js +2 -0
  17. package/dist/contract2.js +1453 -0
  18. package/dist/contract2.js.map +1 -0
  19. package/dist/email.d.ts +169 -0
  20. package/dist/email.d.ts.map +1 -0
  21. package/dist/email.js +670 -0
  22. package/dist/email.js.map +1 -0
  23. package/dist/index.d.ts +1755 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/listen.mjs +1881 -0
  26. package/dist/listen.mjs.map +1 -0
  27. package/dist/runtime-node.d.mts +10040 -0
  28. package/dist/runtime-node.d.mts.map +1 -0
  29. package/dist/runtime-node.mjs +32 -0
  30. package/dist/runtime-node.mjs.map +1 -0
  31. package/dist/server.d.ts +12792 -0
  32. package/dist/server.d.ts.map +1 -0
  33. package/dist/server.js +8475 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/server.mjs +8324 -0
  36. package/dist/server.mjs.map +1 -0
  37. package/dist/server2.mjs +505 -0
  38. package/dist/server2.mjs.map +1 -0
  39. package/package.json +124 -4
  40. package/src/admin/api/routes.ts +223 -0
  41. package/src/admin/api/security.ts +12 -0
  42. package/src/admin/audit/service.ts +138 -0
  43. package/src/admin/email/service.ts +140 -0
  44. package/src/admin/enrollment/email.ts +77 -0
  45. package/src/admin/enrollment/service.ts +308 -0
  46. package/src/admin/errors.ts +20 -0
  47. package/src/admin/index.ts +19 -0
  48. package/src/admin/list.ts +61 -0
  49. package/src/admin/operations/service.ts +70 -0
  50. package/src/admin/schema.ts +28 -0
  51. package/src/admin/users/service.ts +369 -0
  52. package/src/ai-relay/app.ts +251 -0
  53. package/src/ai-relay/config.ts +120 -0
  54. package/src/ai-relay/db/index.ts +10 -0
  55. package/src/ai-relay/db/migrate.ts +32 -0
  56. package/src/ai-relay/db/migrations/001_usage.ts +26 -0
  57. package/src/ai-relay/db/schema.ts +20 -0
  58. package/src/ai-relay/index.ts +18 -0
  59. package/src/ai-relay/metering.ts +68 -0
  60. package/src/ai-relay/usage.ts +115 -0
  61. package/src/client/ai.ts +96 -0
  62. package/src/client/api.ts +528 -0
  63. package/src/client/auth/client.ts +188 -0
  64. package/src/client/auth/failure.ts +54 -0
  65. package/src/client/auth/navigation.ts +45 -0
  66. package/src/client/device-authorization.ts +134 -0
  67. package/src/client/discovery.ts +105 -0
  68. package/src/client/images.ts +81 -0
  69. package/src/client/index.ts +53 -0
  70. package/src/client/portal/account.ts +183 -0
  71. package/src/client/portal/administration.ts +130 -0
  72. package/src/client/portal/client.ts +18 -0
  73. package/src/client/portal/request.ts +115 -0
  74. package/src/client/response.ts +51 -0
  75. package/src/client/workspaces.ts +142 -0
  76. package/src/contract/account.ts +204 -0
  77. package/src/contract/admin/index.ts +187 -0
  78. package/src/contract/ai.ts +150 -0
  79. package/src/contract/collaboration.ts +45 -0
  80. package/src/contract/discovery.ts +81 -0
  81. package/src/contract/documents.ts +265 -0
  82. package/src/contract/entitlements.ts +28 -0
  83. package/src/contract/index.ts +204 -0
  84. package/src/contract/links.ts +87 -0
  85. package/src/contract/portal.ts +11 -0
  86. package/src/contract/relay.ts +368 -0
  87. package/src/contract/sharing.ts +191 -0
  88. package/src/contract/versions.ts +87 -0
  89. package/src/contract/workspaces.ts +100 -0
  90. package/src/email/index.ts +14 -0
  91. package/src/email/render.ts +276 -0
  92. package/src/email/schema.ts +144 -0
  93. package/src/email/templates/brand.ts +105 -0
  94. package/src/email/templates/document-invitation.ts +35 -0
  95. package/src/email/templates/enrollment.ts +27 -0
  96. package/src/email/templates/layout.ts +18 -0
  97. package/src/runtime/cloudflare/email.ts +70 -0
  98. package/src/runtime/cloudflare/environment.ts +57 -0
  99. package/src/runtime/cloudflare/index.ts +3 -0
  100. package/src/runtime/cloudflare/relay.ts +136 -0
  101. package/src/runtime/cloudflare/site.ts +13 -0
  102. package/src/runtime/cloudflare/tsconfig.json +21 -0
  103. package/src/runtime/cloudflare/worker.ts +160 -0
  104. package/src/runtime/node/admin.ts +59 -0
  105. package/src/runtime/node/ai-relay/main.ts +35 -0
  106. package/src/runtime/node/ai-relay/server.ts +63 -0
  107. package/src/runtime/node/application.ts +50 -0
  108. package/src/runtime/node/bootstrap.ts +22 -0
  109. package/src/runtime/node/cleanup.ts +24 -0
  110. package/src/runtime/node/command.ts +17 -0
  111. package/src/runtime/node/config.ts +16 -0
  112. package/src/runtime/node/email/runtime.ts +43 -0
  113. package/src/runtime/node/email/transport.ts +112 -0
  114. package/src/runtime/node/entitlements/main.ts +41 -0
  115. package/src/runtime/node/entitlements/refusal.ts +15 -0
  116. package/src/runtime/node/index.ts +25 -0
  117. package/src/runtime/node/listen.ts +35 -0
  118. package/src/runtime/node/main.ts +29 -0
  119. package/src/runtime/node/migrate.ts +13 -0
  120. package/src/runtime/node/quota-reconcile.ts +9 -0
  121. package/src/runtime/node/relay.ts +54 -0
  122. package/src/runtime/node/server.ts +121 -0
  123. package/src/runtime/node/site.ts +64 -0
  124. package/src/runtime/postgres/database.ts +19 -0
  125. package/src/runtime/s3/objects.ts +244 -0
  126. package/src/runtime/site/server.ts +82 -0
  127. package/src/server/account/actions.ts +66 -0
  128. package/src/server/account/routes.ts +300 -0
  129. package/src/server/ai/errors.ts +7 -0
  130. package/src/server/ai/index.ts +4 -0
  131. package/src/server/ai/keys.ts +43 -0
  132. package/src/server/ai/routes.ts +43 -0
  133. package/src/server/ai/service.ts +70 -0
  134. package/src/server/api/index.ts +8 -0
  135. package/src/server/api/router.ts +117 -0
  136. package/src/server/api/types.ts +7 -0
  137. package/src/server/app.ts +375 -0
  138. package/src/server/auth/account.ts +73 -0
  139. package/src/server/auth/activity.ts +213 -0
  140. package/src/server/auth/adapter.ts +79 -0
  141. package/src/server/auth/email.ts +125 -0
  142. package/src/server/auth/endpoints.ts +57 -0
  143. package/src/server/auth/factory.ts +583 -0
  144. package/src/server/auth/index.ts +17 -0
  145. package/src/server/auth/mfa-assurance.ts +55 -0
  146. package/src/server/auth/runtime.ts +26 -0
  147. package/src/server/auth/session.ts +19 -0
  148. package/src/server/auth/social-providers.ts +55 -0
  149. package/src/server/auth/user-agent.ts +16 -0
  150. package/src/server/auth/workspace-access.ts +23 -0
  151. package/src/server/cleanup/configured.ts +38 -0
  152. package/src/server/cleanup/documents.ts +231 -0
  153. package/src/server/cleanup/index.ts +29 -0
  154. package/src/server/cleanup/objects.ts +27 -0
  155. package/src/server/cleanup/revisions.ts +232 -0
  156. package/src/server/cleanup/uploads.ts +129 -0
  157. package/src/server/cleanup/worker.ts +79 -0
  158. package/src/server/collaboration/index.ts +28 -0
  159. package/src/server/collaboration/relay/authorize.ts +53 -0
  160. package/src/server/collaboration/relay/awareness.ts +104 -0
  161. package/src/server/collaboration/relay/documents.ts +39 -0
  162. package/src/server/collaboration/relay/hub.ts +524 -0
  163. package/src/server/collaboration/relay/index.ts +15 -0
  164. package/src/server/collaboration/relay/persistence.ts +48 -0
  165. package/src/server/collaboration/routes.ts +77 -0
  166. package/src/server/collaboration/service.ts +188 -0
  167. package/src/server/config/deployment.ts +178 -0
  168. package/src/server/config/index.ts +20 -0
  169. package/src/server/config/limits.ts +8 -0
  170. package/src/server/config/public.ts +66 -0
  171. package/src/server/config/schema.ts +512 -0
  172. package/src/server/db/database.ts +15 -0
  173. package/src/server/db/expressions.ts +13 -0
  174. package/src/server/db/index.ts +21 -0
  175. package/src/server/db/migrate.ts +177 -0
  176. package/src/server/db/migrations/001_foundation.ts +164 -0
  177. package/src/server/db/migrations/002_upload_cleanup_claims.ts +34 -0
  178. package/src/server/db/migrations/003_document_cleanup_claims.ts +23 -0
  179. package/src/server/db/migrations/004_document_sharing.ts +82 -0
  180. package/src/server/db/migrations/005_document_collaboration_epoch.ts +13 -0
  181. package/src/server/db/migrations/006_invitation_continuation.ts +27 -0
  182. package/src/server/db/migrations/007_collaboration_state.ts +25 -0
  183. package/src/server/db/migrations/008_storage_reservations.ts +37 -0
  184. package/src/server/db/migrations/009_workspace_entitlements.ts +22 -0
  185. package/src/server/db/migrations/010_upload_finalization.ts +22 -0
  186. package/src/server/db/migrations/011_upload_finalization_lease.ts +12 -0
  187. package/src/server/db/migrations/012_transactional_email.ts +48 -0
  188. package/src/server/db/migrations/013_admin_enrollment.ts +54 -0
  189. package/src/server/db/migrations/014_enrollment_email_kinds.ts +30 -0
  190. package/src/server/db/migrations/015_cloud_rate_limit.ts +22 -0
  191. package/src/server/db/migrations/016_auth_schema.ts +16 -0
  192. package/src/server/db/migrations/017_authentication_email_kinds.ts +32 -0
  193. package/src/server/db/migrations/018_authentication_mfa.ts +78 -0
  194. package/src/server/db/migrations/019_better_auth_account_issuer.ts +42 -0
  195. package/src/server/db/migrations/020_workspace_invitations.ts +57 -0
  196. package/src/server/db/migrations/021_document_versions.ts +66 -0
  197. package/src/server/db/migrations/022_entitlement_external_version.ts +17 -0
  198. package/src/server/db/migrations/023_document_images.ts +61 -0
  199. package/src/server/db/migrations/024_account_activity.ts +66 -0
  200. package/src/server/db/migrations/025_table_names.ts +58 -0
  201. package/src/server/db/migrations/026_user_picture.ts +30 -0
  202. package/src/server/db/migrations/027_document_kind.ts +19 -0
  203. package/src/server/db/migrations/helpers.ts +78 -0
  204. package/src/server/db/tables.ts +394 -0
  205. package/src/server/documents/access.ts +103 -0
  206. package/src/server/documents/errors.ts +16 -0
  207. package/src/server/documents/images.ts +407 -0
  208. package/src/server/documents/index.ts +14 -0
  209. package/src/server/documents/limits.ts +57 -0
  210. package/src/server/documents/repository.ts +141 -0
  211. package/src/server/documents/routes.ts +239 -0
  212. package/src/server/documents/service.ts +597 -0
  213. package/src/server/documents/summary.ts +37 -0
  214. package/src/server/documents/types.ts +14 -0
  215. package/src/server/documents/versions/checkpoint.ts +98 -0
  216. package/src/server/documents/versions/history.ts +25 -0
  217. package/src/server/documents/versions/index.ts +4 -0
  218. package/src/server/documents/versions/routes.ts +112 -0
  219. package/src/server/documents/versions/service.ts +397 -0
  220. package/src/server/email/crypto.ts +57 -0
  221. package/src/server/email/index.ts +18 -0
  222. package/src/server/email/invitations.ts +30 -0
  223. package/src/server/email/service.ts +245 -0
  224. package/src/server/email/types.ts +56 -0
  225. package/src/server/email/worker.ts +33 -0
  226. package/src/server/index.ts +279 -0
  227. package/src/server/internal/index.ts +8 -0
  228. package/src/server/internal/routes.ts +41 -0
  229. package/src/server/internal/schema.ts +10 -0
  230. package/src/server/internal/service.ts +44 -0
  231. package/src/server/invitations/index.ts +6 -0
  232. package/src/server/invitations/types.ts +30 -0
  233. package/src/server/objects/index.ts +16 -0
  234. package/src/server/objects/types.ts +81 -0
  235. package/src/server/pictures/index.ts +9 -0
  236. package/src/server/pictures/provider.ts +61 -0
  237. package/src/server/pictures/routes.ts +21 -0
  238. package/src/server/pictures/service.ts +235 -0
  239. package/src/server/policy/configured.ts +23 -0
  240. package/src/server/policy/database.ts +108 -0
  241. package/src/server/policy/entitlements.ts +29 -0
  242. package/src/server/policy/index.ts +17 -0
  243. package/src/server/policy/keys.ts +23 -0
  244. package/src/server/policy/policy.ts +117 -0
  245. package/src/server/policy/provider.ts +67 -0
  246. package/src/server/policy/schema.ts +69 -0
  247. package/src/server/policy/service.ts +85 -0
  248. package/src/server/policy/static.ts +62 -0
  249. package/src/server/quota/index.ts +7 -0
  250. package/src/server/quota/reconcile.ts +61 -0
  251. package/src/server/quota/storage.ts +165 -0
  252. package/src/server/rate-limit/cleanup.ts +16 -0
  253. package/src/server/rate-limit/index.ts +12 -0
  254. package/src/server/rate-limit/keys.ts +38 -0
  255. package/src/server/rate-limit/middleware.ts +137 -0
  256. package/src/server/rate-limit/postgres.ts +79 -0
  257. package/src/server/sharing/access.ts +29 -0
  258. package/src/server/sharing/actor.ts +12 -0
  259. package/src/server/sharing/capabilities/service.ts +262 -0
  260. package/src/server/sharing/continuation.ts +85 -0
  261. package/src/server/sharing/contracts.ts +80 -0
  262. package/src/server/sharing/crypto.ts +48 -0
  263. package/src/server/sharing/document-routes.ts +41 -0
  264. package/src/server/sharing/errors.ts +12 -0
  265. package/src/server/sharing/grants/service.ts +79 -0
  266. package/src/server/sharing/http.ts +41 -0
  267. package/src/server/sharing/index.ts +39 -0
  268. package/src/server/sharing/invitations/service.ts +315 -0
  269. package/src/server/sharing/policy.ts +44 -0
  270. package/src/server/sharing/routes.ts +251 -0
  271. package/src/server/sharing/service.ts +117 -0
  272. package/src/server/validation.ts +24 -0
  273. package/src/server/worker/interval.ts +23 -0
  274. package/src/server/worker/periodic.ts +42 -0
  275. package/src/server/workspaces/index.ts +16 -0
  276. package/src/server/workspaces/members.ts +502 -0
  277. package/src/server/workspaces/repository.ts +91 -0
  278. package/src/server/workspaces/routes.ts +198 -0
  279. package/src/server/workspaces/service.ts +84 -0
@@ -0,0 +1,41 @@
1
+ import { capabilityHashMatches, hashCapability } from '#cloud/server/sharing/crypto'
2
+ import { validatedJSON } from '#cloud/server/validation'
3
+ import { Hono } from 'hono'
4
+ import { bearerAuth } from 'hono/bearer-auth'
5
+ import * as v from 'valibot'
6
+
7
+ import { parseSetWorkspaceEntitlements, type InternalService } from './service'
8
+
9
+ const uuidSchema = v.pipe(v.string(), v.uuid())
10
+
11
+ /** The internal API on HTTP, for runtimes without a private transport to their services. */
12
+ export function createInternalRoutes(service: InternalService, serviceToken: string) {
13
+ const digest = hashCapability(serviceToken)
14
+ const unauthorized = { error: { code: 'unauthorized' as const } }
15
+ return new Hono()
16
+ .use(
17
+ '*',
18
+ bearerAuth({
19
+ verifyToken: (token) => capabilityHashMatches(digest, token),
20
+ noAuthenticationHeader: { message: unauthorized },
21
+ invalidAuthenticationHeader: { message: unauthorized },
22
+ invalidToken: { message: unauthorized }
23
+ })
24
+ )
25
+ .put(
26
+ '/workspaces/:workspaceId/entitlements',
27
+ validatedJSON(parseSetWorkspaceEntitlements),
28
+ async (context) => {
29
+ const workspaceId = context.req.param('workspaceId')
30
+ if (!v.is(uuidSchema, workspaceId)) {
31
+ return context.json({ error: { code: 'not_found' as const } }, 404)
32
+ }
33
+ const result = await service.setWorkspaceEntitlements(
34
+ workspaceId,
35
+ context.req.valid('json')
36
+ )
37
+ if (!result.found) return context.json({ error: { code: 'not_found' as const } }, 404)
38
+ return context.json({ applied: result.applied })
39
+ }
40
+ )
41
+ }
@@ -0,0 +1,10 @@
1
+ import { staticEntitlementsSchema } from '#cloud/server/policy/schema'
2
+ import * as v from 'valibot'
3
+
4
+ export const setWorkspaceEntitlementsSchema = v.object({
5
+ values: staticEntitlementsSchema,
6
+ /** Who decided these values, such as `billing`; stored as the row's source. */
7
+ source: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),
8
+ /** Increases with every decision the writer makes, such as a billing event's timestamp. */
9
+ externalVersion: v.pipe(v.number(), v.safeInteger(), v.minValue(0))
10
+ })
@@ -0,0 +1,44 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import { createWorkspaceEntitlementRepository } from '#cloud/server/policy'
3
+ import type { Kysely } from 'kysely'
4
+ import * as v from 'valibot'
5
+
6
+ import { setWorkspaceEntitlementsSchema } from './schema'
7
+
8
+ export type SetWorkspaceEntitlementsInput = v.InferInput<typeof setWorkspaceEntitlementsSchema>
9
+
10
+ export function parseSetWorkspaceEntitlements(input: unknown) {
11
+ return v.parse(setWorkspaceEntitlementsSchema, input)
12
+ }
13
+
14
+ /**
15
+ * What services beside Cloud, such as billing, may change. Runtimes expose it to them through
16
+ * their own transport: an authenticated HTTP route on Node, a service binding on Workers.
17
+ */
18
+ export function createInternalService(database: Kysely<CloudDatabase>) {
19
+ const entitlements = createWorkspaceEntitlementRepository(database)
20
+ return {
21
+ /** `found` is false for an unknown workspace; `applied` is false for an outdated version. */
22
+ async setWorkspaceEntitlements(
23
+ workspaceId: string,
24
+ input: SetWorkspaceEntitlementsInput
25
+ ): Promise<{ found: boolean; applied: boolean }> {
26
+ const { values, source, externalVersion } = parseSetWorkspaceEntitlements(input)
27
+ const workspace = await database
28
+ .selectFrom('workspace')
29
+ .select('id')
30
+ .where('id', '=', workspaceId)
31
+ .executeTakeFirst()
32
+ if (!workspace) return { found: false, applied: false }
33
+ const { applied } = await entitlements.setVersioned(
34
+ workspaceId,
35
+ values,
36
+ source,
37
+ externalVersion
38
+ )
39
+ return { found: true, applied }
40
+ }
41
+ }
42
+ }
43
+
44
+ export type InternalService = ReturnType<typeof createInternalService>
@@ -0,0 +1,6 @@
1
+ export {
2
+ noOpInvitationDelivery,
3
+ type DocumentInvitationMessage,
4
+ type InvitationDelivery,
5
+ type InvitationOutbox
6
+ } from './types'
@@ -0,0 +1,30 @@
1
+ import type { DocumentPermission } from '#cloud/contract'
2
+ import type { CloudDatabase } from '#cloud/server/db'
3
+ import type { Transaction } from 'kysely'
4
+
5
+ export type DocumentInvitationMessage = {
6
+ deliveryId: string
7
+ recipientEmail: string
8
+ inviterName: string
9
+ documentName: string
10
+ permission: DocumentPermission
11
+ expiresAt: string
12
+ acceptanceURL: string
13
+ }
14
+
15
+ export type InvitationDelivery = {
16
+ sendDocumentInvitation(message: DocumentInvitationMessage): Promise<void>
17
+ }
18
+
19
+ export type InvitationOutbox = {
20
+ enqueueDocumentInvitation(
21
+ message: DocumentInvitationMessage,
22
+ transaction?: Transaction<CloudDatabase>
23
+ ): Promise<string>
24
+ }
25
+
26
+ export const noOpInvitationDelivery: InvitationDelivery = {
27
+ async sendDocumentInvitation() {
28
+ return undefined
29
+ }
30
+ }
@@ -0,0 +1,16 @@
1
+ export type {
2
+ AbortObjectUploadInput,
3
+ CompletedObjectPart,
4
+ CompleteObjectUploadInput,
5
+ CreateObjectDownloadInput,
6
+ CreateObjectUploadInput,
7
+ ObjectDownload,
8
+ ObjectMultipartUpload,
9
+ ObjectSingleUpload,
10
+ ObjectStore,
11
+ ObjectStoreCapabilities,
12
+ ObjectStoreReadiness,
13
+ ObjectUpload,
14
+ ObjectUploadPart,
15
+ StoredObject
16
+ } from './types'
@@ -0,0 +1,81 @@
1
+ export type ObjectDownload = {
2
+ url: string
3
+ method: 'GET'
4
+ headers: Readonly<Record<string, string>>
5
+ expiresAt: string
6
+ }
7
+
8
+ export type ObjectStoreCapabilities = {
9
+ nativeSHA256: boolean
10
+ multipartUpload: boolean
11
+ conditionalWrites: boolean
12
+ }
13
+
14
+ export type ObjectStoreReadiness = {
15
+ ok: boolean
16
+ checksumVerification: 'native' | 'metadata'
17
+ }
18
+
19
+ export type ObjectUploadPart = {
20
+ partNumber: number
21
+ url: string
22
+ method: 'PUT'
23
+ headers: Readonly<Record<string, string>>
24
+ }
25
+
26
+ export type ObjectMultipartUpload = {
27
+ kind: 'multipart'
28
+ uploadId: string
29
+ partSize: number
30
+ parts: ObjectUploadPart[]
31
+ expiresAt: string
32
+ }
33
+
34
+ export type ObjectSingleUpload = {
35
+ kind: 'single'
36
+ url: string
37
+ method: 'PUT'
38
+ headers: Readonly<Record<string, string>>
39
+ expiresAt: string
40
+ }
41
+
42
+ export type ObjectUpload = ObjectSingleUpload | ObjectMultipartUpload
43
+
44
+ export type CompletedObjectPart = { partNumber: number; etag: string }
45
+
46
+ export type CreateObjectDownloadInput = {
47
+ key: string
48
+ expiresAt: Date
49
+ }
50
+
51
+ export type CreateObjectUploadInput = CreateObjectDownloadInput & {
52
+ byteSize: number
53
+ checksum: string
54
+ contentType: string
55
+ }
56
+
57
+ export type CompleteObjectUploadInput = {
58
+ key: string
59
+ uploadId: string
60
+ parts: CompletedObjectPart[]
61
+ }
62
+
63
+ export type AbortObjectUploadInput = Omit<CompleteObjectUploadInput, 'parts'>
64
+
65
+ export type StoredObject = {
66
+ byteSize: number
67
+ checksum: string
68
+ checksumVerification: 'native' | 'metadata'
69
+ contentType: string
70
+ }
71
+
72
+ export interface ObjectStore {
73
+ readonly capabilities: ObjectStoreCapabilities
74
+ checkReadiness(): Promise<ObjectStoreReadiness>
75
+ createDownload(input: CreateObjectDownloadInput): Promise<ObjectDownload>
76
+ createUpload(input: CreateObjectUploadInput): Promise<ObjectUpload>
77
+ completeUpload(input: CompleteObjectUploadInput): Promise<void>
78
+ abortUpload(input: AbortObjectUploadInput): Promise<void>
79
+ head(key: string): Promise<StoredObject | null>
80
+ delete(key: string): Promise<void>
81
+ }
@@ -0,0 +1,9 @@
1
+ export { providerPicture, providerPictures } from './provider'
2
+ export { createPictureRoutes } from './routes'
3
+ export {
4
+ createUserPictures,
5
+ PICTURE_PATH,
6
+ PictureInvalidError,
7
+ pictureFormat,
8
+ type UserPictureService
9
+ } from './service'
@@ -0,0 +1,61 @@
1
+ import type { BetterAuthPlugin } from 'better-auth'
2
+ import { decodeJwt } from 'jose'
3
+ import * as v from 'valibot'
4
+
5
+ import type { UserPictureService } from './service'
6
+
7
+ /** The providers whose ID token names the person's picture. */
8
+ const PICTURE_PROVIDERS = new Set(['google'])
9
+ const pictureClaimSchema = v.object({ picture: v.pipe(v.string(), v.url()) })
10
+
11
+ /**
12
+ * The picture a linked account's provider names in the ID token Better Auth keeps on its account
13
+ * row, or null. The token came to Better Auth from the provider during its sign-in flow, which no
14
+ * client can write to the row.
15
+ */
16
+ export function providerPicture(account: { providerId: string; idToken?: string | null }) {
17
+ if (!PICTURE_PROVIDERS.has(account.providerId) || !account.idToken) return null
18
+ try {
19
+ const claims = v.safeParse(pictureClaimSchema, decodeJwt(account.idToken))
20
+ return claims.success ? claims.output.picture : null
21
+ } catch {
22
+ return null
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Keeps the picture a Google account names, so pages show the server's copy and never load it
28
+ * from Google. Better Auth writes the account's ID token when it is linked and at each sign-in
29
+ * with it, so accounts made before the server kept pictures move over the next time they sign in
30
+ * this way. Better Auth also takes an `image` on sign-up and user updates; none of those reach the
31
+ * account, since the server writes the addresses of the pictures it keeps itself.
32
+ */
33
+ export function providerPictures(pictures: UserPictureService): BetterAuthPlugin {
34
+ const keep = async (account: { userId: string; providerId: string; idToken?: string | null }) => {
35
+ const picture = providerPicture(account)
36
+ if (picture) await pictures.copyFromProvider(account.userId, picture)
37
+ }
38
+ return {
39
+ id: 'openpencil-provider-pictures',
40
+ init: () => ({
41
+ options: {
42
+ databaseHooks: {
43
+ user: {
44
+ create: {
45
+ before: async (user) => ({ data: { ...user, image: null } })
46
+ },
47
+ update: {
48
+ // Better Auth merges what a hook returns into the update, so `image` is unset.
49
+ before: async (user) =>
50
+ user.image === undefined ? true : { data: { image: undefined } }
51
+ }
52
+ },
53
+ account: {
54
+ create: { after: keep },
55
+ update: { after: keep }
56
+ }
57
+ }
58
+ }
59
+ })
60
+ }
61
+ }
@@ -0,0 +1,21 @@
1
+ import { Hono } from 'hono'
2
+
3
+ import { PICTURE_PATH, type UserPictureService } from './service'
4
+
5
+ /**
6
+ * Account pictures, for anyone with a picture's address: pages show people to those they share
7
+ * documents and workspaces with, and the desktop app shows them from another origin.
8
+ */
9
+ export function createPictureRoutes(pictures: UserPictureService) {
10
+ return new Hono().get(`${PICTURE_PATH}/:userId/:version`, async (context) => {
11
+ const picture = await pictures.read(context.req.param('userId'), context.req.param('version'))
12
+ if (!picture) return context.json({ error: { code: 'not_found' as const } }, 404)
13
+ // The address changes with the picture, but a removed one must stop showing within a day.
14
+ context.header('Cache-Control', 'public, max-age=86400')
15
+ context.header('Content-Type', `image/${picture.format}`)
16
+ context.header('X-Content-Type-Options', 'nosniff')
17
+ context.header('Content-Security-Policy', "default-src 'none'; sandbox")
18
+ context.header('Cross-Origin-Resource-Policy', 'cross-origin')
19
+ return context.body(new Uint8Array(picture.bytes))
20
+ })
21
+ }
@@ -0,0 +1,235 @@
1
+ import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'
2
+ import type { CloudDatabase, UserPictureFormat } from '#cloud/server/db'
3
+ import { sha256 } from '@noble/hashes/sha2.js'
4
+ import { bytesToHex } from '@noble/hashes/utils.js'
5
+ import { imageSize } from 'image-size'
6
+ import type { Kysely } from 'kysely'
7
+ import * as v from 'valibot'
8
+
9
+ /** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */
10
+ export const PICTURE_PATH = '/api/pictures'
11
+ /** The longest side a stored picture may have; pages send 256 pixels. */
12
+ const PICTURE_MAX_SIDE = 1024
13
+ /** How many hex digits of the checksum name a picture in its address. */
14
+ const PICTURE_VERSION_LENGTH = 16
15
+ /** How long a linked account's picture may take to fetch before sign-in goes on without it. */
16
+ const PROVIDER_PICTURE_TIMEOUT_MS = 5000
17
+ /** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */
18
+ const PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']
19
+ const PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }
20
+ const userIdSchema = v.pipe(v.string(), v.uuid())
21
+
22
+ /** The bytes are not a PNG or JPEG picture the server keeps. */
23
+ export class PictureInvalidError extends Error {
24
+ constructor() {
25
+ super('The picture must be a PNG or JPEG image of at most 1024 by 1024 pixels')
26
+ this.name = 'PictureInvalidError'
27
+ }
28
+ }
29
+
30
+ /** The format of a picture the server keeps, read from its bytes; anything else is null. */
31
+ export function pictureFormat(bytes: Uint8Array): UserPictureFormat | null {
32
+ if (bytes.byteLength === 0 || bytes.byteLength > CLOUD_PICTURE_MAX_BYTES) return null
33
+ try {
34
+ const size = imageSize(bytes)
35
+ const format = size.type ? PICTURE_FORMATS[size.type] : undefined
36
+ if (!format || size.width < 1 || size.height < 1) return null
37
+ if (size.width > PICTURE_MAX_SIDE || size.height > PICTURE_MAX_SIDE) return null
38
+ return format
39
+ } catch {
40
+ return null
41
+ }
42
+ }
43
+
44
+ /** Whether `url` is an HTTPS address on a host a linked account's picture comes from. */
45
+ function providerPicture(url: URL): boolean {
46
+ return (
47
+ url.protocol === 'https:' &&
48
+ PROVIDER_PICTURE_HOSTS.some(
49
+ (host) => url.hostname === host || url.hostname.endsWith(`.${host}`)
50
+ )
51
+ )
52
+ }
53
+
54
+ /** Reads at most `limit` bytes of a response body, or null when it holds more. */
55
+ async function boundedBody(response: Response, limit: number): Promise<Uint8Array | null> {
56
+ if (!response.body) return null
57
+ const reader = response.body.getReader()
58
+ const chunks: Uint8Array[] = []
59
+ let length = 0
60
+ for (;;) {
61
+ const { done, value } = await reader.read()
62
+ if (done) break
63
+ length += value.byteLength
64
+ if (length > limit) {
65
+ await reader.cancel()
66
+ return null
67
+ }
68
+ chunks.push(value)
69
+ }
70
+ const bytes = new Uint8Array(length)
71
+ let offset = 0
72
+ for (const chunk of chunks) {
73
+ bytes.set(chunk, offset)
74
+ offset += chunk.byteLength
75
+ }
76
+ return bytes
77
+ }
78
+
79
+ type AccountPicture = { image: string | null; updatedAt: Date }
80
+
81
+ function samePicture(current: AccountPicture | undefined, seen: AccountPicture | undefined) {
82
+ return (
83
+ current?.image === seen?.image && current?.updatedAt.getTime() === seen?.updatedAt.getTime()
84
+ )
85
+ }
86
+
87
+ export type UserPictureOptions = {
88
+ publicURL: string
89
+ /** Fetches a linked account's picture; tests pass their own. */
90
+ fetch?: (url: string, init: RequestInit) => Promise<Response>
91
+ }
92
+
93
+ /**
94
+ * The picture each account shows. The server keeps the bytes and serves them itself, so a page
95
+ * that shows a person never asks another service for them; `user.image` holds their address.
96
+ */
97
+ export function createUserPictures(database: Kysely<CloudDatabase>, options: UserPictureOptions) {
98
+ const fetchPicture = options.fetch ?? ((url, init) => fetch(url, init))
99
+ const origin = new URL(options.publicURL).origin
100
+
101
+ function address(userId: string, checksum: string): string {
102
+ return `${origin}${PICTURE_PATH}/${userId}/${checksum.slice(0, PICTURE_VERSION_LENGTH)}`
103
+ }
104
+
105
+ /** The address `bytes` are served from as the account's picture. */
106
+ function pictureAddress(userId: string, bytes: Uint8Array): string {
107
+ return address(userId, bytesToHex(sha256(bytes)))
108
+ }
109
+
110
+ /** Whether `image` is a picture this server serves, rather than another service's. */
111
+ function served(image: string): boolean {
112
+ return image.startsWith(`${origin}${PICTURE_PATH}/`)
113
+ }
114
+
115
+ /**
116
+ * Keeps `bytes` as the account's picture. A provider's picture is kept only while the account is
117
+ * unchanged since `seen`, read before the picture was fetched: every upload and removal moves
118
+ * `updatedAt`, so one made meanwhile stands, even one that left the image as it was. Returns
119
+ * whether the picture was kept.
120
+ */
121
+ async function save(
122
+ userId: string,
123
+ bytes: Uint8Array,
124
+ source: { from: 'upload' } | { from: 'provider'; seen: AccountPicture | undefined }
125
+ ): Promise<boolean> {
126
+ const format = pictureFormat(bytes)
127
+ if (!format) throw new PictureInvalidError()
128
+ const checksum = bytesToHex(sha256(bytes))
129
+ const image = pictureAddress(userId, bytes)
130
+ const createdAt = new Date()
131
+ return database.transaction().execute(async (transaction) => {
132
+ // Saves and removals lock the account first, so they take turns.
133
+ const current = await transaction
134
+ .selectFrom('user')
135
+ .select(['image', 'updatedAt'])
136
+ .where('id', '=', userId)
137
+ .forUpdate()
138
+ .executeTakeFirst()
139
+ if (source.from === 'provider' && !samePicture(current, source.seen)) return false
140
+ await transaction
141
+ .insertInto('userPicture')
142
+ .values({ userId, bytes, format, checksum, source: source.from, createdAt })
143
+ .onConflict((conflict) =>
144
+ conflict
145
+ .column('userId')
146
+ .doUpdateSet({ bytes, format, checksum, source: source.from, createdAt })
147
+ )
148
+ .execute()
149
+ await transaction
150
+ .updateTable('user')
151
+ .set({ image, updatedAt: createdAt })
152
+ .where('id', '=', userId)
153
+ .execute()
154
+ return true
155
+ })
156
+ }
157
+
158
+ async function remove(userId: string): Promise<void> {
159
+ await database.transaction().execute(async (transaction) => {
160
+ // The account first, in the same order saves lock, so the two never wait on each other.
161
+ await transaction
162
+ .selectFrom('user')
163
+ .select('id')
164
+ .where('id', '=', userId)
165
+ .forUpdate()
166
+ .execute()
167
+ await transaction.deleteFrom('userPicture').where('userId', '=', userId).execute()
168
+ await transaction
169
+ .updateTable('user')
170
+ .set({ image: null, updatedAt: new Date() })
171
+ .where('id', '=', userId)
172
+ .execute()
173
+ })
174
+ }
175
+
176
+ return {
177
+ served,
178
+
179
+ /** Keeps a picture the account's owner uploaded and shows it from now on. */
180
+ async upload(userId: string, bytes: Uint8Array): Promise<string> {
181
+ await save(userId, bytes, { from: 'upload' })
182
+ return pictureAddress(userId, bytes)
183
+ },
184
+
185
+ /** Goes back to initials. */
186
+ remove,
187
+
188
+ /** The picture at `/api/pictures/:userId/:version`, or null for any other address. */
189
+ async read(userId: string, version: string) {
190
+ if (!v.is(userIdSchema, userId) || version.length !== PICTURE_VERSION_LENGTH) return null
191
+ const picture = await database
192
+ .selectFrom('userPicture')
193
+ .select(['bytes', 'format', 'checksum'])
194
+ .where('userId', '=', userId)
195
+ .executeTakeFirst()
196
+ return picture?.checksum.startsWith(version) ? picture : null
197
+ },
198
+
199
+ /**
200
+ * Keeps the picture a linked account named in `image` and shows it instead, so pages never
201
+ * load it from that service. A picture that cannot be fetched or is not one the server keeps
202
+ * leaves initials in its place. An uploaded picture stays.
203
+ */
204
+ async copyFromProvider(userId: string, image: string): Promise<void> {
205
+ if (served(image)) return
206
+ // A picture the account already shows from this server, uploaded or kept before, stays.
207
+ const current = await database
208
+ .selectFrom('user')
209
+ .select(['image', 'updatedAt'])
210
+ .where('id', '=', userId)
211
+ .executeTakeFirst()
212
+ if (current?.image && served(current.image)) return
213
+ try {
214
+ if (!providerPicture(new URL(image))) throw new PictureInvalidError()
215
+ const response = await fetchPicture(image, {
216
+ redirect: 'error',
217
+ signal: AbortSignal.timeout(PROVIDER_PICTURE_TIMEOUT_MS)
218
+ })
219
+ const bytes = response.ok ? await boundedBody(response, CLOUD_PICTURE_MAX_BYTES) : null
220
+ if (!bytes) throw new PictureInvalidError()
221
+ await save(userId, bytes, { from: 'provider', seen: current })
222
+ } catch (error) {
223
+ console.warn('Keeping a linked account picture failed', error)
224
+ await database
225
+ .updateTable('user')
226
+ .set({ image: null, updatedAt: new Date() })
227
+ .where('id', '=', userId)
228
+ .where('image', '=', image)
229
+ .execute()
230
+ }
231
+ }
232
+ }
233
+ }
234
+
235
+ export type UserPictureService = ReturnType<typeof createUserPictures>
@@ -0,0 +1,23 @@
1
+ import type { CloudServerConfig } from '#cloud/server/config'
2
+ import type { CloudDatabase } from '#cloud/server/db'
3
+ import type { Kysely } from 'kysely'
4
+
5
+ import { DatabaseEntitlementSource } from './database'
6
+ import { StaticEntitlementSource } from './entitlements'
7
+ import { createDefaultCloudPolicy } from './policy'
8
+ import { EntitlementOpenFeatureProvider } from './provider'
9
+ import { staticEntitlementValues } from './static'
10
+
11
+ /** The policy a deployment configures: its static entitlements, or the database's. */
12
+ export function createConfiguredCloudPolicy(
13
+ config: Pick<CloudServerConfig, 'staticEntitlements'>,
14
+ database: Kysely<CloudDatabase>
15
+ ) {
16
+ return createDefaultCloudPolicy(
17
+ new EntitlementOpenFeatureProvider(
18
+ config.staticEntitlements
19
+ ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
20
+ : new DatabaseEntitlementSource(database)
21
+ )
22
+ )
23
+ }