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): manage connected sign-in accounts from account settings

Timothy Yin1e65a13cce25
diff --git a/apps/cloud/app/components/CloudAccountConnections.vue b/apps/cloud/app/components/CloudAccountConnections.vue
new file mode 100644
index 00000000..9ec3de60
--- /dev/null
+++ b/apps/cloud/app/components/CloudAccountConnections.vue
@@ -0,0 +1,268 @@
+<script setup lang="ts">
+import { SOCIAL_LOGIN_PROVIDERS } from '@chronoframe/contracts/social-login'
+import { accountError } from '../utils/account-error'
+const { t } = useI18n()
+const route = useRoute()
+const identity = usePortalIdentity()
+type Provider = { id: string; name: string; icon: string }
+type Connection = { id: string; provider: string; canUnlink: boolean }
+const {
+ data,
+ error: loadError,
+ refresh,
+ status,
+} = await useFetch<{ providers: Provider[]; accounts: Connection[] }>(
+ '/api/account/connections',
+ { key: `account-connections-${identity.value?.id}` },
+)
+const busy = ref(''),
+ error = ref(
+ route.query.connection === 'failed' ? t('cloud.connections.failed') : '',
+ ),
+ notice = ref(
+ route.query.connection === 'updated'
+ ? t('cloud.connections.linkedNotice')
+ : '',
+ )
+const removing = ref<{ account: Connection; name: string } | null>(null)
+type ConnectionRow = {
+ provider: Provider
+ account: Connection | null
+ enabled: boolean
+}
+const rows = computed(() => {
+ const linked = data.value?.accounts ?? []
+ const enabled = data.value?.providers ?? []
+ const providers = [
+ ...enabled,
+ ...[...new Set(linked.map((a) => a.provider))]
+ .filter((id) => !enabled.some((p) => p.id === id))
+ .map((id) => ({
+ id,
+ name:
+ id === 'microsoft'
+ ? 'Microsoft'
+ : (SOCIAL_LOGIN_PROVIDERS.find((p) => p.id === id)?.name ?? id),
+ icon:
+ SOCIAL_LOGIN_PROVIDERS.find((p) => p.id === id)?.icon ??
+ 'i-lucide-link',
+ })),
+ ]
+ return providers.flatMap<ConnectionRow>((provider) => {
+ const accounts = linked.filter((a) => a.provider === provider.id)
+ return accounts.length
+ ? accounts.map((account) => ({
+ provider,
+ account,
+ enabled: enabled.some((p) => p.id === provider.id),
+ }))
+ : [{ provider, account: null, enabled: true }]
+ })
+})
+onMounted(() => {
+ if (!route.query.connection) return
+ const { connection, error, error_description, ...query } = route.query
+ void navigateTo(
+ { path: route.path, query, hash: route.hash },
+ { replace: true },
+ )
+})
+async function link(provider: Provider) {
+ if (busy.value) return
+ busy.value = provider.id
+ error.value = ''
+ notice.value = ''
+ try {
+ const result = await $fetch<{ url: string }>('/api/auth/link-social', {
+ method: 'POST',
+ body: {
+ provider: provider.id,
+ callbackURL: new URL(
+ '/account?connection=updated',
+ useRequestURL().origin,
+ ).toString(),
+ },
+ })
+ await navigateTo(result.url, { external: true })
+ } catch (cause) {
+ error.value = accountError(cause, t)
+ } finally {
+ busy.value = ''
+ }
+}
+async function unlink() {
+ if (!removing.value || busy.value) return
+ busy.value = removing.value.account.id
+ error.value = ''
+ notice.value = ''
+ try {
+ await $fetch('/api/account/connections', {
+ method: 'DELETE',
+ body: { id: removing.value.account.id },
+ })
+ removing.value = null
+ await refresh()
+ notice.value = t('cloud.connections.unlinkedNotice')
+ } catch (cause) {
+ const code = (cause as { data?: { data?: { code?: string } } }).data?.data
+ ?.code
+ error.value =
+ code === 'SESSION_IS_NOT_FRESH'
+ ? t('cloud.messages.pleaseSignOutAndSignInAgainBeforeChanging')
+ : code === 'LOGIN_METHOD_REQUIRED'
+ ? t('cloud.connections.keepMethod')
+ : accountError(cause, t)
+ removing.value = null
+ } finally {
+ busy.value = ''
+ }
+}
+</script>
+<template>
+ <CfCard class="cf-security-card">
+ <div class="cf-settings-intro">
+ <div>
+ <h2>{{ $t('cloud.connections.title') }}</h2>
+ <p>{{ $t('cloud.connections.help') }}</p>
+ </div>
+ </div>
+ <div class="cf-settings-body cf-connections-body">
+ <p
+ v-if="error || loadError"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error || $t('cloud.connections.loadFailed') }}
+ </p>
+ <p
+ v-if="notice"
+ class="cf-notice"
+ role="status"
+ >
+ {{ notice }}
+ </p>
+ <p
+ v-if="status === 'pending'"
+ class="cf-field-hint"
+ >
+ {{ $t('cloud.billing.loading') }}
+ </p>
+ <div
+ v-for="row in rows"
+ :key="row.account?.id ?? row.provider.id"
+ class="cf-connection-row"
+ >
+ <div class="flex items-center gap-3">
+ <UIcon
+ :name="row.provider.icon"
+ class="size-5 shrink-0"
+ aria-hidden="true"
+ />
+ <div>
+ <h3>{{ row.provider.name }}</h3>
+ <p class="cf-field-hint">
+ {{
+ row.account
+ ? row.enabled
+ ? $t('cloud.connections.linked')
+ : $t('cloud.connections.disabled')
+ : $t('cloud.connections.notLinked')
+ }}
+ </p>
+ </div>
+ </div>
+ <CfButton
+ v-if="!row.account"
+ variant="outline"
+ :disabled="!!busy"
+ :loading="busy === row.provider.id"
+ :aria-label="
+ $t('cloud.connections.linkProvider', {
+ provider: row.provider.name,
+ })
+ "
+ @click="link(row.provider)"
+ >{{ $t('cloud.connections.link') }}</CfButton
+ >
+ <CfButton
+ v-else
+ variant="outline"
+ :disabled="!!busy || !row.account.canUnlink"
+ :aria-label="
+ $t('cloud.connections.unlinkProvider', {
+ provider: row.provider.name,
+ })
+ "
+ @click="removing = { account: row.account, name: row.provider.name }"
+ >{{ $t('cloud.connections.unlink') }}</CfButton
+ >
+ </div>
+ <p
+ v-if="rows.some((row) => row.account && !row.account.canUnlink)"
+ class="cf-field-hint"
+ >
+ {{ $t('cloud.connections.keepMethod') }}
+ </p>
+ <p
+ v-if="data && !rows.length"
+ class="cf-field-hint"
+ >
+ {{ $t('cloud.connections.empty') }}
+ </p>
+ <div>
+ <CfButton
+ variant="ghost"
+ :disabled="!!busy || status === 'pending'"
+ @click="refresh()"
+ >{{ $t('cloud.messages.reloadSettings') }}</CfButton
+ >
+ </div>
+ </div>
+ <UModal
+ :open="!!removing"
+ :title="
+ $t('cloud.connections.confirmTitle', { provider: removing?.name })
+ "
+ :description="$t('cloud.connections.confirmHelp')"
+ @update:open="
+ (value) => {
+ if (!value && !busy) removing = null
+ }
+ "
+ >
+ <template #footer
+ ><div class="flex justify-end gap-2">
+ <CfButton
+ variant="outline"
+ :disabled="!!busy"
+ @click="removing = null"
+ >{{ $t('cloud.messages.cancel') }}</CfButton
+ ><CfButton
+ variant="destructive"
+ :loading="!!busy"
+ @click="unlink"
+ >{{ $t('cloud.connections.unlink') }}</CfButton
+ >
+ </div></template
+ >
+ </UModal>
+ </CfCard>
+</template>
+<style scoped>
+.cf-connections-body {
+ display: grid;
+ gap: 16px;
+}
+.cf-connection-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding-block: 12px;
+ border-bottom: 1px solid var(--border);
+}
+.cf-connection-row h3 {
+ font-size: 14px;
+ font-weight: 600;
+}
+</style>
diff --git a/apps/cloud/app/pages/account/index.vue b/apps/cloud/app/pages/account/index.vue
index e863e1c6..40f619a4 100644
--- a/apps/cloud/app/pages/account/index.vue
+++ b/apps/cloud/app/pages/account/index.vue
@@ -49,6 +49,7 @@ const user = usePortalIdentity()
<CloudThemeToggle /></div
></CfCard>
</section>
+ <CloudAccountConnections />
<CloudSecuritySettings />
</div>
</template>
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index b28d70bc..20f77a33 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -1,5 +1,24 @@
{
"cloud": {
+ "connections": {
+ "title": "Connected accounts",
+ "help": "Link an enabled sign-in provider using the same verified email as your account.",
+ "linked": "Connected",
+ "notLinked": "Not connected",
+ "disabled": "Connected · sign-in disabled by administrator",
+ "link": "Connect",
+ "unlink": "Disconnect",
+ "linkProvider": "Connect {provider}",
+ "unlinkProvider": "Disconnect {provider}",
+ "linkedNotice": "Account connected.",
+ "unlinkedNotice": "Account disconnected.",
+ "failed": "Unable to connect this account. Use the same verified email and ensure it is not linked to another account.",
+ "loadFailed": "Unable to load connected accounts. Please reload.",
+ "keepMethod": "Keep another available sign-in method. Set a password or connect another enabled provider before disconnecting.",
+ "empty": "No sign-in providers are currently available.",
+ "confirmTitle": "Disconnect {provider}?",
+ "confirmHelp": "You will need another available sign-in method to access your account. Your profile and photographs will be kept."
+ },
"account": {
"nickname": "Nickname",
"nicknamePlaceholder": "Your display name",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index a4f23897..58660b9f 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -1,5 +1,24 @@
{
"cloud": {
+ "connections": {
+ "title": "第三方账号",
+ "help": "可绑定管理员已启用的登录方式,请使用与本账号相同的已验证邮箱。",
+ "linked": "已绑定",
+ "notLinked": "未绑定",
+ "disabled": "已绑定 · 管理员已停用此登录方式",
+ "link": "绑定",
+ "unlink": "解绑",
+ "linkProvider": "绑定 {provider}",
+ "unlinkProvider": "解绑 {provider}",
+ "linkedNotice": "账号绑定成功。",
+ "unlinkedNotice": "已解除账号绑定。",
+ "failed": "绑定失败,请确认使用相同的已验证邮箱,且该第三方账号尚未绑定其他账号。",
+ "loadFailed": "无法加载绑定信息,请重新加载。",
+ "keepMethod": "请保留另一种可用的登录方式。设置密码或绑定另一种已启用的第三方账号后,才能解绑。",
+ "empty": "管理员尚未启用可绑定的第三方登录方式。",
+ "confirmTitle": "解除 {provider} 绑定?",
+ "confirmHelp": "解绑后需使用其他可用方式登录,个人资料和照片将保留。"
+ },
"account": {
"nickname": "昵称",
"nicknamePlaceholder": "填写你的昵称",
diff --git a/apps/cloud/server/api/account/connections.delete.ts b/apps/cloud/server/api/account/connections.delete.ts
new file mode 100644
index 00000000..8c3f8ae0
--- /dev/null
+++ b/apps/cloud/server/api/account/connections.delete.ts
@@ -0,0 +1,48 @@
+import { createError, getRequestHeaders, setResponseHeader } from 'h3'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { cloudAccount } from '../../utils/cloud-account'
+import { siteManagementBody } from '../../utils/site-management'
+import { unlinkLoginAccount } from '../../../../../packages/platform/src/account-connections'
+export default definePlatformHandler(async (event) => {
+ setResponseHeader(event, 'cache-control', 'no-store')
+ const config = useRuntimeConfig(event).platform
+ platformPortalOrigin(event, config.portalOrigin, true)
+ const user = await requirePlatformSession(event, config)
+ const session = await (
+ await cloudAccount(event)
+ ).api.getSession({
+ headers: new Headers(getRequestHeaders(event) as HeadersInit),
+ })
+ const createdAt = session
+ ? new Date(session.session.createdAt).getTime()
+ : NaN
+ if (
+ !session ||
+ Number(session.user.id) !== user.userId ||
+ !Number.isFinite(createdAt) ||
+ Date.now() - createdAt > 10 * 60_000
+ )
+ throw createError({
+ statusCode: 401,
+ data: { code: 'SESSION_IS_NOT_FRESH' },
+ })
+ const body = await siteManagementBody(event)
+ if (
+ !(await unlinkLoginAccount(
+ platformDatabase(event),
+ config.storageSecret,
+ user.userId,
+ body.id,
+ ))
+ )
+ throw createError({
+ statusCode: 400,
+ data: { code: 'LOGIN_METHOD_REQUIRED' },
+ })
+ return { success: true }
+})
diff --git a/apps/cloud/server/api/account/connections.get.ts b/apps/cloud/server/api/account/connections.get.ts
new file mode 100644
index 00000000..50e9b702
--- /dev/null
+++ b/apps/cloud/server/api/account/connections.get.ts
@@ -0,0 +1,19 @@
+import { setResponseHeader } from 'h3'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformPortalOrigin,
+} from '../../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../../shared/platform/context'
+import { accountConnections } from '../../../../../packages/platform/src/account-connections'
+export default definePlatformHandler(async (event) => {
+ setResponseHeader(event, 'cache-control', 'no-store')
+ const config = useRuntimeConfig(event).platform
+ platformPortalOrigin(event, config.portalOrigin)
+ const session = await requirePlatformSession(event, config)
+ return accountConnections(
+ platformDatabase(event),
+ config.storageSecret,
+ session.userId,
+ )
+})
diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.ts
index a09aaad3..67552800 100644
--- a/apps/cloud/server/middleware/platform-boundary.ts
+++ b/apps/cloud/server/middleware/platform-boundary.ts
@@ -22,6 +22,7 @@ export default defineEventHandler((event) => {
'/api/auth/logout',
'/api/auth/security',
'/api/account/profile',
+ '/api/account/connections',
'/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 3014f23b..c4424504 100644
--- a/apps/cloud/server/utils/account-auth.ts
+++ b/apps/cloud/server/utils/account-auth.ts
@@ -106,6 +106,7 @@ export function accountAuthOptions(
secret: config.secret,
database,
trustedOrigins: [origin.origin],
+ onAPIError: { errorURL: `${origin.origin}/account?connection=failed` },
telemetry: { enabled: false },
advanced: {
database: { generateId: 'serial' },
@@ -159,6 +160,7 @@ export function accountAuthOptions(
encryptOAuthTokens: true,
accountLinking: {
enabled: true,
+ allowDifferentEmails: false,
requireLocalEmailVerified: true,
trustedProviders: [],
},
diff --git a/apps/cloud/server/utils/account-handler.ts b/apps/cloud/server/utils/account-handler.ts
index 1d306cfe..84a325ca 100644
--- a/apps/cloud/server/utils/account-handler.ts
+++ b/apps/cloud/server/utils/account-handler.ts
@@ -12,6 +12,7 @@ import {
platformPortalOrigin,
platformRequestURL,
} from '../../../shared/platform/runtime'
+import { requirePlatformSession } from '../../../shared/platform/context'
import { createEmailCodeCrypto } from '../../../shared/platform/crypto'
import { cloudAccount } from './cloud-account'
import { isSocialLoginProvider } from '../../../../packages/contracts/src/social-login'
@@ -33,7 +34,7 @@ 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') {
+ if (path === '/api/auth/sign-in/social' || path === '/api/auth/link-social') {
let body: Record<string, unknown>
try {
body = JSON.parse(raw || '{}')
@@ -47,6 +48,8 @@ export async function forwardAccountRequest(event: H3Event, rewrite?: string) {
)
throw createError({ statusCode: 400 })
}
+ if (path === '/api/auth/link-social')
+ await requirePlatformSession(event, config)
if (
raw &&
[
diff --git a/apps/cloud/server/utils/account-routes.ts b/apps/cloud/server/utils/account-routes.ts
index 2a7d1101..cb35cfaf 100644
--- a/apps/cloud/server/utils/account-routes.ts
+++ b/apps/cloud/server/utils/account-routes.ts
@@ -4,6 +4,7 @@ export const ACCOUNT_POST_ROUTES = new Set([
'/sign-up/email',
'/sign-in/email',
'/sign-in/social',
+ '/link-social',
'/sign-in/email-otp',
'/sign-out',
'/email-otp/send-verification-otp',
diff --git a/apps/cloud/server/utils/cloud-account.ts b/apps/cloud/server/utils/cloud-account.ts
index ce148166..34efcdbd 100644
--- a/apps/cloud/server/utils/cloud-account.ts
+++ b/apps/cloud/server/utils/cloud-account.ts
@@ -14,6 +14,7 @@ export async function cloudAccount(event: H3Event) {
const path = getRequestURL(event).pathname
const providers =
path === '/api/auth/sign-in/social' ||
+ path === '/api/auth/link-social' ||
path.startsWith('/api/auth/callback/')
? await socialLoginProviders(
platformDatabase(event),
diff --git a/packages/platform/src/account-connections.ts b/packages/platform/src/account-connections.ts
new file mode 100644
index 00000000..a1b281a7
--- /dev/null
+++ b/packages/platform/src/account-connections.ts
@@ -0,0 +1,77 @@
+import type { PlatformD1 } from './index.ts'
+import { SOCIAL_LOGIN_PROVIDERS } from '../../contracts/src/social-login.ts'
+import { socialLoginProviders } from './social-login.ts'
+export type LinkedLoginAccount = {
+ id: string
+ provider: string
+ canUnlink: boolean
+}
+type AccountRow = { id: number; provider: string; hasPassword: number }
+async function accounts(db: PlatformD1, userId: number) {
+ const row = await db
+ .prepare(
+ "SELECT COALESCE(json_group_array(json_object('id',id,'provider',provider_id,'hasPassword',CASE WHEN password IS NOT NULL AND password<>'' THEN 1 ELSE 0 END)), '[]') AS items FROM (SELECT id,provider_id,password FROM platform_accounts WHERE user_id=? ORDER BY id)",
+ )
+ .bind(userId)
+ .first<{ items: string }>()
+ return JSON.parse(row?.items ?? '[]') as AccountRow[]
+}
+export async function accountConnections(
+ db: PlatformD1,
+ secret: string,
+ userId: number,
+) {
+ const enabled = Object.keys(await socialLoginProviders(db, secret))
+ const linked = await accounts(db, userId)
+ const usable = (account: AccountRow) =>
+ account.provider === 'credential'
+ ? !!account.hasPassword
+ : enabled.includes(account.provider)
+ return {
+ providers: SOCIAL_LOGIN_PROVIDERS.filter((p) => enabled.includes(p.id)).map(
+ (p) => ({ id: p.id, name: p.name, icon: p.icon }),
+ ),
+ accounts: linked
+ .filter((a) => a.provider !== 'credential')
+ .map((a) => ({
+ id: String(a.id),
+ provider: a.provider,
+ canUnlink: linked.some((other) => other.id !== a.id && usable(other)),
+ })),
+ }
+}
+/** One atomic delete preserves another usable login method even for simultaneous unlink requests. */
+export async function unlinkLoginAccount(
+ db: PlatformD1,
+ secret: string,
+ userId: number,
+ id: unknown,
+) {
+ if (
+ typeof id !== 'string' ||
+ !/^[1-9][0-9]{0,15}$/.test(id) ||
+ !Number.isSafeInteger(Number(id))
+ )
+ return false
+ const enabled = Object.keys(await socialLoginProviders(db, secret))
+ const placeholders = enabled.map(() => '?').join(',') || 'NULL'
+ const row = await db
+ .prepare(
+ `DELETE FROM platform_accounts
+ WHERE id=? AND user_id=? AND provider_id<>'credential'
+ AND EXISTS (
+ SELECT 1 FROM platform_accounts other
+ WHERE other.user_id=? AND other.id<>platform_accounts.id
+ AND (
+ (other.provider_id='credential' AND other.password IS NOT NULL AND other.password<>'')
+ OR (other.provider_id IN (${placeholders}) AND EXISTS (
+ SELECT 1 FROM platform_social_login_providers p
+ WHERE p.provider=other.provider_id AND p.client_id<>'' AND p.credentials_ciphertext<>''
+ ))
+ )
+ ) RETURNING id`,
+ )
+ .bind(Number(id), userId, userId, ...enabled)
+ .first<{ id: number }>()
+ return !!row
+}
diff --git a/tests/account-connections-routes.test.ts b/tests/account-connections-routes.test.ts
new file mode 100644
index 00000000..8a8547c7
--- /dev/null
+++ b/tests/account-connections-routes.test.ts
@@ -0,0 +1,127 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { readFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+const require = createRequire(import.meta.url),
+ ts = require('typescript')
+type Event = { origin?: string; body?: unknown }
+async function handler(name: string, deps: Record<string, unknown>) {
+ const source = (
+ await readFile(
+ new URL(
+ `../apps/cloud/server/api/account/connections.${name}.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
+ return new Function(
+ 'exports',
+ ...Object.keys(deps),
+ code + ';return exports.default',
+ )({}, ...Object.values(deps)) as (event: Event) => Promise<unknown>
+}
+test('connected-account routes use session ownership, canonical origins and fresh sessions for disconnects', async () => {
+ let authenticated = true,
+ authUserId = 42,
+ createdAt = Date.now(),
+ reads = 0,
+ writes = 0
+ const config = {
+ portalOrigin: 'https://app.chronoframe.art',
+ storageSecret: 'fixture-secret',
+ }
+ const deps = {
+ definePlatformHandler: (f: unknown) => f,
+ useRuntimeConfig: () => ({ platform: config }),
+ setResponseHeader: () => {},
+ platformPortalOrigin: (event: Event, _origin: string, mutation = false) => {
+ if (mutation && event.origin !== config.portalOrigin)
+ throw Object.assign(new Error('Origin'), { statusCode: 403 })
+ },
+ requirePlatformSession: async () => {
+ if (!authenticated)
+ throw Object.assign(new Error('Unauthorized'), { statusCode: 401 })
+ return { userId: 42 }
+ },
+ platformDatabase: () => ({}),
+ accountConnections: async (
+ _db: unknown,
+ _secret: string,
+ userId: number,
+ ) => {
+ assert.equal(userId, 42)
+ reads++
+ return { providers: [], accounts: [] }
+ },
+ cloudAccount: async () => ({
+ api: {
+ getSession: async () => ({
+ user: { id: String(authUserId) },
+ session: { createdAt: new Date(createdAt) },
+ }),
+ },
+ }),
+ getRequestHeaders: () => ({}),
+ siteManagementBody: async (event: Event) => event.body,
+ unlinkLoginAccount: async (
+ _db: unknown,
+ _secret: string,
+ userId: number,
+ id: unknown,
+ ) => {
+ assert.equal(userId, 42)
+ assert.equal(id, '5')
+ writes++
+ return true
+ },
+ createError: (value: { statusCode: number; data?: unknown }) =>
+ Object.assign(new Error('Request rejected'), value),
+ }
+ const read = await handler('get', deps),
+ remove = await handler('delete', deps)
+ authenticated = false
+ await assert.rejects(read({}), { statusCode: 401 })
+ await assert.rejects(
+ remove({ origin: config.portalOrigin, body: { id: '5' } }),
+ { statusCode: 401 },
+ )
+ assert.equal(reads, 0)
+ assert.equal(writes, 0)
+ authenticated = true
+ assert.deepEqual(await read({ body: { userId: 99 } }), {
+ providers: [],
+ accounts: [],
+ })
+ await assert.rejects(
+ remove({ origin: 'https://evil.example.com', body: { id: '5' } }),
+ { statusCode: 403 },
+ )
+ createdAt = Date.now() - 11 * 60_000
+ await assert.rejects(
+ remove({ origin: config.portalOrigin, body: { id: '5' } }),
+ { statusCode: 401, data: { code: 'SESSION_IS_NOT_FRESH' } },
+ )
+ createdAt = Date.now()
+ authUserId = 99
+ await assert.rejects(
+ remove({ origin: config.portalOrigin, body: { id: '5' } }),
+ { statusCode: 401 },
+ )
+ assert.equal(writes, 0)
+ authUserId = 42
+ assert.deepEqual(
+ await remove({
+ origin: config.portalOrigin,
+ body: { id: '5', userId: 99 },
+ }),
+ { success: true },
+ )
+ assert.equal(writes, 1)
+})
diff --git a/tests/social-login.test.ts b/tests/social-login.test.ts
index a124a2c1..b72869ce 100644
--- a/tests/social-login.test.ts
+++ b/tests/social-login.test.ts
@@ -1,3 +1,7 @@
+import {
+ accountConnections,
+ unlinkLoginAccount,
+} from '../packages/platform/src/account-connections.ts'
import assert from 'node:assert/strict'
import test from 'node:test'
import { createRequire } from 'node:module'
@@ -27,12 +31,13 @@ test('OAuth callbacks expose only the supported provider surface', () => {
assert(!accountRouteAllowed(`/api/auth/callback/${provider}`, 'DELETE'))
}
assert(accountRouteAllowed('/api/auth/sign-in/social', 'POST'))
+ assert(accountRouteAllowed('/api/auth/link-social', 'POST'))
+ assert(!accountRouteAllowed('/api/auth/link-social', 'GET'))
for (const path of [
'/api/auth/callback/unknown',
'/api/auth/callback/microsoft',
'/api/auth/callback/github/extra',
'/api/auth/update-user',
- '/api/auth/link-social',
'/api/auth/get-access-token',
])
assert(!accountRouteAllowed(path, 'POST'))
@@ -337,6 +342,7 @@ test('credentials are root-only, encrypted, redacted, revision fenced and disabl
}
try {
let attempt = 0
+ let loginCookies = new Map<string, string>()
async function login(expectedRedirect: string) {
const ip = `192.0.2.${++attempt}`
const cookies = new Map<string, string>()
@@ -410,6 +416,7 @@ test('credentials are root-only, encrypted, redacted, revision fenced and disabl
headers: headers(),
}),
)
+ loginCookies = cookies
return (await session.json()) as TestSession
}
const session = await login('/workspace')
@@ -431,6 +438,140 @@ test('credentials are root-only, encrypted, redacted, revision fenced and disabl
)
.first()
assert.notEqual(token.access_token, 'oauth-token')
+
+ const captureConnectionCookies = (response: Response) => {
+ for (const cookie of response.headers.getSetCookie()) {
+ const pair = cookie.split(';')[0]!,
+ index = pair.indexOf('=')
+ loginCookies.set(pair.slice(0, index), pair.slice(index + 1))
+ }
+ }
+ const connectionHeaders = () => ({
+ 'content-type': 'application/json',
+ origin: 'https://app.chronoframe.art',
+ 'cf-connecting-ip': `192.0.2.${++attempt}`,
+ cookie: [...loginCookies].map(([k, v]) => `${k}=${v}`).join('; '),
+ })
+ assert.equal(
+ (
+ await auth.handler(
+ new Request('https://app.chronoframe.art/api/auth/link-social', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ origin: 'https://app.chronoframe.art',
+ },
+ body: JSON.stringify({
+ provider: 'github',
+ callbackURL:
+ 'https://app.chronoframe.art/account?connection=updated',
+ }),
+ }),
+ )
+ ).status,
+ 401,
+ )
+ async function connect(expected: string) {
+ const response = await auth.handler(
+ new Request('https://app.chronoframe.art/api/auth/link-social', {
+ method: 'POST',
+ headers: connectionHeaders(),
+ body: JSON.stringify({
+ provider: 'github',
+ callbackURL:
+ 'https://app.chronoframe.art/account?connection=updated',
+ }),
+ }),
+ )
+ assert.equal(response.status, 200)
+ captureConnectionCookies(response)
+ const url = new URL(((await response.json()) as { url: string }).url)
+ const result = await auth.handler(
+ new Request(
+ `https://app.chronoframe.art/api/auth/callback/github?code=link-code&state=${encodeURIComponent(url.searchParams.get('state')!)}`,
+ { headers: connectionHeaders() },
+ ),
+ )
+ captureConnectionCookies(result)
+ assert.equal(result.status, 302)
+ assert(
+ result.headers.get('location')?.includes(expected),
+ result.headers.get('location') ?? '',
+ )
+ }
+ githubId = 201
+ await connect('connection=updated')
+ const linked = await db
+ .prepare(
+ "SELECT id,user_id FROM platform_accounts WHERE provider_id='github' AND account_id='201'",
+ )
+ .first()
+ assert.equal(linked.user_id, 42)
+ assert.equal(
+ (
+ await db
+ .prepare('SELECT name FROM platform_users WHERE id=42')
+ .first()
+ ).name,
+ 'Updated nickname',
+ )
+ const listing = await accountConnections(db, secret, 42)
+ assert.equal(listing.providers.length, 1)
+ assert.equal(listing.providers[0]?.id, 'github')
+ assert(!JSON.stringify(listing).includes('oauth-token'))
+ assert.equal(
+ (await accountConnections(db, secret, 43)).accounts.length,
+ 0,
+ )
+ assert.equal(
+ await unlinkLoginAccount(db, secret, 43, String(linked.id)),
+ false,
+ )
+ assert.equal(
+ await unlinkLoginAccount(db, secret, 42, String(linked.id)),
+ true,
+ )
+ assert.equal(
+ await unlinkLoginAccount(
+ db,
+ secret,
+ 42,
+ String(
+ (
+ await db
+ .prepare(
+ "SELECT id FROM platform_accounts WHERE provider_id='github' AND account_id='101'",
+ )
+ .first()
+ ).id,
+ ),
+ ),
+ false,
+ )
+ githubId = 202
+ email = '[email protected]'
+ await connect('connection=failed')
+ assert.equal(
+ await db
+ .prepare(
+ "SELECT id FROM platform_accounts WHERE account_id='202' AND provider_id='github'",
+ )
+ .first(),
+ null,
+ )
+ githubId = 203
+ email = '[email protected]'
+ verified = false
+ await connect('connection=failed')
+ assert.equal(
+ await db
+ .prepare(
+ "SELECT id FROM platform_accounts WHERE account_id='203' AND provider_id='github'",
+ )
+ .first(),
+ null,
+ )
+ verified = true
githubId = 102
const pending = await login('second=totp')
@@ -457,6 +598,56 @@ test('credentials are root-only, encrypted, redacted, revision fenced and disabl
} finally {
globalThis.fetch = originalFetch
}
+ // Simultaneous disconnects cannot remove both available login methods.
+ await db
+ .prepare(
+ "INSERT INTO platform_users(id,email,name,email_verified,created_at) VALUES(900,'[email protected]','Concurrent',1,1)",
+ )
+ .run()
+ await db
+ .prepare(
+ "INSERT INTO platform_accounts(account_id,provider_id,user_id,created_at,updated_at) VALUES('900','github',900,1,1),('900','google',900,1,1)",
+ )
+ .run()
+ await db
+ .prepare(
+ "UPDATE platform_social_login_providers SET client_id='google-test',credentials_ciphertext=?,revision=1 WHERE provider='google'",
+ )
+ .bind(
+ await cipher.seal(
+ { clientId: 'google-test', clientSecret: 'test-google-secret' },
+ 'google:1',
+ ),
+ )
+ .run()
+ const concurrent = JSON.parse(
+ (
+ await db
+ .prepare(
+ 'SELECT json_group_array(id) AS ids FROM platform_accounts WHERE user_id=900',
+ )
+ .first()
+ ).ids,
+ ) as number[]
+ const results = await Promise.all(
+ concurrent.map((id) => unlinkLoginAccount(db, secret, 900, String(id))),
+ )
+ assert.equal(results.filter(Boolean).length, 1)
+ assert.equal(
+ (
+ await db
+ .prepare(
+ 'SELECT COUNT(*) AS count FROM platform_accounts WHERE user_id=900',
+ )
+ .first()
+ ).count,
+ 1,
+ )
+ await db
+ .prepare(
+ "UPDATE platform_social_login_providers SET client_id='',credentials_ciphertext='' WHERE provider='google'",
+ )
+ .run()
await saveSocialLoginProvider(db, secret, actor, {
...input,
revision: 2,
@@ -495,6 +686,7 @@ test('auth forwarding checks web origins and rejects ID-token entry while accept
},
}).outputText
let calls = 0
+ let authenticated = false
const deps = {
useRuntimeConfig: () => ({
platform: { portalOrigin: 'https://app.chronoframe.art' },
@@ -510,6 +702,11 @@ test('auth forwarding checks web origins and rejects ID-token entry while accept
if (required && e.origin !== 'https://app.chronoframe.art')
throw Object.assign(new Error('Origin'), { statusCode: 403 })
},
+ requirePlatformSession: async () => {
+ if (!authenticated)
+ throw Object.assign(new Error('Unauthorized'), { statusCode: 401 })
+ return { userId: 42 }
+ },
accountRouteAllowed,
socialLoginCallback: (path: string) =>
/^\/api\/auth\/callback\/(github|google|discord)$/.test(path),
@@ -559,7 +756,17 @@ test('auth forwarding checks web origins and rejects ID-token entry while accept
}),
{ statusCode: 400 },
)
+ await assert.rejects(
+ forwardAccountRequest({ ...event, path: '/api/auth/link-social' }),
+ { statusCode: 401 },
+ )
assert.equal(calls, 0)
+ authenticated = true
+ assert.equal(
+ (await forwardAccountRequest({ ...event, path: '/api/auth/link-social' }))
+ .status,
+ 200,
+ )
assert.equal((await forwardAccountRequest(event)).status, 200)
assert.equal(
(