@open-pencil/cloud 0.17.0-beta.4 → 0.17.0-beta.6
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 +2 -1
- package/dist/bin/server.mjs +1 -1
- package/dist/bin/server.mjs.map +1 -1
- package/dist/bin/services.mjs +1 -1
- package/dist/bin/services.mjs.map +1 -1
- package/dist/client.d.ts +783 -47
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +1651 -382
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +701 -45
- package/dist/contract2.js.map +1 -1
- package/dist/email.d.ts +2138 -34
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +4343 -306
- package/dist/email.js.map +1 -1
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +61 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +1338 -44
- package/dist/index.d.ts.map +1 -1
- package/dist/index2.d.ts +45 -0
- package/dist/index2.d.ts.map +1 -0
- package/dist/listen.mjs +958 -340
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-cloudflare.d.ts +93 -0
- package/dist/runtime-cloudflare.d.ts.map +1 -0
- package/dist/runtime-cloudflare.js +18032 -0
- package/dist/runtime-cloudflare.js.map +1 -0
- package/dist/runtime-node.d.mts +12615 -5249
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/server.d.ts +17367 -8567
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +13587 -7333
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +11601 -5401
- package/dist/server.mjs.map +1 -1
- package/dist/server2.mjs +84 -62
- package/dist/server2.mjs.map +1 -1
- package/package.json +31 -5
- package/src/admin/api/routes.ts +263 -190
- package/src/admin/audit/service.ts +11 -3
- package/src/admin/bootstrap.ts +86 -0
- package/src/admin/documents/service.ts +195 -10
- package/src/admin/email/service.ts +2 -1
- package/src/admin/enrollment/email.ts +17 -3
- package/src/admin/enrollment/service.ts +71 -10
- package/src/admin/errors.ts +5 -0
- package/src/admin/index.ts +1 -0
- package/src/admin/reports/service.ts +15 -3
- package/src/admin/schema.ts +6 -5
- package/src/admin/users/service.ts +173 -16
- package/src/client/api.ts +52 -473
- package/src/client/auth/client.ts +22 -3
- package/src/client/comments.ts +205 -0
- package/src/client/community.ts +40 -0
- package/src/client/device-authorization.ts +4 -20
- package/src/client/discovery.ts +39 -11
- package/src/client/documents.ts +160 -0
- package/src/client/files/archive.ts +60 -0
- package/src/client/files/checksum.ts +7 -0
- package/src/client/files/download.ts +122 -0
- package/src/client/files/images.ts +89 -0
- package/src/client/files/index.ts +15 -0
- package/src/client/files/objects.ts +173 -0
- package/src/client/files/save.ts +79 -0
- package/src/client/index.ts +4 -0
- package/src/client/portal/account.ts +73 -3
- package/src/client/portal/administration.ts +52 -5
- package/src/client/portal/request.ts +6 -2
- package/src/client/response.ts +21 -0
- package/src/client/schema.ts +8 -0
- package/src/client/services.ts +23 -18
- package/src/client/sharing.ts +262 -0
- package/src/client/tour.ts +44 -0
- package/src/client/versions.ts +110 -0
- package/src/contract/account.ts +111 -11
- package/src/contract/admin/index.ts +48 -3
- package/src/contract/billing.ts +235 -0
- package/src/contract/collaboration.ts +5 -0
- package/src/contract/comments.ts +223 -0
- package/src/contract/community.ts +60 -0
- package/src/contract/discovery.ts +94 -5
- package/src/contract/entitlements.ts +10 -0
- package/src/contract/index.ts +64 -5
- package/src/contract/links.ts +62 -4
- package/src/contract/locale.ts +27 -0
- package/src/contract/portal.ts +12 -1
- package/src/contract/relay.ts +3 -1
- package/src/contract/routes.ts +10 -0
- package/src/contract/services.ts +62 -20
- package/src/contract/workspaces.ts +5 -0
- package/src/email/i18n.ts +174 -0
- package/src/email/index.ts +13 -2
- package/src/email/locales/ar.json +169 -0
- package/src/email/locales/de.json +169 -0
- package/src/email/locales/es.json +169 -0
- package/src/email/locales/fr.json +169 -0
- package/src/email/locales/it.json +169 -0
- package/src/email/locales/ja.json +169 -0
- package/src/email/locales/pl.json +169 -0
- package/src/email/locales/pt-br.json +169 -0
- package/src/email/locales/ru.json +169 -0
- package/src/email/locales/zh-cn.json +169 -0
- package/src/email/messages.ts +235 -0
- package/src/email/render.ts +160 -276
- package/src/email/samples.ts +142 -0
- package/src/email/schema.ts +98 -8
- package/src/email/templates/BrandEmail.vue +56 -0
- package/src/email/templates/CommentNotification.vue +39 -0
- package/src/email/templates/DocumentBlocked.vue +45 -0
- package/src/email/templates/DocumentInvitation.vue +24 -0
- package/src/email/templates/DocumentReport.vue +32 -0
- package/src/email/templates/DocumentReportDecided.vue +36 -0
- package/src/email/templates/DocumentReportReceived.vue +18 -0
- package/src/email/templates/DocumentRestored.vue +24 -0
- package/src/email/templates/EmailChangeRequested.vue +24 -0
- package/src/email/templates/EmailRoot.vue +19 -0
- package/src/email/templates/EmailText.vue +9 -0
- package/src/email/templates/EmailVerification.vue +38 -0
- package/src/email/templates/EnrollmentInvitation.vue +53 -0
- package/src/email/templates/EnrollmentNotification.vue +24 -0
- package/src/email/templates/EnrollmentUpdate.vue +52 -0
- package/src/email/templates/NewSignIn.vue +37 -0
- package/src/email/templates/PasswordChanged.vue +22 -0
- package/src/email/templates/PasswordReset.vue +23 -0
- package/src/email/templates/StorageLimitReached.vue +28 -0
- package/src/email/templates/TwoStepChanged.vue +47 -0
- package/src/email/templates/WaitlistConfirmation.vue +29 -0
- package/src/email/templates/WorkspaceInvitation.vue +28 -0
- package/src/email/templates/brand.ts +15 -61
- package/src/email/templates/localization.ts +17 -0
- package/src/errors/index.ts +6 -0
- package/src/{server/errors → errors}/posthog.ts +28 -4
- package/src/global.d.ts +7 -0
- package/src/runtime/cloudflare/email.ts +2 -0
- package/src/runtime/cloudflare/relay/index.ts +28 -7
- package/src/runtime/cloudflare/tsconfig.json +2 -1
- package/src/runtime/cloudflare/worker.ts +14 -1
- package/src/runtime/cloudflare/xml.ts +12 -0
- package/src/runtime/node/admin.ts +51 -47
- package/src/runtime/node/cleanup.ts +5 -1
- package/src/runtime/node/email/runtime.ts +1 -0
- package/src/runtime/node/email/transport.ts +14 -10
- package/src/runtime/node/main.ts +1 -1
- package/src/runtime/node/server.ts +20 -4
- package/src/runtime/node/services/main.ts +1 -1
- package/src/runtime/posthog/errors.ts +5 -2
- package/src/runtime/s3/objects.ts +17 -0
- package/src/runtime/site/community.ts +101 -0
- package/src/runtime/site/server.ts +17 -1
- package/src/server/account/actions.ts +3 -1
- package/src/server/account/deletion.ts +40 -4
- package/src/server/account/routes.ts +305 -253
- package/src/server/account/tokens.ts +57 -0
- package/src/server/api/router.ts +44 -6
- package/src/server/app/checks.ts +89 -0
- package/src/server/app/cors.ts +44 -0
- package/src/server/app/editors.ts +20 -0
- package/src/server/app/index.ts +128 -0
- package/src/server/app/indexing.ts +40 -0
- package/src/server/app/limiters.ts +53 -0
- package/src/server/app/routes.ts +123 -0
- package/src/server/app/services.ts +219 -0
- package/src/server/auth/access-control.ts +13 -8
- package/src/server/auth/access-tokens.ts +62 -0
- package/src/server/auth/account.ts +13 -12
- package/src/server/auth/activity.ts +7 -2
- package/src/server/auth/adapter.ts +36 -3
- package/src/server/auth/email.ts +33 -18
- package/src/server/auth/endpoints.ts +4 -0
- package/src/server/auth/enrollment.ts +116 -0
- package/src/server/auth/factory.ts +165 -189
- package/src/server/auth/index.ts +1 -1
- package/src/server/auth/logger.ts +23 -0
- package/src/server/auth/methods.ts +162 -0
- package/src/server/auth/mfa-assurance.ts +190 -2
- package/src/server/auth/passwords.ts +43 -0
- package/src/server/auth/rate-limit.ts +31 -0
- package/src/server/auth/runtime.ts +19 -5
- package/src/server/auth/session.ts +2 -0
- package/src/server/auth/social-providers.ts +70 -24
- package/src/server/billing/index.ts +8 -0
- package/src/server/billing/notify.ts +55 -0
- package/src/server/billing/routes.ts +27 -0
- package/src/server/billing/seats.ts +17 -0
- package/src/server/billing/tokens.ts +37 -0
- package/src/server/cleanup/configured.ts +16 -3
- package/src/server/cleanup/documents.ts +5 -2
- package/src/server/cleanup/revisions.ts +6 -3
- package/src/server/cleanup/uploads.ts +2 -1
- package/src/server/cleanup/worker.ts +10 -1
- package/src/server/collaboration/relay/connection.ts +7 -2
- package/src/server/collaboration/relay/hub.ts +80 -166
- package/src/server/collaboration/relay/room.ts +154 -0
- package/src/server/collaboration/routes.ts +8 -5
- package/src/server/collaboration/service.ts +21 -2
- package/src/server/comments/index.ts +9 -0
- package/src/server/comments/notify.ts +277 -0
- package/src/server/comments/routes.ts +352 -0
- package/src/server/comments/rows.ts +249 -0
- package/src/server/comments/service.ts +570 -0
- package/src/server/community/index.ts +2 -0
- package/src/server/community/routes.ts +93 -0
- package/src/server/community/service.ts +134 -0
- package/src/server/config/deployment.ts +35 -10
- package/src/server/config/index.ts +2 -2
- package/src/server/config/public.ts +25 -6
- package/src/server/config/schema.ts +53 -293
- package/src/server/config/toml/schema.ts +330 -0
- package/src/server/db/index.ts +3 -1
- package/src/server/db/migrate.ts +33 -1
- package/src/server/db/migrations/009_access_tokens.ts +47 -0
- package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
- package/src/server/db/migrations/011_account_ids.ts +30 -0
- package/src/server/db/migrations/012_email_locales.ts +34 -0
- package/src/server/db/migrations/013_document_block_emails.ts +40 -0
- package/src/server/db/migrations/014_report_replies.ts +28 -0
- package/src/server/db/migrations/015_comments.ts +57 -0
- package/src/server/db/migrations/016_comment_notifications.ts +76 -0
- package/src/server/db/migrations/017_invitation_emails.ts +19 -0
- package/src/server/db/migrations/018_enrollment_source.ts +17 -0
- package/src/server/db/migrations/schema.ts +26 -1
- package/src/server/db/tables.ts +122 -3
- package/src/server/db/users.ts +22 -0
- package/src/server/documents/access.ts +17 -0
- package/src/server/documents/images.ts +6 -1
- package/src/server/documents/index.ts +1 -1
- package/src/server/documents/limits.ts +7 -1
- package/src/server/documents/routes.ts +12 -12
- package/src/server/documents/service.ts +31 -407
- package/src/server/documents/summary.ts +15 -0
- package/src/server/documents/uploads.ts +450 -0
- package/src/server/documents/versions/routes.ts +7 -8
- package/src/server/documents/versions/service.ts +86 -26
- package/src/server/email/invitations.ts +1 -0
- package/src/server/email/service.ts +39 -6
- package/src/server/email/types.ts +13 -0
- package/src/server/errors/index.ts +49 -12
- package/src/server/index.ts +27 -6
- package/src/server/internal/routes.ts +8 -2
- package/src/server/internal/service.ts +10 -0
- package/src/server/invitations/budget.ts +3 -1
- package/src/server/invitations/index.ts +1 -0
- package/src/server/invitations/links.ts +6 -0
- package/src/server/invitations/types.ts +5 -1
- package/src/server/objects/types.ts +5 -0
- package/src/server/pictures/service.ts +3 -1
- package/src/server/policy/configured.ts +9 -3
- package/src/server/policy/database.ts +13 -2
- package/src/server/policy/policy.ts +39 -12
- package/src/server/policy/service.ts +71 -52
- package/src/server/policy/storage.ts +33 -0
- package/src/server/policy/workspace.ts +5 -2
- package/src/server/quota/index.ts +6 -0
- package/src/server/quota/notices.ts +121 -0
- package/src/server/quota/storage.ts +5 -0
- package/src/server/rate-limit/middleware.ts +4 -0
- package/src/server/reports/index.ts +1 -0
- package/src/server/reports/replies.ts +55 -0
- package/src/server/reports/routes.ts +5 -3
- package/src/server/reports/service.ts +27 -3
- package/src/server/services/routes.ts +2 -2
- package/src/server/sharing/capabilities/service.ts +3 -4
- package/src/server/sharing/document-routes.ts +3 -3
- package/src/server/sharing/invitations/service.ts +17 -8
- package/src/server/sharing/routes.ts +15 -15
- package/src/server/validation.ts +35 -24
- package/src/server/workspaces/members.ts +57 -31
- package/src/server/workspaces/repository.ts +23 -12
- package/src/server/workspaces/routes.ts +8 -8
- package/src/services/app.ts +31 -22
- package/src/services/config.ts +48 -8
- package/src/services/metering.ts +15 -27
- package/src/services/usage.ts +6 -14
- package/src/email/templates/document-invitation.ts +0 -35
- package/src/email/templates/enrollment.ts +0 -27
- package/src/email/templates/layout.ts +0 -18
- package/src/server/app.ts +0 -453
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type { CloudServerConfig } from '#cloud/server/config'
|
|
2
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import { APIError, type BetterAuthOptions } from 'better-auth'
|
|
4
|
+
import { getOAuthState } from 'better-auth/api'
|
|
5
|
+
import type { Kysely, Transaction } from 'kysely'
|
|
6
|
+
|
|
7
|
+
import { configuredSocialProviders } from './social-providers'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* An administrator's removal of a Google or Apple identity is kept as one of Better Auth's
|
|
11
|
+
* verification values: its database hooks read them inside the transaction that would create the
|
|
12
|
+
* account, and the removal writes it in its own, so the two cannot come apart.
|
|
13
|
+
*/
|
|
14
|
+
const BLOCK_EXPIRES_AT = new Date(Date.UTC(9999, 11, 31))
|
|
15
|
+
const blockIdentifier = (userId: string, provider: string) =>
|
|
16
|
+
`sign-in-method-block:${userId}:${provider}`
|
|
17
|
+
|
|
18
|
+
/** Better Auth's store of keyed values, as its database hooks are handed it. */
|
|
19
|
+
export type SignInMethodBlockStore = {
|
|
20
|
+
findVerificationValue(identifier: string): Promise<{ value: string } | null>
|
|
21
|
+
deleteVerificationByIdentifier(identifier: string): Promise<void>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The providers this server signs in with now, `credential` for a password. A method linked before
|
|
26
|
+
* its provider was turned off stays on the account but no longer lets anyone in.
|
|
27
|
+
*/
|
|
28
|
+
export function signInProviders(config: CloudServerConfig): ReadonlySet<string> {
|
|
29
|
+
const providers = new Set<string>(configuredSocialProviders(config))
|
|
30
|
+
if (config.emailPasswordEnabled) providers.add('credential')
|
|
31
|
+
return providers
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Whether `method` can come off an account holding `methods`: the account keeps at least one, and,
|
|
36
|
+
* with `providers`, one whose provider is turned on. Taking away a provider that is off changes
|
|
37
|
+
* nothing, so it can always go while another method remains.
|
|
38
|
+
*/
|
|
39
|
+
export function canRemoveSignInMethod(
|
|
40
|
+
method: { id: string; providerId: string },
|
|
41
|
+
methods: readonly { id: string; providerId: string }[],
|
|
42
|
+
providers?: ReadonlySet<string>
|
|
43
|
+
): boolean {
|
|
44
|
+
const counts = (provider: string) => !providers || providers.has(provider)
|
|
45
|
+
const others = methods.filter((candidate) => candidate.id !== method.id)
|
|
46
|
+
if (others.length === 0) return false
|
|
47
|
+
return !counts(method.providerId) || others.some((other) => counts(other.providerId))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The sign-in method a removal took away: its provider (`credential` for a password). */
|
|
51
|
+
export type RemovedSignInMethod = { provider: string }
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Removes one of an account's sign-in methods, by its row. The account's row is locked first, so
|
|
55
|
+
* its owner unlinking one while an administrator removes another cannot leave it with none. An
|
|
56
|
+
* administrator's removal (`block`) also keeps that Google or Apple identity from linking itself
|
|
57
|
+
* back by the account's email; `also` runs in the same transaction, as their audit entry does.
|
|
58
|
+
* With `providers`, only methods whose provider is turned on count as a way still in.
|
|
59
|
+
*/
|
|
60
|
+
export async function removeSignInMethod(
|
|
61
|
+
database: Kysely<CloudDatabase>,
|
|
62
|
+
input: {
|
|
63
|
+
userId: string
|
|
64
|
+
methodId: string
|
|
65
|
+
providers?: ReadonlySet<string>
|
|
66
|
+
block?: boolean
|
|
67
|
+
also?: (transaction: Transaction<CloudDatabase>, provider: string) => Promise<void>
|
|
68
|
+
}
|
|
69
|
+
): Promise<RemovedSignInMethod> {
|
|
70
|
+
return database.transaction().execute(async (transaction) => {
|
|
71
|
+
await transaction
|
|
72
|
+
.selectFrom('user')
|
|
73
|
+
.select('id')
|
|
74
|
+
.where('id', '=', input.userId)
|
|
75
|
+
.forUpdate()
|
|
76
|
+
.executeTakeFirstOrThrow()
|
|
77
|
+
const methods = await transaction
|
|
78
|
+
.selectFrom('account')
|
|
79
|
+
.select(['id', 'providerId', 'accountId'])
|
|
80
|
+
.where('userId', '=', input.userId)
|
|
81
|
+
.execute()
|
|
82
|
+
const method = methods.find((candidate) => candidate.id === input.methodId)
|
|
83
|
+
if (!method) {
|
|
84
|
+
throw APIError.from('NOT_FOUND', { code: 'ACCOUNT_NOT_FOUND', message: 'No such method' })
|
|
85
|
+
}
|
|
86
|
+
if (!canRemoveSignInMethod(method, methods, input.providers)) {
|
|
87
|
+
// Better Auth's own word, which the account routes already answer for.
|
|
88
|
+
throw APIError.from('BAD_REQUEST', {
|
|
89
|
+
code: 'FAILED_TO_UNLINK_LAST_ACCOUNT',
|
|
90
|
+
message: 'An account keeps at least one way to sign in'
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
await transaction.deleteFrom('account').where('id', '=', method.id).execute()
|
|
94
|
+
if (input.block && method.providerId !== 'credential') {
|
|
95
|
+
const identifier = blockIdentifier(input.userId, method.providerId)
|
|
96
|
+
await transaction.deleteFrom('verification').where('identifier', '=', identifier).execute()
|
|
97
|
+
await transaction
|
|
98
|
+
.insertInto('verification')
|
|
99
|
+
.values({
|
|
100
|
+
id: crypto.randomUUID(),
|
|
101
|
+
identifier,
|
|
102
|
+
value: method.accountId,
|
|
103
|
+
expiresAt: BLOCK_EXPIRES_AT,
|
|
104
|
+
createdAt: new Date(),
|
|
105
|
+
updatedAt: new Date()
|
|
106
|
+
})
|
|
107
|
+
.execute()
|
|
108
|
+
}
|
|
109
|
+
await input.also?.(transaction, method.providerId)
|
|
110
|
+
return { provider: method.providerId }
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Whether a sign-in may create `account`: not an identity an administrator removed from that
|
|
116
|
+
* person, unless that person is linking it again from their own security page (`linkingUserId`,
|
|
117
|
+
* which Better Auth carries from the request that started the link).
|
|
118
|
+
*/
|
|
119
|
+
export async function signInMethodAllowed(
|
|
120
|
+
store: SignInMethodBlockStore,
|
|
121
|
+
account: { userId: string; providerId: string; accountId: string },
|
|
122
|
+
linkingUserId: () => Promise<string | null>
|
|
123
|
+
): Promise<boolean> {
|
|
124
|
+
const block = await store.findVerificationValue(
|
|
125
|
+
blockIdentifier(account.userId, account.providerId)
|
|
126
|
+
)
|
|
127
|
+
if (block?.value !== account.accountId) return true
|
|
128
|
+
return (await linkingUserId()) === account.userId
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The person a provider callback links an identity to, when it is a link they started. */
|
|
132
|
+
async function linkingUserId(): Promise<string | null> {
|
|
133
|
+
// Outside a provider callback there is no sign-in state, and nothing is being linked.
|
|
134
|
+
const state = await getOAuthState().catch(() => null)
|
|
135
|
+
return state?.link?.userId ?? null
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Refuses to create an identity an administrator removed, however a sign-in tries to, and lifts
|
|
140
|
+
* the block once its owner has linked it again.
|
|
141
|
+
*/
|
|
142
|
+
export const signInMethodHooks: NonNullable<BetterAuthOptions['databaseHooks']> = {
|
|
143
|
+
account: {
|
|
144
|
+
create: {
|
|
145
|
+
async before(account, context) {
|
|
146
|
+
const store = context?.context.internalAdapter
|
|
147
|
+
// `undefined` lets Better Auth create the account as it is; `false` refuses it.
|
|
148
|
+
return store && !(await signInMethodAllowed(store, account, linkingUserId))
|
|
149
|
+
? false
|
|
150
|
+
: undefined
|
|
151
|
+
},
|
|
152
|
+
async after(account, context) {
|
|
153
|
+
const store = context?.context.internalAdapter
|
|
154
|
+
if (store && (await linkingUserId()) === account.userId) {
|
|
155
|
+
await store.deleteVerificationByIdentifier(
|
|
156
|
+
blockIdentifier(account.userId, account.providerId)
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import type { CloudMFAStatus } from '#cloud/server/auth/adapter'
|
|
2
2
|
import type { CloudServerConfig } from '#cloud/server/config'
|
|
3
|
-
import type { CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import type { CloudDatabase, MFAAssuranceMethod } from '#cloud/server/db'
|
|
4
|
+
import { APIError } from 'better-auth'
|
|
4
5
|
import type { Kysely } from 'kysely'
|
|
6
|
+
import * as v from 'valibot'
|
|
7
|
+
|
|
8
|
+
import { authRequestPath } from './endpoints'
|
|
5
9
|
|
|
6
10
|
const ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000
|
|
7
11
|
|
|
@@ -13,7 +17,7 @@ export function createMFAAssuranceService(
|
|
|
13
17
|
async record(input: {
|
|
14
18
|
sessionId: string
|
|
15
19
|
userId: string
|
|
16
|
-
method:
|
|
20
|
+
method: MFAAssuranceMethod
|
|
17
21
|
}): Promise<void> {
|
|
18
22
|
await database
|
|
19
23
|
.insertInto('mfaAssurance')
|
|
@@ -23,6 +27,40 @@ export function createMFAAssuranceService(
|
|
|
23
27
|
)
|
|
24
28
|
.execute()
|
|
25
29
|
},
|
|
30
|
+
/**
|
|
31
|
+
* Whether a session may act as its account. One whose account has an authenticator or a
|
|
32
|
+
* passkey must have proved it, at sign-in or since; a sign-in through a linked account such
|
|
33
|
+
* as Google never asks for it. Unlike `status().assured`, the proof does not age.
|
|
34
|
+
*/
|
|
35
|
+
async confirmed(input: {
|
|
36
|
+
sessionId: string
|
|
37
|
+
userId: string
|
|
38
|
+
twoFactorEnabled: boolean
|
|
39
|
+
}): Promise<boolean> {
|
|
40
|
+
const row = await database
|
|
41
|
+
.selectNoFrom((expression) => [
|
|
42
|
+
expression
|
|
43
|
+
.exists(
|
|
44
|
+
expression
|
|
45
|
+
.selectFrom('mfaAssurance')
|
|
46
|
+
.select('mfaAssurance.sessionId')
|
|
47
|
+
.where('mfaAssurance.sessionId', '=', input.sessionId)
|
|
48
|
+
.where('mfaAssurance.userId', '=', input.userId)
|
|
49
|
+
)
|
|
50
|
+
.as('assured'),
|
|
51
|
+
expression
|
|
52
|
+
.exists(
|
|
53
|
+
expression
|
|
54
|
+
.selectFrom('passkey')
|
|
55
|
+
.select('passkey.id')
|
|
56
|
+
.where('passkey.userId', '=', input.userId)
|
|
57
|
+
)
|
|
58
|
+
.as('passkey')
|
|
59
|
+
])
|
|
60
|
+
.executeTakeFirstOrThrow()
|
|
61
|
+
if (row.assured) return true
|
|
62
|
+
return !input.twoFactorEnabled && !row.passkey
|
|
63
|
+
},
|
|
26
64
|
async status(input: {
|
|
27
65
|
sessionId: string
|
|
28
66
|
userId: string
|
|
@@ -53,3 +91,153 @@ export function createMFAAssuranceService(
|
|
|
53
91
|
}
|
|
54
92
|
|
|
55
93
|
export type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Records the second step a response just signed in with, against the session it started; false
|
|
97
|
+
* when it started none.
|
|
98
|
+
*/
|
|
99
|
+
export async function recordResponseAssurance(
|
|
100
|
+
response: Response,
|
|
101
|
+
method: MFAAssuranceMethod,
|
|
102
|
+
database: Kysely<CloudDatabase>,
|
|
103
|
+
assurance: MFAAssuranceService
|
|
104
|
+
): Promise<boolean> {
|
|
105
|
+
const signedToken = response.headers.get('set-auth-token')
|
|
106
|
+
const token = signedToken?.split('.', 1)[0]
|
|
107
|
+
if (!token) return false
|
|
108
|
+
const session = await database
|
|
109
|
+
.selectFrom('session')
|
|
110
|
+
.select(['id', 'userId'])
|
|
111
|
+
.where('token', '=', token)
|
|
112
|
+
.executeTakeFirst()
|
|
113
|
+
if (!session) return false
|
|
114
|
+
await assurance.record({ sessionId: session.id, userId: session.userId, method })
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const deviceTokenSchema = v.pipe(v.string(), v.parseJson(), v.object({ access_token: v.string() }))
|
|
119
|
+
|
|
120
|
+
/** Records a desktop app's new session from a device sign-in, whose approval proved the step. */
|
|
121
|
+
export async function recordDeviceAssurance(
|
|
122
|
+
response: Response,
|
|
123
|
+
database: Kysely<CloudDatabase>,
|
|
124
|
+
assurance: MFAAssuranceService
|
|
125
|
+
): Promise<void> {
|
|
126
|
+
const body = v.safeParse(deviceTokenSchema, await response.clone().text())
|
|
127
|
+
if (!body.success) return
|
|
128
|
+
const session = await database
|
|
129
|
+
.selectFrom('session')
|
|
130
|
+
.select(['id', 'userId'])
|
|
131
|
+
.where('token', '=', body.output.access_token)
|
|
132
|
+
.executeTakeFirst()
|
|
133
|
+
if (session) {
|
|
134
|
+
await assurance.record({ sessionId: session.id, userId: session.userId, method: 'device' })
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The auth endpoints whose success proves a second step, by their request paths. */
|
|
139
|
+
export type ProofPaths = {
|
|
140
|
+
totp: string
|
|
141
|
+
recoveryCode: string
|
|
142
|
+
passkeySignIn: string
|
|
143
|
+
passkeyRegistration: string
|
|
144
|
+
deviceToken: string
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Records what a successful auth response proved. Signing in with a code, a recovery code, or a
|
|
149
|
+
* passkey proves it for the session it starts; a device sign-in proves it for the app's session,
|
|
150
|
+
* since only a proved session may approve one; registering a passkey proves it for the session
|
|
151
|
+
* that added it, maybe the account's first second step, so that session is not then held.
|
|
152
|
+
*/
|
|
153
|
+
export function createProofRecorder(
|
|
154
|
+
database: Kysely<CloudDatabase>,
|
|
155
|
+
assurance: MFAAssuranceService,
|
|
156
|
+
paths: ProofPaths
|
|
157
|
+
) {
|
|
158
|
+
const signIns = new Map<string, MFAAssuranceMethod>([
|
|
159
|
+
[paths.totp, 'totp'],
|
|
160
|
+
[paths.recoveryCode, 'recovery-code'],
|
|
161
|
+
[paths.passkeySignIn, 'passkey']
|
|
162
|
+
])
|
|
163
|
+
return async (
|
|
164
|
+
path: string,
|
|
165
|
+
response: Response,
|
|
166
|
+
/** The session the request came from, read only when the step is proved for it. */
|
|
167
|
+
current: () => Promise<{ session: { id: string }; user: { id: string } } | null>
|
|
168
|
+
): Promise<void> => {
|
|
169
|
+
const method = signIns.get(path)
|
|
170
|
+
if (method) {
|
|
171
|
+
const recorded = await recordResponseAssurance(response, method, database, assurance)
|
|
172
|
+
// A code checked for a session whose account already has the step does not replace the
|
|
173
|
+
// session, so it proves it for that one; a passkey sign-in always starts a session.
|
|
174
|
+
const session = !recorded && method !== 'passkey' ? await current() : null
|
|
175
|
+
if (session) {
|
|
176
|
+
await assurance.record({ sessionId: session.session.id, userId: session.user.id, method })
|
|
177
|
+
}
|
|
178
|
+
} else if (path === paths.deviceToken)
|
|
179
|
+
await recordDeviceAssurance(response, database, assurance)
|
|
180
|
+
else if (path === paths.passkeyRegistration) {
|
|
181
|
+
const session = await current()
|
|
182
|
+
if (session) {
|
|
183
|
+
await assurance.record({
|
|
184
|
+
sessionId: session.session.id,
|
|
185
|
+
userId: session.user.id,
|
|
186
|
+
method: 'passkey'
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Better Auth's words for a code that does not match. */
|
|
194
|
+
const WRONG_CODES = new Set(['INVALID_CODE', 'INVALID_TWO_FACTOR_CODE', 'INVALID_BACKUP_CODE'])
|
|
195
|
+
const authErrorSchema = v.pipe(
|
|
196
|
+
v.string(),
|
|
197
|
+
v.parseJson(),
|
|
198
|
+
v.object({ code: v.optional(v.string()) })
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Checks a second-step code through the two-step plugin's own endpoint, and records the session's
|
|
203
|
+
* assurance when it passes.
|
|
204
|
+
*/
|
|
205
|
+
export async function verifySecondFactor(
|
|
206
|
+
auth: { handler(request: Request): Promise<Response> },
|
|
207
|
+
config: CloudServerConfig,
|
|
208
|
+
database: Kysely<CloudDatabase>,
|
|
209
|
+
assurance: MFAAssuranceService,
|
|
210
|
+
headers: Headers,
|
|
211
|
+
code: string,
|
|
212
|
+
method: 'totp' | 'recovery-code',
|
|
213
|
+
/** The two-step plugin's endpoint that checks this kind of code. */
|
|
214
|
+
endpoint: { path: string },
|
|
215
|
+
/** The session the code is checked for, which proves the step when it is not replaced. */
|
|
216
|
+
current: { id: string; userId: string } | null
|
|
217
|
+
): Promise<Response> {
|
|
218
|
+
const response = await auth.handler(
|
|
219
|
+
new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {
|
|
220
|
+
method: 'POST',
|
|
221
|
+
headers: new Headers({
|
|
222
|
+
...Object.fromEntries(headers),
|
|
223
|
+
'Content-Type': 'application/json'
|
|
224
|
+
}),
|
|
225
|
+
body: JSON.stringify({ code, trustDevice: false })
|
|
226
|
+
})
|
|
227
|
+
)
|
|
228
|
+
if (!response.ok) {
|
|
229
|
+
// A wrong code is the person's mistake, not a session to renew: say so, as a 400.
|
|
230
|
+
const answer = v.safeParse(authErrorSchema, await response.clone().text())
|
|
231
|
+
if (answer.success && WRONG_CODES.has(answer.output.code ?? '')) {
|
|
232
|
+
throw new APIError('BAD_REQUEST', { code: 'INVALID_CODE' })
|
|
233
|
+
}
|
|
234
|
+
throw APIError.fromStatus(response.status as 401)
|
|
235
|
+
}
|
|
236
|
+
// A session whose account already has the step proves it without being replaced: it is the one
|
|
237
|
+
// that proved it. Turning an authenticator on replaces the session, and the new one is recorded.
|
|
238
|
+
const recorded = await recordResponseAssurance(response, method, database, assurance)
|
|
239
|
+
if (!recorded && current) {
|
|
240
|
+
await assurance.record({ sessionId: current.id, userId: current.userId, method })
|
|
241
|
+
}
|
|
242
|
+
return response
|
|
243
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { CloudServerConfig } from '#cloud/server/config'
|
|
2
|
+
import type { BetterAuthOptions } from 'better-auth'
|
|
3
|
+
|
|
4
|
+
import type { AuthenticationEmailService } from './email'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Signing in with an email and password, when the deployment allows it: a verified address, the
|
|
8
|
+
* configured password lengths, and mail about resets when the deployment sends email.
|
|
9
|
+
*/
|
|
10
|
+
export function passwordOptions(
|
|
11
|
+
config: CloudServerConfig,
|
|
12
|
+
authenticationEmail: AuthenticationEmailService | undefined
|
|
13
|
+
): BetterAuthOptions['emailAndPassword'] {
|
|
14
|
+
if (!config.emailPasswordEnabled) return undefined
|
|
15
|
+
return {
|
|
16
|
+
enabled: true,
|
|
17
|
+
disableSignUp: !config.emailPasswordSignUpEnabled,
|
|
18
|
+
requireEmailVerification: true,
|
|
19
|
+
minPasswordLength: config.emailPasswordMinimumLength,
|
|
20
|
+
maxPasswordLength: config.emailPasswordMaximumLength,
|
|
21
|
+
autoSignIn: false,
|
|
22
|
+
resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,
|
|
23
|
+
revokeSessionsOnPasswordReset: true,
|
|
24
|
+
sendResetPassword: authenticationEmail
|
|
25
|
+
? ({ user, url, token }) =>
|
|
26
|
+
authenticationEmail.sendPasswordReset({
|
|
27
|
+
email: user.email,
|
|
28
|
+
name: user.name,
|
|
29
|
+
url,
|
|
30
|
+
token
|
|
31
|
+
})
|
|
32
|
+
: undefined,
|
|
33
|
+
onPasswordReset: authenticationEmail
|
|
34
|
+
? ({ user }) =>
|
|
35
|
+
authenticationEmail.sendPasswordChanged({
|
|
36
|
+
email: user.email,
|
|
37
|
+
name: user.name,
|
|
38
|
+
userId: user.id,
|
|
39
|
+
url: config.publicURL
|
|
40
|
+
})
|
|
41
|
+
: undefined
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { deviceAuthorization } from 'better-auth/plugins'
|
|
2
|
+
|
|
3
|
+
import { CORE_AUTH_PATHS } from './endpoints'
|
|
4
|
+
|
|
5
|
+
type DeviceEndpoints = ReturnType<typeof deviceAuthorization>['endpoints']
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Better Auth's request budgets, counted per client IP in the database: a general one, and tighter
|
|
9
|
+
* ones for steps that send email, check passwords, or hand out desktop sign-in codes.
|
|
10
|
+
*/
|
|
11
|
+
export function authRateLimit(devices: DeviceEndpoints) {
|
|
12
|
+
return {
|
|
13
|
+
enabled: true,
|
|
14
|
+
storage: 'database' as const,
|
|
15
|
+
window: 60,
|
|
16
|
+
max: 100,
|
|
17
|
+
customRules: {
|
|
18
|
+
[devices.deviceCode.path]: { window: 60, max: 10 },
|
|
19
|
+
[devices.deviceToken.path]: { window: 60, max: 60 },
|
|
20
|
+
// The plugin's own budget is 5 lookups per code lifetime (30 minutes), so reopening the
|
|
21
|
+
// sign-in page a few times turned away every new code for half an hour.
|
|
22
|
+
[devices.deviceVerify.path]: { window: 60, max: 20 },
|
|
23
|
+
[devices.deviceApprove.path]: { window: 60, max: 10 },
|
|
24
|
+
[devices.deviceDeny.path]: { window: 60, max: 10 },
|
|
25
|
+
[CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },
|
|
26
|
+
[CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },
|
|
27
|
+
[CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },
|
|
28
|
+
[CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EnrollmentEmailOptions } from '#cloud/admin/enrollment/email'
|
|
1
2
|
import { createEnrollmentService } from '#cloud/admin/enrollment/service'
|
|
2
3
|
import type { CloudServerConfig } from '#cloud/server/config'
|
|
3
4
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
@@ -7,17 +8,30 @@ import type { Kysely } from 'kysely'
|
|
|
7
8
|
import { createAuthenticationEmailService } from './email'
|
|
8
9
|
import { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
|
|
9
10
|
|
|
11
|
+
/**
|
|
12
|
+
* What the enrollment service tells people, from the server's settings: where its links go, who
|
|
13
|
+
* hears about new requests, and whether approvals may carry the official deployment's letter.
|
|
14
|
+
* Every place that builds the service takes it from here, so none of them disagrees.
|
|
15
|
+
*/
|
|
16
|
+
export function enrollmentEmailOptions(
|
|
17
|
+
config: CloudServerConfig,
|
|
18
|
+
email: TransactionalEmailService | undefined
|
|
19
|
+
): EnrollmentEmailOptions {
|
|
20
|
+
return {
|
|
21
|
+
publicURL: config.publicURL,
|
|
22
|
+
adminRecipients: config.enrollmentAdminNotificationEmails,
|
|
23
|
+
email,
|
|
24
|
+
invitations: config.deployment === 'official'
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
10
28
|
export function createCloudAuthenticationRuntime(
|
|
11
29
|
config: CloudServerConfig,
|
|
12
30
|
database: Kysely<CloudDatabase>,
|
|
13
31
|
email: TransactionalEmailService,
|
|
14
32
|
options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}
|
|
15
33
|
) {
|
|
16
|
-
const enrollment = createEnrollmentService(database,
|
|
17
|
-
publicURL: config.publicURL,
|
|
18
|
-
adminRecipients: config.enrollmentAdminNotificationEmails,
|
|
19
|
-
email
|
|
20
|
-
})
|
|
34
|
+
const enrollment = createEnrollmentService(database, enrollmentEmailOptions(config, email))
|
|
21
35
|
const auth = createBetterAuthAdapter(config, database, enrollment, {
|
|
22
36
|
email: createAuthenticationEmailService(email, config.publicURL),
|
|
23
37
|
...options
|
|
@@ -5,6 +5,8 @@ export type CloudActor = {
|
|
|
5
5
|
email: string
|
|
6
6
|
name: string
|
|
7
7
|
deploymentRole?: 'user' | 'admin'
|
|
8
|
+
/** How the request proved who it is: a signed-in session, or a personal access token. */
|
|
9
|
+
credential?: 'session' | 'token'
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
export type CloudIdentityResolver = (request: Request) => Promise<CloudIdentity | null>
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CLOUD_SOCIAL_PROVIDERS, type CloudSocialProvider } from '#cloud/contract/account'
|
|
1
2
|
import type { CloudServerConfig } from '#cloud/server/config'
|
|
2
3
|
import type { BetterAuthOptions } from 'better-auth'
|
|
3
4
|
import { importPKCS8, SignJWT } from 'jose'
|
|
@@ -26,30 +27,75 @@ async function generateAppleClientSecret(config: CloudServerConfig): Promise<str
|
|
|
26
27
|
.sign(privateKey)
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
30
|
+
type ProviderOptions = NonNullable<BetterAuthOptions['socialProviders']>
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Each provider as the server sets it up: its Better Auth options from the deployment's config, or
|
|
34
|
+
* `undefined` where it is not configured, and whether its email may link to an existing account
|
|
35
|
+
* whatever it says of that address (`trusted`). The one place a new provider's server side goes,
|
|
36
|
+
* beside its config fields.
|
|
37
|
+
*/
|
|
38
|
+
const PROVIDERS: {
|
|
39
|
+
[Provider in CloudSocialProvider]: {
|
|
40
|
+
options: (config: CloudServerConfig) => ProviderOptions[Provider]
|
|
41
|
+
trusted: boolean
|
|
37
42
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
43
|
+
} = {
|
|
44
|
+
// Google only gives an address it has verified.
|
|
45
|
+
google: {
|
|
46
|
+
options: (config) =>
|
|
47
|
+
config.googleClientId && config.googleClientSecret
|
|
48
|
+
? { clientId: config.googleClientId, clientSecret: config.googleClientSecret }
|
|
49
|
+
: undefined,
|
|
50
|
+
trusted: true
|
|
51
|
+
},
|
|
52
|
+
// Apple's addresses are verified, or relays it delivers itself. Its client secret is a token the
|
|
53
|
+
// server signs, so it is made when Better Auth asks.
|
|
54
|
+
apple: {
|
|
55
|
+
options: (config) =>
|
|
56
|
+
config.appleClientId
|
|
57
|
+
? async () => ({
|
|
58
|
+
clientId: config.appleClientId ?? '',
|
|
59
|
+
clientSecret: await generateAppleClientSecret(config),
|
|
60
|
+
...(config.appleAppBundleIdentifier && {
|
|
61
|
+
appBundleIdentifier: config.appleAppBundleIdentifier
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
: undefined,
|
|
65
|
+
trusted: true
|
|
66
|
+
},
|
|
67
|
+
// GitHub can hand over an address it has not verified, such as an account's first listed email
|
|
68
|
+
// when none is primary; untrusted, it links only when GitHub says the address is verified.
|
|
69
|
+
github: {
|
|
70
|
+
options: (config) =>
|
|
71
|
+
config.githubClientId && config.githubClientSecret
|
|
72
|
+
? { clientId: config.githubClientId, clientSecret: config.githubClientSecret }
|
|
73
|
+
: undefined,
|
|
74
|
+
trusted: false
|
|
53
75
|
}
|
|
54
|
-
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Providers whose sign-in links to the account with the same email even when it does not say the
|
|
80
|
+
* address is verified. Better Auth links any other provider only when it does.
|
|
81
|
+
*/
|
|
82
|
+
export const TRUSTED_SOCIAL_PROVIDERS: CloudSocialProvider[] = CLOUD_SOCIAL_PROVIDERS.filter(
|
|
83
|
+
(provider) => PROVIDERS[provider].trusted
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
/** The providers the deployment configures, in the order the editor shows them. */
|
|
87
|
+
export function configuredSocialProviders(config: CloudServerConfig): CloudSocialProvider[] {
|
|
88
|
+
return CLOUD_SOCIAL_PROVIDERS.filter(
|
|
89
|
+
(provider) => PROVIDERS[provider].options(config) !== undefined
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Better Auth's options for the providers the deployment configures. */
|
|
94
|
+
export function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {
|
|
95
|
+
return Object.fromEntries(
|
|
96
|
+
configuredSocialProviders(config).map((provider) => [
|
|
97
|
+
provider,
|
|
98
|
+
PROVIDERS[provider].options(config)
|
|
99
|
+
])
|
|
100
|
+
)
|
|
55
101
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createBillingRoutes, type BillingRouteEnvironment } from './routes'
|
|
2
|
+
export { createSeatNotifier, type SeatNotifier, type SeatNotifierOptions } from './notify'
|
|
3
|
+
export { accountSeats } from './seats'
|
|
4
|
+
export {
|
|
5
|
+
createBillingTokenService,
|
|
6
|
+
type BillingTokenService,
|
|
7
|
+
type BillingTokenServiceOptions
|
|
8
|
+
} from './tokens'
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { CLOUD_BILLING_API_PATHS } from '#cloud/contract'
|
|
2
|
+
import { userIdText, type CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import type { Kysely } from 'kysely'
|
|
4
|
+
import { joinURL } from 'ufo'
|
|
5
|
+
|
|
6
|
+
import type { BillingTokenService } from './tokens'
|
|
7
|
+
|
|
8
|
+
export type SeatNotifierOptions = {
|
|
9
|
+
database: Kysely<CloudDatabase>
|
|
10
|
+
/** The billing service's discovered endpoint. */
|
|
11
|
+
endpoint: string
|
|
12
|
+
tokens: BillingTokenService
|
|
13
|
+
/** Sends a notice; the global `fetch` by default. */
|
|
14
|
+
fetch?: (url: string, init: RequestInit) => Promise<Response>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Tells the billing service when the people who can edit in an account's workspaces change, so it
|
|
19
|
+
* can charge for the seats. Each notice carries a billing token for that account and nothing
|
|
20
|
+
* else: the service reads the count from Cloud's internal API, so a notice that never arrives only
|
|
21
|
+
* leaves the change to the service's own reconciliation.
|
|
22
|
+
*/
|
|
23
|
+
export function createSeatNotifier(options: SeatNotifierOptions) {
|
|
24
|
+
const send = options.fetch ?? ((url: string, init: RequestInit) => fetch(url, init))
|
|
25
|
+
return {
|
|
26
|
+
async notify(accountIds: readonly string[]): Promise<void> {
|
|
27
|
+
if (accountIds.length === 0) return
|
|
28
|
+
const accounts = await options.database
|
|
29
|
+
.selectFrom('user')
|
|
30
|
+
.select((eb) => [userIdText(eb).as('userId'), 'email'])
|
|
31
|
+
.where((eb) => eb(userIdText(eb), 'in', accountIds))
|
|
32
|
+
.execute()
|
|
33
|
+
// Every notice is sent before any failure is reported, so one refusal never leaves
|
|
34
|
+
// another account's notice cut off.
|
|
35
|
+
const sent = await Promise.allSettled(
|
|
36
|
+
accounts.map(async (account) => {
|
|
37
|
+
const { token } = await options.tokens.issue(account)
|
|
38
|
+
const response = await send(joinURL(options.endpoint, CLOUD_BILLING_API_PATHS.seats), {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
41
|
+
})
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
throw new Error(`Billing refused a seat notice with status ${response.status}`)
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
)
|
|
47
|
+
const failed: unknown[] = sent.flatMap((result): unknown[] =>
|
|
48
|
+
result.status === 'rejected' ? [result.reason] : []
|
|
49
|
+
)
|
|
50
|
+
if (failed.length > 0) throw new AggregateError(failed, 'Billing missed seat notices')
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export type SeatNotifier = ReturnType<typeof createSeatNotifier>
|