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(auth): add configurable social login and account profiles

Timothy Yinf54c7e38d0bd
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 45dda2fc..019095ee 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -307,15 +307,16 @@
.cf-auth-form form {
display: flex;
flex-direction: column;
- gap: 12px;
- margin-top: 30px;
+ gap: 8px;
+ margin-top: 24px;
}
.cf-auth-form label {
font-size: 12px;
font-weight: 550;
}
.cf-auth-form .cf-button[type='submit'] {
- margin-top: 8px;
+ justify-content: center;
+ margin-top: 16px;
width: 100%;
}
.cf-auth-hint {
@@ -3139,3 +3140,15 @@ a.cf-domain-address:hover {
.cf-handover-options input {
flex-shrink: 0;
}
+
+/* Keep primary actions, alternative methods and account navigation in distinct rows. */
+.cf-auth-form form > label:not(:first-child) { margin-top: 12px; }
+.cf-auth-form form > .cf-text-link { align-self: flex-end; font-size: 12px; margin: 2px 0 4px; }
+.cf-auth-form form > .cf-auth-hint { margin: 0; line-height: 1.6; }
+.cf-auth-form form > .cf-button:not([type='submit']) { justify-content: center; white-space: normal; text-align: center; }
+.cf-auth-alternatives { display: grid; gap: 16px; margin-top: 24px; }
+.cf-auth-alternatives > .cf-button { width: 100%; justify-content: center; }
+.cf-social-login { display: grid; gap: 12px; }
+.cf-social-login-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
+.cf-social-login-grid > .cf-button { width: 100%; min-width: 0; justify-content: center; }
+.cf-auth-form > .cf-auth-footer { display: flex; flex-wrap: wrap; justify-content: center; align-items: baseline; gap: 6px; margin: 24px 0 0; font-size: 13px; line-height: 1.6; }
diff --git a/apps/cloud/app/components/CloudAccountProfile.vue b/apps/cloud/app/components/CloudAccountProfile.vue
new file mode 100644
index 00000000..115b4405
--- /dev/null
+++ b/apps/cloud/app/components/CloudAccountProfile.vue
@@ -0,0 +1,165 @@
+<script setup lang="ts">
+const { t } = useI18n()
+const user = usePortalIdentity()
+const name = ref(user.value?.name ?? '')
+const image = ref(user.value?.image ?? '')
+const upload = useTemplateRef<{ inputRef: HTMLInputElement }>('upload')
+const busy = ref(false),
+ processing = ref(false),
+ error = ref(''),
+ notice = ref('')
+async function chooseImage(event: Event) {
+ const input = event.target as HTMLInputElement
+ const file = input.files?.[0]
+ error.value = ''
+ notice.value = ''
+ if (!file) return
+ if (
+ !['image/png', 'image/jpeg', 'image/webp'].includes(file.type) ||
+ file.size > 2 * 1024 * 1024
+ ) {
+ error.value = t('cloud.messages.chooseAPngJpegOrWebpImageUpTo')
+ input.value = ''
+ return
+ }
+ processing.value = true
+ try {
+ const bitmap = await createImageBitmap(file)
+ try {
+ const canvas = document.createElement('canvas')
+ canvas.width = canvas.height = 128
+ const size = Math.min(bitmap.width, bitmap.height)
+ canvas
+ .getContext('2d')!
+ .drawImage(
+ bitmap,
+ (bitmap.width - size) / 2,
+ (bitmap.height - size) / 2,
+ size,
+ size,
+ 0,
+ 0,
+ 128,
+ 128,
+ )
+ const result = canvas.toDataURL('image/webp', 0.85)
+ if (result.length > 65536) throw new Error('Image too large')
+ image.value = result
+ } finally {
+ bitmap.close()
+ }
+ } catch {
+ error.value = t('cloud.messages.thisImageCouldNotBeUsedTryAnotherImage')
+ } finally {
+ processing.value = false
+ input.value = ''
+ }
+}
+async function save() {
+ if (busy.value || processing.value) return
+ busy.value = true
+ error.value = ''
+ notice.value = ''
+ try {
+ const result = await $fetch<{ user: NonNullable<typeof user.value> }>(
+ '/api/account/profile',
+ { method: 'PUT', body: { name: name.value, image: image.value || null } },
+ )
+ user.value = result.user
+ name.value = result.user.name ?? ''
+ image.value = result.user.image ?? ''
+ notice.value = t('cloud.account.profileSaved')
+ } catch {
+ error.value = t('cloud.account.profileFailed')
+ } finally {
+ busy.value = false
+ }
+}
+</script>
+<template>
+ <form
+ class="cf-profile-form"
+ @submit.prevent="save"
+ >
+ <UFormField
+ :label="$t('cloud.account.nickname')"
+ name="nickname"
+ >
+ <CfInput
+ v-model="name"
+ :placeholder="$t('cloud.account.nicknamePlaceholder')"
+ autocomplete="nickname"
+ maxlength="80"
+ required
+ :disabled="busy"
+ />
+ </UFormField>
+ <UFormField
+ :label="$t('cloud.account.avatar')"
+ :help="$t('cloud.account.avatarHelp')"
+ >
+ <div class="flex flex-wrap items-center gap-4">
+ <UAvatar
+ :src="image || undefined"
+ :alt="name"
+ size="3xl"
+ />
+ <div class="flex flex-wrap gap-2">
+ <CfButton
+ variant="outline"
+ :disabled="busy || processing"
+ :loading="processing"
+ @click="upload?.inputRef?.click()"
+ >{{ $t('cloud.account.chooseAvatar') }}</CfButton
+ >
+ <CfButton
+ v-if="image"
+ variant="ghost"
+ :disabled="busy || processing"
+ @click="image = ''"
+ >{{ $t('cloud.account.removeAvatar') }}</CfButton
+ >
+ </div>
+ </div>
+ <UInput
+ ref="upload"
+ type="file"
+ class="hidden"
+ accept="image/png,image/jpeg,image/webp"
+ :disabled="busy || processing"
+ :aria-label="$t('cloud.account.chooseAvatar')"
+ @change="chooseImage"
+ />
+ </UFormField>
+ <p
+ v-if="error"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <p
+ v-if="notice"
+ class="cf-notice"
+ role="status"
+ >
+ {{ notice }}
+ </p>
+ <div>
+ <CfButton
+ type="submit"
+ :disabled="!name.trim() || processing"
+ :loading="busy"
+ >{{ $t('cloud.messages.saveChanges') }}</CfButton
+ >
+ </div>
+ </form>
+</template>
+<style scoped>
+.cf-profile-form {
+ display: grid;
+ gap: 20px;
+ padding: 20px;
+ max-width: 560px;
+}
+</style>
diff --git a/apps/cloud/app/components/CloudHeaderLayoutChoice.vue b/apps/cloud/app/components/CloudHeaderLayoutChoice.vue
index e7e0f864..a9be42c7 100644
--- a/apps/cloud/app/components/CloudHeaderLayoutChoice.vue
+++ b/apps/cloud/app/components/CloudHeaderLayoutChoice.vue
@@ -9,7 +9,6 @@ const items = computed(() =>
})),
)
</script>
-
<template>
<URadioGroup
v-model="model"
@@ -18,96 +17,94 @@ const items = computed(() =>
:items="items"
orientation="horizontal"
variant="card"
- size="sm"
+ indicator="hidden"
:ui="{
root: 'w-full',
fieldset: 'grid grid-cols-2 gap-3',
- item: 'relative min-w-0 p-3',
- container: 'absolute bottom-3.5 left-3',
+ item: 'relative min-w-0 overflow-hidden p-0',
wrapper: 'w-full min-w-0',
label: 'block w-full',
}"
>
<template #label="{ item }">
- <span class="flex flex-col gap-3">
+ <span class="sr-only">{{ item.label }}</span>
+ <span
+ aria-hidden="true"
+ class="flex aspect-video w-full flex-col gap-[6%] overflow-hidden p-[6%]"
+ >
<span
- aria-hidden="true"
- class="flex h-32 flex-col gap-2 overflow-hidden rounded border border-default bg-default p-2"
+ v-if="item.value === 'fixed'"
+ class="flex h-1/4 shrink-0 items-center gap-[6%] rounded-sm bg-[var(--input)] p-[2%]"
>
- <span
- v-if="item.value === 'fixed'"
- class="flex items-center gap-2 border-b border-default pb-2"
- >
+ <USkeleton
+ as="span"
+ class="aspect-square h-full shrink-0 animate-none rounded-full"
+ />
+ <span class="flex h-full flex-1 flex-col justify-center gap-[20%]">
<USkeleton
as="span"
- class="size-5 shrink-0 animate-none rounded-full"
+ class="h-1/4 w-1/2 animate-none"
/>
- <span class="flex flex-1 flex-col gap-1">
- <USkeleton
- as="span"
- class="h-1.5 w-1/2 animate-none"
- />
- <USkeleton
- as="span"
- class="h-1 w-1/3 animate-none"
- />
- </span>
<USkeleton
as="span"
- class="h-2 w-5 animate-none"
+ class="h-1/5 w-1/3 animate-none"
/>
</span>
- <span class="grid flex-1 grid-cols-3 items-start gap-1.5">
- <span class="flex flex-col gap-1.5">
- <span
- v-if="item.value === 'embedded'"
- class="flex h-16 flex-col items-center justify-center gap-1.5 rounded bg-elevated/50"
- >
- <USkeleton
- as="span"
- class="size-5 animate-none rounded-full"
- />
- <USkeleton
- as="span"
- class="h-1.5 w-3/4 animate-none"
- />
- <USkeleton
- as="span"
- class="h-1 w-1/2 animate-none"
- />
- </span>
- <USkeleton
- as="span"
- class="h-11 w-full animate-none rounded-sm"
- />
- <USkeleton
- as="span"
- class="h-12 w-full animate-none rounded-sm"
- />
- </span>
- <span class="flex flex-col gap-1.5">
- <USkeleton
- as="span"
- class="h-12 w-full animate-none rounded-sm"
- />
+ <USkeleton
+ as="span"
+ class="h-1/3 w-1/6 animate-none"
+ />
+ </span>
+ <span class="grid min-h-0 flex-1 grid-cols-3 gap-[5%]">
+ <span class="flex min-h-0 flex-col gap-[8%]">
+ <span
+ v-if="item.value === 'embedded'"
+ class="flex h-3/5 shrink-0 flex-col items-center justify-center gap-[10%] rounded-sm bg-[var(--input)] p-[6%]"
+ >
<USkeleton
as="span"
- class="h-16 w-full animate-none rounded-sm"
+ class="aspect-square h-1/2 animate-none rounded-full"
/>
- </span>
- <span class="flex flex-col gap-1.5">
<USkeleton
as="span"
- class="h-16 w-full animate-none rounded-sm"
+ class="h-[10%] w-3/4 animate-none"
/>
<USkeleton
as="span"
- class="h-11 w-full animate-none rounded-sm"
+ class="h-[8%] w-1/2 animate-none"
/>
</span>
+ <USkeleton
+ as="span"
+ class="min-h-0 flex-1 animate-none rounded-sm"
+ />
+ <USkeleton
+ v-if="item.value === 'fixed'"
+ as="span"
+ class="h-2/5 animate-none rounded-sm"
+ />
+ </span>
+ <span class="flex min-h-0 flex-col gap-[8%]">
+ <USkeleton
+ as="span"
+ class="h-2/5 animate-none rounded-sm"
+ />
+ <USkeleton
+ as="span"
+ class="min-h-0 flex-1 animate-none rounded-sm"
+ />
+ </span>
+ <span class="flex min-h-0 flex-col gap-[8%]">
+ <USkeleton
+ as="span"
+ class="h-3/5 animate-none rounded-sm"
+ />
+ <USkeleton
+ as="span"
+ class="min-h-0 flex-1 animate-none rounded-sm"
+ />
</span>
</span>
- <span class="pl-6">{{ item.label }}</span>
</span>
</template>
</URadioGroup>
diff --git a/apps/cloud/app/components/CloudSocialLogin.vue b/apps/cloud/app/components/CloudSocialLogin.vue
new file mode 100644
index 00000000..7cb1ea41
--- /dev/null
+++ b/apps/cloud/app/components/CloudSocialLogin.vue
@@ -0,0 +1,68 @@
+<script setup lang="ts">
+import { SOCIAL_LOGIN_PROVIDERS } from '@chronoframe/contracts/social-login'
+import { accountError } from '../utils/account-error'
+const props = defineProps<{ providers: readonly string[] }>()
+const busy = defineModel<boolean>('busy', { default: false })
+const { t } = useI18n()
+const { destination, authLink } = useCloudAuthDestination()
+const available = computed(() =>
+ SOCIAL_LOGIN_PROVIDERS.filter((provider) =>
+ props.providers.includes(provider.id),
+ ),
+)
+const selected = ref(''),
+ error = ref('')
+async function signIn(provider: string) {
+ if (busy.value) return
+ busy.value = true
+ selected.value = provider
+ error.value = ''
+ try {
+ const origin = useRequestURL().origin
+ const failure = new URL('/signin', origin)
+ failure.searchParams.set('oauthError', '1')
+ const next = authLink('/signin').query.next
+ if (next) failure.searchParams.set('next', next)
+ const result = await $fetch<{ url: string }>('/api/auth/sign-in/social', {
+ method: 'POST',
+ body: {
+ provider,
+ callbackURL: new URL(destination.value, origin).toString(),
+ errorCallbackURL: failure.toString(),
+ },
+ })
+ await navigateTo(result.url, { external: true })
+ } catch (cause) {
+ error.value = accountError(cause, t)
+ } finally {
+ busy.value = false
+ selected.value = ''
+ }
+}
+</script>
+<template>
+ <div
+ v-if="available.length"
+ class="cf-social-login"
+ >
+ <div class="cf-social-login-grid">
+ <CfButton
+ v-for="provider in available"
+ :key="provider.id"
+ variant="outline"
+ :disabled="busy"
+ :loading="busy && selected === provider.id"
+ :leading-icon="provider.icon"
+ @click="signIn(provider.id)"
+ >{{ provider.name }}</CfButton
+ >
+ </div>
+ <p
+ v-if="error"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ </div>
+</template>
diff --git a/apps/cloud/app/components/CloudUserMenu.vue b/apps/cloud/app/components/CloudUserMenu.vue
index 3f76302b..7dbd3390 100644
--- a/apps/cloud/app/components/CloudUserMenu.vue
+++ b/apps/cloud/app/components/CloudUserMenu.vue
@@ -79,6 +79,7 @@ const menuItems = computed(() => [
>
<UAvatar
:text="initials"
+ :src="user?.image || undefined"
size="sm"
/>
<span class="cf-user-identity"
diff --git a/apps/cloud/app/composables/useCloudAuthDestination.ts b/apps/cloud/app/composables/useCloudAuthDestination.ts
index 274b6826..3ef1c1dc 100644
--- a/apps/cloud/app/composables/useCloudAuthDestination.ts
+++ b/apps/cloud/app/composables/useCloudAuthDestination.ts
@@ -4,7 +4,7 @@ export function useCloudAuthDestination() {
const destination = computed(
() => purchaseReturnPath(route.query.next) ?? '/workspace',
)
- function authLink(path: '/signin' | '/signup') {
+ function authLink(path: '/signin' | '/signup' | '/forgot-password') {
const next = purchaseReturnPath(route.query.next)
return { path, query: next ? { next } : {} }
}
diff --git a/apps/cloud/app/composables/usePortalIdentity.ts b/apps/cloud/app/composables/usePortalIdentity.ts
index 30aadaee..67eb618a 100644
--- a/apps/cloud/app/composables/usePortalIdentity.ts
+++ b/apps/cloud/app/composables/usePortalIdentity.ts
@@ -1,6 +1,7 @@
export interface PortalIdentity {
id: number
name?: string | null
+ image?: string | null
email?: string
}
export function usePortalIdentity() {
diff --git a/apps/cloud/app/pages/account/index.vue b/apps/cloud/app/pages/account/index.vue
index 3d44a326..e863e1c6 100644
--- a/apps/cloud/app/pages/account/index.vue
+++ b/apps/cloud/app/pages/account/index.vue
@@ -29,7 +29,8 @@ const user = usePortalIdentity()
{{ $t('cloud.messages.profile') }}
</h2>
<CfCard class="cf-settings-card"
- ><div class="cf-setting-row">
+ ><CloudAccountProfile />
+ <div class="cf-setting-row">
<div>
<h3>{{ $t('cloud.messages.emailAddress') }}</h3>
<p>{{ user?.email }}</p>
diff --git a/apps/cloud/app/pages/forgot-password.vue b/apps/cloud/app/pages/forgot-password.vue
index cfb0edf1..39660ddb 100644
--- a/apps/cloud/app/pages/forgot-password.vue
+++ b/apps/cloud/app/pages/forgot-password.vue
@@ -66,7 +66,7 @@ async function submit() {
>{{ $t('cloud.messages.sendResetLink') }}</CfButton
>
</form>
- <p class="cf-auth-hint">
+ <p class="cf-auth-footer">
<NuxtLink
to="/signin"
class="cf-text-link"
diff --git a/apps/cloud/app/pages/reset-password.vue b/apps/cloud/app/pages/reset-password.vue
index c7f14229..27a1ead2 100644
--- a/apps/cloud/app/pages/reset-password.vue
+++ b/apps/cloud/app/pages/reset-password.vue
@@ -97,7 +97,7 @@ async function submit() {
}}</NuxtLink
>.
</p>
- <p class="cf-auth-hint">
+ <p class="cf-auth-footer">
<NuxtLink
to="/signin"
class="cf-text-link"
diff --git a/apps/cloud/app/pages/signin.vue b/apps/cloud/app/pages/signin.vue
index d6fa72b9..8aaad5d2 100644
--- a/apps/cloud/app/pages/signin.vue
+++ b/apps/cloud/app/pages/signin.vue
@@ -12,16 +12,29 @@ const email = ref(''),
password = ref(''),
code = ref('')
const mode = ref<'password' | 'email'>('password')
-const step = ref<'credentials' | 'code' | 'second'>('credentials')
+const route = useRoute()
+const second = ['totp', 'email'].includes(String(route.query.second))
+ ? String(route.query.second)
+ : ''
+const step = ref<'credentials' | 'code' | 'second'>(
+ second ? 'second' : 'credentials',
+)
function setMode(value: 'email' | 'password') {
mode.value = value
error.value = ''
}
-const authenticatorRequired = ref(false)
-const factor = ref<'email' | 'totp' | 'recovery'>('email')
+const authenticatorRequired = ref(second === 'totp')
+const factor = ref<'email' | 'totp' | 'recovery'>(
+ second === 'totp' ? 'totp' : 'email',
+)
const busy = ref(false),
- error = ref('')
-const codeInput = ref<{ $el: HTMLInputElement }>()
+ error = ref(
+ route.query.oauthError ? t('cloud.account.socialLoginFailed') : '',
+ )
+const codeInput = ref<{ focus(): void }>()
+onMounted(() => {
+ if (second === 'email') void resend()
+})
async function sendSecond() {
await $fetch('/api/auth/two-factor/send-otp', { method: 'POST', body: {} })
}
@@ -84,7 +97,7 @@ async function submit() {
busy.value = false
if (step.value !== 'credentials') {
await nextTick()
- codeInput.value?.$el?.focus()
+ codeInput.value?.focus()
}
}
}
@@ -139,7 +152,7 @@ async function resend() {
}}
</p>
<div
- v-if="step === 'credentials'"
+ v-if="step === 'credentials' && status.emailEnabled"
class="cf-auth-tabs"
:aria-label="$t('cloud.messages.signInMethod')"
>
@@ -156,6 +169,7 @@ async function resend() {
>
</div>
<form
+ v-if="status.emailEnabled || step === 'second'"
@submit.prevent="submit"
:aria-busy="busy"
>
@@ -180,7 +194,7 @@ async function resend() {
required
/><NuxtLink
class="cf-text-link"
- to="/forgot-password"
+ :to="authLink('/forgot-password')"
>{{ $t('cloud.messages.forgotYourPassword') }}</NuxtLink
></template
>
@@ -261,15 +275,34 @@ async function resend() {
>{{ $t('cloud.messages.sendANewCode') }}</CfButton
>
</form>
- <CfButton
+ <p
+ v-if="error && !status.emailEnabled && step !== 'second'"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <div
v-if="step === 'credentials'"
- class="cf-action-spaced"
- variant="secondary"
- :disabled="busy"
- @click="passkeySignIn"
- >{{ $t('cloud.messages.signInWithAPasskey') }}</CfButton
+ class="cf-auth-alternatives"
>
- <p class="cf-auth-hint">
+ <USeparator
+ v-if="status.emailEnabled"
+ :label="$t('cloud.account.orContinueWith')"
+ />
+ <CfButton
+ variant="outline"
+ :disabled="busy"
+ leading-icon="i-lucide-key-round"
+ @click="passkeySignIn"
+ >{{ $t('cloud.messages.signInWithAPasskey') }}</CfButton
+ >
+ <CloudSocialLogin
+ v-model:busy="busy"
+ :providers="status.providers ?? []"
+ />
+ </div>
+ <p class="cf-auth-footer">
{{ $t('cloud.messages.newHere')
}}<NuxtLink
:to="authLink('/signup')"
diff --git a/apps/cloud/app/pages/signup.vue b/apps/cloud/app/pages/signup.vue
index 711a3b93..75aafc82 100644
--- a/apps/cloud/app/pages/signup.vue
+++ b/apps/cloud/app/pages/signup.vue
@@ -14,7 +14,7 @@ const email = ref(''),
sent = ref(false),
busy = ref(false),
error = ref('')
-const codeInput = ref<{ $el: HTMLInputElement }>()
+const codeInput = ref<{ focus(): void }>()
async function submit() {
busy.value = true
error.value = ''
@@ -43,7 +43,7 @@ async function submit() {
busy.value = false
if (sent.value) {
await nextTick()
- codeInput.value?.$el?.focus()
+ codeInput.value?.focus()
}
}
}
@@ -73,7 +73,10 @@ async function resend() {
: $t('cloud.messages.aHomeForYourPhotographs')
}}
</h1>
- <template v-if="status?.enabled"
+ <template
+ v-if="
+ status?.enabled && (status.emailEnabled || status.providers?.length)
+ "
><p>
{{
sent
@@ -82,6 +85,7 @@ async function resend() {
}}
</p>
<form
+ v-if="status.emailEnabled"
@submit.prevent="submit"
:aria-busy="busy"
>
@@ -151,7 +155,20 @@ async function resend() {
}}</CfButton
>
</form>
- <p class="cf-auth-hint">
+ <div
+ v-if="!sent && status.providers?.length"
+ class="cf-auth-alternatives"
+ >
+ <USeparator
+ v-if="status.emailEnabled"
+ :label="$t('cloud.account.orContinueWith')"
+ />
+ <CloudSocialLogin
+ v-model:busy="busy"
+ :providers="status.providers"
+ />
+ </div>
+ <p class="cf-auth-footer">
{{ $t('cloud.messages.alreadyHaveAnAccount')
}}<NuxtLink
:to="authLink('/signin')"
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index 52e9fef3..b28d70bc 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -1,5 +1,17 @@
{
"cloud": {
+ "account": {
+ "nickname": "Nickname",
+ "nicknamePlaceholder": "Your display name",
+ "avatar": "Avatar",
+ "avatarHelp": "PNG, JPEG or WebP, up to 2 MiB. Images are cropped to a square.",
+ "chooseAvatar": "Choose image",
+ "removeAvatar": "Remove image",
+ "profileSaved": "Profile updated.",
+ "profileFailed": "Unable to save your profile. Use a nickname of up to 80 characters and a supported image.",
+ "socialLoginFailed": "Unable to sign in with this provider. Try again, or verify your email using an email code.",
+ "orContinueWith": "Or continue with"
+ },
"home": {
"trialRibbon": "14-day trial",
"selfHostedTitle": "Self-hosted",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index 638775e8..a4f23897 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -1,5 +1,17 @@
{
"cloud": {
+ "account": {
+ "nickname": "昵称",
+ "nicknamePlaceholder": "填写你的昵称",
+ "avatar": "头像",
+ "avatarHelp": "支持 PNG、JPEG 或 WebP,最大 2 MiB,将裁剪为正方形。",
+ "chooseAvatar": "选择图片",
+ "removeAvatar": "移除图片",
+ "profileSaved": "个人资料已更新。",
+ "profileFailed": "保存失败,请填写不超过 80 个字符的昵称并使用支持的图片。",
+ "socialLoginFailed": "第三方登录失败,请重试,或使用邮箱验证码验证邮箱后登录。",
+ "orContinueWith": "或使用其他方式"
+ },
"home": {
"trialRibbon": "14 天试用",
"selfHostedTitle": "自部署",
diff --git a/apps/cloud/server/api/account/profile.put.ts b/apps/cloud/server/api/account/profile.put.ts
new file mode 100644
index 00000000..155291f6
--- /dev/null
+++ b/apps/cloud/server/api/account/profile.put.ts
@@ -0,0 +1,32 @@
+import { createError, setResponseHeader } from 'h3'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { siteManagementBody } from '../../utils/site-management'
+import { parseAccountProfile } from '../../../../../packages/contracts/src/account-profile'
+export default definePlatformHandler(async (event) => {
+ setResponseHeader(event, 'cache-control', 'no-store')
+ const config = useRuntimeConfig(event).platform
+ platformPortalOrigin(event, config.portalOrigin, true)
+ const session = await requirePlatformSession(event, config)
+ let profile
+ try {
+ profile = parseAccountProfile(await siteManagementBody(event, 98304))
+ } catch {
+ throw createError({
+ statusCode: 400,
+ statusMessage: 'Invalid account profile',
+ })
+ }
+ const user = await platformDatabase(event)
+ .prepare(
+ 'UPDATE platform_users SET name=?,image=?,updated_at=? WHERE id=? AND NOT EXISTS(SELECT 1 FROM platform_account_deletions WHERE user_id=platform_users.id) RETURNING id,name,email,image',
+ )
+ .bind(profile.name, profile.image, Date.now(), session.userId)
+ .first<{ id: number; name: string; email: string; image: string | null }>()
+ if (!user) throw createError({ statusCode: 404 })
+ return { user }
+})
diff --git a/apps/cloud/server/api/auth/session.get.ts b/apps/cloud/server/api/auth/session.get.ts
index 39be8a02..682a09fb 100644
--- a/apps/cloud/server/api/auth/session.get.ts
+++ b/apps/cloud/server/api/auth/session.get.ts
@@ -10,9 +10,9 @@ export default definePlatformHandler(async (event) => {
const session = await platformSession(event, config.secret)
if (!session) return { authenticated: false, user: null }
const profile = await platformDatabase(event)
- .prepare('SELECT name,email FROM platform_users WHERE id=?')
+ .prepare('SELECT name,email,image FROM platform_users WHERE id=?')
.bind(session.userId)
- .first<{ name: string | null; email: string }>()
+ .first<{ name: string | null; email: string; image: string | null }>()
return profile
? { authenticated: true, user: { id: session.userId, ...profile } }
: { authenticated: false, user: null }
diff --git a/apps/cloud/server/api/auth/status.get.ts b/apps/cloud/server/api/auth/status.get.ts
index d6894f64..046d58f5 100644
--- a/apps/cloud/server/api/auth/status.get.ts
+++ b/apps/cloud/server/api/auth/status.get.ts
@@ -1,26 +1,37 @@
+import { socialLoginProviders } from '../../../../../packages/platform/src/social-login'
+import { setResponseHeader } from 'h3'
import { platformEmailReady } from '../../../../shared/platform/email'
import {
platformRequestURL,
platformDatabase,
} from '../../../../shared/platform/runtime'
export default defineEventHandler(async (event) => {
+ setResponseHeader(event, 'cache-control', 'no-store')
const config = useRuntimeConfig(event).platform
const origin = platformRequestURL(event).origin
const configured =
origin === config.portalOrigin &&
- platformEmailReady(
- event.context.cloudflare?.env?.EMAIL,
- ) &&
config.secret.length >= 32 &&
!!event.context.cloudflare?.env?.DB
- if (!configured) return { enabled: false }
+ if (!configured)
+ return { enabled: false, emailEnabled: false, providers: [] as string[] }
try {
await platformDatabase(event)
.prepare('SELECT id FROM platform_auth_sessions LIMIT 1')
.first()
- return { enabled: true }
+ const providers = await socialLoginProviders(
+ platformDatabase(event),
+ config.storageSecret,
+ )
+ return {
+ enabled: true,
+ emailEnabled: platformEmailReady(
+ event.context.cloudflare?.env?.EMAIL,
+ ),
+ providers: Object.keys(providers),
+ }
} catch {
- return { enabled: false }
+ return { enabled: false, emailEnabled: false, providers: [] as string[] }
}
})
diff --git a/apps/cloud/server/middleware/00-account-session.ts b/apps/cloud/server/middleware/00-account-session.ts
index bed32e2a..51f7eb99 100644
--- a/apps/cloud/server/middleware/00-account-session.ts
+++ b/apps/cloud/server/middleware/00-account-session.ts
@@ -5,7 +5,9 @@ import { cloudAccount } from '../utils/cloud-account'
export default defineEventHandler((event) => {
event.context.platformSessionResolver = async () => {
if (!getCookie(event, '__Host-chronoframe-auth')) return null
- const session = await cloudAccount(event).api.getSession({
+ const session = await (
+ await cloudAccount(event)
+ ).api.getSession({
headers: new Headers(getRequestHeaders(event) as HeadersInit),
})
const id = Number(session?.user.id)
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index 0cb2a400..a09aaad3 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -21,6 +21,7 @@ export default defineEventHandler((event) => {
'/api/auth/marketing-session',
'/api/auth/logout',
'/api/auth/security',
+ '/api/account/profile',
'/api/sites',
'/api/billing/catalog',
'/api/legal/terms',
diff --git a/apps/cloud/server/utils/account-auth.ts b/apps/cloud/server/utils/account-auth.ts
index d899e2e2..3014f23b 100644
--- a/apps/cloud/server/utils/account-auth.ts
+++ b/apps/cloud/server/utils/account-auth.ts
@@ -16,6 +16,7 @@ export interface AccountAuthConfig {
portalOrigin: string
secret: string
emailFrom: string
+ socialProviders?: BetterAuthOptions['socialProviders']
}
/** Request-scoped Workers/D1 auth. Existing platform user IDs and memberships stay intact. */
export function accountAuthOptions(
@@ -50,6 +51,7 @@ export function accountAuthOptions(
}
return {
appName: 'ChronoFrame Cloud',
+ socialProviders: config.socialProviders ?? {},
databaseHooks: {
user: {
create: {
@@ -154,6 +156,12 @@ export function accountAuthOptions(
},
account: {
modelName: 'platform_accounts',
+ encryptOAuthTokens: true,
+ accountLinking: {
+ enabled: true,
+ requireLocalEmailVerified: true,
+ trustedProviders: [],
+ },
fields: {
userId: 'user_id',
accountId: 'account_id',
diff --git a/apps/cloud/server/utils/account-factors.ts b/apps/cloud/server/utils/account-factors.ts
index 7aec0b59..a3cad581 100644
--- a/apps/cloud/server/utils/account-factors.ts
+++ b/apps/cloud/server/utils/account-factors.ts
@@ -5,10 +5,19 @@ import {
type DispatchContext,
} from 'better-auth/api'
+import { isSocialLoginProvider } from '../../../../packages/contracts/src/social-login.ts'
+
/** Reuse Better Auth's challenge/session lifecycle for verified email-code logins too. */
export function accountFactors(options: Parameters<typeof twoFactor>[0]) {
const emailEntry = (path: string | undefined) =>
['/sign-in/email-otp', '/email-otp/verify-email'].includes(path ?? '')
+ const socialEntry = (ctx: {
+ path?: string
+ params?: Record<string, unknown>
+ }) =>
+ (ctx.path === '/callback/:id' && isSocialLoginProvider(ctx.params?.id)) ||
+ (!!ctx.path?.startsWith('/callback/') &&
+ isSocialLoginProvider(ctx.path.slice('/callback/'.length)))
const plugin = twoFactor(options)
const credentialGate = plugin.hooks.after[0]!
return {
@@ -58,7 +67,10 @@ export function accountFactors(options: Parameters<typeof twoFactor>[0]) {
after: [
{
matcher: (ctx: Parameters<typeof credentialGate.matcher>[0]) =>
- credentialGate.matcher(ctx) || emailEntry(ctx.path),
+ ctx.path === '/sign-in/social' ||
+ credentialGate.matcher(ctx) ||
+ emailEntry(ctx.path) ||
+ socialEntry(ctx),
handler: Object.assign(
async (input: Parameters<typeof credentialGate.handler>[0]) => {
const ctx = input as typeof input & DispatchContext
@@ -74,7 +86,39 @@ export function accountFactors(options: Parameters<typeof twoFactor>[0]) {
if (!authenticator?.verified)
return { response: undefined, headers: undefined }
}
- return credentialGate.handler(ctx)
+ const callback = ctx.context.responseHeaders?.get('location')
+ const result = await credentialGate.handler(ctx)
+ const challenge = result.response as
+ | { twoFactorRedirect?: boolean; twoFactorMethods?: string[] }
+ | undefined
+ if (socialEntry(ctx) && challenge?.twoFactorRedirect) {
+ const target = new URL('/signin', ctx.context.baseURL)
+ target.searchParams.set(
+ 'second',
+ challenge.twoFactorMethods?.includes('totp')
+ ? 'totp'
+ : 'email',
+ )
+ if (callback) {
+ const destination = new URL(callback, ctx.context.baseURL)
+ if (destination.origin === target.origin)
+ target.searchParams.set(
+ 'next',
+ destination.pathname +
+ destination.search +
+ destination.hash,
+ )
+ }
+ const headers = new Headers(result.headers)
+ headers.set('location', target.toString())
+ return {
+ response: new APIError('FOUND', undefined, {
+ location: target.toString(),
+ }),
+ headers,
+ }
+ }
+ return result
},
{ options: credentialGate.handler.options },
),
diff --git a/apps/cloud/server/utils/account-handler.ts b/apps/cloud/server/utils/account-handler.ts
index c44a69fe..1d306cfe 100644
--- a/apps/cloud/server/utils/account-handler.ts
+++ b/apps/cloud/server/utils/account-handler.ts
@@ -14,13 +14,18 @@ import {
} from '../../../shared/platform/runtime'
import { createEmailCodeCrypto } from '../../../shared/platform/crypto'
import { cloudAccount } from './cloud-account'
-import { accountRouteAllowed } from './account-routes'
+import { isSocialLoginProvider } from '../../../../packages/contracts/src/social-login'
+import { accountRouteAllowed, socialLoginCallback } from './account-routes'
/** Keep credentials on the canonical origin and share account-level limits across Workers. */
export async function forwardAccountRequest(event: H3Event, rewrite?: string) {
const config = useRuntimeConfig(event).platform
- platformPortalOrigin(event, config.portalOrigin, event.method !== 'GET')
const path = rewrite ? '/api/auth' + rewrite : getRequestURL(event).pathname
+ platformPortalOrigin(
+ event,
+ config.portalOrigin,
+ event.method !== 'GET' && !socialLoginCallback(path),
+ )
if (!accountRouteAllowed(path, event.method))
throw createError({ statusCode: 404 })
if (Number(getHeader(event, 'content-length')) > 32 * 1024)
@@ -28,6 +33,20 @@ export async function forwardAccountRequest(event: H3Event, rewrite?: string) {
const raw = event.method === 'GET' ? undefined : await readRawBody(event)
if (raw && new TextEncoder().encode(raw).length > 32 * 1024)
throw createError({ statusCode: 400 })
+ if (path === '/api/auth/sign-in/social') {
+ let body: Record<string, unknown>
+ try {
+ body = JSON.parse(raw || '{}')
+ } catch {
+ throw createError({ statusCode: 400 })
+ }
+ if (
+ !body ||
+ !isSocialLoginProvider(body.provider) ||
+ body.idToken !== undefined
+ )
+ throw createError({ statusCode: 400 })
+ }
if (
raw &&
[
@@ -70,7 +89,7 @@ export async function forwardAccountRequest(event: H3Event, rewrite?: string) {
headers: new Headers(getRequestHeaders(event) as HeadersInit),
...(raw ? { body: raw } : {}),
})
- const response = await cloudAccount(event).handler(request)
+ const response = await (await cloudAccount(event)).handler(request)
response.headers.set('cache-control', 'no-store')
response.headers.set('referrer-policy', 'no-referrer')
return sendWebResponse(event, response)
diff --git a/apps/cloud/server/utils/account-routes.ts b/apps/cloud/server/utils/account-routes.ts
index 1e8beb51..2a7d1101 100644
--- a/apps/cloud/server/utils/account-routes.ts
+++ b/apps/cloud/server/utils/account-routes.ts
@@ -1,7 +1,9 @@
+import { isSocialLoginProvider } from '../../../../packages/contracts/src/social-login.ts'
/** Explicit public account surface; internal OTP retrieval and unrelated plugin APIs stay closed. */
export const ACCOUNT_POST_ROUTES = new Set([
'/sign-up/email',
'/sign-in/email',
+ '/sign-in/social',
'/sign-in/email-otp',
'/sign-out',
'/email-otp/send-verification-otp',
@@ -26,8 +28,17 @@ export const ACCOUNT_GET_ROUTES = new Set([
'/passkey/generate-authenticate-options',
'/passkey/list-user-passkeys',
])
+export function socialLoginCallback(path: string) {
+ const match = /^\/api\/auth\/callback\/([^/]+)$/.exec(path)
+ return !!match && isSocialLoginProvider(match[1])
+}
export function accountRouteAllowed(path: string, method?: string) {
const endpoint = path.replace(/^\/api\/auth/, '')
+ if (
+ socialLoginCallback(path) &&
+ (!method || ['GET', 'POST'].includes(method))
+ )
+ return true
return (
((!method || method === 'POST') && ACCOUNT_POST_ROUTES.has(endpoint)) ||
((!method || method === 'GET') &&
diff --git a/apps/cloud/server/utils/cloud-account.ts b/apps/cloud/server/utils/cloud-account.ts
index 7e3ad7bc..ce148166 100644
--- a/apps/cloud/server/utils/cloud-account.ts
+++ b/apps/cloud/server/utils/cloud-account.ts
@@ -1,18 +1,34 @@
-import type { H3Event } from 'h3'
+import { getRequestURL, type H3Event } from 'h3'
import type { BetterAuthOptions } from 'better-auth'
+import { socialLoginProviders } from '../../../../packages/platform/src/social-login'
import { createAccountAuth } from './account-auth'
import { platformDatabase } from '../../../shared/platform/runtime'
import type { PlatformEmailBinding } from '../../../shared/platform/email'
/** Cache only within this H3 request; never share an identity between requests. */
-export function cloudAccount(event: H3Event) {
+export async function cloudAccount(event: H3Event) {
if (!event.context.cloudAccountAuth) {
const config = useRuntimeConfig(event).platform
const execution = event.context.cloudflare?.context as
| { waitUntil(task: Promise<unknown>): void }
| undefined
+ const path = getRequestURL(event).pathname
+ const providers =
+ path === '/api/auth/sign-in/social' ||
+ path.startsWith('/api/auth/callback/')
+ ? await socialLoginProviders(
+ platformDatabase(event),
+ config.storageSecret,
+ )
+ : {}
+ const socialProviders = Object.fromEntries(
+ Object.entries(providers).map(([id, credentials]) => [
+ id,
+ { ...credentials, requireEmailVerification: true },
+ ]),
+ )
event.context.cloudAccountAuth = createAccountAuth(
platformDatabase(event) as unknown as BetterAuthOptions['database'],
- { ...config, localDevelopment: import.meta.dev },
+ { ...config, socialProviders, localDevelopment: import.meta.dev },
event.context.cloudflare?.env?.EMAIL as PlatformEmailBinding,
execution ? (task) => execution.waitUntil(task) : undefined,
)
diff --git a/packages/contracts/package.json b/packages/contracts/package.json
index aa5bca7b..bbeaa96c 100644
--- a/packages/contracts/package.json
+++ b/packages/contracts/package.json
@@ -20,7 +20,9 @@
"./gallery-settings": "./src/gallery-settings.ts",
"./reactions": "./src/reactions.ts",
"./domains": "./src/domains.ts",
- "./processor": "./src/processor.ts"
+ "./processor": "./src/processor.ts",
+ "./social-login": "./src/social-login.ts",
+ "./account-profile": "./src/account-profile.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
diff --git a/packages/contracts/src/account-profile.ts b/packages/contracts/src/account-profile.ts
new file mode 100644
index 00000000..d9b1d27e
--- /dev/null
+++ b/packages/contracts/src/account-profile.ts
@@ -0,0 +1,40 @@
+export interface AccountProfile {
+ name: string
+ image: string | null
+}
+export function parseAccountProfile(value: unknown): AccountProfile {
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ throw new Error('Invalid profile')
+ const input = value as Record<string, unknown>
+ if (
+ Object.keys(input).some((key) => !['name', 'image'].includes(key)) ||
+ typeof input.name !== 'string' ||
+ !input.name.trim() ||
+ input.name.trim().length > 80 ||
+ [...input.name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)
+ )
+ throw new Error('Invalid nickname')
+ if (input.image !== null && typeof input.image !== 'string')
+ throw new Error('Invalid avatar')
+ const image = typeof input.image === 'string' ? input.image.trim() : ''
+ if (image && image.startsWith('data:')) {
+ if (
+ image.length > 65536 ||
+ !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(image)
+ )
+ throw new Error('Invalid avatar image')
+ const body = atob(image.slice(image.indexOf(',') + 1))
+ const valid = image.startsWith('data:image/png;')
+ ? body.startsWith('\x89PNG\r\n\x1a\n')
+ : image.startsWith('data:image/jpeg;')
+ ? body.startsWith('\xff\xd8\xff')
+ : body.startsWith('RIFF') && body.slice(8, 12) === 'WEBP'
+ if (!valid) throw new Error('Invalid avatar image')
+ } else if (image) {
+ if (image.length > 2048) throw new Error('Avatar URL too long')
+ const url = new URL(image)
+ if (url.protocol !== 'https:' || url.username || url.password)
+ throw new Error('Use an HTTPS avatar URL')
+ }
+ return { name: input.name.trim(), image: image || null }
+}
diff --git a/packages/contracts/src/social-login.ts b/packages/contracts/src/social-login.ts
new file mode 100644
index 00000000..36d7ebd0
--- /dev/null
+++ b/packages/contracts/src/social-login.ts
@@ -0,0 +1,103 @@
+/** Provider identifiers are fixed; arbitrary OAuth endpoints cannot be configured. */
+export const SOCIAL_LOGIN_PROVIDERS = [
+ { id: 'github', name: 'GitHub', icon: 'i-tabler-brand-github' },
+ { id: 'google', name: 'Google', icon: 'i-tabler-brand-google' },
+ { id: 'microsoft', name: 'Microsoft', icon: 'i-tabler-brand-windows' },
+ { id: 'discord', name: 'Discord', icon: 'i-tabler-brand-discord' },
+] as const
+export type SocialLoginProvider = (typeof SOCIAL_LOGIN_PROVIDERS)[number]['id']
+export interface SocialLoginCredentials {
+ clientId: string
+ clientSecret: string
+}
+export function isSocialLoginProvider(
+ value: unknown,
+): value is SocialLoginProvider {
+ return SOCIAL_LOGIN_PROVIDERS.some((provider) => provider.id === value)
+}
+export function parseSocialLoginCredentials(
+ value: unknown,
+): SocialLoginCredentials {
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ throw new Error('Invalid login credentials')
+ const { clientId, clientSecret } = value as Record<string, unknown>
+ if (
+ [clientId, clientSecret].some(
+ (v) =>
+ typeof v !== 'string' ||
+ !v.trim() ||
+ v.length > 4096 ||
+ [...v].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127),
+ )
+ )
+ throw new Error('Complete login credentials are required')
+ return {
+ clientId: (clientId as string).trim(),
+ clientSecret: (clientSecret as string).trim(),
+ }
+}
+const encoder = new TextEncoder()
+const encode = (value: Uint8Array) => btoa(String.fromCharCode(...value))
+const decode = (value: string) =>
+ Uint8Array.from(atob(value), (c) => c.charCodeAt(0))
+/** Dedicated key derivation; credentials are authenticated to provider and revision. */
+export async function socialLoginCipher(secret: string) {
+ if (secret.length < 32)
+ throw new Error('Login credential encryption unavailable')
+ const material = await crypto.subtle.importKey(
+ 'raw',
+ encoder.encode(secret),
+ 'HKDF',
+ false,
+ ['deriveKey'],
+ )
+ const key = await crypto.subtle.deriveKey(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: encoder.encode('chronoframe-social-login-v1'),
+ info: encoder.encode('credentials'),
+ },
+ material,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ ['encrypt', 'decrypt'],
+ )
+ return {
+ async seal(value: SocialLoginCredentials, context: string) {
+ const iv = crypto.getRandomValues(new Uint8Array(12))
+ const encrypted = await crypto.subtle.encrypt(
+ { name: 'AES-GCM', iv, additionalData: encoder.encode(context) },
+ key,
+ encoder.encode(JSON.stringify(value)),
+ )
+ return `v1.${encode(iv)}.${encode(new Uint8Array(encrypted))}`
+ },
+ async open(
+ value: string,
+ context: string,
+ ): Promise<SocialLoginCredentials> {
+ const [version, iv, body, ...extra] = value.split('.')
+ if (
+ version !== 'v1' ||
+ !iv ||
+ !body ||
+ extra.length ||
+ value.length > 24576
+ )
+ throw new Error('Invalid login credential envelope')
+ const decrypted = await crypto.subtle.decrypt(
+ {
+ name: 'AES-GCM',
+ iv: decode(iv),
+ additionalData: encoder.encode(context),
+ },
+ key,
+ decode(body),
+ )
+ return parseSocialLoginCredentials(
+ JSON.parse(new TextDecoder().decode(decrypted)),
+ )
+ },
+ }
+}
diff --git a/packages/platform/migrations/0040_social_login.sql b/packages/platform/migrations/0040_social_login.sql
new file mode 100644
index 00000000..c462cfde
--- /dev/null
+++ b/packages/platform/migrations/0040_social_login.sql
@@ -0,0 +1,9 @@
+-- OAuth app credentials are encrypted with the platform storage key, never returned publicly.
+CREATE TABLE platform_social_login_providers (
+ provider TEXT PRIMARY KEY CHECK(provider IN ('github','google','microsoft','discord')),
+ client_id TEXT NOT NULL DEFAULT '',
+ credentials_ciphertext TEXT NOT NULL DEFAULT '',
+ revision INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL DEFAULT 0
+);
+INSERT INTO platform_social_login_providers(provider) VALUES ('github'),('google'),('microsoft'),('discord');
diff --git a/packages/platform/src/social-login.ts b/packages/platform/src/social-login.ts
new file mode 100644
index 00000000..d91d1c69
--- /dev/null
+++ b/packages/platform/src/social-login.ts
@@ -0,0 +1,157 @@
+import type { PlatformD1 } from './index.ts'
+import {
+ SOCIAL_LOGIN_PROVIDERS,
+ isSocialLoginProvider,
+ parseSocialLoginCredentials,
+ socialLoginCipher,
+ type SocialLoginCredentials,
+ type SocialLoginProvider,
+} from '../../contracts/src/social-login.ts'
+
+type ProviderRow = {
+ provider: SocialLoginProvider
+ client_id: string
+ credentials_ciphertext: string
+ revision: number
+}
+export class SocialLoginError extends Error {
+ status: number
+ constructor(status: number, message: string) {
+ super(message)
+ this.status = status
+ }
+}
+async function providerRow(db: PlatformD1, provider: SocialLoginProvider) {
+ return db
+ .prepare(
+ 'SELECT provider,client_id,credentials_ciphertext,revision FROM platform_social_login_providers WHERE provider=?',
+ )
+ .bind(provider)
+ .first<ProviderRow>()
+}
+export async function socialLoginSettings(db: PlatformD1) {
+ return Promise.all(
+ SOCIAL_LOGIN_PROVIDERS.map(async ({ id, name }) => {
+ const row = await providerRow(db, id)
+ return {
+ id,
+ name,
+ clientId: row?.client_id ?? '',
+ configured: !!row?.client_id && !!row.credentials_ciphertext,
+ revision: row?.revision ?? 0,
+ }
+ }),
+ )
+}
+export async function socialLoginProviders(db: PlatformD1, secret: string) {
+ const result: Partial<Record<SocialLoginProvider, SocialLoginCredentials>> =
+ {}
+ let cipher: Awaited<ReturnType<typeof socialLoginCipher>> | undefined
+ for (const { id } of SOCIAL_LOGIN_PROVIDERS) {
+ const row = await providerRow(db, id)
+ if (!row?.client_id || !row.credentials_ciphertext) continue
+ try {
+ cipher ??= await socialLoginCipher(secret)
+ const credentials = await cipher.open(
+ row.credentials_ciphertext,
+ `${id}:${row.revision}`,
+ )
+ if (credentials.clientId === row.client_id) result[id] = credentials
+ } catch {
+ // An unreadable credential disables this provider; it must never enable a fallback.
+ }
+ }
+ return result
+}
+/** Root role is rechecked inside the same batch as the revision-fenced write and redacted audit. */
+export async function saveSocialLoginProvider(
+ db: PlatformD1,
+ secret: string,
+ actor: { userId: number; role: string },
+ input: Record<string, unknown>,
+) {
+ if (actor.role !== 'root')
+ throw new SocialLoginError(403, 'Root administrator required')
+ if (
+ !isSocialLoginProvider(input.provider) ||
+ !Number.isSafeInteger(input.revision) ||
+ Number(input.revision) < 0 ||
+ !['save', 'remove'].includes(String(input.operation)) ||
+ typeof input.reason !== 'string' ||
+ input.reason.trim().length < 5 ||
+ input.reason.length > 500
+ )
+ throw new SocialLoginError(400, 'Invalid login configuration')
+ const provider = input.provider
+ const row = await providerRow(db, provider)
+ if (!row || row.revision !== input.revision)
+ throw new SocialLoginError(
+ 409,
+ 'Login configuration changed; reload and try again',
+ )
+ let credentials: SocialLoginCredentials | undefined
+ let encrypted = ''
+ if (input.operation === 'save') {
+ let clientSecret = input.clientSecret
+ if (clientSecret === '' && row.credentials_ciphertext) {
+ clientSecret = (
+ await (
+ await socialLoginCipher(secret)
+ ).open(row.credentials_ciphertext, `${provider}:${row.revision}`)
+ ).clientSecret
+ // Reusing a secret for a different OAuth application is almost always a mistake.
+ if (input.clientId !== row.client_id)
+ throw new SocialLoginError(
+ 400,
+ 'Provide a new secret when changing the client ID',
+ )
+ }
+ try {
+ credentials = parseSocialLoginCredentials({
+ clientId: input.clientId,
+ clientSecret,
+ })
+ } catch {
+ throw new SocialLoginError(400, 'Complete login credentials are required')
+ }
+ encrypted = await (
+ await socialLoginCipher(secret)
+ ).seal(credentials, `${provider}:${row.revision + 1}`)
+ }
+ const audit = (configured: boolean, revision: number) =>
+ JSON.stringify({ provider, configured, revision })
+ const result = await db.batch([
+ db
+ .prepare(
+ "UPDATE platform_social_login_providers SET client_id=?,credentials_ciphertext=?,revision=revision+1,updated_at=? WHERE provider=? AND revision=? AND EXISTS(SELECT 1 FROM platform_admin_roles WHERE user_id=? AND role='root')",
+ )
+ .bind(
+ credentials?.clientId ?? '',
+ encrypted,
+ Date.now(),
+ provider,
+ row.revision,
+ actor.userId,
+ ),
+ db
+ .prepare(
+ 'INSERT INTO platform_admin_audit(id,actor_id,action,target,reason,before_json,after_json,created_at) SELECT ?,?,?,?,?,?,?,? WHERE changes()=1',
+ )
+ .bind(
+ crypto.randomUUID(),
+ actor.userId,
+ `social-login-${input.operation}`,
+ provider,
+ input.reason.trim(),
+ audit(!!row.credentials_ciphertext, row.revision),
+ audit(!!credentials, row.revision + 1),
+ Date.now(),
+ ),
+ ])
+ if (!result[0]?.meta.changes)
+ throw new SocialLoginError(
+ 409,
+ 'Login configuration changed or permission revoked',
+ )
+ return socialLoginSettings(db)
+}
diff --git a/tests/social-login.test.ts b/tests/social-login.test.ts
new file mode 100644
index 00000000..55dd897b
--- /dev/null
+++ b/tests/social-login.test.ts
@@ -0,0 +1,488 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { createRequire } from 'node:module'
+import { readFile, readdir } from 'node:fs/promises'
+import { splitSqlQuery } from './helpers/sql.ts'
+import { createAccountAuth } from '../apps/cloud/server/utils/account-auth.ts'
+import { accountRouteAllowed } from '../apps/cloud/server/utils/account-routes.ts'
+import { socialLoginCipher } from '../packages/contracts/src/social-login.ts'
+import {
+ socialLoginProviders,
+ socialLoginSettings,
+ saveSocialLoginProvider,
+} from '../packages/platform/src/social-login.ts'
+import { parseAccountProfile } from '../packages/contracts/src/account-profile.ts'
+const require = createRequire(import.meta.url)
+const { Miniflare, convertV4MiniflareOptions } = createRequire(
+ require.resolve('wrangler/package.json'),
+)('miniflare')
+
+test('OAuth callbacks expose only the supported provider surface', () => {
+ for (const provider of ['github', 'google', 'microsoft', 'discord']) {
+ assert(accountRouteAllowed(`/api/auth/callback/${provider}`, 'GET'))
+ assert(accountRouteAllowed(`/api/auth/callback/${provider}`, 'POST'))
+ assert(!accountRouteAllowed(`/api/auth/callback/${provider}`, 'DELETE'))
+ }
+ assert(accountRouteAllowed('/api/auth/sign-in/social', 'POST'))
+ for (const path of [
+ '/api/auth/callback/unknown',
+ '/api/auth/callback/github/extra',
+ '/api/auth/update-user',
+ '/api/auth/link-social',
+ '/api/auth/get-access-token',
+ ])
+ assert(!accountRouteAllowed(path, 'POST'))
+})
+
+test('profile updates accept bounded nicknames/images and reject identity changes and active content', () => {
+ assert.deepEqual(parseAccountProfile({ name: ' New name ', image: null }), {
+ name: 'New name',
+ image: null,
+ })
+ assert.equal(
+ parseAccountProfile({
+ name: 'Name',
+ image: 'https://avatars.githubusercontent.com/u/123',
+ }).image,
+ 'https://avatars.githubusercontent.com/u/123',
+ )
+ for (const profile of [
+ { name: '', image: null },
+ { name: 'x'.repeat(81), image: null },
+ { name: 'ok', image: 'javascript:alert(1)' },
+ { name: 'ok', image: 'data:image/svg+xml;base64,PHN2Zz4=' },
+ { name: 'ok', image: 'data:image/png;base64,bm90LWFuLWltYWdl' },
+ { name: 'ok', image: 'https://user:[email protected]/a' },
+ { name: 'ok', image: null, userId: 2 },
+ { name: 'ok', image: null, email: '[email protected]' },
+ ])
+ assert.throws(() => parseAccountProfile(profile))
+})
+
+test('credentials are root-only, encrypted, redacted, revision fenced and disabled immediately on removal; OAuth preserves identities and MFA', async () => {
+ const mf = new Miniflare(
+ convertV4MiniflareOptions({
+ modules: true,
+ compatibilityDate: '2026-10-26',
+ script: 'export default {fetch(){return new Response("ok")}}',
+ d1Databases: ['DB'],
+ }),
+ )
+ try {
+ const db = await mf.getD1Database('DB')
+ for (const file of (
+ await readdir(
+ new URL('../packages/platform/migrations/', import.meta.url),
+ )
+ )
+ .filter((f) => f.endsWith('.sql'))
+ .sort()) {
+ const sql = await readFile(
+ new URL('../packages/platform/migrations/' + file, import.meta.url),
+ 'utf8',
+ )
+ for (const statement of splitSqlQuery(sql.replace(/^--.*$/gm, ''))
+ .map((s) => s.trim())
+ .filter(Boolean))
+ await db.prepare(statement).run()
+ }
+ await db
+ .prepare(
+ 'CREATE TABLE platform_admin_roles(user_id INTEGER PRIMARY KEY,role TEXT)',
+ )
+ .run()
+ await db
+ .prepare(
+ 'CREATE TABLE platform_admin_audit(id TEXT PRIMARY KEY,actor_id INTEGER,action TEXT,target TEXT,reason TEXT,before_json TEXT,after_json TEXT,created_at INTEGER)',
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,name,email_verified,two_factor_enabled,created_at) VALUES(42,'[email protected]','Existing',1,0,1),(43,'[email protected]','MFA',1,1,1)",
+ )
+ .run()
+ await db.prepare("INSERT INTO platform_admin_roles VALUES(42,'root')").run()
+ await db
+ .prepare(
+ "INSERT INTO platform_two_factors(user_id,secret,backup_codes,verified) VALUES(43,'test','[]',1)",
+ )
+ .run()
+ const secret = crypto.randomUUID() + crypto.randomUUID(),
+ actor = { userId: 42, role: 'root' }
+ const input = {
+ provider: 'github',
+ revision: 0,
+ operation: 'save',
+ clientId: 'client-test',
+ clientSecret: 'secret-test',
+ reason: 'Enable GitHub login',
+ }
+ assert.deepEqual(await socialLoginProviders(db, secret), {})
+ await assert.rejects(
+ saveSocialLoginProvider(db, secret, { ...actor, role: 'admin' }, input),
+ { status: 403 },
+ )
+ await assert.rejects(
+ saveSocialLoginProvider(db, secret, actor, {
+ ...input,
+ clientSecret: '',
+ }),
+ { status: 400 },
+ )
+ const settings = await saveSocialLoginProvider(db, secret, actor, input)
+ assert(!JSON.stringify(settings).includes('secret-test'))
+ assert.equal(settings.find((p) => p.id === 'github')?.configured, true)
+ const row = await db
+ .prepare(
+ "SELECT * FROM platform_social_login_providers WHERE provider='github'",
+ )
+ .first()
+ assert(!row.credentials_ciphertext.includes('secret-test'))
+ const cipher = await socialLoginCipher(secret)
+ await assert.rejects(cipher.open(row.credentials_ciphertext, 'google:1'))
+ await assert.rejects(cipher.open(row.credentials_ciphertext, 'github:2'))
+ assert.equal(
+ (await socialLoginProviders(db, secret)).github?.clientSecret,
+ 'secret-test',
+ )
+ await assert.rejects(saveSocialLoginProvider(db, secret, actor, input), {
+ status: 409,
+ })
+ await saveSocialLoginProvider(db, secret, actor, {
+ ...input,
+ revision: 1,
+ clientSecret: '',
+ })
+ const audit = await db
+ .prepare(
+ "SELECT json_group_array(json_object('before',before_json,'after',after_json)) AS rows FROM platform_admin_audit",
+ )
+ .first()
+ assert(!audit.rows.includes('secret-test'))
+ assert(!audit.rows.includes('client-test'))
+ assert.deepEqual(await socialLoginProviders(db, 'wrong-key'.repeat(5)), {})
+
+ const ts = require('typescript')
+ const source = (
+ await readFile(
+ new URL(
+ '../apps/cloud/server/api/account/profile.put.ts',
+ import.meta.url,
+ ),
+ 'utf8',
+ )
+ ).replace(/^import[\s\S]*?from ['"][^'"]+['"]\s*\n/gm, '')
+ const code = ts.transpileModule(source, {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText
+ const deps = {
+ definePlatformHandler: (f: unknown) => f,
+ setResponseHeader: () => {},
+ useRuntimeConfig: () => ({
+ platform: { portalOrigin: 'https://app.chronoframe.art' },
+ }),
+ platformPortalOrigin: () => {},
+ requirePlatformSession: async () => ({ userId: 42 }),
+ platformDatabase: () => db,
+ siteManagementBody: async (event: any) => event.body,
+ parseAccountProfile,
+ createError: (value: any) =>
+ Object.assign(new Error(value.statusMessage), value),
+ }
+ const profileHandler = new Function(
+ 'exports',
+ ...Object.keys(deps),
+ code + ';return exports.default',
+ )({}, ...Object.values(deps))
+ const profile = await profileHandler({
+ body: {
+ name: 'Updated nickname',
+ image: 'https://example.com/avatar.png',
+ },
+ })
+ assert.equal(profile.user.id, 42)
+ assert.equal(profile.user.name, 'Updated nickname')
+ assert.equal(
+ (await db.prepare('SELECT name FROM platform_users WHERE id=43').first())
+ .name,
+ 'MFA',
+ )
+ await assert.rejects(
+ profileHandler({ body: { name: 'Intruder', image: null, userId: 43 } }),
+ { statusCode: 400 },
+ )
+ const providers = await socialLoginProviders(db, secret)
+ const auth = createAccountAuth(
+ db,
+ {
+ portalOrigin: 'https://app.chronoframe.art',
+ secret,
+ emailFrom: '[email protected]',
+ socialProviders: {
+ github: { ...providers.github!, requireEmailVerification: true },
+ },
+ },
+ { send: async () => ({ messageId: 'test' }) },
+ )
+ let email = '[email protected]',
+ githubId = 101,
+ verified = true
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async (input, init) => {
+ const url = String(input instanceof Request ? input.url : input)
+ if (url === 'https://github.com/login/oauth/access_token')
+ return Response.json({
+ access_token: 'oauth-token',
+ token_type: 'bearer',
+ scope: 'read:user,user:email',
+ })
+ if (url === 'https://api.github.com/user')
+ return Response.json({
+ id: githubId,
+ login: 'test-user',
+ name: 'OAuth name',
+ email,
+ avatar_url: 'https://example.com/avatar.png',
+ })
+ if (url === 'https://api.github.com/user/emails')
+ return Response.json([{ email, verified, primary: true }])
+ return originalFetch(input, init)
+ }
+ try {
+ let attempt = 0
+ async function login(expectedRedirect: string) {
+ const ip = `192.0.2.${++attempt}`
+ const cookies = new Map<string, string>()
+ const capture = (response: Response) => {
+ for (const cookie of response.headers.getSetCookie()) {
+ const pair = cookie.split(';')[0]!,
+ i = pair.indexOf('=')
+ cookies.set(pair.slice(0, i), pair.slice(i + 1))
+ }
+ }
+ const headers = () => ({
+ 'content-type': 'application/json',
+ origin: 'https://app.chronoframe.art',
+ 'cf-connecting-ip': ip,
+ cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '),
+ })
+ const start = await auth.handler(
+ new Request('https://app.chronoframe.art/api/auth/sign-in/social', {
+ method: 'POST',
+ headers: headers(),
+ body: JSON.stringify({
+ provider: 'github',
+ callbackURL: 'https://app.chronoframe.art/workspace',
+ errorCallbackURL:
+ 'https://app.chronoframe.art/signin?oauthError=1',
+ }),
+ }),
+ )
+ assert.equal(start.status, 200)
+ capture(start)
+ const { url } = (await start.json()) as { url: string }
+ const state = new URL(url).searchParams.get('state')!
+ assert(state)
+ assert.equal(
+ new URL(url).searchParams.get('redirect_uri'),
+ 'https://app.chronoframe.art/api/auth/callback/github',
+ )
+ const callback = await auth.handler(
+ new Request(
+ `https://app.chronoframe.art/api/auth/callback/github?code=test-code&state=${encodeURIComponent(state)}`,
+ { headers: headers() },
+ ),
+ )
+ capture(callback)
+ if (expectedRedirect.includes('second=')) {
+ assert(
+ [...cookies].some(
+ ([key, value]) => key.endsWith('.two_factor') && !!value,
+ ),
+ 'MFA challenge cookie must survive the redirect',
+ )
+ const otp = await auth.handler(
+ new Request(
+ 'https://app.chronoframe.art/api/auth/two-factor/send-otp',
+ { method: 'POST', headers: headers(), body: '{}' },
+ ),
+ )
+ assert.equal(otp.status, 403)
+ assert.equal(
+ ((await otp.json()) as { code: string }).code,
+ 'AUTHENTICATOR_REQUIRED',
+ )
+ }
+ assert.equal(callback.status, 302)
+ assert(
+ callback.headers.get('location')?.includes(expectedRedirect),
+ callback.headers.get('location') || (await callback.text()),
+ )
+ const session = await auth.handler(
+ new Request('https://app.chronoframe.art/api/auth/get-session', {
+ headers: headers(),
+ }),
+ )
+ return (await session.json()) as any
+ }
+ const session = await login('/workspace')
+ assert.equal(Number(session.user.id), 42)
+ assert.equal(
+ (
+ await db
+ .prepare(
+ "SELECT user_id FROM platform_accounts WHERE provider_id='github' AND account_id='101'",
+ )
+ .first()
+ ).user_id,
+ 42,
+ )
+ const token = await db
+ .prepare(
+ "SELECT access_token FROM platform_accounts WHERE provider_id='github'",
+ )
+ .first()
+ assert.notEqual(token.access_token, 'oauth-token')
+ email = '[email protected]'
+ githubId = 102
+ const pending = await login('second=totp')
+ assert.equal(
+ pending,
+ null,
+ 'OAuth must not leave an authenticated session before MFA',
+ )
+ email = '[email protected]'
+ githubId = 103
+ const newUser = await login('/workspace')
+ assert(newUser.user.emailVerified)
+ assert(
+ await db
+ .prepare('SELECT id FROM platform_workspaces WHERE owner_user_id=?')
+ .bind(Number(newUser.user.id))
+ .first(),
+ )
+ email = '[email protected]'
+ githubId = 104
+ verified = false
+ assert.equal(await login('oauthError=1'), null)
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+ await saveSocialLoginProvider(db, secret, actor, {
+ ...input,
+ revision: 2,
+ operation: 'remove',
+ })
+ assert.deepEqual(await socialLoginProviders(db, secret), {})
+ assert(
+ !(await socialLoginSettings(db)).find((p) => p.id === 'github')
+ ?.configured,
+ )
+ await db
+ .prepare("UPDATE platform_admin_roles SET role='admin' WHERE user_id=42")
+ .run()
+ await assert.rejects(
+ saveSocialLoginProvider(db, secret, actor, { ...input, revision: 3 }),
+ { status: 409 },
+ )
+ assert.deepEqual(await socialLoginProviders(db, secret), {})
+ } finally {
+ await mf.dispose()
+ }
+})
+
+test('auth forwarding checks web origins and rejects ID-token entry while accepting state-validated OAuth callback transport', async () => {
+ const ts = require('typescript')
+ const source = (
+ await readFile(
+ new URL('../apps/cloud/server/utils/account-handler.ts', import.meta.url),
+ 'utf8',
+ )
+ ).replace(/^import[\s\S]*?from ['"][^'"]+['"]\s*\n/gm, '')
+ const code = ts.transpileModule(source, {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText
+ let calls = 0
+ const deps = {
+ useRuntimeConfig: () => ({
+ platform: { portalOrigin: 'https://app.chronoframe.art' },
+ }),
+ getRequestURL: (e: any) => new URL(e.path, 'https://app.chronoframe.art'),
+ platformRequestURL: () => new URL('https://app.chronoframe.art'),
+ platformPortalOrigin: (e: any, _origin: string, required: boolean) => {
+ if (required && e.origin !== 'https://app.chronoframe.art')
+ throw Object.assign(new Error('Origin'), { statusCode: 403 })
+ },
+ accountRouteAllowed,
+ socialLoginCallback: (path: string) =>
+ /^\/api\/auth\/callback\/(github|google|microsoft|discord)$/.test(path),
+ isSocialLoginProvider: (id: string) =>
+ ['github', 'google', 'microsoft', 'discord'].includes(id),
+ getHeader: () => undefined,
+ readRawBody: async (e: any) => e.raw,
+ getRequestHeaders: () => ({}),
+ cloudAccount: async () => ({
+ handler: async () => {
+ calls++
+ return new Response('ok')
+ },
+ }),
+ sendWebResponse: (_e: any, r: Response) => r,
+ createError: (v: any) => Object.assign(new Error(v.statusMessage), v),
+ }
+ const { forwardAccountRequest } = new Function(
+ 'exports',
+ ...Object.keys(deps),
+ code + ';return exports',
+ )({}, ...Object.values(deps))
+ const event = {
+ method: 'POST',
+ path: '/api/auth/sign-in/social',
+ origin: 'https://app.chronoframe.art',
+ raw: JSON.stringify({ provider: 'github' }),
+ }
+ await assert.rejects(
+ forwardAccountRequest({ ...event, origin: 'https://evil.example.com' }),
+ { statusCode: 403 },
+ )
+ await assert.rejects(
+ forwardAccountRequest({
+ ...event,
+ raw: JSON.stringify({
+ provider: 'google',
+ idToken: { token: 'unwanted-entry' },
+ }),
+ }),
+ { statusCode: 400 },
+ )
+ await assert.rejects(
+ forwardAccountRequest({
+ ...event,
+ raw: JSON.stringify({ provider: 'unknown' }),
+ }),
+ { statusCode: 400 },
+ )
+ assert.equal(calls, 0)
+ assert.equal((await forwardAccountRequest(event)).status, 200)
+ assert.equal(
+ (
+ await forwardAccountRequest({
+ ...event,
+ path: '/api/auth/callback/github',
+ origin: undefined,
+ raw: '{"code":"test","state":"test"}',
+ })
+ ).status,
+ 200,
+ )
+ await assert.rejects(
+ forwardAccountRequest({ ...event, path: '/api/auth/callback/unknown' }),
+ { statusCode: 404 },
+ )
+})