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