@open-pencil/cloud 0.17.0-beta.2 → 0.17.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/bin/{ai-relay.mjs → services.mjs} +8 -8
- package/dist/bin/services.mjs.map +1 -0
- package/dist/client.d.ts +236 -46
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +649 -400
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +680 -443
- package/dist/contract2.js.map +1 -1
- package/dist/email.d.ts +9 -1
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +99 -58
- package/dist/email.js.map +1 -1
- package/dist/index.d.ts +469 -65
- package/dist/index.d.ts.map +1 -1
- package/dist/listen.mjs +505 -787
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-node.d.mts +3920 -2524
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/runtime-node.mjs +6 -5
- package/dist/runtime-node.mjs.map +1 -1
- package/dist/server.d.ts +3586 -1897
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +5216 -4272
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +5179 -3623
- package/dist/server.mjs.map +1 -1
- package/dist/server2.mjs +101 -79
- package/dist/server2.mjs.map +1 -1
- package/package.json +7 -6
- package/src/admin/api/routes.ts +59 -0
- package/src/admin/audit/service.ts +25 -6
- package/src/admin/documents/service.ts +361 -0
- package/src/admin/errors.ts +9 -1
- package/src/admin/index.ts +6 -0
- package/src/admin/operations/service.ts +7 -0
- package/src/admin/reports/service.ts +147 -0
- package/src/admin/schema.ts +6 -0
- package/src/client/api.ts +36 -21
- package/src/client/auth/navigation.ts +6 -5
- package/src/client/index.ts +7 -7
- package/src/client/portal/account.ts +25 -0
- package/src/client/portal/administration.ts +56 -0
- package/src/client/{ai.ts → services.ts} +44 -27
- package/src/contract/account.ts +58 -2
- package/src/contract/admin/index.ts +67 -3
- package/src/contract/collaboration.ts +6 -1
- package/src/contract/discovery.ts +22 -4
- package/src/contract/documents.ts +27 -0
- package/src/contract/entitlements.ts +2 -2
- package/src/contract/index.ts +63 -37
- package/src/contract/relay.ts +6 -0
- package/src/contract/reports.ts +42 -0
- package/src/contract/services.ts +233 -0
- package/src/contract/sharing.ts +3 -9
- package/src/email/render.ts +26 -0
- package/src/email/schema.ts +11 -1
- package/src/email/templates/brand.ts +1 -1
- package/src/runtime/cloudflare/environment.ts +22 -11
- package/src/runtime/cloudflare/index.ts +1 -1
- package/src/runtime/cloudflare/logging.ts +15 -0
- package/src/runtime/cloudflare/maintenance.ts +31 -0
- package/src/runtime/cloudflare/relay/index.ts +62 -14
- package/src/runtime/cloudflare/worker.ts +39 -13
- package/src/runtime/node/application.ts +5 -3
- package/src/runtime/node/bootstrap.ts +15 -4
- package/src/runtime/node/cleanup.ts +16 -3
- package/src/runtime/node/entitlements/main.ts +14 -11
- package/src/runtime/node/index.ts +1 -1
- package/src/runtime/node/migrate.ts +5 -1
- package/src/runtime/node/relay.ts +8 -2
- package/src/runtime/node/request-id.ts +13 -0
- package/src/runtime/node/server.ts +39 -15
- package/src/runtime/node/{ai-relay → services}/main.ts +6 -6
- package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
- package/src/runtime/postgres/database.ts +20 -1
- package/src/runtime/posthog/errors.ts +15 -31
- package/src/runtime/s3/objects.ts +24 -1
- package/src/runtime/site/server.ts +32 -5
- package/src/server/account/actions.ts +5 -0
- package/src/server/account/deletion.ts +302 -0
- package/src/server/account/routes.ts +47 -3
- package/src/server/account/terms.ts +42 -0
- package/src/server/api/router.ts +9 -5
- package/src/server/api/types.ts +2 -0
- package/src/server/app.ts +90 -16
- package/src/server/auth/access-control.ts +63 -0
- package/src/server/auth/adapter.ts +11 -0
- package/src/server/auth/endpoints.ts +5 -1
- package/src/server/auth/factory.ts +30 -3
- package/src/server/auth/index.ts +10 -1
- package/src/server/cleanup/configured.ts +12 -5
- package/src/server/cleanup/documents.ts +165 -71
- package/src/server/cleanup/revisions.ts +16 -5
- package/src/server/cleanup/uploads.ts +8 -2
- package/src/server/cleanup/worker.ts +5 -2
- package/src/server/collaboration/relay/connection.ts +4 -3
- package/src/server/collaboration/relay/documents.ts +13 -10
- package/src/server/collaboration/relay/hub.ts +97 -25
- package/src/server/collaboration/relay/log.ts +5 -2
- package/src/server/collaboration/service.ts +27 -31
- package/src/server/config/deployment.ts +24 -4
- package/src/server/config/public.ts +5 -4
- package/src/server/config/schema.ts +82 -16
- package/src/server/db/expressions.ts +15 -1
- package/src/server/db/migrate.ts +34 -116
- package/src/server/db/migrations/001_accounts.ts +79 -0
- package/src/server/db/migrations/002_workspaces.ts +48 -0
- package/src/server/db/migrations/003_storage.ts +44 -0
- package/src/server/db/migrations/004_documents.ts +193 -0
- package/src/server/db/migrations/005_sharing.ts +95 -0
- package/src/server/db/migrations/006_operations.ts +110 -0
- package/src/server/db/migrations/007_trash.ts +33 -0
- package/src/server/db/migrations/008_terms.ts +18 -0
- package/src/server/db/migrations/schema.ts +71 -0
- package/src/server/db/tables.ts +52 -3
- package/src/server/documents/access.ts +66 -55
- package/src/server/documents/errors.ts +7 -0
- package/src/server/documents/images.ts +2 -1
- package/src/server/documents/limits.ts +9 -9
- package/src/server/documents/purge.ts +75 -0
- package/src/server/documents/repository.ts +2 -0
- package/src/server/documents/routes.ts +26 -0
- package/src/server/documents/service.ts +18 -4
- package/src/server/documents/summary.ts +1 -0
- package/src/server/documents/trash.ts +203 -0
- package/src/server/documents/versions/checkpoint.ts +2 -1
- package/src/server/documents/versions/history.ts +11 -7
- package/src/server/documents/versions/service.ts +13 -4
- package/src/server/errors/index.ts +59 -16
- package/src/server/errors/posthog.ts +80 -0
- package/src/server/index.ts +46 -17
- package/src/server/internal/index.ts +3 -3
- package/src/server/internal/routes.ts +7 -10
- package/src/server/internal/schema.ts +1 -1
- package/src/server/internal/service.ts +17 -23
- package/src/server/invitations/budget.ts +66 -0
- package/src/server/invitations/index.ts +1 -0
- package/src/server/logging.ts +76 -0
- package/src/server/pictures/service.ts +2 -1
- package/src/server/policy/database.ts +39 -25
- package/src/server/policy/index.ts +2 -1
- package/src/server/policy/keys.ts +5 -2
- package/src/server/policy/policy.ts +1 -0
- package/src/server/policy/schema.ts +2 -2
- package/src/server/policy/service.ts +12 -9
- package/src/server/policy/static.ts +5 -5
- package/src/server/policy/workspace.ts +41 -0
- package/src/server/quota/reconcile.ts +2 -0
- package/src/server/quota/storage.ts +69 -31
- package/src/server/rate-limit/cleanup.ts +17 -5
- package/src/server/rate-limit/middleware.ts +2 -2
- package/src/server/reports/index.ts +8 -0
- package/src/server/reports/routes.ts +37 -0
- package/src/server/reports/service.ts +123 -0
- package/src/server/services/errors.ts +7 -0
- package/src/server/services/index.ts +8 -0
- package/src/server/{ai → services}/keys.ts +11 -11
- package/src/server/services/routes.ts +47 -0
- package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
- package/src/server/sharing/capabilities/service.ts +68 -22
- package/src/server/sharing/grants/service.ts +11 -18
- package/src/server/sharing/http.ts +4 -0
- package/src/server/sharing/invitations/service.ts +21 -11
- package/src/server/sharing/policy.ts +9 -14
- package/src/server/sharing/routes.ts +0 -16
- package/src/server/sharing/service.ts +1 -17
- package/src/server/validation.ts +1 -0
- package/src/server/workspaces/index.ts +1 -0
- package/src/server/workspaces/members.ts +89 -38
- package/src/server/workspaces/repository.ts +2 -1
- package/src/server/workspaces/routes.ts +4 -0
- package/src/{ai-relay → services}/app.ts +48 -44
- package/src/{ai-relay → services}/config.ts +25 -19
- package/src/services/db/index.ts +10 -0
- package/src/services/db/migrate.ts +37 -0
- package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
- package/src/services/db/schema.ts +22 -0
- package/src/services/index.ts +18 -0
- package/src/{ai-relay → services}/metering.ts +2 -2
- package/src/{ai-relay → services}/usage.ts +43 -19
- package/dist/bin/ai-relay.mjs.map +0 -1
- package/src/ai-relay/db/index.ts +0 -10
- package/src/ai-relay/db/migrate.ts +0 -32
- package/src/ai-relay/db/schema.ts +0 -20
- package/src/ai-relay/index.ts +0 -18
- package/src/contract/ai.ts +0 -150
- package/src/server/ai/errors.ts +0 -7
- package/src/server/ai/index.ts +0 -4
- package/src/server/ai/routes.ts +0 -43
- package/src/server/auth/workspace-access.ts +0 -23
- package/src/server/db/migrations/001_foundation.ts +0 -164
- package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
- package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
- package/src/server/db/migrations/004_document_sharing.ts +0 -82
- package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
- package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
- package/src/server/db/migrations/007_collaboration_state.ts +0 -25
- package/src/server/db/migrations/008_storage_reservations.ts +0 -37
- package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
- package/src/server/db/migrations/010_upload_finalization.ts +0 -22
- package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
- package/src/server/db/migrations/012_transactional_email.ts +0 -48
- package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
- package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
- package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
- package/src/server/db/migrations/016_auth_schema.ts +0 -16
- package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
- package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
- package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
- package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
- package/src/server/db/migrations/021_document_versions.ts +0 -66
- package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
- package/src/server/db/migrations/023_document_images.ts +0 -61
- package/src/server/db/migrations/024_account_activity.ts +0 -66
- package/src/server/db/migrations/025_table_names.ts +0 -58
- package/src/server/db/migrations/026_user_picture.ts +0 -30
- package/src/server/db/migrations/027_document_kind.ts +0 -19
- package/src/server/db/migrations/028_collaboration_updates.ts +0 -84
- package/src/server/db/migrations/helpers.ts +0 -78
- /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
package/src/server/index.ts
CHANGED
|
@@ -20,16 +20,16 @@ export {
|
|
|
20
20
|
type EnrollmentStatus
|
|
21
21
|
} from '#cloud/admin'
|
|
22
22
|
export {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
type
|
|
29
|
-
type
|
|
30
|
-
type
|
|
31
|
-
type
|
|
32
|
-
} from './
|
|
23
|
+
ServicesNotEntitledError,
|
|
24
|
+
createServicesRoutes,
|
|
25
|
+
createServicesTokenService,
|
|
26
|
+
importServicesSigningKey,
|
|
27
|
+
loadServicesSigningKey,
|
|
28
|
+
type ServicesRouteEnvironment,
|
|
29
|
+
type ServicesSigningKey,
|
|
30
|
+
type ServicesTokenService,
|
|
31
|
+
type ServicesTokenServiceOptions
|
|
32
|
+
} from './services'
|
|
33
33
|
export {
|
|
34
34
|
createAuthenticationEmailService,
|
|
35
35
|
createAccountAuthenticationService,
|
|
@@ -45,9 +45,14 @@ export {
|
|
|
45
45
|
type CloudSessionResolver,
|
|
46
46
|
type AccountAuthenticationService,
|
|
47
47
|
type AuthenticationEmailService,
|
|
48
|
-
|
|
48
|
+
accessControl,
|
|
49
|
+
accessStatements,
|
|
50
|
+
documentRoleCan,
|
|
51
|
+
documentRoles,
|
|
52
|
+
workspaceRoleCan,
|
|
49
53
|
workspaceRoles,
|
|
50
|
-
|
|
54
|
+
type AccessRequest,
|
|
55
|
+
type DocumentRole
|
|
51
56
|
} from './auth'
|
|
52
57
|
export {
|
|
53
58
|
createCloudAPIRouter,
|
|
@@ -188,20 +193,36 @@ export {
|
|
|
188
193
|
export {
|
|
189
194
|
CLOUD_ERROR_SOURCES,
|
|
190
195
|
cloudErrorHandler,
|
|
196
|
+
createLoggingErrorReporter,
|
|
191
197
|
reportCloudError,
|
|
192
198
|
type CloudErrorContext,
|
|
193
199
|
type CloudErrorReporter,
|
|
194
|
-
type CloudErrorSource
|
|
200
|
+
type CloudErrorSource,
|
|
201
|
+
createPostHogErrorReporter,
|
|
202
|
+
type ErrorReportContext,
|
|
203
|
+
type ErrorReporter,
|
|
204
|
+
type PostHogErrorReporterOptions
|
|
195
205
|
} from './errors'
|
|
206
|
+
export {
|
|
207
|
+
cloudRequestId,
|
|
208
|
+
logCloud,
|
|
209
|
+
loggedError,
|
|
210
|
+
writeJSONLine,
|
|
211
|
+
type CloudLogLine,
|
|
212
|
+
type CloudLogWriter,
|
|
213
|
+
type ForwardedRequestId
|
|
214
|
+
} from './logging'
|
|
196
215
|
export {
|
|
197
216
|
createInternalRoutes,
|
|
198
217
|
createInternalService,
|
|
199
|
-
|
|
200
|
-
|
|
218
|
+
parseSetAccountEntitlements,
|
|
219
|
+
setAccountEntitlementsSchema,
|
|
201
220
|
type InternalService,
|
|
202
|
-
type
|
|
221
|
+
type SetAccountEntitlementsInput
|
|
203
222
|
} from './internal'
|
|
204
223
|
export {
|
|
224
|
+
INVITATION_BUDGET,
|
|
225
|
+
InvitationLimitError,
|
|
205
226
|
noOpInvitationDelivery,
|
|
206
227
|
type DocumentInvitationMessage,
|
|
207
228
|
type InvitationDelivery,
|
|
@@ -244,7 +265,7 @@ export {
|
|
|
244
265
|
CLOUD_FEATURE_KEYS,
|
|
245
266
|
CloudPolicy,
|
|
246
267
|
createConfiguredCloudPolicy,
|
|
247
|
-
|
|
268
|
+
createAccountEntitlementRepository,
|
|
248
269
|
DatabaseEntitlementSource,
|
|
249
270
|
EntitlementOpenFeatureProvider,
|
|
250
271
|
createDefaultCloudPolicy,
|
|
@@ -288,3 +309,11 @@ export {
|
|
|
288
309
|
type WorkspaceRouteEnvironment,
|
|
289
310
|
type WorkspaceService
|
|
290
311
|
} from './workspaces'
|
|
312
|
+
export {
|
|
313
|
+
createDocumentReportService,
|
|
314
|
+
createPublicReportRoutes,
|
|
315
|
+
DOCUMENT_REPORT_BUDGET,
|
|
316
|
+
DocumentReportLimitError,
|
|
317
|
+
type DocumentReportService,
|
|
318
|
+
type DocumentReportServiceOptions
|
|
319
|
+
} from './reports'
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export { createInternalRoutes } from './routes'
|
|
2
2
|
export {
|
|
3
3
|
createInternalService,
|
|
4
|
-
|
|
4
|
+
parseSetAccountEntitlements,
|
|
5
5
|
type InternalService,
|
|
6
|
-
type
|
|
6
|
+
type SetAccountEntitlementsInput
|
|
7
7
|
} from './service'
|
|
8
|
-
export {
|
|
8
|
+
export { setAccountEntitlementsSchema } from './schema'
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { capabilityHashMatches, hashCapability } from '#cloud/server/sharing/crypto'
|
|
2
|
-
import {
|
|
2
|
+
import { accountParams, validatedJSON } from '#cloud/server/validation'
|
|
3
3
|
import { Hono } from 'hono'
|
|
4
4
|
import { bearerAuth } from 'hono/bearer-auth'
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { parseSetAccountEntitlements, type InternalService } from './service'
|
|
7
7
|
|
|
8
8
|
/** The internal API on HTTP, for runtimes without a private transport to their services. */
|
|
9
9
|
export function createInternalRoutes(service: InternalService, serviceToken: string) {
|
|
@@ -20,15 +20,12 @@ export function createInternalRoutes(service: InternalService, serviceToken: str
|
|
|
20
20
|
})
|
|
21
21
|
)
|
|
22
22
|
.put(
|
|
23
|
-
'/
|
|
24
|
-
|
|
25
|
-
validatedJSON(
|
|
23
|
+
'/accounts/:userId/entitlements',
|
|
24
|
+
accountParams,
|
|
25
|
+
validatedJSON(parseSetAccountEntitlements),
|
|
26
26
|
async (context) => {
|
|
27
|
-
const {
|
|
28
|
-
const result = await service.
|
|
29
|
-
workspaceId,
|
|
30
|
-
context.req.valid('json')
|
|
31
|
-
)
|
|
27
|
+
const { userId } = context.req.valid('param')
|
|
28
|
+
const result = await service.setAccountEntitlements(userId, context.req.valid('json'))
|
|
32
29
|
if (!result.found) return context.json({ error: { code: 'not_found' as const } }, 404)
|
|
33
30
|
return context.json({ applied: result.applied })
|
|
34
31
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { staticEntitlementsSchema } from '#cloud/server/policy/schema'
|
|
2
2
|
import * as v from 'valibot'
|
|
3
3
|
|
|
4
|
-
export const
|
|
4
|
+
export const setAccountEntitlementsSchema = v.object({
|
|
5
5
|
values: staticEntitlementsSchema,
|
|
6
6
|
/** Who decided these values, such as `billing`; stored as the row's source. */
|
|
7
7
|
source: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
2
|
-
import {
|
|
2
|
+
import { createAccountEntitlementRepository } from '#cloud/server/policy'
|
|
3
3
|
import type { Kysely } from 'kysely'
|
|
4
4
|
import * as v from 'valibot'
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { setAccountEntitlementsSchema } from './schema'
|
|
7
7
|
|
|
8
|
-
export type
|
|
8
|
+
export type SetAccountEntitlementsInput = v.InferInput<typeof setAccountEntitlementsSchema>
|
|
9
9
|
|
|
10
|
-
export function
|
|
11
|
-
return v.parse(
|
|
10
|
+
export function parseSetAccountEntitlements(input: unknown) {
|
|
11
|
+
return v.parse(setAccountEntitlementsSchema, input)
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
/**
|
|
@@ -16,26 +16,20 @@ export function parseSetWorkspaceEntitlements(input: unknown) {
|
|
|
16
16
|
* their own transport: an authenticated HTTP route on Node, a service binding on Workers.
|
|
17
17
|
*/
|
|
18
18
|
export function createInternalService(database: Kysely<CloudDatabase>) {
|
|
19
|
-
const entitlements =
|
|
19
|
+
const entitlements = createAccountEntitlementRepository(database)
|
|
20
20
|
return {
|
|
21
|
-
/**
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Sets an account's plan, which every workspace it owns takes. `found` is false for an
|
|
23
|
+
* unknown account; `applied` is false for an outdated version.
|
|
24
|
+
*/
|
|
25
|
+
async setAccountEntitlements(
|
|
26
|
+
userId: string,
|
|
27
|
+
input: SetAccountEntitlementsInput
|
|
25
28
|
): Promise<{ found: boolean; applied: boolean }> {
|
|
26
|
-
const { values, source, externalVersion } =
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
)
|
|
29
|
+
const { values, source, externalVersion } = parseSetAccountEntitlements(input)
|
|
30
|
+
const account = await entitlements.account(userId)
|
|
31
|
+
if (!account) return { found: false, applied: false }
|
|
32
|
+
const { applied } = await entitlements.setVersioned(account, values, source, externalVersion)
|
|
39
33
|
return { found: true, applied }
|
|
40
34
|
}
|
|
41
35
|
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
2
|
+
import { lockForTransaction } from '#cloud/server/db/expressions'
|
|
3
|
+
import type { Transaction } from 'kysely'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* How many invitations, to documents and workspaces alike, one person may send in a day, and how
|
|
7
|
+
* many one address may receive from everyone. Each sends an email naming the inviter and the file,
|
|
8
|
+
* both of which the sender chooses, so without a daily budget invitations are a way to send spam.
|
|
9
|
+
*/
|
|
10
|
+
export const INVITATION_BUDGET = {
|
|
11
|
+
windowMs: 24 * 60 * 60 * 1000,
|
|
12
|
+
perSender: 100,
|
|
13
|
+
perRecipient: 5
|
|
14
|
+
} as const
|
|
15
|
+
|
|
16
|
+
/** An invitation past the sender's or the recipient's daily budget. */
|
|
17
|
+
export class InvitationLimitError extends Error {
|
|
18
|
+
override readonly name = 'InvitationLimitError'
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function sentSince(
|
|
22
|
+
transaction: Transaction<CloudDatabase>,
|
|
23
|
+
column: 'senderId' | 'emailNormalized',
|
|
24
|
+
value: string,
|
|
25
|
+
since: Date
|
|
26
|
+
): Promise<number> {
|
|
27
|
+
const row = await transaction
|
|
28
|
+
.selectFrom('invitationSend')
|
|
29
|
+
.select((expression) => expression.fn.countAll<string>().as('count'))
|
|
30
|
+
.where(column, '=', value)
|
|
31
|
+
.where('sentAt', '>', since)
|
|
32
|
+
.executeTakeFirstOrThrow()
|
|
33
|
+
return Number(row.count)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Counts an invitation from `senderId` to `email` against both daily budgets, in the transaction
|
|
38
|
+
* that creates it, or refuses it once either budget is used. Sends are logged apart from the
|
|
39
|
+
* invitations, so deleting a workspace or document gives nothing back, and the check holds locks
|
|
40
|
+
* on the sender and the recipient, so two invitations at once cannot both take the last one.
|
|
41
|
+
*/
|
|
42
|
+
export async function spendInvitationBudget(
|
|
43
|
+
transaction: Transaction<CloudDatabase>,
|
|
44
|
+
invitation: { senderId: string; email: string },
|
|
45
|
+
now = new Date()
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
const email = invitation.email.trim().toLowerCase()
|
|
48
|
+
// Always sender first, then recipient, so two transactions never wait on each other in turn.
|
|
49
|
+
await lockForTransaction(transaction, `invitation-sender:${invitation.senderId}`)
|
|
50
|
+
await lockForTransaction(transaction, `invitation-recipient:${email}`)
|
|
51
|
+
const since = new Date(now.getTime() - INVITATION_BUDGET.windowMs)
|
|
52
|
+
const bySender = await sentSince(transaction, 'senderId', invitation.senderId, since)
|
|
53
|
+
const byRecipient = await sentSince(transaction, 'emailNormalized', email, since)
|
|
54
|
+
if (bySender >= INVITATION_BUDGET.perSender || byRecipient >= INVITATION_BUDGET.perRecipient) {
|
|
55
|
+
throw new InvitationLimitError()
|
|
56
|
+
}
|
|
57
|
+
await transaction
|
|
58
|
+
.insertInto('invitationSend')
|
|
59
|
+
.values({
|
|
60
|
+
id: crypto.randomUUID(),
|
|
61
|
+
senderId: invitation.senderId,
|
|
62
|
+
emailNormalized: email,
|
|
63
|
+
sentAt: now
|
|
64
|
+
})
|
|
65
|
+
.execute()
|
|
66
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono'
|
|
2
|
+
|
|
3
|
+
export type CloudLogLevel = 'error' | 'warn' | 'info'
|
|
4
|
+
|
|
5
|
+
export type CloudLoggedError = {
|
|
6
|
+
name: string
|
|
7
|
+
message: string
|
|
8
|
+
stack?: string
|
|
9
|
+
cause?: CloudLoggedError
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** What a log line carries besides its message; never who made a request or what it carried. */
|
|
13
|
+
export type CloudLogFields = Record<
|
|
14
|
+
string,
|
|
15
|
+
string | number | boolean | undefined | CloudLoggedError
|
|
16
|
+
>
|
|
17
|
+
|
|
18
|
+
/** One structured log line. */
|
|
19
|
+
export type CloudLogLine = CloudLogFields & { level: CloudLogLevel; message: string }
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Writes a log line where the runtime's logs go, in the form they index best. Runtimes pass their
|
|
23
|
+
* own to `createLoggingErrorReporter`; `writeJSONLine` is the default.
|
|
24
|
+
*/
|
|
25
|
+
export type CloudLogWriter = (line: CloudLogLine) => void
|
|
26
|
+
|
|
27
|
+
/** Writes the line as one line of JSON, at the console method of its level. */
|
|
28
|
+
export const writeJSONLine: CloudLogWriter = (line) => {
|
|
29
|
+
console[line.level](JSON.stringify(line))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** How deep a chain of causes is written out. */
|
|
33
|
+
const MAXIMUM_CAUSES = 4
|
|
34
|
+
|
|
35
|
+
/** An error as a log line keeps it: its name, message, stack, and causes. */
|
|
36
|
+
export function loggedError(error: unknown, depth = 0): CloudLoggedError {
|
|
37
|
+
if (!(error instanceof Error)) return { name: 'NonError', message: String(error) }
|
|
38
|
+
const cause =
|
|
39
|
+
error.cause !== undefined && depth < MAXIMUM_CAUSES
|
|
40
|
+
? loggedError(error.cause, depth + 1)
|
|
41
|
+
: undefined
|
|
42
|
+
return { name: error.name, message: error.message, stack: error.stack, ...(cause && { cause }) }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Writes a warning or note through the default writer, from code no runtime hands a writer to.
|
|
47
|
+
* Errors go through `reportCloudError`, which logs with the runtime's.
|
|
48
|
+
*/
|
|
49
|
+
export function logCloud(level: CloudLogLevel, message: string, fields: CloudLogFields = {}): void {
|
|
50
|
+
writeJSONLine({ ...fields, level, message })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Reads the ID that what stands in front of the server gave a request, if the runtime trusts it. */
|
|
54
|
+
export type ForwardedRequestId = (headers: Headers) => string | undefined
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Names each request as the `requestId` variable, from what the runtime trusts in front of it
|
|
58
|
+
* (such as Cloudflare's ray ID) or else a new UUID, and answers with it as `X-Request-Id` so a
|
|
59
|
+
* person reporting a failure can quote it. Nested servers each name the request; the innermost
|
|
60
|
+
* one that answered keeps its ID on the response.
|
|
61
|
+
*/
|
|
62
|
+
export function cloudRequestId(
|
|
63
|
+
forwarded?: ForwardedRequestId
|
|
64
|
+
): MiddlewareHandler<{ Variables: { requestId: string } }> {
|
|
65
|
+
return async (context, next) => {
|
|
66
|
+
const id = forwarded?.(context.req.raw.headers) ?? crypto.randomUUID()
|
|
67
|
+
context.set('requestId', id)
|
|
68
|
+
context.header('X-Request-Id', id)
|
|
69
|
+
await next()
|
|
70
|
+
// A response the handler built itself, such as a page an inner server answered, misses the
|
|
71
|
+
// prepared header; one an inner layer named keeps its ID. A socket upgrade is left alone.
|
|
72
|
+
if (context.res.status !== 101 && !context.res.headers.has('X-Request-Id')) {
|
|
73
|
+
context.header('X-Request-Id', id)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'
|
|
2
2
|
import type { CloudDatabase, UserPictureFormat } from '#cloud/server/db'
|
|
3
|
+
import { logCloud, loggedError } from '#cloud/server/logging'
|
|
3
4
|
import { sha256 } from '@noble/hashes/sha2.js'
|
|
4
5
|
import { bytesToHex } from '@noble/hashes/utils.js'
|
|
5
6
|
import { imageSize } from 'image-size'
|
|
@@ -220,7 +221,7 @@ export function createUserPictures(database: Kysely<CloudDatabase>, options: Use
|
|
|
220
221
|
if (!bytes) throw new PictureInvalidError()
|
|
221
222
|
await save(userId, bytes, { from: 'provider', seen: current })
|
|
222
223
|
} catch (error) {
|
|
223
|
-
|
|
224
|
+
logCloud('warn', 'Keeping a linked account picture failed', { error: loggedError(error) })
|
|
224
225
|
await database
|
|
225
226
|
.updateTable('user')
|
|
226
227
|
.set({ image: null, updatedAt: new Date() })
|
|
@@ -10,11 +10,11 @@ export class DatabaseEntitlementSource implements EntitlementSource {
|
|
|
10
10
|
constructor(private readonly database: Kysely<CloudDatabase>) {}
|
|
11
11
|
|
|
12
12
|
private async values(subject: EntitlementSubject): Promise<Record<string, boolean | number>> {
|
|
13
|
-
if (subject.type !== '
|
|
13
|
+
if (subject.type !== 'user') return {}
|
|
14
14
|
const row = await this.database
|
|
15
|
-
.selectFrom('
|
|
15
|
+
.selectFrom('accountEntitlement')
|
|
16
16
|
.select('values')
|
|
17
|
-
.where('
|
|
17
|
+
.where('userId', '=', subject.id)
|
|
18
18
|
.executeTakeFirst()
|
|
19
19
|
return row ? staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values)) : {}
|
|
20
20
|
}
|
|
@@ -34,26 +34,43 @@ export class DatabaseEntitlementSource implements EntitlementSource {
|
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
/** Each account's stored entitlements, which every workspace it owns takes. */
|
|
38
|
+
const accountIdSchema = v.pipe(v.string(), v.uuid())
|
|
39
|
+
|
|
40
|
+
export function createAccountEntitlementRepository(database: Kysely<CloudDatabase>) {
|
|
38
41
|
return {
|
|
39
|
-
|
|
42
|
+
/**
|
|
43
|
+
* The account `userId` names, as the user table spells it, or null when there is none, so a
|
|
44
|
+
* plan is stored under the key policy reads, whatever case the caller wrote the ID in.
|
|
45
|
+
*/
|
|
46
|
+
async account(userId: string): Promise<string | null> {
|
|
47
|
+
if (!v.is(accountIdSchema, userId)) return null
|
|
48
|
+
const user = await database
|
|
49
|
+
.selectFrom('user')
|
|
50
|
+
.select('id')
|
|
51
|
+
.where('id', '=', userId)
|
|
52
|
+
.executeTakeFirst()
|
|
53
|
+
return user?.id ?? null
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
async get(userId: string) {
|
|
40
57
|
return database
|
|
41
|
-
.selectFrom('
|
|
58
|
+
.selectFrom('accountEntitlement')
|
|
42
59
|
.selectAll()
|
|
43
|
-
.where('
|
|
60
|
+
.where('userId', '=', userId)
|
|
44
61
|
.executeTakeFirst()
|
|
45
62
|
},
|
|
46
63
|
|
|
47
|
-
async set(
|
|
64
|
+
async set(userId: string, values: StaticEntitlementsInput, source: string) {
|
|
48
65
|
const validated = v.parse(staticEntitlementsSchema, values)
|
|
49
66
|
return database
|
|
50
|
-
.insertInto('
|
|
51
|
-
.values({
|
|
67
|
+
.insertInto('accountEntitlement')
|
|
68
|
+
.values({ userId, values: validated, source })
|
|
52
69
|
.onConflict((conflict) =>
|
|
53
|
-
conflict.column('
|
|
70
|
+
conflict.column('userId').doUpdateSet({
|
|
54
71
|
values: validated,
|
|
55
72
|
source,
|
|
56
|
-
revision: (expression) => expression('
|
|
73
|
+
revision: (expression) => expression('accountEntitlement.revision', '+', 1),
|
|
57
74
|
updatedAt: new Date()
|
|
58
75
|
})
|
|
59
76
|
)
|
|
@@ -67,42 +84,39 @@ export function createWorkspaceEntitlementRepository(database: Kysely<CloudDatab
|
|
|
67
84
|
* An unversioned row, such as one an operator set, is replaced.
|
|
68
85
|
*/
|
|
69
86
|
async setVersioned(
|
|
70
|
-
|
|
87
|
+
userId: string,
|
|
71
88
|
values: StaticEntitlementsInput,
|
|
72
89
|
source: string,
|
|
73
90
|
externalVersion: number
|
|
74
91
|
): Promise<{ applied: boolean }> {
|
|
75
92
|
const validated = v.parse(staticEntitlementsSchema, values)
|
|
76
93
|
const row = await database
|
|
77
|
-
.insertInto('
|
|
78
|
-
.values({
|
|
94
|
+
.insertInto('accountEntitlement')
|
|
95
|
+
.values({ userId, values: validated, source, externalVersion })
|
|
79
96
|
.onConflict((conflict) =>
|
|
80
97
|
conflict
|
|
81
|
-
.column('
|
|
98
|
+
.column('userId')
|
|
82
99
|
.doUpdateSet({
|
|
83
100
|
values: validated,
|
|
84
101
|
source,
|
|
85
102
|
externalVersion,
|
|
86
|
-
revision: (expression) => expression('
|
|
103
|
+
revision: (expression) => expression('accountEntitlement.revision', '+', 1),
|
|
87
104
|
updatedAt: new Date()
|
|
88
105
|
})
|
|
89
106
|
.where((expression) =>
|
|
90
107
|
expression.or([
|
|
91
|
-
expression('
|
|
92
|
-
expression('
|
|
108
|
+
expression('accountEntitlement.externalVersion', 'is', null),
|
|
109
|
+
expression('accountEntitlement.externalVersion', '<', externalVersion)
|
|
93
110
|
])
|
|
94
111
|
)
|
|
95
112
|
)
|
|
96
|
-
.returning('
|
|
113
|
+
.returning('userId')
|
|
97
114
|
.executeTakeFirst()
|
|
98
115
|
return { applied: row !== undefined }
|
|
99
116
|
},
|
|
100
117
|
|
|
101
|
-
async clear(
|
|
102
|
-
await database
|
|
103
|
-
.deleteFrom('workspaceEntitlement')
|
|
104
|
-
.where('workspaceId', '=', workspaceId)
|
|
105
|
-
.execute()
|
|
118
|
+
async clear(userId: string): Promise<void> {
|
|
119
|
+
await database.deleteFrom('accountEntitlement').where('userId', '=', userId).execute()
|
|
106
120
|
}
|
|
107
121
|
}
|
|
108
122
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { createAccountEntitlementRepository, DatabaseEntitlementSource } from './database'
|
|
2
|
+
export { workspacePolicyContext } from './workspace'
|
|
2
3
|
export {
|
|
3
4
|
StaticEntitlementSource,
|
|
4
5
|
type EntitlementSource,
|
|
@@ -9,12 +9,15 @@ export const CLOUD_FEATURE_KEYS = {
|
|
|
9
9
|
maximumFileBytes: 'cloud.documents.maximum-file-bytes',
|
|
10
10
|
maximumStorageBytes: 'cloud.storage.maximum-bytes',
|
|
11
11
|
maximumParticipants: 'cloud.collaboration.maximum-participants',
|
|
12
|
-
|
|
13
|
-
monthlyCreditAllowance: 'cloud.
|
|
12
|
+
cloudServices: 'cloud.services.enabled',
|
|
13
|
+
monthlyCreditAllowance: 'cloud.services.monthly-credit-allowance'
|
|
14
14
|
} as const
|
|
15
15
|
|
|
16
16
|
export type CloudPolicyContext = {
|
|
17
|
+
/** Whose entitlements apply: an account by default for a workspace, its owner's. */
|
|
17
18
|
targetingKey: string
|
|
19
|
+
/** Required, so an account ID never reads as a workspace's and falls back to defaults. */
|
|
20
|
+
subjectType: 'workspace' | 'user' | 'organization' | 'deployment'
|
|
18
21
|
actorId?: string
|
|
19
22
|
workspaceId?: string
|
|
20
23
|
organizationId?: string
|
|
@@ -57,6 +57,7 @@ function evaluationContext(context: CloudPolicyContext): EvaluationContext {
|
|
|
57
57
|
targetingKey: context.targetingKey,
|
|
58
58
|
deploymentMode: context.deploymentMode
|
|
59
59
|
}
|
|
60
|
+
evaluation.subjectType = context.subjectType
|
|
60
61
|
if (context.actorId) evaluation.actorId = context.actorId
|
|
61
62
|
if (context.workspaceId) evaluation.workspaceId = context.workspaceId
|
|
62
63
|
if (context.organizationId) evaluation.organizationId = context.organizationId
|
|
@@ -28,7 +28,7 @@ export const staticEntitlementsSchema = v.object({
|
|
|
28
28
|
}),
|
|
29
29
|
{}
|
|
30
30
|
),
|
|
31
|
-
|
|
31
|
+
services: v.optional(
|
|
32
32
|
v.object({
|
|
33
33
|
enabled: v.optional(v.boolean()),
|
|
34
34
|
monthlyCreditAllowance: v.optional(nonNegativeIntegerSchema)
|
|
@@ -60,7 +60,7 @@ export const staticEntitlementsTOMLSchema = v.strictObject({
|
|
|
60
60
|
maximum_participants: v.optional(positiveIntegerSchema)
|
|
61
61
|
})
|
|
62
62
|
),
|
|
63
|
-
|
|
63
|
+
services: v.optional(
|
|
64
64
|
v.strictObject({
|
|
65
65
|
enabled: v.optional(v.boolean()),
|
|
66
66
|
monthly_credit_allowance: v.optional(nonNegativeIntegerSchema)
|
|
@@ -7,6 +7,7 @@ import type { Kysely } from 'kysely'
|
|
|
7
7
|
|
|
8
8
|
import { CLOUD_FEATURE_KEYS } from './keys'
|
|
9
9
|
import type { CloudPolicy } from './policy'
|
|
10
|
+
import { workspacePolicyContext } from './workspace'
|
|
10
11
|
|
|
11
12
|
export function createEntitlementService(
|
|
12
13
|
database: Kysely<CloudDatabase>,
|
|
@@ -18,12 +19,12 @@ export function createEntitlementService(
|
|
|
18
19
|
return {
|
|
19
20
|
async workspace(userId: string, workspaceId: string): Promise<WorkspaceEntitlements> {
|
|
20
21
|
if (!(await workspaceRole(database, userId, workspaceId))) throw new DocumentNotFoundError()
|
|
21
|
-
const context =
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
22
|
+
const context = await workspacePolicyContext(
|
|
23
|
+
database,
|
|
24
|
+
{ workspaceId },
|
|
25
|
+
{ actorId: userId, deploymentMode: 'self-hosted' }
|
|
26
|
+
)
|
|
27
|
+
if (!context) throw new DocumentNotFoundError()
|
|
27
28
|
const [
|
|
28
29
|
links,
|
|
29
30
|
guestView,
|
|
@@ -31,7 +32,7 @@ export function createEntitlementService(
|
|
|
31
32
|
guestPresence,
|
|
32
33
|
collaboration,
|
|
33
34
|
revisionHistory,
|
|
34
|
-
|
|
35
|
+
cloudServices,
|
|
35
36
|
maximumFileBytes,
|
|
36
37
|
maximumStorage,
|
|
37
38
|
maximumParticipants,
|
|
@@ -44,7 +45,7 @@ export function createEntitlementService(
|
|
|
44
45
|
policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),
|
|
45
46
|
policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),
|
|
46
47
|
policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),
|
|
47
|
-
policy.boolean(CLOUD_FEATURE_KEYS.
|
|
48
|
+
policy.boolean(CLOUD_FEATURE_KEYS.cloudServices, false, context),
|
|
48
49
|
policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),
|
|
49
50
|
policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),
|
|
50
51
|
policy.number(
|
|
@@ -55,6 +56,8 @@ export function createEntitlementService(
|
|
|
55
56
|
policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context),
|
|
56
57
|
quota.snapshot(workspaceId)
|
|
57
58
|
])
|
|
59
|
+
// The workspace may have gone since its role was read; it has no usage to report then.
|
|
60
|
+
if (!usage) throw new DocumentNotFoundError()
|
|
58
61
|
// Technical limits are ceilings: an entitlement can lower them but never raise them.
|
|
59
62
|
const participants = Math.min(technicalMaximumParticipants, maximumParticipants)
|
|
60
63
|
return {
|
|
@@ -65,7 +68,7 @@ export function createEntitlementService(
|
|
|
65
68
|
guestPresence,
|
|
66
69
|
collaboration,
|
|
67
70
|
revisionHistory,
|
|
68
|
-
|
|
71
|
+
cloudServices
|
|
69
72
|
},
|
|
70
73
|
limits: {
|
|
71
74
|
maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),
|
|
@@ -32,9 +32,9 @@ export function staticEntitlementsFromTOML(
|
|
|
32
32
|
enabled: value.collaboration?.enabled,
|
|
33
33
|
maximumParticipants: value.collaboration?.maximum_participants
|
|
34
34
|
},
|
|
35
|
-
|
|
36
|
-
enabled: value.
|
|
37
|
-
monthlyCreditAllowance: value.
|
|
35
|
+
services: {
|
|
36
|
+
enabled: value.services?.enabled,
|
|
37
|
+
monthlyCreditAllowance: value.services?.monthly_credit_allowance
|
|
38
38
|
}
|
|
39
39
|
})
|
|
40
40
|
}
|
|
@@ -55,8 +55,8 @@ export function staticEntitlementValues(input: unknown): Record<string, boolean
|
|
|
55
55
|
[CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,
|
|
56
56
|
[CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,
|
|
57
57
|
[CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants,
|
|
58
|
-
[CLOUD_FEATURE_KEYS.
|
|
59
|
-
[CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: entitlements.
|
|
58
|
+
[CLOUD_FEATURE_KEYS.cloudServices]: entitlements.services.enabled,
|
|
59
|
+
[CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: entitlements.services.monthlyCreditAllowance
|
|
60
60
|
}
|
|
61
61
|
return pickBy(values, isNotNil) as Record<string, boolean | number>
|
|
62
62
|
}
|