@open-pencil/cloud 0.17.0-beta.1 → 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 (235) 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 +468 -64
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/listen.mjs +575 -738
  19. package/dist/listen.mjs.map +1 -1
  20. package/dist/runtime-node.d.mts +6564 -2934
  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 +8931 -4198
  25. package/dist/server.d.ts.map +1 -1
  26. package/dist/server.js +5260 -3859
  27. package/dist/server.js.map +1 -1
  28. package/dist/server.mjs +5686 -3736
  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 +9 -6
  33. package/src/admin/api/routes.ts +103 -33
  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 +31 -6
  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 +176 -0
  66. package/src/runtime/cloudflare/relay/sockets.ts +112 -0
  67. package/src/runtime/cloudflare/worker.ts +89 -26
  68. package/src/runtime/node/application.ts +5 -3
  69. package/src/runtime/node/bootstrap.ts +20 -4
  70. package/src/runtime/node/cleanup.ts +16 -3
  71. package/src/runtime/node/entitlements/main.ts +14 -11
  72. package/src/runtime/node/index.ts +1 -1
  73. package/src/runtime/node/migrate.ts +5 -1
  74. package/src/runtime/node/relay.ts +8 -2
  75. package/src/runtime/node/request-id.ts +13 -0
  76. package/src/runtime/node/server.ts +71 -15
  77. package/src/runtime/node/{ai-relay → services}/main.ts +6 -6
  78. package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
  79. package/src/runtime/postgres/database.ts +20 -1
  80. package/src/runtime/posthog/errors.ts +32 -0
  81. package/src/runtime/s3/objects.ts +50 -1
  82. package/src/runtime/site/server.ts +33 -4
  83. package/src/server/account/actions.ts +5 -0
  84. package/src/server/account/deletion.ts +302 -0
  85. package/src/server/account/routes.ts +47 -3
  86. package/src/server/account/terms.ts +42 -0
  87. package/src/server/api/router.ts +12 -7
  88. package/src/server/api/types.ts +9 -0
  89. package/src/server/app.ts +93 -15
  90. package/src/server/auth/access-control.ts +63 -0
  91. package/src/server/auth/adapter.ts +11 -0
  92. package/src/server/auth/endpoints.ts +5 -1
  93. package/src/server/auth/factory.ts +30 -3
  94. package/src/server/auth/index.ts +10 -1
  95. package/src/server/cleanup/configured.ts +12 -5
  96. package/src/server/cleanup/documents.ts +165 -71
  97. package/src/server/cleanup/objects.ts +10 -2
  98. package/src/server/cleanup/revisions.ts +24 -7
  99. package/src/server/cleanup/uploads.ts +8 -2
  100. package/src/server/cleanup/worker.ts +5 -2
  101. package/src/server/collaboration/index.ts +3 -0
  102. package/src/server/collaboration/relay/connection.ts +196 -0
  103. package/src/server/collaboration/relay/documents.ts +13 -10
  104. package/src/server/collaboration/relay/hub.ts +279 -195
  105. package/src/server/collaboration/relay/index.ts +3 -1
  106. package/src/server/collaboration/relay/log.ts +79 -0
  107. package/src/server/collaboration/relay/persistence.ts +147 -22
  108. package/src/server/collaboration/relay/resume.ts +28 -0
  109. package/src/server/collaboration/routes.ts +27 -16
  110. package/src/server/collaboration/service.ts +27 -31
  111. package/src/server/config/deployment.ts +35 -4
  112. package/src/server/config/public.ts +5 -4
  113. package/src/server/config/schema.ts +104 -16
  114. package/src/server/db/expressions.ts +15 -1
  115. package/src/server/db/migrate.ts +34 -114
  116. package/src/server/db/migrations/001_accounts.ts +79 -0
  117. package/src/server/db/migrations/002_workspaces.ts +48 -0
  118. package/src/server/db/migrations/003_storage.ts +44 -0
  119. package/src/server/db/migrations/004_documents.ts +193 -0
  120. package/src/server/db/migrations/005_sharing.ts +95 -0
  121. package/src/server/db/migrations/006_operations.ts +110 -0
  122. package/src/server/db/migrations/007_trash.ts +33 -0
  123. package/src/server/db/migrations/008_terms.ts +18 -0
  124. package/src/server/db/migrations/schema.ts +71 -0
  125. package/src/server/db/tables.ts +70 -7
  126. package/src/server/documents/access.ts +66 -55
  127. package/src/server/documents/errors.ts +7 -0
  128. package/src/server/documents/images.ts +2 -1
  129. package/src/server/documents/limits.ts +9 -9
  130. package/src/server/documents/purge.ts +75 -0
  131. package/src/server/documents/repository.ts +2 -0
  132. package/src/server/documents/routes.ts +132 -80
  133. package/src/server/documents/service.ts +18 -4
  134. package/src/server/documents/summary.ts +1 -0
  135. package/src/server/documents/trash.ts +203 -0
  136. package/src/server/documents/versions/checkpoint.ts +2 -1
  137. package/src/server/documents/versions/history.ts +11 -7
  138. package/src/server/documents/versions/routes.ts +36 -25
  139. package/src/server/documents/versions/service.ts +22 -4
  140. package/src/server/errors/index.ts +99 -0
  141. package/src/server/errors/posthog.ts +80 -0
  142. package/src/server/index.ts +56 -16
  143. package/src/server/internal/index.ts +3 -3
  144. package/src/server/internal/routes.ts +7 -15
  145. package/src/server/internal/schema.ts +1 -1
  146. package/src/server/internal/service.ts +17 -23
  147. package/src/server/invitations/budget.ts +66 -0
  148. package/src/server/invitations/index.ts +1 -0
  149. package/src/server/logging.ts +76 -0
  150. package/src/server/objects/types.ts +12 -0
  151. package/src/server/pictures/routes.ts +4 -2
  152. package/src/server/pictures/service.ts +2 -1
  153. package/src/server/policy/database.ts +39 -25
  154. package/src/server/policy/index.ts +2 -1
  155. package/src/server/policy/keys.ts +5 -2
  156. package/src/server/policy/policy.ts +1 -0
  157. package/src/server/policy/schema.ts +2 -2
  158. package/src/server/policy/service.ts +12 -9
  159. package/src/server/policy/static.ts +5 -5
  160. package/src/server/policy/workspace.ts +41 -0
  161. package/src/server/quota/reconcile.ts +2 -0
  162. package/src/server/quota/storage.ts +69 -31
  163. package/src/server/rate-limit/cleanup.ts +17 -5
  164. package/src/server/rate-limit/index.ts +4 -1
  165. package/src/server/rate-limit/middleware.ts +100 -12
  166. package/src/server/reports/index.ts +8 -0
  167. package/src/server/reports/routes.ts +37 -0
  168. package/src/server/reports/service.ts +123 -0
  169. package/src/server/services/errors.ts +7 -0
  170. package/src/server/services/index.ts +8 -0
  171. package/src/server/{ai → services}/keys.ts +11 -11
  172. package/src/server/services/routes.ts +47 -0
  173. package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
  174. package/src/server/sharing/capabilities/service.ts +68 -22
  175. package/src/server/sharing/document-routes.ts +30 -22
  176. package/src/server/sharing/grants/service.ts +11 -18
  177. package/src/server/sharing/http.ts +4 -0
  178. package/src/server/sharing/invitations/service.ts +21 -11
  179. package/src/server/sharing/policy.ts +9 -14
  180. package/src/server/sharing/routes.ts +108 -85
  181. package/src/server/sharing/service.ts +1 -17
  182. package/src/server/validation.ts +59 -2
  183. package/src/server/workspaces/index.ts +1 -0
  184. package/src/server/workspaces/members.ts +89 -38
  185. package/src/server/workspaces/repository.ts +2 -1
  186. package/src/server/workspaces/routes.ts +67 -45
  187. package/src/{ai-relay → services}/app.ts +48 -44
  188. package/src/{ai-relay → services}/config.ts +25 -19
  189. package/src/services/db/index.ts +10 -0
  190. package/src/services/db/migrate.ts +37 -0
  191. package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
  192. package/src/services/db/schema.ts +22 -0
  193. package/src/services/index.ts +18 -0
  194. package/src/{ai-relay → services}/metering.ts +2 -2
  195. package/src/{ai-relay → services}/usage.ts +43 -19
  196. package/dist/bin/ai-relay.mjs.map +0 -1
  197. package/src/ai-relay/db/index.ts +0 -10
  198. package/src/ai-relay/db/migrate.ts +0 -32
  199. package/src/ai-relay/db/schema.ts +0 -20
  200. package/src/ai-relay/index.ts +0 -18
  201. package/src/contract/ai.ts +0 -150
  202. package/src/runtime/cloudflare/relay.ts +0 -136
  203. package/src/server/ai/errors.ts +0 -7
  204. package/src/server/ai/index.ts +0 -4
  205. package/src/server/ai/routes.ts +0 -43
  206. package/src/server/auth/workspace-access.ts +0 -23
  207. package/src/server/db/migrations/001_foundation.ts +0 -164
  208. package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
  209. package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
  210. package/src/server/db/migrations/004_document_sharing.ts +0 -82
  211. package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
  212. package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
  213. package/src/server/db/migrations/007_collaboration_state.ts +0 -25
  214. package/src/server/db/migrations/008_storage_reservations.ts +0 -37
  215. package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
  216. package/src/server/db/migrations/010_upload_finalization.ts +0 -22
  217. package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
  218. package/src/server/db/migrations/012_transactional_email.ts +0 -48
  219. package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
  220. package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
  221. package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
  222. package/src/server/db/migrations/016_auth_schema.ts +0 -16
  223. package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
  224. package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
  225. package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
  226. package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
  227. package/src/server/db/migrations/021_document_versions.ts +0 -66
  228. package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
  229. package/src/server/db/migrations/023_document_images.ts +0 -61
  230. package/src/server/db/migrations/024_account_activity.ts +0 -66
  231. package/src/server/db/migrations/025_table_names.ts +0 -58
  232. package/src/server/db/migrations/026_user_picture.ts +0 -30
  233. package/src/server/db/migrations/027_document_kind.ts +0 -19
  234. package/src/server/db/migrations/helpers.ts +0 -78
  235. /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
