Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(platform): send sign-in codes through Cloudflare Email binding

HoshinoSuzumiBote4a53cf050e9
diff --git a/.github/workflows/deploy-saas.yml b/.github/workflows/deploy-saas.yml
index ec857984..b65c4900 100644
--- a/.github/workflows/deploy-saas.yml
+++ b/.github/workflows/deploy-saas.yml
@@ -134,6 +134,7 @@ jobs:
ENTRIES: ${{ needs.plan.outputs.entries }}
DEPLOY_ENVIRONMENT: ${{ inputs.environment }}
PLATFORM_D1_DATABASE_ID: ${{ vars.PLATFORM_D1_DATABASE_ID }}
+ PLATFORM_EMAIL_FROM: ${{ vars.PLATFORM_EMAIL_FROM }}
run: |
set -euo pipefail
for entry in $ENTRIES; do
@@ -162,6 +163,14 @@ jobs:
config.d1_databases = [binding]
}
}
+ const emailFrom = process.env.PLATFORM_EMAIL_FROM
+ if (process.env.ENTRY === 'cloud' && emailFrom) {
+ if (!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(emailFrom)) throw new Error('Invalid platform email sender address')
+ const target = process.env.DEPLOY_ENVIRONMENT === 'staging' ? config.previews : config
+ target.send_email = [{ name: 'EMAIL', allowed_sender_addresses: [emailFrom] }]
+ target.vars = { ...target.vars, NUXT_PLATFORM_EMAIL_FROM: emailFrom }
+ if (process.env.DEPLOY_ENVIRONMENT === 'staging') delete config.send_email
+ }
config.routes = []
delete config.route
delete config.env
diff --git a/apps/cloud/.env.example b/apps/cloud/.env.example
index 7b50905c..0883cdc8 100644
--- a/apps/cloud/.env.example
+++ b/apps/cloud/.env.example
@@ -1,11 +1,11 @@
# App-local configuration; the root Self-hosted .env is not loaded.
# NUXT_SESSION_PASSWORD=replace-with-a-unique-secret-of-at-least-32-characters
-# Platform runtime configuration. No mail provider is enabled by default.
+# Platform runtime configuration. Email sign-in also requires migrated D1.
# NUXT_PLATFORM_PORTAL_ORIGIN=https://app.chronoframe.art
# NUXT_PLATFORM_SECRET=use-an-independent-random-secret-of-at-least-32-bytes
-# Optional Resend adapter (select only after choosing a provider):
-# NUXT_PLATFORM_EMAIL_PROVIDER=resend
-# NUXT_PLATFORM_EMAIL_API_KEY=configure-as-a-Worker-secret
-# NUXT_PLATFORM_EMAIL_FROM=ChronoFrame <signin@your-verified-domain>
+# EMAIL is a Cloudflare Email Sending send_email binding, not an API key.
# PLATFORM_DB is a D1 binding, not a string environment variable.
+# The deploy workflow reads PLATFORM_EMAIL_FROM and PLATFORM_D1_DATABASE_ID
+# from the selected GitHub Environment variables. No mail provider key is needed.
diff --git a/apps/cloud/nuxt.config.ts b/apps/cloud/nuxt.config.ts
index 41fd9926..209ce2bf 100644
--- a/apps/cloud/nuxt.config.ts
+++ b/apps/cloud/nuxt.config.ts
@@ -20,8 +20,6 @@ export default defineNuxtConfig({
platform: {
portalOrigin: 'https://app.chronoframe.art',
secret: '',
- emailProvider: '',
- emailApiKey: '',
emailFrom: '',
},
},
diff --git a/apps/cloud/server/api/auth/status.get.ts b/apps/cloud/server/api/auth/status.get.ts
index d260b0c5..003b0d6e 100644
--- a/apps/cloud/server/api/auth/status.get.ts
+++ b/apps/cloud/server/api/auth/status.get.ts
@@ -1,3 +1,4 @@
+import { platformEmailReady } from '../../../../platform-email'
import {
platformRequestURL,
platformDatabase,
@@ -7,9 +8,10 @@ export default defineEventHandler(async (event) => {
const origin = platformRequestURL(event).origin
const configured =
origin === config.portalOrigin &&
- config.emailProvider === 'resend' &&
- !!config.emailApiKey &&
- !!config.emailFrom &&
+ platformEmailReady(
+ event.context.cloudflare?.env?.EMAIL,
+ config.emailFrom,
+ ) &&
config.secret.length >= 32 &&
!!event.context.cloudflare?.env?.PLATFORM_DB
if (!configured) return { enabled: false }
diff --git a/apps/cloud/server/utils/platform-auth.ts b/apps/cloud/server/utils/platform-auth.ts
index f13dd29d..4f7de61d 100644
--- a/apps/cloud/server/utils/platform-auth.ts
+++ b/apps/cloud/server/utils/platform-auth.ts
@@ -6,14 +6,17 @@ import {
} from '../../../platform.runtime'
import { createEmailCodeCrypto } from '../../../platform-crypto'
import type { H3Event } from 'h3'
+import {
+ createCloudflareEmailSender,
+ platformEmailReady,
+} from '../../../platform-email'
export async function emailSignIn(event: H3Event) {
const config = useRuntimeConfig(event).platform
platformPortalOrigin(event, config.portalOrigin, true)
+ const emailBinding = event.context.cloudflare?.env?.EMAIL
if (
- config.emailProvider !== 'resend' ||
- !config.emailApiKey ||
- !config.emailFrom ||
+ !platformEmailReady(emailBinding, config.emailFrom) ||
config.secret.length < 32
) {
throw createError({
@@ -24,24 +27,6 @@ export async function emailSignIn(event: H3Event) {
return createEmailCodeSignIn(
createD1EmailCodeStore(platformDatabase(event)),
await createEmailCodeCrypto(config.secret),
- {
- async send({ email, code, expiresInMinutes }) {
- const response = await fetch('https://api.resend.com/emails', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${config.emailApiKey}`,
- 'Content-Type': 'application/json',
- },
- signal: AbortSignal.timeout(10_000),
- body: JSON.stringify({
- from: config.emailFrom,
- to: [email],
- subject: 'Your ChronoFrame sign-in code',
- text: `Your ChronoFrame sign-in code is ${code}. It expires in ${expiresInMinutes} minutes. If you did not request this code, you can ignore this email.`,
- }),
- })
- if (!response.ok) throw new Error('Email delivery failed')
- },
- },
+ createCloudflareEmailSender(emailBinding, config.emailFrom),
)
}
diff --git a/apps/platform-email.ts b/apps/platform-email.ts
new file mode 100644
index 00000000..9231727f
--- /dev/null
+++ b/apps/platform-email.ts
@@ -0,0 +1,39 @@
+import type { EmailCodeSender } from '../packages/core/src/email-auth'
+
+/** Cloudflare Email Sending structured-message binding; no REST credentials. */
+export interface PlatformEmailBinding {
+ send(message: {
+ from: string
+ to: string
+ subject: string
+ text: string
+ }): Promise<{ messageId: string }>
+}
+
+export function platformEmailReady(
+ binding: unknown,
+ from: string,
+): binding is PlatformEmailBinding {
+ return (
+ !!binding &&
+ typeof (binding as PlatformEmailBinding).send === 'function' &&
+ /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(from)
+ )
+}
+
+export function createCloudflareEmailSender(
+ binding: PlatformEmailBinding,
+ from: string,
+): EmailCodeSender {
+ return {
+ async send({ email, code, expiresInMinutes }) {
+ const result = await binding.send({
+ from,
+ to: email,
+ subject: 'Your ChronoFrame sign-in code',
+ text: `Your ChronoFrame sign-in code is ${code}. It expires in ${expiresInMinutes} minutes. If you did not request this code, you can ignore this email.`,
+ })
+ if (!result?.messageId) throw new Error('Email delivery failed')
+ },
+ }
+}
diff --git a/packages/platform/README.md b/packages/platform/README.md
index 01915204..170d56d8 100644
--- a/packages/platform/README.md
+++ b/packages/platform/README.md
@@ -23,9 +23,22 @@ Cloud runtime settings are private Worker configuration:
`https://app.chronoframe.art`. A staging Preview needs its own exact origin.
- `NUXT_PLATFORM_SECRET`: independent random secret of at least 32 bytes in each
environment. Used for keyed email-code digests and opaque session-token digests.
-- `NUXT_PLATFORM_EMAIL_PROVIDER`, `NUXT_PLATFORM_EMAIL_API_KEY`, and
- `NUXT_PLATFORM_EMAIL_FROM`: enable only after selecting a mail provider.
- An optional Resend adapter is available; it is disabled by default.
+- `NUXT_PLATFORM_EMAIL_FROM`: a plain sender address on your verified Cloudflare
+ Email Service domain, for example `[email protected]`.
+- `EMAIL`: a Cloudflare Email Sending `send_email` binding, using the structured
+ `send({ from, to, subject, text })` API. No Resend or email API key is needed.
+
+Set the GitHub Environment variable `PLATFORM_EMAIL_FROM` to that sender address.
+The workflow adds `EMAIL` only to cloud, restricts `allowed_sender_addresses` to
+this address, and sets `NUXT_PLATFORM_EMAIL_FROM`. Production uses top-level
+configuration; staging uses `previews.send_email` and `previews.vars`. This keeps
+runtime bindings reproducible on subsequent deployments. With no sender variable
+or binding, email sign-in stays disabled. Local Wrangler simulation must use
+`remote: false` (the default) to avoid real delivery.
+
+See the [Cloudflare binding API](https://developers.cloudflare.com/email-service/api/send-emails/workers-api/).
+The verified sending domain must be active; any account recipient restrictions
+or sending limits still apply. A binding does not verify the domain itself.
Configure Preview secrets separately from production. Runtime credentials are
not GitHub deployment credentials, and no plaintext OTP is stored in D1.
diff --git a/scripts/check-entry-boundaries.mjs b/scripts/check-entry-boundaries.mjs
index c9c9fb68..ee6d5f98 100644
--- a/scripts/check-entry-boundaries.mjs
+++ b/scripts/check-entry-boundaries.mjs
@@ -27,6 +27,7 @@ for (const entry of ['cloud', 'site']) {
'apps/nuxt.shared.ts',
'apps/platform.runtime.ts',
'apps/platform-crypto.ts',
+ 'apps/platform-email.ts',
]) {
const code = await readFile(file, 'utf8')
for (const match of code.matchAll(
diff --git a/tests/platform-email-binding.test.ts b/tests/platform-email-binding.test.ts
new file mode 100644
index 00000000..f6ec7711
--- /dev/null
+++ b/tests/platform-email-binding.test.ts
@@ -0,0 +1,50 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import {
+ createCloudflareEmailSender,
+ platformEmailReady,
+} from '../apps/platform-email.ts'
+
+test('Cloudflare Email Sending uses the structured binding without REST credentials', async () => {
+ const messages: unknown[] = []
+ const binding = {
+ async send(message: unknown) {
+ messages.push(message)
+ return { messageId: 'local-only' }
+ },
+ }
+ assert.equal(
+ platformEmailReady(binding, '[email protected]'),
+ true,
+ )
+ assert.equal(
+ platformEmailReady(undefined, '[email protected]'),
+ false,
+ )
+ assert.equal(
+ platformEmailReady(binding, '[email protected]\r\nBcc: [email protected]'),
+ false,
+ )
+ await createCloudflareEmailSender(
+ binding,
+ ).send({ email: '[email protected]', code: '123456', expiresInMinutes: 10 })
+ assert.deepEqual(messages, [
+ {
+ subject: 'Your ChronoFrame sign-in code',
+ text: 'Your ChronoFrame sign-in code is 123456. It expires in 10 minutes. If you did not request this code, you can ignore this email.',
+ },
+ ])
+ await assert.rejects(
+ createCloudflareEmailSender(
+ {
+ async send() {
+ throw new Error('provider unavailable')
+ },
+ },
+ ).send({ email: '[email protected]', code: '123456', expiresInMinutes: 10 }),
+ )
+})