AI-native design editor. Open-source Figma alternative.
import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
import {
createCloudApp,
createBetterAuthAdapter,
parseCloudServerConfig,
type AuthenticationEmailService
} from '#cloud/server'
export const accountAuthenticationConfig = parseCloudServerConfig({
deployment: 'self-hosted',
publicURL: 'https://cloud.example.com',
databaseURL: 'postgresql://test:test@localhost/test',
authSecret: 'account-authentication-test-secret-at-least-32-characters',
enrollmentMode: 'approval',
emailPasswordEnabled: true,
emailTransport: 'smtp',
emailFrom: '[email protected]',
smtpHost: 'smtp.example.com',
smtpPort: 465,
smtpSecure: true,
s3Endpoint: 'https://objects.example.com',
s3Region: 'us-east-1',
s3Bucket: 'openpencil',
s3AccessKeyId: 'access-key',
s3SecretAccessKey: 'secret-key'
})
const ignore = async (): Promise<void> => {
await Promise.resolve()
}
/** Security notices for an account email service whose test does not read them. */
export const ignoredSecurityNotices = {
sendEmailChangeRequested: ignore,
sendNewSignIn: ignore,
sendTwoStepChanged: ignore
}
export function accountAuthenticationRequest(
path: string,
body?: object,
cookie?: string,
init: { headers?: Record<string, string>; method?: string } = {}
): Request {
const headers = new Headers(init.headers)
if (body) headers.set('Content-Type', 'application/json')
if (cookie) headers.set('Cookie', cookie)
return new Request(new URL(path, accountAuthenticationConfig.publicURL), {
method: init.method ?? (body ? 'POST' : 'GET'),
headers,
body: body ? JSON.stringify(body) : undefined
})
}
export function authenticationCookie(response: Response): string {
const value = response.headers.get('set-cookie')?.split(';', 1)[0]
if (!value) throw new Error('Authentication response did not set a cookie')
return value
}
export function accountAuthenticationObjects() {
return {
capabilities: { nativeSHA256: true, multipartUpload: false, conditionalWrites: false },
async checkReadiness() {
return { ok: true, checksumVerification: 'native' as const }
},
async createDownload() {
throw new Error('not used')
},
async createUpload() {
throw new Error('not used')
},
completeUpload: ignore,
abortUpload: ignore,
async head() {
return null
},
delete: ignore
}
}
export async function createAccountAuthenticationFixture(
options: {
config?: typeof accountAuthenticationConfig
onPasswordChanged?: () => void
/** Account emails the test reads; the rest go nowhere. */
email?: Partial<AuthenticationEmailService>
} = {}
) {
const config = options.config ?? accountAuthenticationConfig
const runtime = await createCloudTestDatabase()
const auth = createBetterAuthAdapter(config, runtime.database, undefined, {
email: {
...ignoredSecurityNotices,
sendVerification: ignore,
sendPasswordReset: ignore,
async sendPasswordChanged() {
options.onPasswordChanged?.()
},
...options.email
}
})
return {
...runtime,
app: createCloudApp({
config,
database: runtime.database,
auth,
objects: accountAuthenticationObjects()
})
}
}
export async function approveAccount(
database: Awaited<ReturnType<typeof createAccountAuthenticationFixture>>['database'],
input: { email: string; name: string; userId: string }
): Promise<void> {
await database
.insertInto('enrollment')
.values({
id: crypto.randomUUID(),
emailNormalized: input.email,
name: input.name,
reason: null,
status: 'approved',
reviewedAt: new Date(),
reviewedBy: 'admin',
reviewNote: null,
approvedUserId: input.userId
})
.execute()
}
export async function createVerifiedCredentialAccount(
fixture: Awaited<ReturnType<typeof createAccountAuthenticationFixture>>,
input: { email: string; name: string; password: string; approved: boolean; image?: string }
): Promise<{ userId: string; sessionCookie: string }> {
await fixture.app.fetch(
accountAuthenticationRequest('/api/auth/sign-up/email', {
name: input.name,
email: input.email,
password: input.password,
image: input.image
})
)
const user = await fixture.database
.selectFrom('user')
.select('id')
.where('email', '=', input.email)
.executeTakeFirstOrThrow()
await fixture.database
.updateTable('user')
.set({ emailVerified: true })
.where('id', '=', user.id)
.execute()
if (input.approved) {
await approveAccount(fixture.database, {
email: input.email,
name: input.name,
userId: user.id
})
}
const signIn = await fixture.app.fetch(
accountAuthenticationRequest('/api/auth/sign-in/email', {
email: input.email,
password: input.password
})
)
return { userId: user.id, sessionCookie: authenticationCookie(signIn) }
}