@pairdraw/cloud 0.0.0-stage → 0.16.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.
- package/LICENSE +202 -0
- package/LICENSE-MIT +21 -0
- package/NOTICE +7 -0
- package/README.md +37 -2
- package/dist/bin/ai-relay.d.mts +1 -0
- package/dist/bin/ai-relay.mjs +31 -0
- package/dist/bin/ai-relay.mjs.map +1 -0
- package/dist/bin/server.d.mts +1 -0
- package/dist/bin/server.mjs +29 -0
- package/dist/bin/server.mjs.map +1 -0
- package/dist/client.d.ts +1578 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +2008 -0
- package/dist/client.js.map +1 -0
- package/dist/contract.d.ts +2 -0
- package/dist/contract.js +2 -0
- package/dist/contract2.js +1673 -0
- package/dist/contract2.js.map +1 -0
- package/dist/email.d.ts +155 -0
- package/dist/email.d.ts.map +1 -0
- package/dist/email.js +700 -0
- package/dist/email.js.map +1 -0
- package/dist/index.d.ts +1945 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/listen.mjs +1905 -0
- package/dist/listen.mjs.map +1 -0
- package/dist/runtime-node.d.mts +10715 -0
- package/dist/runtime-node.d.mts.map +1 -0
- package/dist/runtime-node.mjs +32 -0
- package/dist/runtime-node.mjs.map +1 -0
- package/dist/server.d.ts +13772 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +8856 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +8836 -0
- package/dist/server.mjs.map +1 -0
- package/dist/server2.mjs +505 -0
- package/dist/server2.mjs.map +1 -0
- package/package.json +132 -4
- package/src/admin/api/routes.ts +223 -0
- package/src/admin/api/security.ts +12 -0
- package/src/admin/audit/service.ts +138 -0
- package/src/admin/email/service.ts +140 -0
- package/src/admin/enrollment/email.ts +77 -0
- package/src/admin/enrollment/service.ts +308 -0
- package/src/admin/errors.ts +20 -0
- package/src/admin/index.ts +19 -0
- package/src/admin/list.ts +61 -0
- package/src/admin/operations/service.ts +70 -0
- package/src/admin/schema.ts +26 -0
- package/src/admin/users/service.ts +369 -0
- package/src/ai-relay/app.ts +251 -0
- package/src/ai-relay/config.ts +120 -0
- package/src/ai-relay/db/index.ts +10 -0
- package/src/ai-relay/db/migrate.ts +32 -0
- package/src/ai-relay/db/migrations/001_usage.ts +26 -0
- package/src/ai-relay/db/schema.ts +20 -0
- package/src/ai-relay/index.ts +18 -0
- package/src/ai-relay/metering.ts +68 -0
- package/src/ai-relay/usage.ts +115 -0
- package/src/client/ai.ts +96 -0
- package/src/client/api.ts +530 -0
- package/src/client/auth/client.ts +188 -0
- package/src/client/auth/failure.ts +54 -0
- package/src/client/auth/navigation.ts +45 -0
- package/src/client/device-authorization.ts +134 -0
- package/src/client/discovery.ts +105 -0
- package/src/client/images.ts +81 -0
- package/src/client/index.ts +53 -0
- package/src/client/portal/account.ts +183 -0
- package/src/client/portal/administration.ts +130 -0
- package/src/client/portal/client.ts +18 -0
- package/src/client/portal/request.ts +115 -0
- package/src/client/profiles.ts +79 -0
- package/src/client/response.ts +51 -0
- package/src/client/workspaces.ts +142 -0
- package/src/contract/account.ts +204 -0
- package/src/contract/admin/index.ts +187 -0
- package/src/contract/ai.ts +150 -0
- package/src/contract/collaboration.ts +45 -0
- package/src/contract/comments.ts +149 -0
- package/src/contract/discovery.ts +81 -0
- package/src/contract/documents.ts +263 -0
- package/src/contract/entitlements.ts +28 -0
- package/src/contract/index.ts +210 -0
- package/src/contract/links.ts +108 -0
- package/src/contract/portal.ts +11 -0
- package/src/contract/profiles.ts +88 -0
- package/src/contract/relay.ts +370 -0
- package/src/contract/sharing.ts +215 -0
- package/src/contract/versions.ts +87 -0
- package/src/contract/workspaces.ts +100 -0
- package/src/email/index.ts +13 -0
- package/src/email/render.ts +304 -0
- package/src/email/schema.ts +144 -0
- package/src/email/templates/brand.ts +125 -0
- package/src/email/templates/document-invitation.ts +39 -0
- package/src/email/templates/enrollment.ts +30 -0
- package/src/email/templates/layout.ts +20 -0
- package/src/runtime/cloudflare/email.ts +70 -0
- package/src/runtime/cloudflare/environment.ts +57 -0
- package/src/runtime/cloudflare/index.ts +3 -0
- package/src/runtime/cloudflare/relay.ts +136 -0
- package/src/runtime/cloudflare/site.ts +13 -0
- package/src/runtime/cloudflare/tsconfig.json +21 -0
- package/src/runtime/cloudflare/worker.ts +161 -0
- package/src/runtime/node/admin.ts +59 -0
- package/src/runtime/node/ai-relay/main.ts +35 -0
- package/src/runtime/node/ai-relay/server.ts +63 -0
- package/src/runtime/node/application.ts +50 -0
- package/src/runtime/node/bootstrap.ts +22 -0
- package/src/runtime/node/cleanup.ts +24 -0
- package/src/runtime/node/command.ts +17 -0
- package/src/runtime/node/config.ts +16 -0
- package/src/runtime/node/email/runtime.ts +44 -0
- package/src/runtime/node/email/transport.ts +112 -0
- package/src/runtime/node/entitlements/main.ts +41 -0
- package/src/runtime/node/entitlements/refusal.ts +15 -0
- package/src/runtime/node/index.ts +25 -0
- package/src/runtime/node/listen.ts +35 -0
- package/src/runtime/node/main.ts +29 -0
- package/src/runtime/node/migrate.ts +13 -0
- package/src/runtime/node/quota-reconcile.ts +9 -0
- package/src/runtime/node/relay.ts +54 -0
- package/src/runtime/node/server.ts +119 -0
- package/src/runtime/node/site.ts +64 -0
- package/src/runtime/postgres/database.ts +19 -0
- package/src/runtime/s3/objects.ts +244 -0
- package/src/runtime/site/server.ts +82 -0
- package/src/server/account/actions.ts +66 -0
- package/src/server/account/routes.ts +300 -0
- package/src/server/ai/errors.ts +7 -0
- package/src/server/ai/index.ts +4 -0
- package/src/server/ai/keys.ts +43 -0
- package/src/server/ai/routes.ts +43 -0
- package/src/server/ai/service.ts +70 -0
- package/src/server/api/index.ts +8 -0
- package/src/server/api/router.ts +129 -0
- package/src/server/api/types.ts +7 -0
- package/src/server/app.ts +385 -0
- package/src/server/auth/account.ts +73 -0
- package/src/server/auth/activity.ts +213 -0
- package/src/server/auth/adapter.ts +79 -0
- package/src/server/auth/email.ts +125 -0
- package/src/server/auth/endpoints.ts +57 -0
- package/src/server/auth/factory.ts +583 -0
- package/src/server/auth/index.ts +17 -0
- package/src/server/auth/mfa-assurance.ts +55 -0
- package/src/server/auth/runtime.ts +26 -0
- package/src/server/auth/session.ts +19 -0
- package/src/server/auth/social-providers.ts +55 -0
- package/src/server/auth/user-agent.ts +16 -0
- package/src/server/auth/workspace-access.ts +23 -0
- package/src/server/cleanup/configured.ts +38 -0
- package/src/server/cleanup/documents.ts +231 -0
- package/src/server/cleanup/index.ts +29 -0
- package/src/server/cleanup/objects.ts +27 -0
- package/src/server/cleanup/revisions.ts +246 -0
- package/src/server/cleanup/uploads.ts +129 -0
- package/src/server/cleanup/worker.ts +79 -0
- package/src/server/collaboration/index.ts +28 -0
- package/src/server/collaboration/relay/authorize.ts +54 -0
- package/src/server/collaboration/relay/awareness.ts +104 -0
- package/src/server/collaboration/relay/comments.ts +86 -0
- package/src/server/collaboration/relay/documents.ts +39 -0
- package/src/server/collaboration/relay/hub.ts +567 -0
- package/src/server/collaboration/relay/index.ts +15 -0
- package/src/server/collaboration/relay/persistence.ts +48 -0
- package/src/server/collaboration/routes.ts +77 -0
- package/src/server/collaboration/service.ts +190 -0
- package/src/server/config/deployment.ts +178 -0
- package/src/server/config/index.ts +20 -0
- package/src/server/config/limits.ts +8 -0
- package/src/server/config/public.ts +66 -0
- package/src/server/config/schema.ts +512 -0
- package/src/server/db/database.ts +15 -0
- package/src/server/db/expressions.ts +13 -0
- package/src/server/db/index.ts +21 -0
- package/src/server/db/migrate.ts +177 -0
- package/src/server/db/migrations/001_foundation.ts +164 -0
- package/src/server/db/migrations/002_upload_cleanup_claims.ts +34 -0
- package/src/server/db/migrations/003_document_cleanup_claims.ts +23 -0
- package/src/server/db/migrations/004_document_sharing.ts +82 -0
- package/src/server/db/migrations/005_document_collaboration_epoch.ts +13 -0
- package/src/server/db/migrations/006_invitation_continuation.ts +27 -0
- package/src/server/db/migrations/007_collaboration_state.ts +25 -0
- package/src/server/db/migrations/008_storage_reservations.ts +37 -0
- package/src/server/db/migrations/009_workspace_entitlements.ts +22 -0
- package/src/server/db/migrations/010_upload_finalization.ts +22 -0
- package/src/server/db/migrations/011_upload_finalization_lease.ts +12 -0
- package/src/server/db/migrations/012_transactional_email.ts +48 -0
- package/src/server/db/migrations/013_admin_enrollment.ts +54 -0
- package/src/server/db/migrations/014_enrollment_email_kinds.ts +30 -0
- package/src/server/db/migrations/015_cloud_rate_limit.ts +22 -0
- package/src/server/db/migrations/016_auth_schema.ts +16 -0
- package/src/server/db/migrations/017_authentication_email_kinds.ts +32 -0
- package/src/server/db/migrations/018_authentication_mfa.ts +78 -0
- package/src/server/db/migrations/019_better_auth_account_issuer.ts +42 -0
- package/src/server/db/migrations/020_workspace_invitations.ts +57 -0
- package/src/server/db/migrations/021_document_versions.ts +66 -0
- package/src/server/db/migrations/022_entitlement_external_version.ts +17 -0
- package/src/server/db/migrations/023_document_images.ts +61 -0
- package/src/server/db/migrations/024_account_activity.ts +66 -0
- package/src/server/db/migrations/025_table_names.ts +58 -0
- package/src/server/db/migrations/026_user_picture.ts +30 -0
- package/src/server/db/migrations/027_sharing_comments_snapshots_profiles.ts +74 -0
- package/src/server/db/migrations/helpers.ts +78 -0
- package/src/server/db/tables.ts +399 -0
- package/src/server/documents/access.ts +103 -0
- package/src/server/documents/errors.ts +16 -0
- package/src/server/documents/images.ts +405 -0
- package/src/server/documents/index.ts +14 -0
- package/src/server/documents/limits.ts +57 -0
- package/src/server/documents/repository.ts +131 -0
- package/src/server/documents/routes.ts +239 -0
- package/src/server/documents/service.ts +607 -0
- package/src/server/documents/summary.ts +36 -0
- package/src/server/documents/types.ts +13 -0
- package/src/server/documents/versions/checkpoint.ts +98 -0
- package/src/server/documents/versions/history.ts +25 -0
- package/src/server/documents/versions/index.ts +4 -0
- package/src/server/documents/versions/routes.ts +112 -0
- package/src/server/documents/versions/service.ts +396 -0
- package/src/server/email/crypto.ts +57 -0
- package/src/server/email/index.ts +18 -0
- package/src/server/email/invitations.ts +30 -0
- package/src/server/email/service.ts +247 -0
- package/src/server/email/types.ts +56 -0
- package/src/server/email/worker.ts +33 -0
- package/src/server/index.ts +288 -0
- package/src/server/internal/index.ts +8 -0
- package/src/server/internal/routes.ts +41 -0
- package/src/server/internal/schema.ts +10 -0
- package/src/server/internal/service.ts +44 -0
- package/src/server/invitations/index.ts +6 -0
- package/src/server/invitations/types.ts +30 -0
- package/src/server/objects/index.ts +16 -0
- package/src/server/objects/types.ts +81 -0
- package/src/server/pictures/index.ts +9 -0
- package/src/server/pictures/provider.ts +61 -0
- package/src/server/pictures/routes.ts +21 -0
- package/src/server/pictures/service.ts +235 -0
- package/src/server/policy/configured.ts +23 -0
- package/src/server/policy/database.ts +108 -0
- package/src/server/policy/entitlements.ts +29 -0
- package/src/server/policy/index.ts +17 -0
- package/src/server/policy/keys.ts +23 -0
- package/src/server/policy/policy.ts +117 -0
- package/src/server/policy/provider.ts +67 -0
- package/src/server/policy/schema.ts +69 -0
- package/src/server/policy/service.ts +85 -0
- package/src/server/policy/static.ts +62 -0
- package/src/server/profiles/index.ts +12 -0
- package/src/server/profiles/routes.ts +103 -0
- package/src/server/profiles/service.ts +266 -0
- package/src/server/quota/index.ts +7 -0
- package/src/server/quota/reconcile.ts +61 -0
- package/src/server/quota/storage.ts +165 -0
- package/src/server/rate-limit/cleanup.ts +16 -0
- package/src/server/rate-limit/index.ts +12 -0
- package/src/server/rate-limit/keys.ts +38 -0
- package/src/server/rate-limit/middleware.ts +137 -0
- package/src/server/rate-limit/postgres.ts +79 -0
- package/src/server/sharing/access.ts +29 -0
- package/src/server/sharing/actor.ts +12 -0
- package/src/server/sharing/capabilities/service.ts +318 -0
- package/src/server/sharing/continuation.ts +83 -0
- package/src/server/sharing/contracts.ts +82 -0
- package/src/server/sharing/crypto.ts +48 -0
- package/src/server/sharing/document-routes.ts +41 -0
- package/src/server/sharing/errors.ts +20 -0
- package/src/server/sharing/grants/service.ts +79 -0
- package/src/server/sharing/http.ts +45 -0
- package/src/server/sharing/index.ts +40 -0
- package/src/server/sharing/invitations/service.ts +315 -0
- package/src/server/sharing/policy.ts +42 -0
- package/src/server/sharing/routes.ts +251 -0
- package/src/server/sharing/service.ts +117 -0
- package/src/server/validation.ts +24 -0
- package/src/server/worker/interval.ts +23 -0
- package/src/server/worker/periodic.ts +42 -0
- package/src/server/workspaces/index.ts +16 -0
- package/src/server/workspaces/members.ts +502 -0
- package/src/server/workspaces/repository.ts +91 -0
- package/src/server/workspaces/routes.ts +198 -0
- package/src/server/workspaces/service.ts +84 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { CloudAPIEnvironment } from '#cloud/server/api/types'
|
|
2
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import type { Context, Env, Input } from 'hono'
|
|
4
|
+
import { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'
|
|
5
|
+
import { matchedRoutes } from 'hono/route'
|
|
6
|
+
import type { Kysely } from 'kysely'
|
|
7
|
+
|
|
8
|
+
import { trustedClientIP, type ClientIdentityOptions } from './keys'
|
|
9
|
+
import { PostgresRateLimitStore } from './postgres'
|
|
10
|
+
|
|
11
|
+
export type RateLimitPolicy = {
|
|
12
|
+
namespace: string
|
|
13
|
+
windowMs: number
|
|
14
|
+
limit: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const CLOUD_RATE_LIMITS = {
|
|
18
|
+
publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },
|
|
19
|
+
collaborationTicket: { namespace: 'collaboration-ticket', windowMs: 60_000, limit: 60 },
|
|
20
|
+
invitationMutation: { namespace: 'invitation-mutation', windowMs: 60_000, limit: 30 },
|
|
21
|
+
workspaceCreation: { namespace: 'workspace-creation', windowMs: 60_000, limit: 30 },
|
|
22
|
+
documentCreation: { namespace: 'document-creation', windowMs: 60_000, limit: 60 },
|
|
23
|
+
uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120 },
|
|
24
|
+
authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },
|
|
25
|
+
aiToken: { namespace: 'ai-token', windowMs: 60_000, limit: 30 },
|
|
26
|
+
adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },
|
|
27
|
+
adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }
|
|
28
|
+
} as const satisfies Record<string, RateLimitPolicy>
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The limiters routes mount for their own budget, each with which requests it counts. A general
|
|
32
|
+
* limiter leaves those requests to it rather than counting them twice; the routes themselves say
|
|
33
|
+
* which have one, so the general limiter never matches paths.
|
|
34
|
+
*/
|
|
35
|
+
const routeBudgets = new WeakMap<object, (context: Context) => boolean>()
|
|
36
|
+
|
|
37
|
+
/** Whether a limiter the request's route mounts for its own budget counts this request. */
|
|
38
|
+
export function routeHasOwnBudget(context: Context): boolean {
|
|
39
|
+
return matchedRoutes(context).some((route) => routeBudgets.get(route.handler)?.(context))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function ownBudget<Limiter extends object>(
|
|
43
|
+
limiter: Limiter,
|
|
44
|
+
skip?: (context: Context) => boolean
|
|
45
|
+
): Limiter {
|
|
46
|
+
routeBudgets.set(limiter, (context) => !skip?.(context))
|
|
47
|
+
return limiter
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type RateLimitOptions<E extends Env, P extends string, I extends Input> = {
|
|
51
|
+
database: Kysely<CloudDatabase>
|
|
52
|
+
secret: string
|
|
53
|
+
policy: RateLimitPolicy
|
|
54
|
+
keyGenerator(context: Context<E, P, I>): string
|
|
55
|
+
handler?: RateLimitExceededEventHandler<E, P, I>
|
|
56
|
+
skip?: (context: Context<E, P, I>) => boolean
|
|
57
|
+
standardHeaders?: boolean | 'draft-6' | 'draft-7'
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createCloudRateLimiter<
|
|
61
|
+
E extends Env = Env,
|
|
62
|
+
P extends string = string,
|
|
63
|
+
I extends Input = Input
|
|
64
|
+
>(options: RateLimitOptions<E, P, I>) {
|
|
65
|
+
return rateLimiter<E, P, I>({
|
|
66
|
+
windowMs: options.policy.windowMs,
|
|
67
|
+
limit: options.policy.limit,
|
|
68
|
+
standardHeaders: options.standardHeaders ?? 'draft-7',
|
|
69
|
+
store: new PostgresRateLimitStore(options.database, options.secret, options.policy.namespace),
|
|
70
|
+
keyGenerator: (context) => options.keyGenerator(context),
|
|
71
|
+
handler: options.handler
|
|
72
|
+
? (context, next, used) => options.handler?.(context, next, used)
|
|
73
|
+
: undefined,
|
|
74
|
+
skip: options.skip
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function createTrustedIPRateLimiter(
|
|
79
|
+
database: Kysely<CloudDatabase>,
|
|
80
|
+
secret: string,
|
|
81
|
+
policy: RateLimitPolicy,
|
|
82
|
+
client: ClientIdentityOptions,
|
|
83
|
+
handler?: RateLimitExceededEventHandler,
|
|
84
|
+
options?: {
|
|
85
|
+
resource?: (context: Context) => string
|
|
86
|
+
skip?: (context: Context) => boolean
|
|
87
|
+
/** The limiter is a route's own budget, which general limiters leave to it. */
|
|
88
|
+
route?: boolean
|
|
89
|
+
}
|
|
90
|
+
) {
|
|
91
|
+
const limiter = createCloudRateLimiter({
|
|
92
|
+
database,
|
|
93
|
+
secret,
|
|
94
|
+
policy,
|
|
95
|
+
keyGenerator: (context) => {
|
|
96
|
+
const ip = trustedClientIP(context, client) ?? 'unavailable'
|
|
97
|
+
return options?.resource ? `resource:${options.resource(context)}:ip:${ip}` : `ip:${ip}`
|
|
98
|
+
},
|
|
99
|
+
skip: (context) =>
|
|
100
|
+
trustedClientIP(context, client) === null || Boolean(options?.skip?.(context)),
|
|
101
|
+
handler
|
|
102
|
+
})
|
|
103
|
+
return options?.route ? ownBudget(limiter, options.skip) : limiter
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function createActorRateLimiter(
|
|
107
|
+
database: Kysely<CloudDatabase>,
|
|
108
|
+
secret: string,
|
|
109
|
+
policy: RateLimitPolicy,
|
|
110
|
+
skip?: (context: Context) => boolean,
|
|
111
|
+
resource?: (context: Context<CloudAPIEnvironment, '*'>) => string
|
|
112
|
+
) {
|
|
113
|
+
return createCloudRateLimiter<CloudAPIEnvironment, '*'>({
|
|
114
|
+
database,
|
|
115
|
+
secret,
|
|
116
|
+
policy,
|
|
117
|
+
keyGenerator: (context) =>
|
|
118
|
+
resource
|
|
119
|
+
? `resource:${resource(context)}:actor:${context.get('actor').userId}`
|
|
120
|
+
: `actor:${context.get('actor').userId}`,
|
|
121
|
+
skip
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A limiter a route mounts for its own budget, such as document creation; general limiters leave
|
|
127
|
+
* the requests it counts to it.
|
|
128
|
+
*/
|
|
129
|
+
export function createRouteRateLimiter(
|
|
130
|
+
database: Kysely<CloudDatabase>,
|
|
131
|
+
secret: string,
|
|
132
|
+
policy: RateLimitPolicy,
|
|
133
|
+
skip?: (context: Context) => boolean,
|
|
134
|
+
resource?: (context: Context<CloudAPIEnvironment, '*'>) => string
|
|
135
|
+
) {
|
|
136
|
+
return ownBudget(createActorRateLimiter(database, secret, policy, skip, resource), skip)
|
|
137
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
2
|
+
import { sha256 } from '@noble/hashes/sha2.js'
|
|
3
|
+
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'
|
|
4
|
+
import type { ClientRateLimitInfo, Store } from 'hono-rate-limiter'
|
|
5
|
+
import type { Kysely } from 'kysely'
|
|
6
|
+
|
|
7
|
+
export class PostgresRateLimitStore implements Store {
|
|
8
|
+
readonly localKeys = false
|
|
9
|
+
readonly prefix: string
|
|
10
|
+
private windowMs = 60_000
|
|
11
|
+
|
|
12
|
+
constructor(
|
|
13
|
+
private readonly database: Kysely<CloudDatabase>,
|
|
14
|
+
private readonly secret: string,
|
|
15
|
+
namespace: string,
|
|
16
|
+
options: { windowMs?: number } = {}
|
|
17
|
+
) {
|
|
18
|
+
this.prefix = `${namespace}:`
|
|
19
|
+
this.windowMs = options.windowMs ?? this.windowMs
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
init(options: { windowMs: number }): void {
|
|
23
|
+
this.windowMs = options.windowMs
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
private hash(key: string): string {
|
|
27
|
+
return bytesToHex(sha256(utf8ToBytes(`${this.secret}:${this.prefix}:${key}`)))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async increment(key: string): Promise<ClientRateLimitInfo> {
|
|
31
|
+
const now = new Date()
|
|
32
|
+
const resetTime = new Date(
|
|
33
|
+
Math.floor(now.getTime() / this.windowMs) * this.windowMs + this.windowMs
|
|
34
|
+
)
|
|
35
|
+
const row = await this.database
|
|
36
|
+
.insertInto('apiRateLimit')
|
|
37
|
+
.values({
|
|
38
|
+
keyHash: this.hash(key),
|
|
39
|
+
windowStartedAt: new Date(resetTime.getTime() - this.windowMs),
|
|
40
|
+
requestCount: 1,
|
|
41
|
+
updatedAt: now
|
|
42
|
+
})
|
|
43
|
+
.onConflict((conflict) =>
|
|
44
|
+
conflict.column('keyHash').doUpdateSet((expression) => ({
|
|
45
|
+
requestCount: expression
|
|
46
|
+
.case()
|
|
47
|
+
.whenRef('apiRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')
|
|
48
|
+
.then(expression('apiRateLimit.requestCount', '+', 1))
|
|
49
|
+
.else(1)
|
|
50
|
+
.end(),
|
|
51
|
+
windowStartedAt: expression.ref('excluded.windowStartedAt'),
|
|
52
|
+
updatedAt: expression.ref('excluded.updatedAt')
|
|
53
|
+
}))
|
|
54
|
+
)
|
|
55
|
+
.returning(['requestCount', 'windowStartedAt'])
|
|
56
|
+
.executeTakeFirstOrThrow()
|
|
57
|
+
return {
|
|
58
|
+
totalHits: Number(row.requestCount),
|
|
59
|
+
resetTime: new Date(new Date(row.windowStartedAt).getTime() + this.windowMs)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async decrement(key: string): Promise<void> {
|
|
64
|
+
await this.database
|
|
65
|
+
.updateTable('apiRateLimit')
|
|
66
|
+
.set((expression) => ({
|
|
67
|
+
requestCount: expression.fn('greatest', [
|
|
68
|
+
expression('requestCount', '-', 1),
|
|
69
|
+
expression.val(0)
|
|
70
|
+
])
|
|
71
|
+
}))
|
|
72
|
+
.where('keyHash', '=', this.hash(key))
|
|
73
|
+
.execute()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async resetKey(key: string): Promise<void> {
|
|
77
|
+
await this.database.deleteFrom('apiRateLimit').where('keyHash', '=', this.hash(key)).execute()
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
2
|
+
import { resolveDocumentAccess } from '#cloud/server/documents/access'
|
|
3
|
+
import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'
|
|
4
|
+
import type { Kysely } from 'kysely'
|
|
5
|
+
|
|
6
|
+
export async function requireSharingAccess(
|
|
7
|
+
database: Kysely<CloudDatabase>,
|
|
8
|
+
userId: string,
|
|
9
|
+
documentId: string
|
|
10
|
+
): Promise<void> {
|
|
11
|
+
const access = await resolveDocumentAccess(database, userId, documentId)
|
|
12
|
+
if (!access) throw new DocumentNotFoundError()
|
|
13
|
+
if (!access.canManageSharing) throw new DocumentForbiddenError()
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Ends every collaboration ticket and room key issued for the document so far: removing someone's
|
|
18
|
+
* access must also remove them from its live room.
|
|
19
|
+
*/
|
|
20
|
+
export async function advanceCollaborationEpoch(
|
|
21
|
+
database: Kysely<CloudDatabase>,
|
|
22
|
+
documentId: string
|
|
23
|
+
): Promise<void> {
|
|
24
|
+
await database
|
|
25
|
+
.updateTable('document')
|
|
26
|
+
.set({ collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1) })
|
|
27
|
+
.where('id', '=', documentId)
|
|
28
|
+
.executeTakeFirst()
|
|
29
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Who follows a link: the person signed in to the server, if any, whom the server lets in where
|
|
5
|
+
* it turns guests away.
|
|
6
|
+
*/
|
|
7
|
+
export async function shareActor(
|
|
8
|
+
request: Request,
|
|
9
|
+
resolveSession?: CloudSessionResolver
|
|
10
|
+
): Promise<CloudActor | undefined> {
|
|
11
|
+
return resolveSession ? ((await resolveSession(request)) ?? undefined) : undefined
|
|
12
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CreateDocumentShareInput,
|
|
3
|
+
DocumentPermission,
|
|
4
|
+
DocumentShare,
|
|
5
|
+
ResolveDocumentShareInput,
|
|
6
|
+
ShareSnapshot,
|
|
7
|
+
UpdateDocumentShareInput
|
|
8
|
+
} from '#cloud/contract'
|
|
9
|
+
import type { CloudActor } from '#cloud/server/auth'
|
|
10
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
11
|
+
import { DocumentNotFoundError } from '#cloud/server/documents/errors'
|
|
12
|
+
import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
|
|
13
|
+
import type { CloudPolicy } from '#cloud/server/policy/policy'
|
|
14
|
+
import type { Kysely, Transaction, UpdateObject } from 'kysely'
|
|
15
|
+
|
|
16
|
+
import { randomHex } from '@pairdraw/scene-graph/random'
|
|
17
|
+
|
|
18
|
+
import { advanceCollaborationEpoch, requireSharingAccess } from '../access'
|
|
19
|
+
import { shareContract } from '../contracts'
|
|
20
|
+
import { capabilityHashMatches, hashCapability } from '../crypto'
|
|
21
|
+
import {
|
|
22
|
+
DocumentShareInvalidError,
|
|
23
|
+
DocumentShareKindError,
|
|
24
|
+
DocumentShareSignInRequiredError
|
|
25
|
+
} from '../errors'
|
|
26
|
+
import { createSharingPolicy } from '../policy'
|
|
27
|
+
|
|
28
|
+
const SHARE_SECRET_BYTES = 24
|
|
29
|
+
|
|
30
|
+
export type DocumentShareCapability = {
|
|
31
|
+
share: DocumentShare
|
|
32
|
+
secret: string
|
|
33
|
+
path: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type ResolvedSharePrincipal =
|
|
37
|
+
| { kind: 'user'; userId: string; name: string; email: string }
|
|
38
|
+
| { kind: 'guest'; guestId: string; name: string }
|
|
39
|
+
|
|
40
|
+
export type ResolvedDocumentShare = {
|
|
41
|
+
documentId: string
|
|
42
|
+
permission: DocumentPermission
|
|
43
|
+
principal: ResolvedSharePrincipal
|
|
44
|
+
roomEpoch: number
|
|
45
|
+
/** The revision a snapshot link shows; null for a live link. */
|
|
46
|
+
revisionId: string | null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type CapabilityServiceOptions = {
|
|
50
|
+
policy?: CloudPolicy
|
|
51
|
+
deploymentMode?: 'official' | 'self-hosted'
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The revision a snapshot pins: the document's current one, or one of its own revisions. Anything
|
|
56
|
+
* else, as a document with no revision yet, cannot be shared as a snapshot.
|
|
57
|
+
*/
|
|
58
|
+
async function snapshotRevision(
|
|
59
|
+
database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,
|
|
60
|
+
documentId: string,
|
|
61
|
+
snapshot: ShareSnapshot
|
|
62
|
+
): Promise<string> {
|
|
63
|
+
if (snapshot === 'current') {
|
|
64
|
+
const document = await database
|
|
65
|
+
.selectFrom('document')
|
|
66
|
+
.select('currentRevisionId')
|
|
67
|
+
.where('id', '=', documentId)
|
|
68
|
+
.executeTakeFirst()
|
|
69
|
+
if (!document?.currentRevisionId) throw new DocumentShareKindError()
|
|
70
|
+
return document.currentRevisionId
|
|
71
|
+
}
|
|
72
|
+
const revision = await database
|
|
73
|
+
.selectFrom('documentRevision')
|
|
74
|
+
.select('id')
|
|
75
|
+
.where('id', '=', snapshot)
|
|
76
|
+
.where('documentId', '=', documentId)
|
|
77
|
+
.executeTakeFirst()
|
|
78
|
+
if (!revision) throw new DocumentShareKindError()
|
|
79
|
+
return revision.id
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createCapabilityService(
|
|
83
|
+
database: Kysely<CloudDatabase>,
|
|
84
|
+
options: CapabilityServiceOptions
|
|
85
|
+
) {
|
|
86
|
+
const sharingPolicy = createSharingPolicy(database, options)
|
|
87
|
+
|
|
88
|
+
async function updateActiveShare(
|
|
89
|
+
userId: string,
|
|
90
|
+
documentId: string,
|
|
91
|
+
shareId: string,
|
|
92
|
+
changes: UpdateObject<CloudDatabase, 'documentShare'>
|
|
93
|
+
) {
|
|
94
|
+
await requireSharingAccess(database, userId, documentId)
|
|
95
|
+
const row = await database
|
|
96
|
+
.updateTable('documentShare')
|
|
97
|
+
.set(changes)
|
|
98
|
+
.where('id', '=', shareId)
|
|
99
|
+
.where('documentId', '=', documentId)
|
|
100
|
+
.where('revokedAt', 'is', null)
|
|
101
|
+
.returningAll()
|
|
102
|
+
.executeTakeFirst()
|
|
103
|
+
if (!row) throw new DocumentNotFoundError()
|
|
104
|
+
return row
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
async listShares(userId: string, documentId: string): Promise<DocumentShare[]> {
|
|
109
|
+
await requireSharingAccess(database, userId, documentId)
|
|
110
|
+
const rows = await database
|
|
111
|
+
.selectFrom('documentShare')
|
|
112
|
+
.selectAll()
|
|
113
|
+
.where('documentId', '=', documentId)
|
|
114
|
+
.where('revokedAt', 'is', null)
|
|
115
|
+
.orderBy('createdAt', 'desc')
|
|
116
|
+
.execute()
|
|
117
|
+
return rows.map(shareContract)
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
async createShare(
|
|
121
|
+
userId: string,
|
|
122
|
+
documentId: string,
|
|
123
|
+
input: CreateDocumentShareInput
|
|
124
|
+
): Promise<DocumentShareCapability> {
|
|
125
|
+
await requireSharingAccess(database, userId, documentId)
|
|
126
|
+
await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })
|
|
127
|
+
const id = crypto.randomUUID()
|
|
128
|
+
const secret = randomHex(SHARE_SECRET_BYTES)
|
|
129
|
+
const row = await database.transaction().execute(async (transaction) => {
|
|
130
|
+
const document = await transaction
|
|
131
|
+
.selectFrom('document')
|
|
132
|
+
.select('collaborationEpoch')
|
|
133
|
+
.where('id', '=', documentId)
|
|
134
|
+
.forUpdate()
|
|
135
|
+
.executeTakeFirstOrThrow()
|
|
136
|
+
const revisionId = input.snapshot
|
|
137
|
+
? await snapshotRevision(transaction, documentId, input.snapshot)
|
|
138
|
+
: null
|
|
139
|
+
return transaction
|
|
140
|
+
.insertInto('documentShare')
|
|
141
|
+
.values({
|
|
142
|
+
id,
|
|
143
|
+
documentId,
|
|
144
|
+
// A snapshot shows a frozen revision, so it only ever lets people look.
|
|
145
|
+
permission: revisionId ? 'view' : input.permission,
|
|
146
|
+
secretHash: hashCapability(secret),
|
|
147
|
+
roomEpoch: document.collaborationEpoch,
|
|
148
|
+
createdBy: userId,
|
|
149
|
+
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
|
|
150
|
+
revokedAt: null,
|
|
151
|
+
lastUsedAt: null,
|
|
152
|
+
revisionId
|
|
153
|
+
})
|
|
154
|
+
.returningAll()
|
|
155
|
+
.executeTakeFirstOrThrow()
|
|
156
|
+
})
|
|
157
|
+
return { share: shareContract(row), secret, path: `/share/${id}#${secret}` }
|
|
158
|
+
},
|
|
159
|
+
|
|
160
|
+
async updateShare(
|
|
161
|
+
userId: string,
|
|
162
|
+
documentId: string,
|
|
163
|
+
shareId: string,
|
|
164
|
+
input: UpdateDocumentShareInput
|
|
165
|
+
): Promise<DocumentShare> {
|
|
166
|
+
// Authorization comes first, so a caller without access learns nothing about the share
|
|
167
|
+
// or the document's link policy.
|
|
168
|
+
await requireSharingAccess(database, userId, documentId)
|
|
169
|
+
const current = await database
|
|
170
|
+
.selectFrom('documentShare')
|
|
171
|
+
.select(['id', 'revisionId'])
|
|
172
|
+
.where('id', '=', shareId)
|
|
173
|
+
.where('documentId', '=', documentId)
|
|
174
|
+
.where('revokedAt', 'is', null)
|
|
175
|
+
.executeTakeFirst()
|
|
176
|
+
if (!current) throw new DocumentNotFoundError()
|
|
177
|
+
await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })
|
|
178
|
+
const snapshot = current.revisionId !== null
|
|
179
|
+
if (input.snapshot !== undefined && !snapshot) throw new DocumentShareKindError()
|
|
180
|
+
if (snapshot && input.permission !== undefined && input.permission !== 'view') {
|
|
181
|
+
throw new DocumentShareKindError()
|
|
182
|
+
}
|
|
183
|
+
const changes: UpdateObject<CloudDatabase, 'documentShare'> = { updatedAt: new Date() }
|
|
184
|
+
if (input.permission) changes.permission = input.permission
|
|
185
|
+
// Update snapshot: the same link shows the revision named now.
|
|
186
|
+
if (input.snapshot !== undefined) {
|
|
187
|
+
changes.revisionId = await snapshotRevision(database, documentId, input.snapshot)
|
|
188
|
+
}
|
|
189
|
+
if (input.expiresAt !== undefined) {
|
|
190
|
+
changes.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null
|
|
191
|
+
}
|
|
192
|
+
const row = await updateActiveShare(userId, documentId, shareId, changes)
|
|
193
|
+
return shareContract(row)
|
|
194
|
+
},
|
|
195
|
+
|
|
196
|
+
async rotateShare(
|
|
197
|
+
userId: string,
|
|
198
|
+
documentId: string,
|
|
199
|
+
shareId: string
|
|
200
|
+
): Promise<DocumentShareCapability> {
|
|
201
|
+
const secret = randomHex(SHARE_SECRET_BYTES)
|
|
202
|
+
const row = await database.transaction().execute(async (transaction) => {
|
|
203
|
+
await requireSharingAccess(transaction, userId, documentId)
|
|
204
|
+
const document = await transaction
|
|
205
|
+
.selectFrom('document')
|
|
206
|
+
.select('collaborationEpoch')
|
|
207
|
+
.where('id', '=', documentId)
|
|
208
|
+
.forUpdate()
|
|
209
|
+
.executeTakeFirstOrThrow()
|
|
210
|
+
const updated = await transaction
|
|
211
|
+
.updateTable('documentShare')
|
|
212
|
+
.set({
|
|
213
|
+
secretHash: hashCapability(secret),
|
|
214
|
+
roomEpoch: document.collaborationEpoch,
|
|
215
|
+
updatedAt: new Date()
|
|
216
|
+
})
|
|
217
|
+
.where('id', '=', shareId)
|
|
218
|
+
.where('documentId', '=', documentId)
|
|
219
|
+
.where('revokedAt', 'is', null)
|
|
220
|
+
.returningAll()
|
|
221
|
+
.executeTakeFirst()
|
|
222
|
+
if (!updated) throw new DocumentNotFoundError()
|
|
223
|
+
return updated
|
|
224
|
+
})
|
|
225
|
+
return { share: shareContract(row), secret, path: `/share/${shareId}#${secret}` }
|
|
226
|
+
},
|
|
227
|
+
|
|
228
|
+
async revokeShare(userId: string, documentId: string, shareId: string): Promise<void> {
|
|
229
|
+
await database.transaction().execute(async (transaction) => {
|
|
230
|
+
await requireSharingAccess(transaction, userId, documentId)
|
|
231
|
+
const revoked = await transaction
|
|
232
|
+
.updateTable('documentShare')
|
|
233
|
+
.set({ revokedAt: new Date(), updatedAt: new Date() })
|
|
234
|
+
.where('id', '=', shareId)
|
|
235
|
+
.where('documentId', '=', documentId)
|
|
236
|
+
.where('revokedAt', 'is', null)
|
|
237
|
+
.returning('revisionId')
|
|
238
|
+
.executeTakeFirst()
|
|
239
|
+
if (!revoked) throw new DocumentNotFoundError()
|
|
240
|
+
// Nobody joins the room through a snapshot link, so its room carries on undisturbed.
|
|
241
|
+
if (revoked.revisionId === null) await advanceCollaborationEpoch(transaction, documentId)
|
|
242
|
+
})
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
async resolveShare(
|
|
246
|
+
shareId: string,
|
|
247
|
+
input: ResolveDocumentShareInput,
|
|
248
|
+
actor?: CloudActor
|
|
249
|
+
): Promise<ResolvedDocumentShare> {
|
|
250
|
+
const row = await database
|
|
251
|
+
.selectFrom('documentShare')
|
|
252
|
+
.innerJoin('document', 'document.id', 'documentShare.documentId')
|
|
253
|
+
.select([
|
|
254
|
+
'documentShare.id',
|
|
255
|
+
'documentShare.documentId',
|
|
256
|
+
'documentShare.permission',
|
|
257
|
+
'documentShare.secretHash',
|
|
258
|
+
'documentShare.roomEpoch',
|
|
259
|
+
'documentShare.expiresAt',
|
|
260
|
+
'documentShare.revisionId'
|
|
261
|
+
])
|
|
262
|
+
.where('documentShare.id', '=', shareId)
|
|
263
|
+
.where('documentShare.revokedAt', 'is', null)
|
|
264
|
+
.where('document.deletedAt', 'is', null)
|
|
265
|
+
.executeTakeFirst()
|
|
266
|
+
if (
|
|
267
|
+
!row ||
|
|
268
|
+
!capabilityHashMatches(row.secretHash, input.secret) ||
|
|
269
|
+
(row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now())
|
|
270
|
+
) {
|
|
271
|
+
throw new DocumentShareInvalidError()
|
|
272
|
+
}
|
|
273
|
+
if (!actor && options.policy) {
|
|
274
|
+
const document = await database
|
|
275
|
+
.selectFrom('document')
|
|
276
|
+
.select('workspaceId')
|
|
277
|
+
.where('id', '=', row.documentId)
|
|
278
|
+
.executeTakeFirstOrThrow()
|
|
279
|
+
// Commenting is looking with a say: guests who may view a link may comment through it.
|
|
280
|
+
const featureKey =
|
|
281
|
+
row.permission === 'edit' ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView
|
|
282
|
+
if (
|
|
283
|
+
!(await options.policy.boolean(featureKey, false, {
|
|
284
|
+
targetingKey: document.workspaceId,
|
|
285
|
+
workspaceId: document.workspaceId,
|
|
286
|
+
documentId: row.documentId,
|
|
287
|
+
deploymentMode: options.deploymentMode ?? 'self-hosted'
|
|
288
|
+
}))
|
|
289
|
+
) {
|
|
290
|
+
// Guests are not let in here; people signed in to the server are.
|
|
291
|
+
throw new DocumentShareSignInRequiredError()
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
await database
|
|
295
|
+
.updateTable('documentShare')
|
|
296
|
+
.set({ lastUsedAt: new Date() })
|
|
297
|
+
.where('id', '=', shareId)
|
|
298
|
+
.execute()
|
|
299
|
+
return {
|
|
300
|
+
documentId: row.documentId,
|
|
301
|
+
permission: row.permission,
|
|
302
|
+
principal: actor
|
|
303
|
+
? { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email }
|
|
304
|
+
: // A guest goes by the name they chose: it labels their presence and comments,
|
|
305
|
+
// and proves nothing about who they are.
|
|
306
|
+
{
|
|
307
|
+
kind: 'guest',
|
|
308
|
+
guestId: input.guestId ?? crypto.randomUUID(),
|
|
309
|
+
name: input.guestName ?? 'Guest'
|
|
310
|
+
},
|
|
311
|
+
roomEpoch: row.roomEpoch,
|
|
312
|
+
revisionId: row.revisionId
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export type CapabilityService = ReturnType<typeof createCapabilityService>
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { InvitationPreview } from '#cloud/contract'
|
|
2
|
+
import type { CloudActor } from '#cloud/server/auth'
|
|
3
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
4
|
+
import { DocumentShareInvalidError } from '#cloud/server/sharing/errors'
|
|
5
|
+
import type { Kysely } from 'kysely'
|
|
6
|
+
|
|
7
|
+
import { capabilityHashMatches, decryptContinuationToken, encryptContinuationToken } from './crypto'
|
|
8
|
+
|
|
9
|
+
const CONTINUATION_LIFETIME_MS = 10 * 60_000
|
|
10
|
+
|
|
11
|
+
export function createInvitationContinuationService(
|
|
12
|
+
database: Kysely<CloudDatabase>,
|
|
13
|
+
secret: string,
|
|
14
|
+
validateInvitation: (invitationId: string, token: string) => Promise<InvitationPreview>
|
|
15
|
+
) {
|
|
16
|
+
return {
|
|
17
|
+
async create(input: { invitationId: string; token: string }): Promise<{ id: string }> {
|
|
18
|
+
await validateInvitation(input.invitationId, input.token)
|
|
19
|
+
const id = crypto.randomUUID()
|
|
20
|
+
await database
|
|
21
|
+
.insertInto('invitationContinuation')
|
|
22
|
+
.values({
|
|
23
|
+
id,
|
|
24
|
+
invitationId: input.invitationId,
|
|
25
|
+
tokenEncrypted: await encryptContinuationToken(secret, input.token),
|
|
26
|
+
expiresAt: new Date(Date.now() + CONTINUATION_LIFETIME_MS),
|
|
27
|
+
consumedAt: null
|
|
28
|
+
})
|
|
29
|
+
.execute()
|
|
30
|
+
return { id }
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
async consume(id: string): Promise<{ invitationId: string; token: string }> {
|
|
34
|
+
return database.transaction().execute(async (transaction) => {
|
|
35
|
+
const row = await transaction
|
|
36
|
+
.selectFrom('invitationContinuation')
|
|
37
|
+
.select(['invitationId', 'tokenEncrypted', 'expiresAt', 'consumedAt'])
|
|
38
|
+
.where('id', '=', id)
|
|
39
|
+
.forUpdate()
|
|
40
|
+
.executeTakeFirst()
|
|
41
|
+
if (!row || row.consumedAt || new Date(row.expiresAt).getTime() <= Date.now()) {
|
|
42
|
+
throw new DocumentShareInvalidError()
|
|
43
|
+
}
|
|
44
|
+
await transaction
|
|
45
|
+
.updateTable('invitationContinuation')
|
|
46
|
+
.set({ consumedAt: new Date() })
|
|
47
|
+
.where('id', '=', id)
|
|
48
|
+
.execute()
|
|
49
|
+
return {
|
|
50
|
+
invitationId: row.invitationId,
|
|
51
|
+
token: await decryptContinuationToken(secret, row.tokenEncrypted)
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function invitationTokenIsActive(
|
|
59
|
+
invitation: {
|
|
60
|
+
tokenHash: string
|
|
61
|
+
expiresAt: Date | string
|
|
62
|
+
acceptedAt: Date | string | null
|
|
63
|
+
revokedAt: Date | string | null
|
|
64
|
+
},
|
|
65
|
+
token: string
|
|
66
|
+
): boolean {
|
|
67
|
+
return (
|
|
68
|
+
capabilityHashMatches(invitation.tokenHash, token) &&
|
|
69
|
+
!invitation.acceptedAt &&
|
|
70
|
+
!invitation.revokedAt &&
|
|
71
|
+
new Date(invitation.expiresAt).getTime() > Date.now()
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function recipientHint(email: string): string {
|
|
76
|
+
const [local = '', domain = ''] = email.split('@')
|
|
77
|
+
const visible = local.slice(0, 2)
|
|
78
|
+
return `${visible}${'*'.repeat(Math.max(3, local.length - visible.length))}@${domain}`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function invitationMatchesActor(actor: CloudActor, email: string): boolean {
|
|
82
|
+
return email === actor.email.trim().toLowerCase()
|
|
83
|
+
}
|