@@ -0,0 +1,123 @@
1
+ import type { FileDocumentReportInput } from '#cloud/contract'
2
+ import type { CloudActor } from '#cloud/server/auth'
3
+ import type { CloudDatabase } from '#cloud/server/db'
4
+ import type { TransactionalEmailService } from '#cloud/server/email'
5
+ import type { DocumentSharingService } from '#cloud/server/sharing'
6
+ import type { Kysely } from 'kysely'
7
+
8
+ /**
9
+ * How many reports one person, or guest, may file about one link in a day, and how many a link
10
+ * may gather from everyone, since a guest names themselves and could otherwise flood the queue.
11
+ */
12
+ export const DOCUMENT_REPORT_BUDGET = {
13
+ windowMs: 24 * 60 * 60 * 1000,
14
+ perReporter: 3,
15
+ perShare: 50
16
+ } as const
17
+
18
+ /** How much of a description an administrator's email quotes; the console shows all of it. */
19
+ const EMAIL_DESCRIPTION_CHARACTERS = 500
20
+
21
+ /** A report past the reporter's or the link's daily budget. */
22
+ export class DocumentReportLimitError extends Error {
23
+ override readonly name = 'DocumentReportLimitError'
24
+ }
25
+
26
+ export type DocumentReportServiceOptions = {
27
+ sharing: Pick<DocumentSharingService, 'resolveShare'>
28
+ email?: TransactionalEmailService
29
+ /** Who hears of a new report: the deployment's administrators. */
30
+ adminRecipients: readonly string[]
31
+ publicURL: string
32
+ }
33
+
34
+ export function createDocumentReportService(
35
+ database: Kysely<CloudDatabase>,
36
+ options: DocumentReportServiceOptions
37
+ ) {
38
+ return {
39
+ /**
40
+ * Files a report about the document a share link opens, for someone the link lets in, and
41
+ * tells the deployment's administrators. It answers nothing about the document, so a report
42
+ * never tells its reporter more than the link already did.
43
+ */
44
+ async file(shareId: string, input: FileDocumentReportInput, actor?: CloudActor): Promise<void> {
45
+ const resolved = await options.sharing.resolveShare(
46
+ shareId,
47
+ { secret: input.secret, guestId: input.guestId },
48
+ actor
49
+ )
50
+ const reporterUserId = actor?.userId ?? null
51
+ const reporterGuestId = actor ? null : (input.guestId ?? null)
52
+ const since = new Date(Date.now() - DOCUMENT_REPORT_BUDGET.windowMs)
53
+ await database.transaction().execute(async (transaction) => {
54
+ const [byReporter, byShare] = await Promise.all([
55
+ transaction
56
+ .selectFrom('documentReport')
57
+ .select((expression) => expression.fn.countAll<string>().as('count'))
58
+ .where('shareId', '=', shareId)
59
+ .where('createdAt', '>', since)
60
+ .where((expression) => {
61
+ if (reporterUserId) return expression('reporterUserId', '=', reporterUserId)
62
+ if (reporterGuestId) return expression('reporterGuestId', '=', reporterGuestId)
63
+ return expression.and([
64
+ expression('reporterUserId', 'is', null),
65
+ expression('reporterGuestId', 'is', null)
66
+ ])
67
+ })
68
+ .executeTakeFirstOrThrow(),
69
+ transaction
70
+ .selectFrom('documentReport')
71
+ .select((expression) => expression.fn.countAll<string>().as('count'))
72
+ .where('shareId', '=', shareId)
73
+ .where('createdAt', '>', since)
74
+ .executeTakeFirstOrThrow()
75
+ ])
76
+ if (
77
+ Number(byReporter.count) >= DOCUMENT_REPORT_BUDGET.perReporter ||
78
+ Number(byShare.count) >= DOCUMENT_REPORT_BUDGET.perShare
79
+ ) {
80
+ throw new DocumentReportLimitError()
81
+ }
82
+ const id = crypto.randomUUID()
83
+ await transaction
84
+ .insertInto('documentReport')
85
+ .values({
86
+ id,
87
+ documentId: resolved.documentId,
88
+ shareId,
89
+ reporterUserId,
90
+ reporterGuestId,
91
+ replyEmail: input.replyEmail ?? actor?.email ?? null,
92
+ reason: input.reason,
93
+ description: input.description
94
+ })
95
+ .execute()
96
+ if (!options.email) return
97
+ const document = await transaction
98
+ .selectFrom('document')
99
+ .select('name')
100
+ .where('id', '=', resolved.documentId)
101
+ .executeTakeFirstOrThrow()
102
+ for (const recipientEmail of options.adminRecipients) {
103
+ await options.email.enqueue(
104
+ {
105
+ idempotencyKey: `document-report/${id}/${recipientEmail}`,
106
+ kind: 'document-report',
107
+ recipientEmail,
108
+ payload: {
109
+ documentName: document.name,
110
+ reason: input.reason,
111
+ description: input.description.slice(0, EMAIL_DESCRIPTION_CHARACTERS),
112
+ actionURL: new URL('/admin/reports', options.publicURL).href
113
+ }
114
+ },
115
+ transaction
116
+ )
117
+ }
118
+ })
119
+ }
120
+ }
121
+ }
122
+
123
+ export type DocumentReportService = ReturnType<typeof createDocumentReportService>
@@ -0,0 +1,7 @@
1
+ /** The workspace's plan does not include services. */
2
+ export class ServicesNotEntitledError extends Error {
3
+ constructor() {
4
+ super('The workspace is not entitled to services')
5
+ this.name = 'ServicesNotEntitledError'
6
+ }
7
+ }
@@ -0,0 +1,8 @@
1
+ export { ServicesNotEntitledError } from './errors'
2
+ export { importServicesSigningKey, loadServicesSigningKey, type ServicesSigningKey } from './keys'
3
+ export { createServicesRoutes, type ServicesRouteEnvironment } from './routes'
4
+ export {
5
+ createServicesTokenService,
6
+ type ServicesTokenService,
7
+ type ServicesTokenServiceOptions
8
+ } from './tokens'
@@ -3,18 +3,18 @@ import { calculateJwkThumbprint, exportJWK, importPKCS8, type JWK } from 'jose'
3
3
 
4
4
  const ALGORITHM = 'ES256'
5
5
 
6
- export type AISigningKey = {
6
+ export type ServicesSigningKey = {
7
7
  privateKey: CryptoKey
8
8
  /** The public half, as published in the JWKS. */
9
9
  publicJWK: JWK & { kid: string }
10
10
  }
11
11
 
12
12
  /**
13
- * Imports the P-256 key that signs AI service tokens. Its `kid` is the public key's thumbprint,
13
+ * Imports the P-256 key that signs service tokens. Its `kid` is the public key's thumbprint,
14
14
  * so replacing the key changes the `kid`, and a service that caches the JWKS refetches it on the
15
15
  * first token it cannot match. Tokens the old key signed fail once and are re-requested.
16
16
  */
17
- export async function importAISigningKey(pem: string): Promise<AISigningKey> {
17
+ export async function importServicesSigningKey(pem: string): Promise<ServicesSigningKey> {
18
18
  const privateKey = await importPKCS8(pem, ALGORITHM, { extractable: true })
19
19
  const { kty, crv, x, y } = await exportJWK(privateKey)
20
20
  const publicJWK = { kty, crv, x, y }
@@ -27,17 +27,17 @@ export async function importAISigningKey(pem: string): Promise<AISigningKey> {
27
27
 
28
28
  /**
29
29
  * Imports the configured signing key at startup, so a key that cannot sign stops the runtime
30
- * instead of failing every token request after discovery has advertised the AI service.
30
+ * instead of failing every token request after discovery has advertised services.
31
31
  */
32
- export async function loadAISigningKey(
33
- config: Pick<CloudServerConfig, 'aiSigningKey'>
34
- ): Promise<AISigningKey | undefined> {
35
- if (!config.aiSigningKey) return undefined
32
+ export async function loadServicesSigningKey(
33
+ config: Pick<CloudServerConfig, 'servicesSigningKey'>
34
+ ): Promise<ServicesSigningKey | undefined> {
35
+ if (!config.servicesSigningKey) return undefined
36
36
  try {
37
- return await importAISigningKey(config.aiSigningKey)
37
+ return await importServicesSigningKey(config.servicesSigningKey)
38
38
  } catch {
39
- throw new CloudConfigError('AI signing key must be a PKCS #8 P-256 private key')
39
+ throw new CloudConfigError('Services signing key must be a PKCS #8 P-256 private key')
40
40
  }
41
41
  }
42
42
 
43
- export const AI_SIGNING_ALGORITHM = ALGORITHM
43
+ export const SERVICES_SIGNING_ALGORITHM = ALGORITHM
@@ -0,0 +1,47 @@
1
+ import { parseCreateServicesToken } from '#cloud/contract'
2
+ import type { CloudActor } from '#cloud/server/auth'
3
+ import type { CloudDatabase } from '#cloud/server/db'
4
+ import { DocumentNotFoundError } from '#cloud/server/documents'
5
+ import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
6
+ import { validatedJSON } from '#cloud/server/validation'
7
+ import { Hono } from 'hono'
8
+ import type { Kysely } from 'kysely'
9
+
10
+ import { ServicesNotEntitledError } from './errors'
11
+ import type { ServicesTokenService } from './tokens'
12
+
13
+ export type ServicesRouteEnvironment = { Variables: { actor: CloudActor } }
14
+
15
+ /** Without a service, the deployment offers no services and the token route is not found. */
16
+ export function createServicesRoutes(
17
+ service: ServicesTokenService | undefined,
18
+ rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
19
+ ) {
20
+ const router = new Hono<ServicesRouteEnvironment>()
21
+ if (service && rateLimit) {
22
+ router.use(
23
+ '/services/token',
24
+ createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.servicesToken)
25
+ )
26
+ }
27
+ return router.post(
28
+ '/services/token',
29
+ validatedJSON(parseCreateServicesToken),
30
+ async (context) => {
31
+ if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)
32
+ try {
33
+ return context.json(
34
+ await service.issue(context.get('actor'), context.req.valid('json').workspaceId)
35
+ )
36
+ } catch (error) {
37
+ if (error instanceof DocumentNotFoundError) {
38
+ return context.json({ error: { code: 'not_found' as const } }, 404)
39
+ }
40
+ if (error instanceof ServicesNotEntitledError) {
41
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
42
+ }
43
+ throw error
44
+ }
45
+ }
46
+ )
47
+ }
@@ -1,59 +1,62 @@
1
- import { CLOUD_AI_TOKEN_AUDIENCE, type AIToken } from '#cloud/contract'
1
+ import { CLOUD_SERVICES_TOKEN_AUDIENCE, type ServicesToken } from '#cloud/contract'
2
2
  import type { CloudActor } from '#cloud/server/auth'
3
3
  import type { CloudDatabase } from '#cloud/server/db'
4
4
  import { DocumentNotFoundError } from '#cloud/server/documents/errors'
5
5
  import { workspaceRole } from '#cloud/server/documents/repository'
6
6
  import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
7
7
  import type { CloudPolicy } from '#cloud/server/policy/policy'
8
+ import { workspacePolicyContext } from '#cloud/server/policy/workspace'
8
9
  import { SignJWT } from 'jose'
9
10
  import type { Kysely } from 'kysely'
10
11
 
11
- import { AINotEntitledError } from './errors'
12
- import { AI_SIGNING_ALGORITHM, type AISigningKey } from './keys'
12
+ import { ServicesNotEntitledError } from './errors'
13
+ import { SERVICES_SIGNING_ALGORITHM, type ServicesSigningKey } from './keys'
13
14
 
14
- export type AITokenServiceOptions = {
15
+ export type ServicesTokenServiceOptions = {
15
16
  database: Kysely<CloudDatabase>
16
17
  policy: CloudPolicy
17
18
  deploymentMode: 'official' | 'self-hosted'
18
19
  /** The Cloud public URL, which services check as the token's `iss`. */
19
20
  issuer: string
20
- signingKey: AISigningKey
21
+ signingKey: ServicesSigningKey
21
22
  lifetimeSeconds: number
22
23
  }
23
24
 
24
- export function createAITokenService(options: AITokenServiceOptions) {
25
+ export function createServicesTokenService(options: ServicesTokenServiceOptions) {
25
26
  const { privateKey, publicJWK } = options.signingKey
26
27
 
27
28
  return {
28
29
  /**
29
- * Signs a token that lets a workspace member reach the AI service on the workspace's behalf.
30
- * Entitlements are read for every token, so a plan change reaches the service within one
30
+ * Signs a token that lets a workspace member reach the services on the workspace's behalf,
31
+ * spending its owner's credits. Entitlements are read for every token, so a plan change reaches the service within one
31
32
  * token lifetime.
32
33
  */
33
- async issue(actor: CloudActor, workspaceId: string): Promise<AIToken> {
34
+ async issue(actor: CloudActor, workspaceId: string): Promise<ServicesToken> {
34
35
  if (!(await workspaceRole(options.database, actor.userId, workspaceId))) {
35
36
  throw new DocumentNotFoundError()
36
37
  }
37
- const context = {
38
- targetingKey: workspaceId,
39
- actorId: actor.userId,
40
- workspaceId,
41
- deploymentMode: options.deploymentMode
42
- }
38
+ const context = await workspacePolicyContext(
39
+ options.database,
40
+ { workspaceId },
41
+ { actorId: actor.userId, deploymentMode: options.deploymentMode }
42
+ )
43
+ if (!context) throw new DocumentNotFoundError()
43
44
  const [enabled, allowance] = await Promise.all([
44
- options.policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),
45
+ options.policy.boolean(CLOUD_FEATURE_KEYS.cloudServices, false, context),
45
46
  options.policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)
46
47
  ])
47
- if (!enabled) throw new AINotEntitledError()
48
+ if (!enabled) throw new ServicesNotEntitledError()
48
49
  const issuedAt = Math.floor(Date.now() / 1000)
49
50
  const expiresAt = issuedAt + options.lifetimeSeconds
50
51
  const token = await new SignJWT({
51
52
  workspaceId,
53
+ // Credits are the owner's, shared by every workspace they own.
54
+ accountId: context.targetingKey,
52
55
  monthlyCreditAllowance: allowance < 0 ? null : allowance
53
56
  })
54
- .setProtectedHeader({ alg: AI_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })
57
+ .setProtectedHeader({ alg: SERVICES_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })
55
58
  .setIssuer(options.issuer)
56
- .setAudience(CLOUD_AI_TOKEN_AUDIENCE)
59
+ .setAudience(CLOUD_SERVICES_TOKEN_AUDIENCE)
57
60
  .setSubject(actor.userId)
58
61
  .setIssuedAt(issuedAt)
59
62
  .setExpirationTime(expiresAt)
@@ -67,4 +70,4 @@ export function createAITokenService(options: AITokenServiceOptions) {
67
70
  }
68
71
  }
69
72
 
70
- export type AITokenService = ReturnType<typeof createAITokenService>
73
+ export type ServicesTokenService = ReturnType<typeof createServicesTokenService>
@@ -10,7 +10,9 @@ import type { CloudDatabase } from '#cloud/server/db'
10
10
  import { DocumentNotFoundError } from '#cloud/server/documents/errors'
11
11
  import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
12
12
  import type { CloudPolicy } from '#cloud/server/policy/policy'
13
+ import { workspacePolicyContext } from '#cloud/server/policy/workspace'
13
14
  import type { Kysely, UpdateObject } from 'kysely'
15
+ import * as v from 'valibot'
14
16
 
15
17
  import { randomHex } from '@open-pencil/scene-graph/random'
16
18
 
@@ -22,6 +24,27 @@ import { createSharingPolicy } from '../policy'
22
24
 
23
25
  const SHARE_SECRET_BYTES = 24
24
26
 
27
+ /** An account ID as the user table keys it; other IDs in `createdBy` name no account. */
28
+ const accountIdSchema = v.pipe(v.string(), v.uuid())
29
+
30
+ /**
31
+ * Whether any of these people is banned, for a ban that has not run out. A link stops working
32
+ * while whoever made it, or made its document, is banned, so what a banned person put up is no
33
+ * longer public. The IDs are matched as the user table keys them, so the lookup uses its index.
34
+ */
35
+ async function anyBanned(database: Kysely<CloudDatabase>, userIds: string[]): Promise<boolean> {
36
+ const accounts = userIds.filter((id) => v.is(accountIdSchema, id))
37
+ if (accounts.length === 0) return false
38
+ const banned = await database
39
+ .selectFrom('user')
40
+ .select('id')
41
+ .where('id', 'in', accounts)
42
+ .where('banned', '=', true)
43
+ .where((user) => user.or([user('banExpires', 'is', null), user('banExpires', '>', new Date())]))
44
+ .executeTakeFirst()
45
+ return banned !== undefined
46
+ }
47
+
25
48
  export type DocumentShareCapability = {
26
49
  share: DocumentShare
27
50
  secret: string
@@ -34,7 +57,10 @@ export type ResolvedSharePrincipal =
34
57
 
35
58
  export type ResolvedDocumentShare = {
36
59
  documentId: string
60
+ /** What this person may do: the link's permission, or view for a guest who may not edit. */
37
61
  permission: DocumentPermission
62
+ /** What the link lets someone signed in to the server do. */
63
+ linkPermission: DocumentPermission
38
64
  principal: ResolvedSharePrincipal
39
65
  roomEpoch: number
40
66
  }
@@ -50,6 +76,33 @@ export function createCapabilityService(
50
76
  ) {
51
77
  const sharingPolicy = createSharingPolicy(database, options)
52
78
 
79
+ /**
80
+ * What a guest may do through a link: edit only where guests may edit, otherwise view where
81
+ * guests may view, so an edit link still shows the document to someone not signed in. `null`
82
+ * means the guest signs in first. Without a policy, guests get the link's own permission.
83
+ */
84
+ async function guestPermission(
85
+ documentId: string,
86
+ linkPermission: DocumentPermission
87
+ ): Promise<DocumentPermission | null> {
88
+ const policy = options.policy
89
+ if (!policy) return linkPermission
90
+ // A workspace takes its owner's plan.
91
+ const context = await workspacePolicyContext(
92
+ database,
93
+ { documentId },
94
+ { deploymentMode: options.deploymentMode ?? 'self-hosted' }
95
+ )
96
+ if (!context) return null
97
+ if (
98
+ linkPermission === 'edit' &&
99
+ (await policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context))
100
+ ) {
101
+ return 'edit'
102
+ }
103
+ return (await policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context)) ? 'view' : null
104
+ }
105
+
53
106
  async function updateActiveShare(
54
107
  userId: string,
55
108
  documentId: string,
@@ -205,38 +258,30 @@ export function createCapabilityService(
205
258
  'documentShare.permission',
206
259
  'documentShare.secretHash',
207
260
  'documentShare.roomEpoch',
208
- 'documentShare.expiresAt'
261
+ 'documentShare.expiresAt',
262
+ 'documentShare.createdBy as linkMaker',
263
+ 'document.createdBy as documentMaker'
209
264
  ])
210
265
  .where('documentShare.id', '=', shareId)
211
266
  .where('documentShare.revokedAt', 'is', null)
212
267
  .where('document.deletedAt', 'is', null)
268
+ // A document an administrator took down opens for nobody.
269
+ .where('document.disabledAt', 'is', null)
213
270
  .executeTakeFirst()
214
271
  if (
215
272
  !row ||
216
273
  !capabilityHashMatches(row.secretHash, input.secret) ||
217
- (row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now())
274
+ (row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now()) ||
275
+ (await anyBanned(database, [row.linkMaker, row.documentMaker]))
218
276
  ) {
219
277
  throw new DocumentShareInvalidError()
220
278
  }
221
- if (!actor && options.policy) {
222
- const document = await database
223
- .selectFrom('document')
224
- .select('workspaceId')
225
- .where('id', '=', row.documentId)
226
- .executeTakeFirstOrThrow()
227
- const featureKey =
228
- row.permission === 'edit' ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView
229
- if (
230
- !(await options.policy.boolean(featureKey, false, {
231
- targetingKey: document.workspaceId,
232
- workspaceId: document.workspaceId,
233
- documentId: row.documentId,
234
- deploymentMode: options.deploymentMode ?? 'self-hosted'
235
- }))
236
- ) {
237
- // Guests are not let in here; people signed in to the server are.
238
- throw new DocumentShareSignInRequiredError()
239
- }
279
+ const permission = actor
280
+ ? row.permission
281
+ : await guestPermission(row.documentId, row.permission)
282
+ if (!permission) {
283
+ // Guests are not let in here; people signed in to the server are.
284
+ throw new DocumentShareSignInRequiredError()
240
285
  }
241
286
  await database
242
287
  .updateTable('documentShare')
@@ -245,7 +290,8 @@ export function createCapabilityService(
245
290
  .execute()
246
291
  return {
247
292
  documentId: row.documentId,
248
- permission: row.permission,
293
+ permission,
294
+ linkPermission: row.permission,
249
295
  principal: actor
250
296
  ? { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email }
251
297
  : {
@@ -3,7 +3,7 @@ import type { CloudSessionResolver } from '#cloud/server/auth'
3
3
  import type { DocumentService } from '#cloud/server/documents'
4
4
  import type { DocumentSharingService } from '#cloud/server/sharing'
5
5
  import { sharingRoute } from '#cloud/server/sharing/http'
6
- import { validatedJSON } from '#cloud/server/validation'
6
+ import { shareParams, validatedJSON } from '#cloud/server/validation'
7
7
  import { Hono } from 'hono'
8
8
 
9
9
  import { shareActor } from './actor'
@@ -14,28 +14,36 @@ export function createPublicDocumentRoutes(
14
14
  resolveSession?: CloudSessionResolver
15
15
  ) {
16
16
  return new Hono()
17
- .post('/shares/:shareId/document', validatedJSON(parseResolveDocumentShare), (context) =>
18
- sharingRoute(context, async () => {
19
- const resolution = await sharing.resolveShare(
20
- context.req.param('shareId'),
21
- context.req.valid('json'),
22
- await shareActor(context.req.raw, resolveSession)
23
- )
24
- return context.json({
25
- resolution,
26
- document: await documents.downloadShared(resolution.documentId)
17
+ .post(
18
+ '/shares/:shareId/document',
19
+ shareParams,
20
+ validatedJSON(parseResolveDocumentShare),
21
+ (context) =>
22
+ sharingRoute(context, async () => {
23
+ const resolution = await sharing.resolveShare(
24
+ context.req.valid('param').shareId,
25
+ context.req.valid('json'),
26
+ await shareActor(context.req.raw, resolveSession)
27
+ )
28
+ return context.json({
29
+ resolution,
30
+ document: await documents.downloadShared(resolution.documentId)
31
+ })
27
32
  })
28
- })
29
33
  )
30
- .post('/shares/:shareId/images', validatedJSON(parseRequestSharedImageLinks), (context) =>
31
- sharingRoute(context, async () => {
32
- const { checksums, ...share } = context.req.valid('json')
33
- const resolution = await sharing.resolveShare(
34
- context.req.param('shareId'),
35
- share,
36
- await shareActor(context.req.raw, resolveSession)
37
- )
38
- return context.json(await documents.imageLinksShared(resolution.documentId, checksums))
39
- })
34
+ .post(
35
+ '/shares/:shareId/images',
36
+ shareParams,
37
+ validatedJSON(parseRequestSharedImageLinks),
38
+ (context) =>
39
+ sharingRoute(context, async () => {
40
+ const { checksums, ...share } = context.req.valid('json')
41
+ const resolution = await sharing.resolveShare(
42
+ context.req.valid('param').shareId,
43
+ share,
44
+ await shareActor(context.req.raw, resolveSession)
45
+ )
46
+ return context.json(await documents.imageLinksShared(resolution.documentId, checksums))
47
+ })
40
48
  )
41
49
  }
@@ -20,6 +20,10 @@ export function createGrantService(database: Kysely<CloudDatabase>) {
20
20
  return rows.map(grantContract)
21
21
  },
22
22
 
23
+ /**
24
+ * Changes the permission of someone who already has access. Access itself is only given by an
25
+ * invitation the person accepts, so nobody can put a document in a stranger's files.
26
+ */
23
27
  async putGrant(
24
28
  userId: string,
25
29
  documentId: string,
@@ -28,23 +32,11 @@ export function createGrantService(database: Kysely<CloudDatabase>) {
28
32
  ): Promise<DocumentGrant> {
29
33
  await requireSharingAccess(database, userId, documentId)
30
34
  const row = await database
31
- .insertInto('documentGrant')
32
- .values({
33
- id: crypto.randomUUID(),
34
- documentId,
35
- userId: targetUserId,
36
- permission: input.permission,
37
- createdBy: userId,
38
- revokedAt: null
39
- })
40
- .onConflict((conflict) =>
41
- conflict.columns(['documentId', 'userId']).doUpdateSet({
42
- permission: input.permission,
43
- createdBy: userId,
44
- revokedAt: null,
45
- updatedAt: new Date()
46
- })
47
- )
35
+ .updateTable('documentGrant')
36
+ .set({ permission: input.permission, createdBy: userId, updatedAt: new Date() })
37
+ .where('documentId', '=', documentId)
38
+ .where('userId', '=', targetUserId)
39
+ .where('revokedAt', 'is', null)
48
40
  .returning([
49
41
  'id',
50
42
  'documentId',
@@ -54,7 +46,8 @@ export function createGrantService(database: Kysely<CloudDatabase>) {
54
46
  'createdAt',
55
47
  'updatedAt'
56
48
  ])
57
- .executeTakeFirstOrThrow()
49
+ .executeTakeFirst()
50
+ if (!row) throw new DocumentNotFoundError()
58
51
  return grantContract(row)
59
52
  },
60
53
 
@@ -1,4 +1,5 @@
1
1
  import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents'
2
+ import { InvitationLimitError } from '#cloud/server/invitations'
2
3
  import {
3
4
  DocumentShareInvalidError,
4
5
  DocumentShareSignInRequiredError,
@@ -21,6 +22,9 @@ export function sharingDomainError(context: Context, error: unknown): Response |
21
22
  if (error instanceof InvitationDeliveryError) {
22
23
  return context.json({ error: { code: 'invitation_delivery_failed' as const } }, 502)
23
24
  }
25
+ if (error instanceof InvitationLimitError) {
26
+ return context.json({ error: { code: 'rate_limited' as const } }, 429)
27
+ }
24
28
  if (error instanceof DocumentForbiddenError) {
25
29
  return context.json({ error: { code: 'forbidden' as const } }, 403)
26
30
  }
@@ -11,7 +11,11 @@ import { cloudInvitationURL } from '#cloud/contract'
11
11
  import type { CloudActor } from '#cloud/server/auth'
12
12
  import type { CloudDatabase } from '#cloud/server/db'
13
13
  import { DocumentNotFoundError } from '#cloud/server/documents/errors'
14
- import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
14
+ import {
15
+ spendInvitationBudget,
16
+ type InvitationDelivery,
17
+ type InvitationOutbox
18
+ } from '#cloud/server/invitations'
15
19
  import type { Kysely } from 'kysely'
16
20
 
17
21
  import { randomHex } from '@open-pencil/scene-graph/random'
@@ -70,6 +74,8 @@ export function createInvitationService(
70
74
  'document.name as documentName'
71
75
  ])
72
76
  .where('documentInvitation.id', '=', invitationId)
77
+ // A taken-down document's invitations name nothing until it is restored.
78
+ .where('document.disabledAt', 'is', null)
73
79
  .executeTakeFirst()
74
80
  if (!invitation || !invitationTokenIsActive(invitation, input.token)) {
75
81
  throw new DocumentShareInvalidError()
@@ -161,6 +167,7 @@ export function createInvitationService(
161
167
  }
162
168
  : null
163
169
  const row = await database.transaction().execute(async (transaction) => {
170
+ await spendInvitationBudget(transaction, { senderId: userId, email: input.email })
164
171
  const inserted = await transaction
165
172
  .insertInto('documentInvitation')
166
173
  .values({
@@ -234,18 +241,21 @@ export function createInvitationService(
234
241
  if (workspace) return { kind: 'workspace', ...workspace }
235
242
  const invitation = await database
236
243
  .selectFrom('documentInvitation')
244
+ .innerJoin('document', 'document.id', 'documentInvitation.documentId')
237
245
  .select([
238
- 'id',
239
- 'documentId',
240
- 'emailNormalized',
241
- 'permission',
242
- 'invitedBy',
243
- 'tokenHash',
244
- 'expiresAt',
245
- 'acceptedAt',
246
- 'revokedAt'
246
+ 'documentInvitation.id',
247
+ 'documentInvitation.documentId',
248
+ 'documentInvitation.emailNormalized',
249
+ 'documentInvitation.permission',
250
+ 'documentInvitation.invitedBy',
251
+ 'documentInvitation.tokenHash',
252
+ 'documentInvitation.expiresAt',
253
+ 'documentInvitation.acceptedAt',
254
+ 'documentInvitation.revokedAt'
247
255
  ])
248
- .where('id', '=', invitationId)
256
+ .where('documentInvitation.id', '=', invitationId)
257
+ // Refused, not consumed, while the document is taken down, so it works again on restore.
258
+ .where('document.disabledAt', 'is', null)
249
259
  .executeTakeFirst()
250
260
  if (
251
261
  !invitation ||